b1a0ce179a62eb470db1309a94f2be4147ee9166
[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           << "  " << it->ret_type << " res;\n"
339           << "  friend class boost::serialization::access;\n"
340           << "  template<class Archive>\n"
341           << "  void serialize(Archive & ar, const unsigned int /* version */)\n"
342           << "  {\n"
343           << "          ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::result);\n"
344           << "          ar & BOOST_SERIALIZATION_NVP(res);\n"
345           << "  }\n"
346           << "public:\n"
347           << "  " << it->ret_classname() << "() {}\n"
348           << "  " << it->ret_classname() << "(const " << it->ret_type << " &_res) : res(_res) {}\n"
349           << "  " << it->ret_type << " get_data() { return res; }\n"
350           << "};\n";
351     }
352     for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
353         o << "class " << it->cmd_classname() << " : public " << groupClass(group) << "\n"
354           << "{\n"
355           << "private:\n";
356         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
357             o << "      " << ait->second.noref() << " " << ait->first << ";\n";
358         }
359         o << "  friend class boost::serialization::access;\n"
360           << "  template<class Archive>\n"
361           << "  void serialize(Archive & ar, const unsigned int /* version */)\n"
362           << "  {\n"
363           << "          ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(" << groupClass(group) << ");\n";
364         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
365             o << "              ar & BOOST_SERIALIZATION_NVP(" << ait->first << ");\n";
366         }
367         
368         // default constructor
369         o << "  }\n"
370           << "\n"
371           << "public:\n"
372           << "  " << it->cmd_classname() << "() {}\n";
373         
374         // constructor taking all arguments
375         o << "  " << it->cmd_classname() << "(";
376         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
377             if (ait!=it->args.begin()) o << ", ";
378             o << ait->second << " _" << ait->first;
379         }
380         o << ") : ";
381         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
382             if (ait!=it->args.begin()) o << ", ";
383             // pointers are const pointers and must be dereferenced
384             o << ait->first << "(" << ((ait->second.name.find_first_of('*')!=std::string::npos) ? "*" : "" ) << "_" << ait->first << ")";
385         }
386         o << " {}\n"
387           << "  libt2n::result* operator()();\n"
388           << "};\n";
389     }
390 }
391
392 void output_common_cpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
393      o << "#include \"" << common_hpp << "\"\n"
394        << "#include <boost/serialization/export.hpp>\n"
395        << "\n"
396        << "/* register types with boost serialization */\n";
397      o << "BOOST_CLASS_EXPORT(" << groupClass(group) << ")\n";
398      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
399           o << "BOOST_CLASS_EXPORT("<<it->ret_classname()<<")\n"
400             << "BOOST_CLASS_EXPORT("<<it->cmd_classname()<<")\n";
401      }
402 }
403
404 void output_client_hpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs) {
405      o << "#include <command_client.hxx>\n";
406
407      o << "class " << groupClass(group) << "_client : public libt2n::command_client\n"
408        << "{\n"
409        << "public:\n"
410        << groupClass(group) << "_client(libt2n::client_connection &_c,\n"
411        << "     long long _command_timeout_usec=command_timeout_usec_default,\n"
412        << "     long long _hello_timeout_usec=hello_timeout_usec_default)\n"
413        << "     : libt2n::command_client(_c,_command_timeout_usec,_hello_timeout_usec)\n"
414        << "     {}\n";
415      for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
416          o << " " << *pit << ";\n";
417      }
418      o << "};\n";
419 }
420
421 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) {
422      o << "#include \"" << client_hpp << "\"\n"
423        << "#include \"" << common_hpp << "\"\n"
424        << "// fake\n";
425      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
426           o << "libt2n::result* " << it->cmd_classname() << "::operator()() { return NULL; }\n";
427      }
428
429      for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
430          o << pit->ret_type << " " << groupClass(group) << "_client::" << pit->name << "(" << pit->args << ")\n"
431            << "{\n"
432            << " libt2n::result_container rc;\n"
433            << " send_command(new " << pit->cmd_classname() << "(";
434          for (t2n_procedure::Args::const_iterator ait=pit->args.begin();ait!=pit->args.end();++ait) {
435              if (ait!=pit->args.begin()) o << ", ";
436              o << ait->first;
437          }
438          o << "), rc);\n"
439            << " " << pit->ret_classname() << "* res=dynamic_cast<" << pit->ret_classname() << "*>(rc.get_result());\n"
440            << " if (!res) throw libt2n::t2n_communication_error(\"result object of wrong type\");\n"
441            << " return res->get_data();\n"
442            << "}\n";
443      }
444
445      // include in this compilation unit to ensure the compilation unit is used
446      // see also:
447      // http://www.google.de/search?q=g%2B%2B+static+initializer+in+static+library
448      o << "#include \"" << common_cpp << "\"\n";
449 }
450
451 void output_server_hpp(std::ostream &o, const std::string & /* group */, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
452      o << "#include \"" << common_hpp << "\"\n";
453
454      // output function declarations
455      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it)
456        o << *it << ";\n";
457 }
458
459 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) {
460      o << "#include \"" << common_hpp << "\"\n";
461
462      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
463           o << *it << ";\n";
464           o << "libt2n::result* " << it->cmd_classname() << "::operator()() { return new " << it->ret_classname() << "(" << it->name << "(";
465           for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
466                if (ait!=it->args.begin()) o << ", ";
467                // get pointer
468                if (ait->second.name.find_first_of('*')!=std::string::npos)
469                  o << '&';
470                o << ait->first;
471           }
472           o << ")); }\n";
473      }
474      o << "#include \"" << common_cpp << "\"\n";
475 }
476
477 struct header_file : public std::ofstream
478 {
479      header_file(const char* fname) : std::ofstream(fname) {
480           std::cerr << "create header: '" << fname << "'" << std::endl;
481           std::string macro(replace(toupper(fname),'.','_'));
482           *this << "// automatically generated code (generated by libt2n-codegen " << VERSION << ") - do not edit\n" << std::endl;
483           *this << "#ifndef " << macro << "\n"
484                 << "#define " << macro << "\n";
485      }
486      ~header_file() {
487           *this << "#endif" << std::endl;
488      }
489 };
490
491 struct cpp_file : public std::ofstream
492 {
493      cpp_file(const char* fname) : std::ofstream(fname) {
494           std::cerr << "create cpp: '" << fname << "'" << std::endl;
495           *this << "// automatically generated code - do not edit\n" << std::endl;
496      }
497 };
498
499 int
500 main(int argc, char* argv[])
501 {
502     // todo: maybe use getopt
503     if ((argc>1)&&(std::string(argv[1])=="--version")) {
504         std::cerr << VERSION << std::endl;
505         return 0;
506     }
507     if (argc < 3)
508     {
509         std::cerr << "Usage: " << argv[0] << "default-group gccxml-file1 gccxml-file2 ... " << std::endl;
510         return 1;
511     }
512
513     try{
514           std::string group(argv[1]);
515           std::list<std::string> xmlfiles;
516           for (int i=2;i<argc;++i)
517             xmlfiles.push_back(argv[i]);
518
519           std::string prefix=group+"_";
520           std::list<t2n_procedure> procedures;
521           for (std::list<std::string>::iterator it=xmlfiles.begin();it!=xmlfiles.end();++it) {
522               std::cerr << "Parse " << *it << std::endl;
523               Parser parser(*it);
524               const std::list<t2n_procedure> &p(parser.get_procedures());
525               std::copy(p.begin(), p.end(), std::back_inserter(procedures));
526           }
527
528           std::cerr << "Procedures:" << std::endl;
529           for (std::list<t2n_procedure>::const_iterator it=procedures.begin();it!=procedures.end();++it)
530                std::cerr << *it << ";" << std::endl;
531
532           std::string common_hpp_fname(prefix+"common.hxx");
533           std::string common_cpp_fname(prefix+"common.cpp");
534           std::string client_hpp_fname(prefix+"client.hxx");
535           std::string client_cpp_fname(prefix+"client.cpp");
536           std::string server_hpp_fname(prefix+"server.hxx");
537           std::string server_cpp_fname(prefix+"server.cpp");
538
539           header_file common_hpp(common_hpp_fname.c_str());
540           common_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
541                      << "#include \"codegen-stubhead.hxx\"\n"
542                      << "#include \"" << group << ".hxx\"\n";
543
544           output_common_hpp(common_hpp, group, procedures);
545
546           cpp_file common_cpp(common_cpp_fname.c_str());
547           output_common_cpp(common_cpp, group, procedures, common_hpp_fname);
548
549           header_file client_hpp(client_hpp_fname.c_str());
550           client_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
551                      << "#include \"codegen-stubhead.hxx\"\n"
552                      << "#include \"" << group << ".hxx\"\n";
553           output_client_hpp(client_hpp, group, procedures);
554
555           cpp_file client_cpp(client_cpp_fname.c_str());
556           output_client_cpp(client_cpp, group, procedures, common_hpp_fname, common_cpp_fname, client_hpp_fname);
557
558           header_file server_hpp(server_hpp_fname.c_str());
559           output_server_hpp(server_hpp, group, procedures, common_hpp_fname);
560
561           cpp_file server_cpp(server_cpp_fname.c_str());
562           output_server_cpp(server_cpp, group, procedures, common_hpp_fname, common_cpp_fname);
563      }catch(const parse_error &e){
564        std::cerr << e.what() << std::endl;
565        return EXIT_FAILURE;
566      }
567      return EXIT_SUCCESS;
568 }