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