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