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