added support for void return and no args
[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           // todo: nearly the same as reference type handling
173           assert(element->get_attribute("type"));
174           type_info ret(get_type(root, element->get_attribute("type")->get_value()));
175           if (ret==error) return error;
176           // at the moment we only support const &
177           // todo: nice error message!
178           if ((ret.noref_name=strip(ret.name,"const ")).empty()) return error;
179           ret.name=ret.name+"*";
180           return ret;
181      }
182
183      assert(element->get_attribute("name"));
184      type_info ret;
185      if (element->get_attribute("context")) {
186           ret.name=get_namespace(root, element->get_attribute("context")->get_value());
187           if (ret.name!="::")
188                ret.name+="::";
189           else
190                // do not explicitely add ::
191                ret.name="";
192      }
193      ret.name+=element->get_attribute("name")->get_value();
194      return ret;
195 }
196
197 struct t2n_procedure
198 {
199      typedef std::list<std::pair<std::string, type_info> > Args;
200
201      type_info ret_type;
202      std::string name;
203      std::string mangled;
204      Args  args;
205
206      std::string ret_classname() const {
207           return name+mangled+"_res";
208      }
209      std::string cmd_classname() const {
210           return name+mangled+"_cmd";
211      }
212 };
213
214 std::ostream &operator<<(std::ostream &o, const t2n_procedure::Args &args) {
215      for (t2n_procedure::Args::const_iterator it=args.begin();it!=args.end();++it) {
216           if (it!=args.begin()) o << ", ";
217           o << it->second << " " << it->first;
218      }
219      return o;
220 }
221
222 std::ostream &operator<<(std::ostream &o, const t2n_procedure &f) {
223      o << f.ret_type << " " << f.name << "(" << f.args << ")";
224      return o;
225 }
226
227 class Parser
228 {
229 public:
230      Parser(const std::string &fname) : m_fname(fname) {}
231
232      std::list<t2n_procedure> get_procedures() {
233           xmlpp::DomParser parser;
234           //    parser.set_validate();
235           parser.set_substitute_entities(); //We just want the text to be resolved/unescaped automatically.
236           parser.parse_file(m_fname);
237           if(parser)
238           {
239                //Walk the tree:
240                const xmlpp::Node* pNode = parser.get_document()->get_root_node(); //deleted by DomParser.
241                const xmlpp::Element* root = dynamic_cast<const xmlpp::Element*>(pNode);
242                assert(root);
243                visit_node(root);
244           }
245           return m_procedures;
246      }
247 protected:
248      std::string m_fname;
249      std::list<t2n_procedure> m_procedures;
250
251      void parse_function(const xmlpp::Element* root, const xmlpp::Node* node) {
252           const xmlpp::Element* element = dynamic_cast<const xmlpp::Element*>(node);
253           if (!element) return;
254
255           const xmlpp::Attribute* attributes = element->get_attribute("attributes");
256           const xmlpp::Attribute* name = element->get_attribute("name");
257           const xmlpp::Attribute* mangled = element->get_attribute("mangled");
258           const xmlpp::Attribute* returns = element->get_attribute("returns");
259           if ((!attributes)||(!name)||(!mangled)||(!returns)) return;
260
261           // check wether the procedure is marked (TODO: improve)
262           // attributes are speparated by spaces?
263
264           t2n_procedure f;
265           if (!is_marked(attributes->get_value())) return;
266
267           // we need the return type
268           f.ret_type=get_type(root, returns->get_value());
269           f.name=name->get_value();
270           f.mangled=mangled->get_value();
271
272           xmlpp::Node::NodeList list = node->get_children("Argument");
273           for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
274           {
275                const xmlpp::Element* arg = dynamic_cast<const xmlpp::Element*>(*iter);
276                if ( arg ) {
277                     assert(arg->get_name() == "Argument");
278                     assert(arg->get_attribute("name"));
279                     assert(arg->get_attribute("type"));
280                     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())));
281                     // todo: ugly - could be any other error
282                     if (f.args.back().second.name.empty()) {
283                          assert(element->get_attribute("file"));
284                          assert(element->get_attribute("line"));
285                          throw parse_error(get_file(root, element->get_attribute("file")->get_value()),
286                                            boost::lexical_cast<unsigned>(element->get_attribute("line")->get_value())-1,
287                                            std::string("type of parameter `")+f.args.back().first+"' not (yet?) supported");
288                     }
289                }
290           }
291           std::cerr << "Found function: " << f << std::endl;
292           m_procedures.push_back(f);
293      }
294
295      void visit_node(const xmlpp::Element* root, const xmlpp::Node* node = NULL, unsigned int indentation = 0)
296           {
297                if (!node) node=root;
298           
299                const xmlpp::ContentNode* nodeContent = dynamic_cast<const xmlpp::ContentNode*>(node);
300                const xmlpp::TextNode* nodeText = dynamic_cast<const xmlpp::TextNode*>(node);
301                const xmlpp::CommentNode* nodeComment = dynamic_cast<const xmlpp::CommentNode*>(node);
302
303                if(nodeText && nodeText->is_white_space()) //Let's ignore the indenting - you don't always want to do this.
304                     return;
305     
306                std::string nodename = node->get_name();
307
308                if(!nodeText && !nodeComment && !nodename.empty()) //Let's not say "name: text".
309                {
310                     if (node->get_name() == "Function") parse_function(root, node);
311                }
312                if(!nodeContent)
313                {
314                     //Recurse through child nodes:
315                     xmlpp::Node::NodeList list = node->get_children();
316                     for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
317                     {
318                          visit_node(root, *iter, indentation + 2); //recursive
319                     }
320                }
321           }
322 };
323
324 void output_common_hpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs) {
325     o << "class " << groupClass(group) << " : public libt2n::command\n"
326       << "{\n"
327       << "private:\n"
328       << "      friend class boost::serialization::access;\n"
329       << "      template<class Archive>\n"
330       << "      void serialize(Archive & ar, const unsigned int /* version */)\n"
331       << "      {ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::command);}\n"
332       << "};\n";
333      
334     for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
335         o << "class " << it->ret_classname() << " : public libt2n::result\n"
336           << "{\n"
337           << "private:\n";
338         if (it->ret_type.name!="void")
339           o << "        " << it->ret_type << " res;\n";
340         o << "  friend class boost::serialization::access;\n"
341           << "  template<class Archive>\n"
342           << "  void serialize(Archive & ar, const unsigned int /* version */)\n"
343           << "  {\n"
344           << "          ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::result);\n";
345         if (it->ret_type.name!="void")
346           o << "                ar & BOOST_SERIALIZATION_NVP(res);\n";
347         o << "  }\n"
348           << "public:\n"
349           << "  " << it->ret_classname() << "() {}\n";
350         if (it->ret_type.name!="void") {
351           o << "        " << it->ret_classname() << "(const " << it->ret_type << " &_res) : res(_res) {}\n"
352             << "        " << it->ret_type << " get_data() { return res; }\n";
353         }
354         o << "};\n";
355     }
356     for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
357         o << "class " << it->cmd_classname() << " : public " << groupClass(group) << "\n"
358           << "{\n"
359           << "private:\n";
360         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
361             o << "      " << ait->second.noref() << " " << ait->first << ";\n";
362         }
363         o << "  friend class boost::serialization::access;\n"
364           << "  template<class Archive>\n"
365           << "  void serialize(Archive & ar, const unsigned int /* version */)\n"
366           << "  {\n"
367           << "          ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(" << groupClass(group) << ");\n";
368         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
369             o << "              ar & BOOST_SERIALIZATION_NVP(" << ait->first << ");\n";
370         }
371         
372         // default constructor
373         o << "  }\n"
374           << "\n"
375           << "public:\n"
376           << "  " << it->cmd_classname() << "() {}\n";
377         
378         // constructor taking all arguments
379         if (!it->args.empty()) {
380           o << "        " << it->cmd_classname() << "(";
381           for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
382             if (ait!=it->args.begin()) o << ", ";
383             o << ait->second << " _" << ait->first;
384           }
385           o << ") : ";
386           for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
387             if (ait!=it->args.begin()) o << ", ";
388             // pointers are const pointers and must be dereferenced
389             o << ait->first << "(" << ((ait->second.name.find_first_of('*')!=std::string::npos) ? "*" : "" ) << "_" << ait->first << ")";
390           }
391           o << " {}\n";
392         }
393         o << "  libt2n::result* operator()();\n"
394           << "};\n";
395     }
396 }
397
398 void output_common_cpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
399      o << "#include \"" << common_hpp << "\"\n"
400        << "#include <boost/serialization/export.hpp>\n"
401        << "\n"
402        << "/* register types with boost serialization */\n";
403      o << "BOOST_CLASS_EXPORT(" << groupClass(group) << ")\n";
404      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
405           o << "BOOST_CLASS_EXPORT("<<it->ret_classname()<<")\n"
406             << "BOOST_CLASS_EXPORT("<<it->cmd_classname()<<")\n";
407      }
408 }
409
410 void output_client_hpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs) {
411      o << "#include <command_client.hxx>\n";
412
413      o << "class " << groupClass(group) << "_client : public libt2n::command_client\n"
414        << "{\n"
415        << "public:\n"
416        << groupClass(group) << "_client(libt2n::client_connection &_c,\n"
417        << "     long long _command_timeout_usec=command_timeout_usec_default,\n"
418        << "     long long _hello_timeout_usec=hello_timeout_usec_default)\n"
419        << "     : libt2n::command_client(_c,_command_timeout_usec,_hello_timeout_usec)\n"
420        << "     {}\n";
421      for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
422          o << " " << *pit << ";\n";
423      }
424      o << "};\n";
425 }
426
427 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) {
428      o << "#include \"" << client_hpp << "\"\n"
429        << "#include \"" << common_hpp << "\"\n"
430        << "// fake\n";
431      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
432           o << "libt2n::result* " << it->cmd_classname() << "::operator()() { return NULL; }\n";
433      }
434
435      for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
436          o << pit->ret_type << " " << groupClass(group) << "_client::" << pit->name << "(" << pit->args << ")\n"
437            << "{\n"
438            << " libt2n::result_container rc;\n"
439            << " send_command(new " << pit->cmd_classname() << "(";
440          for (t2n_procedure::Args::const_iterator ait=pit->args.begin();ait!=pit->args.end();++ait) {
441              if (ait!=pit->args.begin()) o << ", ";
442              o << ait->first;
443          }
444          o << "), rc);\n"
445            << " " << pit->ret_classname() << "* res=dynamic_cast<" << pit->ret_classname() << "*>(rc.get_result());\n"
446            << " if (!res) throw libt2n::t2n_communication_error(\"result object of wrong type\");\n";
447          if (pit->ret_type.name!="void")
448            o << "       return res->get_data();\n";
449          o << "}\n";
450      }
451
452      // include in this compilation unit to ensure the compilation unit is used
453      // see also:
454      // http://www.google.de/search?q=g%2B%2B+static+initializer+in+static+library
455      o << "#include \"" << common_cpp << "\"\n";
456 }
457
458 void output_server_hpp(std::ostream &o, const std::string & /* group */, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
459      o << "#include \"" << common_hpp << "\"\n";
460
461      // output function declarations
462      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it)
463        o << *it << ";\n";
464 }
465
466 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) {
467      o << "#include \"" << common_hpp << "\"\n";
468
469      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
470           o << *it << ";\n";
471           o << "libt2n::result* " << it->cmd_classname() << "::operator()() { ";
472           if (it->ret_type.name!="void") {
473             o << "return new " << it->ret_classname() << "(" << it->name << "(";
474             for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
475               if (ait!=it->args.begin()) o << ", ";
476               // get pointer
477               if (ait->second.name.find_first_of('*')!=std::string::npos)
478                 o << '&';
479               o << ait->first;
480             }
481             o << "));";
482           }else{
483             o << it->name << "(); return new " << it->ret_classname() << "();";
484           }
485           o << " }\n";
486      }
487      o << "#include \"" << common_cpp << "\"\n";
488 }
489
490 struct header_file : public std::ofstream
491 {
492      header_file(const char* fname) : std::ofstream(fname) {
493           std::cerr << "create header: '" << fname << "'" << std::endl;
494           std::string macro(replace(toupper(fname),'.','_'));
495           *this << "// automatically generated code (generated by libt2n-codegen " << VERSION << ") - do not edit\n" << std::endl;
496           *this << "#ifndef " << macro << "\n"
497                 << "#define " << macro << "\n";
498      }
499      ~header_file() {
500           *this << "#endif" << std::endl;
501      }
502 };
503
504 struct cpp_file : public std::ofstream
505 {
506      cpp_file(const char* fname) : std::ofstream(fname) {
507           std::cerr << "create cpp: '" << fname << "'" << std::endl;
508           *this << "// automatically generated code - do not edit\n" << std::endl;
509      }
510 };
511
512 int
513 main(int argc, char* argv[])
514 {
515     // todo: maybe use getopt
516     if ((argc>1)&&(std::string(argv[1])=="--version")) {
517         std::cerr << VERSION << std::endl;
518         return 0;
519     }
520     if (argc < 3)
521     {
522         std::cerr << "Usage: " << argv[0] << "default-group gccxml-file1 gccxml-file2 ... " << std::endl;
523         return 1;
524     }
525
526     try{
527           std::string group(argv[1]);
528           std::list<std::string> xmlfiles;
529           for (int i=2;i<argc;++i)
530             xmlfiles.push_back(argv[i]);
531
532           std::string prefix=group+"_";
533           std::list<t2n_procedure> procedures;
534           for (std::list<std::string>::iterator it=xmlfiles.begin();it!=xmlfiles.end();++it) {
535               std::cerr << "Parse " << *it << std::endl;
536               Parser parser(*it);
537               const std::list<t2n_procedure> &p(parser.get_procedures());
538               std::copy(p.begin(), p.end(), std::back_inserter(procedures));
539           }
540
541           std::cerr << "Procedures:" << std::endl;
542           for (std::list<t2n_procedure>::const_iterator it=procedures.begin();it!=procedures.end();++it)
543                std::cerr << *it << ";" << std::endl;
544
545           std::string common_hpp_fname(prefix+"common.hxx");
546           std::string common_cpp_fname(prefix+"common.cpp");
547           std::string client_hpp_fname(prefix+"client.hxx");
548           std::string client_cpp_fname(prefix+"client.cpp");
549           std::string server_hpp_fname(prefix+"server.hxx");
550           std::string server_cpp_fname(prefix+"server.cpp");
551
552           header_file common_hpp(common_hpp_fname.c_str());
553           common_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
554                      << "#include \"codegen-stubhead.hxx\"\n"
555                      << "#include \"" << group << ".hxx\"\n";
556
557           output_common_hpp(common_hpp, group, procedures);
558
559           cpp_file common_cpp(common_cpp_fname.c_str());
560           output_common_cpp(common_cpp, group, procedures, common_hpp_fname);
561
562           header_file client_hpp(client_hpp_fname.c_str());
563           client_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
564                      << "#include \"codegen-stubhead.hxx\"\n"
565                      << "#include \"" << group << ".hxx\"\n";
566           output_client_hpp(client_hpp, group, procedures);
567
568           cpp_file client_cpp(client_cpp_fname.c_str());
569           output_client_cpp(client_cpp, group, procedures, common_hpp_fname, common_cpp_fname, client_hpp_fname);
570
571           header_file server_hpp(server_hpp_fname.c_str());
572           output_server_hpp(server_hpp, group, procedures, common_hpp_fname);
573
574           cpp_file server_cpp(server_cpp_fname.c_str());
575           output_server_cpp(server_cpp, group, procedures, common_hpp_fname, common_cpp_fname);
576      }catch(const parse_error &e){
577        std::cerr << e.what() << std::endl;
578        return EXIT_FAILURE;
579      }
580      return EXIT_SUCCESS;
581 }