updated TODOs
[libt2n] / codegen / main.cpp
1 #include <libxml++/libxml++.h>
2 #include <cassert>
3 #include <iostream>
4 #include <set>
5 #include <fstream>
6 #include <list>
7 #include <stdexcept>
8 #include <boost/lexical_cast.hpp>
9 #ifdef HAVE_CONFIG_H
10 #include "config.h"
11 #endif
12
13 //! convert string to upper case
14 std::string
15 toupper(std::string s) {
16      for (unsigned i=0; i<s.length(); ++i) s[i]=toupper(s[i]);
17      return s;
18 }
19
20 //! replace all characters f by r in string s
21 std::string
22 replace(std::string s, char f, char r) {
23      for (unsigned i=0; i<s.length(); ++i) if (s[i]==f) s[i]=r;
24      return s;
25 }
26
27 //! strip prefix from string s
28 /*!
29   \return string s without prefix or an empty string on error
30  */
31 std::string
32 strip(std::string s, std::string prefix)
33 {
34      std::string error;
35      if ( (prefix.length()>s.length() ) || ( std::string(s,0,prefix.length())!=prefix ) ) return error;
36      return std::string(s, prefix.length(), s.length()-prefix.length());
37 }
38
39 //! get child element by id
40 /*!
41   \return pointer to element having id or null on error
42   \todo find libxmlpp pendant
43 */
44 const xmlpp::Element* get_element_by_id(const xmlpp::Element* element, const std::string &id)
45 {
46      const xmlpp::Attribute* cid = element->get_attribute("id");
47      if ( cid && ( cid->get_value() == id)) return element;
48
49      //Recurse through child nodes:
50      xmlpp::Node::NodeList list = element->get_children();
51      for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
52      {
53           const xmlpp::Element* element = dynamic_cast<const xmlpp::Element*>(*iter);
54           if (element) {
55                const xmlpp::Element* match = get_element_by_id(element, id);
56                if (match) return match;
57           }
58      }
59      return NULL;
60 }
61
62 std::string
63 get_file(const xmlpp::Element* root, const std::string &file_id)
64 {
65      std::string error;
66      const xmlpp::Element* e=get_element_by_id(root, file_id);
67      if ((!e)||(!e->get_attribute("name"))) return error;
68      return e->get_attribute("name")->get_value();
69 }
70
71 //! get namespace by id
72 /*!
73   \return namespace name or empty string on error
74 */
75 std::string get_namespace(const xmlpp::Element* root, const std::string &id)
76 {
77      std::string error;
78      const xmlpp::Element* element(get_element_by_id(root, id));
79      if ((!element)||(!element->get_attribute("name"))) return error;
80      return element->get_attribute("name")->get_value();
81 }
82
83 //! extract group from attributes
84 std::string
85 extract_group(const std::string &attrs)
86 {
87      // todo: improve this
88      std::string error;
89      std::string to_match("gccxml(libt2n-");
90      std::string::size_type p(attrs.find(to_match));
91      if (p==std::string::npos) return error;
92      std::string group(attrs, p+to_match.length(), attrs.length());
93      p=group.find_first_of(')');
94      assert(p!=std::string::npos);
95      return std::string(group,0,p);
96 }
97
98 struct type_info
99 {
100      std::string name;
101      std::string noref_name;
102      bool operator==(const type_info& o) {return (name==o.name) && (noref_name == o.noref_name);}
103      std::string noref() const {return noref_name.empty() ? name : noref_name;}
104 };
105
106 std::ostream &operator<<(std::ostream &o, const type_info &t) {
107      o << t.name;
108      return o;
109 }
110
111 struct parse_error : public std::runtime_error
112 {
113      parse_error(const std::string &file, unsigned line, const std::string &msg)
114           : std::runtime_error(file+":"+boost::lexical_cast<std::string>(line)+": error: "+msg)
115           {}
116 };
117
118 //! get type by id
119 /*!
120   \return type name or empty string on error
121 */
122 type_info get_type(const xmlpp::Element* root, const std::string &id)
123 {
124      type_info error;
125      const xmlpp::Element* element(get_element_by_id(root, id));
126      if (!element) return error;
127
128      // TODO: not yet complete
129      // if we recurse - when do we stop?
130      // if it is a typedef? yes? (hmm if the typedef is in the file parsed this will not work)
131
132      // TODO: const and reference types handling is a ugly hack
133
134      std::string tag(element->get_name());
135      if (tag=="ReferenceType") {
136           assert(element->get_attribute("type"));
137           type_info ret(get_type(root, element->get_attribute("type")->get_value()));
138           if (ret==error) return error;
139           // at the moment we only support const &
140           // todo: nice error message!
141           if ((ret.noref_name=strip(ret.name,"const ")).empty()) return error;
142           ret.name=ret.name+"&";
143           return ret;
144      }else if (tag=="CvQualifiedType") {
145           assert(element->get_attribute("type"));
146           type_info ret(get_type(root, element->get_attribute("type")->get_value()));
147           if (ret==error) return error;
148           ret.name=std::string("const ")+ret.name;
149           return ret;
150      }else if (tag=="PointerType") {
151           // not yet supported
152           return error;
153      }
154
155      assert(element->get_attribute("name"));
156      type_info ret;
157      if (element->get_attribute("context")) {
158           ret.name=get_namespace(root, element->get_attribute("context")->get_value());
159           if (ret.name!="::")
160                ret.name+="::";
161           else
162                // do not explicitely add ::
163                ret.name="";
164      }
165      ret.name+=element->get_attribute("name")->get_value();
166      return ret;
167 }
168
169 struct t2n_procedure
170 {
171      typedef std::list<std::pair<std::string, type_info> > Args;
172
173      type_info ret_type;
174      std::string name;
175      std::string mangled;
176      Args  args;
177
178      std::string ret_classname() const {
179           return name+mangled+"_res";
180      }
181      std::string cmd_classname() const {
182           return name+mangled+"_cmd";
183      }
184 };
185
186 std::ostream &operator<<(std::ostream &o, const t2n_procedure::Args &args) {
187      for (t2n_procedure::Args::const_iterator it=args.begin();it!=args.end();++it) {
188           if (it!=args.begin()) o << ", ";
189           o << it->second << " " << it->first;
190      }
191      return o;
192 }
193
194 std::ostream &operator<<(std::ostream &o, const t2n_procedure &f) {
195      o << f.ret_type << " " << f.name << "(" << f.args << ")";
196      return o;
197 }
198
199 class Parser
200 {
201 public:
202      Parser(const std::string &fname) : m_fname(fname) {}
203
204      std::list<t2n_procedure> get_procedures() {
205           xmlpp::DomParser parser;
206           //    parser.set_validate();
207           parser.set_substitute_entities(); //We just want the text to be resolved/unescaped automatically.
208           parser.parse_file(m_fname);
209           if(parser)
210           {
211                //Walk the tree:
212                const xmlpp::Node* pNode = parser.get_document()->get_root_node(); //deleted by DomParser.
213                const xmlpp::Element* root = dynamic_cast<const xmlpp::Element*>(pNode);
214                assert(root);
215                visit_node(root);
216           }
217           return m_procedures;
218      }
219 protected:
220      std::string m_fname;
221      std::list<t2n_procedure> m_procedures;
222
223      void parse_function(const xmlpp::Element* root, const xmlpp::Node* node) {
224           const xmlpp::Element* element = dynamic_cast<const xmlpp::Element*>(node);
225           if (!element) return;
226
227           const xmlpp::Attribute* attributes = element->get_attribute("attributes");
228           const xmlpp::Attribute* name = element->get_attribute("name");
229           const xmlpp::Attribute* mangled = element->get_attribute("mangled");
230           const xmlpp::Attribute* returns = element->get_attribute("returns");
231           if ((!attributes)||(!name)||(!mangled)||(!returns)) return;
232
233           // check wether the procedure is marked (TODO: improve)
234           // attributes are speparated by spaces?
235
236           t2n_procedure f;
237           if (extract_group(attributes->get_value()).empty()) return;
238
239           // we need the return type
240           f.ret_type=get_type(root, returns->get_value());
241           f.name=name->get_value();
242           f.mangled=mangled->get_value();
243
244           xmlpp::Node::NodeList list = node->get_children("Argument");
245           for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
246           {
247                const xmlpp::Element* arg = dynamic_cast<const xmlpp::Element*>(*iter);
248                if ( arg ) {
249                     assert(arg->get_name() == "Argument");
250                     assert(arg->get_attribute("name"));
251                     assert(arg->get_attribute("type"));
252                     f.args.push_back(std::pair<std::string, type_info>(arg->get_attribute("name")->get_value(), get_type(root, arg->get_attribute("type")->get_value())));
253                     // todo: ugly - could be any other error
254                     if (f.args.back().second.name.empty()) {
255                          assert(element->get_attribute("file"));
256                          assert(element->get_attribute("line"));
257                          throw parse_error(get_file(root, element->get_attribute("file")->get_value()),
258                                            boost::lexical_cast<unsigned>(element->get_attribute("line")->get_value())-1,
259                                            std::string("type of parameter `")+f.args.back().first+"' not (yet?) supported");
260                     }
261                }
262           }
263           std::cerr << "Found function: " << f << std::endl;
264           m_procedures.push_back(f);
265      }
266
267      void visit_node(const xmlpp::Element* root, const xmlpp::Node* node = NULL, unsigned int indentation = 0)
268           {
269                if (!node) node=root;
270           
271                const xmlpp::ContentNode* nodeContent = dynamic_cast<const xmlpp::ContentNode*>(node);
272                const xmlpp::TextNode* nodeText = dynamic_cast<const xmlpp::TextNode*>(node);
273                const xmlpp::CommentNode* nodeComment = dynamic_cast<const xmlpp::CommentNode*>(node);
274
275                if(nodeText && nodeText->is_white_space()) //Let's ignore the indenting - you don't always want to do this.
276                     return;
277     
278                std::string nodename = node->get_name();
279
280                if(!nodeText && !nodeComment && !nodename.empty()) //Let's not say "name: text".
281                {
282                     if (node->get_name() == "Function") parse_function(root, node);
283                }
284                if(!nodeContent)
285                {
286                     //Recurse through child nodes:
287                     xmlpp::Node::NodeList list = node->get_children();
288                     for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
289                     {
290                          visit_node(root, *iter, indentation + 2); //recursive
291                     }
292                }
293           }
294 };
295
296 void output_common_hpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs) {
297     o << "class cmd_group_" << group << " : public libt2n::command\n"
298       << "{\n"
299       << "private:\n"
300       << "      friend class boost::serialization::access;\n"
301       << "      template<class Archive>\n"
302       << "      void serialize(Archive & ar, const unsigned int /* version */)\n"
303       << "      {ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::command);}\n"
304       << "};\n";
305      
306     for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
307         o << "class " << it->ret_classname() << " : public libt2n::result\n"
308           << "{\n"
309           << "private:\n"
310           << "  " << it->ret_type << " res;\n"
311           << "  friend class boost::serialization::access;\n"
312           << "  template<class Archive>\n"
313           << "  void serialize(Archive & ar, const unsigned int /* version */)\n"
314           << "  {\n"
315           << "          ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::result);\n"
316           << "          ar & BOOST_SERIALIZATION_NVP(res);\n"
317           << "  }\n"
318           << "public:\n"
319           << "  " << it->ret_classname() << "() {}\n"
320           << "  " << it->ret_classname() << "(const " << it->ret_type << " &_res) : res(_res) {}\n"
321           << "  " << it->ret_type << " get_data() { return res; }\n"
322           << "};\n";
323     }
324     for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
325         o << "class " << it->cmd_classname() << " : public " << "cmd_group_" << group << "\n"
326           << "{\n"
327           << "private:\n";
328         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
329             o << "      " << ait->second.noref() << " " << ait->first << ";\n";
330         }
331         o << "  friend class boost::serialization::access;\n"
332           << "  template<class Archive>\n"
333           << "  void serialize(Archive & ar, const unsigned int /* version */)\n"
334           << "  {\n"
335           << "          ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(cmd_group_" << group << ");\n";
336         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
337             o << "              ar & BOOST_SERIALIZATION_NVP(" << ait->first << ");\n";
338         }
339         
340         // default constructor
341         o << "  }\n"
342           << "\n"
343           << "public:\n"
344           << "  " << it->cmd_classname() << "() {}\n";
345         
346         // constructor taking all arguments
347         o << "  " << it->cmd_classname() << "(";
348         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
349             if (ait!=it->args.begin()) o << ", ";
350             o << ait->second << " _" << ait->first;
351         }
352         o << ") : ";
353         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
354             if (ait!=it->args.begin()) o << ", ";
355             o << ait->first << "(_" << ait->first << ")";
356         }
357         o << " {}\n"
358           << "  libt2n::result* operator()();\n"
359           << "};\n";
360     }
361 }
362
363 void output_common_cpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
364      o << "#include \"" << common_hpp << "\"\n"
365        << "#include <boost/serialization/export.hpp>\n"
366        << "\n"
367        << "/* register types with boost serialization */\n";
368      o << "BOOST_CLASS_EXPORT(cmd_group_" << group << ")\n";
369      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
370           o << "BOOST_CLASS_EXPORT("<<it->ret_classname()<<")\n"
371             << "BOOST_CLASS_EXPORT("<<it->cmd_classname()<<")\n";
372      }
373 }
374
375 void output_client_hpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs) {
376      o << "#include <command_client.hxx>\n";
377
378      o << "class cmd_group_" << group << "_client : public libt2n::command_client\n"
379        << "{\n"
380        << "public:\n"
381        << "cmd_group_" << group << "_client(libt2n::client_connection &_c,\n"
382        << "     long long _command_timeout_usec=command_timeout_usec_default,\n"
383        << "     long long _hello_timeout_usec=hello_timeout_usec_default)\n"
384        << "     : libt2n::command_client(_c,_command_timeout_usec,_hello_timeout_usec)\n"
385        << "     {}\n";
386      for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
387          o << " " << *pit << ";\n";
388      }
389      o << "};\n";
390 }
391
392 void output_client_cpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs, const std::string &common_hpp, const std::string &common_cpp, const std::string &client_hpp) {
393      o << "#include \"" << client_hpp << "\"\n"
394        << "#include \"" << common_hpp << "\"\n"
395        << "// fake\n";
396      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
397           o << "libt2n::result* " << it->cmd_classname() << "::operator()() { return NULL; }\n";
398      }
399
400      for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
401          o << pit->ret_type << " cmd_group_" << group << "_client::" << pit->name << "(" << pit->args << ")\n"
402            << "{\n"
403            << " libt2n::result_container rc;\n"
404            << " send_command(new " << pit->cmd_classname() << "(";
405          for (t2n_procedure::Args::const_iterator ait=pit->args.begin();ait!=pit->args.end();++ait) {
406              if (ait!=pit->args.begin()) o << ", ";
407              o << ait->first;
408          }
409          o << "), rc);\n"
410            << " " << pit->ret_classname() << "* res=dynamic_cast<" << pit->ret_classname() << "*>(rc.get_result());\n"
411            << " if (!res) throw libt2n::t2n_communication_error(\"result object of wrong type\");\n"
412            << " return res->get_data();\n"
413            << "}\n";
414      }
415
416      // include in this compilation unit to ensure the compilation unit is used
417      // see also:
418      // http://www.google.de/search?q=g%2B%2B+static+initializer+in+static+library
419      o << "#include \"" << common_cpp << "\"\n";
420 }
421
422 void output_server_hpp(std::ostream &o, const std::string & /* group */, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
423      o << "#include \"" << common_hpp << "\"\n";
424
425      // output function declarations
426      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it)
427        o << *it << ";\n";
428 }
429
430 void output_server_cpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs, const std::string &common_hpp, const std::string &common_cpp) {
431      o << "#include \"" << common_hpp << "\"\n";
432
433      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
434           o << *it << ";\n";
435           o << "libt2n::result* " << it->cmd_classname() << "::operator()() { return new " << it->ret_classname() << "(" << it->name << "(";
436           for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
437                if (ait!=it->args.begin()) o << ", ";
438                o << ait->first;
439           }
440           o << ")); }\n";
441      }
442      o << "#include \"" << common_cpp << "\"\n";
443 }
444
445 struct header_file : public std::ofstream
446 {
447      header_file(const char* fname) : std::ofstream(fname) {
448           std::cerr << "create header: '" << fname << "'" << std::endl;
449           std::string macro(replace(toupper(fname),'.','_'));
450           *this << "// automatically generated code (generated by libt2n-codegen " << VERSION << ") - do not edit\n" << std::endl;
451           *this << "#ifndef " << macro << "\n"
452                 << "#define " << macro << "\n";
453      }
454      ~header_file() {
455           *this << "#endif" << std::endl;
456      }
457 };
458
459 struct cpp_file : public std::ofstream
460 {
461      cpp_file(const char* fname) : std::ofstream(fname) {
462           std::cerr << "create cpp: '" << fname << "'" << std::endl;
463           *this << "// automatically generated code - do not edit\n" << std::endl;
464      }
465 };
466
467 int
468 main(int argc, char* argv[])
469 {
470     // todo: maybe use getopt
471     if ((argc>1)&&(std::string(argv[1])=="--version")) {
472         std::cerr << VERSION << std::endl;
473         return 0;
474     }
475     if (argc < 3)
476     {
477         std::cerr << "Usage: " << argv[0] << "default-group gccxml-file1 gccxml-file2 ... " << std::endl;
478         return 1;
479     }
480
481     try{
482           std::string group(argv[1]);
483           std::list<std::string> xmlfiles;
484           for (int i=2;i<argc;++i)
485             xmlfiles.push_back(argv[i]);
486
487           std::string prefix=group+"_";
488           std::list<t2n_procedure> procedures;
489           for (std::list<std::string>::iterator it=xmlfiles.begin();it!=xmlfiles.end();++it) {
490               std::cerr << "Parse " << *it << std::endl;
491               Parser parser(*it);
492               const std::list<t2n_procedure> &p(parser.get_procedures());
493               std::copy(p.begin(), p.end(), std::back_inserter(procedures));
494           }
495
496           std::cerr << "Procedures:" << std::endl;
497           for (std::list<t2n_procedure>::const_iterator it=procedures.begin();it!=procedures.end();++it)
498                std::cerr << *it << ";" << std::endl;
499
500           std::string common_hpp_fname(prefix+"common.hxx");
501           std::string common_cpp_fname(prefix+"common.cpp");
502           std::string client_hpp_fname(prefix+"client.hxx");
503           std::string client_cpp_fname(prefix+"client.cpp");
504           std::string server_hpp_fname(prefix+"server.hxx");
505           std::string server_cpp_fname(prefix+"server.cpp");
506
507           header_file common_hpp(common_hpp_fname.c_str());
508           common_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
509                      << "#include \"codegen-stubhead.hxx\"\n"
510                      << "#include \"" << group << ".hxx\"\n";
511
512           output_common_hpp(common_hpp, group, procedures);
513
514           cpp_file common_cpp(common_cpp_fname.c_str());
515           output_common_cpp(common_cpp, group, procedures, common_hpp_fname);
516
517           header_file client_hpp(client_hpp_fname.c_str());
518           client_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
519                      << "#include \"codegen-stubhead.hxx\"\n"
520                      << "#include \"" << group << ".hxx\"\n";
521           output_client_hpp(client_hpp, group, procedures);
522
523           cpp_file client_cpp(client_cpp_fname.c_str());
524           output_client_cpp(client_cpp, group, procedures, common_hpp_fname, common_cpp_fname, client_hpp_fname);
525
526           header_file server_hpp(server_hpp_fname.c_str());
527           output_server_hpp(server_hpp, group, procedures, common_hpp_fname);
528
529           cpp_file server_cpp(server_cpp_fname.c_str());
530           output_server_cpp(server_cpp, group, procedures, common_hpp_fname, common_cpp_fname);
531      }catch(const parse_error &e){
532        std::cerr << e.what() << std::endl;
533        return EXIT_FAILURE;
534      }
535      return EXIT_SUCCESS;
536 }