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