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