do not ship generated files (dist-hook hack). added codegen.make
[libt2n] / codegen / main.cpp
1 #include <libxml++/libxml++.h>
2 #include <cassert>
3 #include <iostream>
4 #include <set>
5 #include <fstream>
6 #include <list>
7 #include <stdexcept>
8 #include <boost/lexical_cast.hpp>
9
10 //! convert string to upper case
11 std::string
12 toupper(std::string s) {
13      for (unsigned i=0; i<s.length(); ++i) s[i]=toupper(s[i]);
14      return s;
15 }
16
17 //! replace all characters f by r in string s
18 std::string
19 replace(std::string s, char f, char r) {
20      for (unsigned i=0; i<s.length(); ++i) if (s[i]==f) s[i]=r;
21      return s;
22 }
23
24 //! strip prefix from string s
25 /*!
26   \return string s without prefix or an empty string on error
27  */
28 std::string
29 strip(std::string s, std::string prefix)
30 {
31      std::string error;
32      if ( (prefix.length()>s.length() ) || ( std::string(s,0,prefix.length())!=prefix ) ) return error;
33      return std::string(s, prefix.length(), s.length()-prefix.length());
34 }
35
36 //! extract group from attributes
37 std::string
38 extract_group(const std::string &attrs)
39 {
40      // todo: improve this
41      std::string error;
42      std::string to_match("gccxml(libt2n-");
43      std::string::size_type p(attrs.find(to_match));
44      if (p==std::string::npos) return error;
45      std::string group(attrs, p+to_match.length(), attrs.length());
46      p=group.find_first_of(')');
47      assert(p!=std::string::npos);
48      return std::string(group,0,p);
49 }
50
51 //! get child element by id
52 /*!
53   \return pointer to element having id or null on error
54   \todo find libxmlpp pendant
55 */
56 const xmlpp::Element* get_element_by_id(const xmlpp::Element* element, const std::string &id)
57 {
58      const xmlpp::Attribute* cid = element->get_attribute("id");
59      if ( cid && ( cid->get_value() == id)) return element;
60
61      //Recurse through child nodes:
62      xmlpp::Node::NodeList list = element->get_children();
63      for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
64      {
65           const xmlpp::Element* element = dynamic_cast<const xmlpp::Element*>(*iter);
66           if (element) {
67                const xmlpp::Element* match = get_element_by_id(element, id);
68                if (match) return match;
69           }
70      }
71      return NULL;
72 }
73
74 std::string
75 get_file(const xmlpp::Element* root, const std::string &file_id)
76 {
77      std::string error;
78      const xmlpp::Element* e=get_element_by_id(root, file_id);
79      if ((!e)||(!e->get_attribute("name"))) return error;
80      return e->get_attribute("name")->get_value();
81 }
82
83 //! get namespace by id
84 /*!
85   \return namespace name or empty string on error
86 */
87 std::string get_namespace(const xmlpp::Element* root, const std::string &id)
88 {
89      std::string error;
90      const xmlpp::Element* element(get_element_by_id(root, id));
91      if ((!element)||(!element->get_attribute("name"))) return error;
92      return element->get_attribute("name")->get_value();
93 }
94
95 struct type_info
96 {
97      std::string name;
98      std::string noref_name;
99      bool operator==(const type_info& o) {return (name==o.name) && (noref_name == o.noref_name);}
100      std::string noref() const {return noref_name.empty() ? name : noref_name;}
101 };
102
103 std::ostream &operator<<(std::ostream &o, const type_info &t) {
104      o << t.name;
105      return o;
106 }
107
108 struct parse_error : public std::runtime_error
109 {
110      parse_error(const std::string &file, unsigned line, const std::string &msg)
111           : std::runtime_error(file+":"+boost::lexical_cast<std::string>(line)+": error: "+msg)
112           {}
113 };
114
115 //! get type by id
116 /*!
117   \return type name or empty string on error
118 */
119 type_info get_type(const xmlpp::Element* root, const std::string &id)
120 {
121      type_info error;
122      const xmlpp::Element* element(get_element_by_id(root, id));
123      if (!element) return error;
124
125      // TODO: not yet complete
126      // if we recurse - when do we stop?
127      // if it is a typedef? yes? (hmm if the typedef is in the file parsed this will not work)
128
129      // TODO: const and reference types handling is a ugly hack
130
131      std::string tag(element->get_name());
132      if (tag=="ReferenceType") {
133           assert(element->get_attribute("type"));
134           type_info ret(get_type(root, element->get_attribute("type")->get_value()));
135           if (ret==error) return error;
136           // at the moment we only support const &
137           // todo: nice error message!
138           if ((ret.noref_name=strip(ret.name,"const ")).empty()) return error;
139           ret.name=ret.name+"&";
140           return ret;
141      }else if (tag=="CvQualifiedType") {
142           assert(element->get_attribute("type"));
143           type_info ret(get_type(root, element->get_attribute("type")->get_value()));
144           if (ret==error) return error;
145           ret.name=std::string("const ")+ret.name;
146           return ret;
147      }else if (tag=="PointerType") {
148           // not yet supported
149           return error;
150      }
151
152      assert(element->get_attribute("name"));
153      type_info ret;
154      if (element->get_attribute("context")) {
155           ret.name=get_namespace(root, element->get_attribute("context")->get_value());
156           if (ret.name!="::")
157                ret.name+="::";
158           else
159                // do not explicitely add ::
160                ret.name="";
161      }
162      ret.name+=element->get_attribute("name")->get_value();
163      return ret;
164 }
165
166 struct t2n_procedure
167 {
168      typedef std::list<std::pair<std::string, type_info> > Args;
169
170      std::string group;
171      type_info ret_type;
172      std::string name;
173      std::string mangled;
174      Args  args;
175
176      std::string ret_classname() const {
177           return name+mangled+"_res";
178      }
179      std::string cmd_classname() const {
180           return name+mangled+"_cmd";
181      }
182 };
183
184 std::ostream &operator<<(std::ostream &o, const t2n_procedure::Args &args) {
185      for (t2n_procedure::Args::const_iterator it=args.begin();it!=args.end();++it) {
186           if (it!=args.begin()) o << ", ";
187           o << it->second << " " << it->first;
188      }
189      return o;
190 }
191
192 std::ostream &operator<<(std::ostream &o, const t2n_procedure &f) {
193      o << f.ret_type << " " << f.name << "(" << f.args << ")";
194      return o;
195 }
196
197 class Parser
198 {
199 public:
200      Parser(const std::string &fname, const std::string &default_group) : m_fname(fname), m_default_group(default_group) {}
201
202      std::list<t2n_procedure> get_procedures() {
203           xmlpp::DomParser parser;
204           //    parser.set_validate();
205           parser.set_substitute_entities(); //We just want the text to be resolved/unescaped automatically.
206           parser.parse_file(m_fname);
207           if(parser)
208           {
209                //Walk the tree:
210                const xmlpp::Node* pNode = parser.get_document()->get_root_node(); //deleted by DomParser.
211                const xmlpp::Element* root = dynamic_cast<const xmlpp::Element*>(pNode);
212                assert(root);
213                visit_node(root);
214           }
215           return m_procedures;
216      }
217 protected:
218      std::string m_fname;
219      std::string m_default_group;
220      std::list<t2n_procedure> m_procedures;
221
222      void parse_function(const xmlpp::Element* root, const xmlpp::Node* node) {
223           const xmlpp::Element* element = dynamic_cast<const xmlpp::Element*>(node);
224           if (!element) return;
225
226           const xmlpp::Attribute* attributes = element->get_attribute("attributes");
227           const xmlpp::Attribute* name = element->get_attribute("name");
228           const xmlpp::Attribute* mangled = element->get_attribute("mangled");
229           const xmlpp::Attribute* returns = element->get_attribute("returns");
230           if ((!attributes)||(!name)||(!mangled)||(!returns)) return;
231
232           // check wether the procedure is marked (TODO: improve)
233           // attributes are speparated by spaces?
234
235           t2n_procedure f;
236           f.group=extract_group(attributes->get_value());
237           if (f.group.empty()) return;
238           if (f.group=="default") f.group=m_default_group;
239
240           // we need the return type
241           f.ret_type=get_type(root, returns->get_value());
242           f.name=name->get_value();
243           f.mangled=mangled->get_value();
244
245           xmlpp::Node::NodeList list = node->get_children("Argument");
246           for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
247           {
248                const xmlpp::Element* arg = dynamic_cast<const xmlpp::Element*>(*iter);
249                if ( arg ) {
250                     assert(arg->get_name() == "Argument");
251                     assert(arg->get_attribute("name"));
252                     assert(arg->get_attribute("type"));
253                     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())));
254                     // todo: ugly - could be any other error
255                     if (f.args.back().second.name.empty()) {
256                          assert(element->get_attribute("file"));
257                          assert(element->get_attribute("line"));
258                          throw parse_error(get_file(root, element->get_attribute("file")->get_value()),
259                                            boost::lexical_cast<unsigned>(element->get_attribute("line")->get_value())-1,
260                                            std::string("type of parameter `")+f.args.back().first+"' not (yet?) supported");
261                     }
262                }
263           }
264           std::cerr << "Found function: " << f << std::endl;
265           m_procedures.push_back(f);
266      }
267
268      void visit_node(const xmlpp::Element* root, const xmlpp::Node* node = NULL, unsigned int indentation = 0)
269           {
270                if (!node) node=root;
271           
272                const xmlpp::ContentNode* nodeContent = dynamic_cast<const xmlpp::ContentNode*>(node);
273                const xmlpp::TextNode* nodeText = dynamic_cast<const xmlpp::TextNode*>(node);
274                const xmlpp::CommentNode* nodeComment = dynamic_cast<const xmlpp::CommentNode*>(node);
275
276                if(nodeText && nodeText->is_white_space()) //Let's ignore the indenting - you don't always want to do this.
277                     return;
278     
279                std::string nodename = node->get_name();
280
281                if(!nodeText && !nodeComment && !nodename.empty()) //Let's not say "name: text".
282                {
283                     if (node->get_name() == "Function") parse_function(root, node);
284                }
285                if(!nodeContent)
286                {
287                     //Recurse through child nodes:
288                     xmlpp::Node::NodeList list = node->get_children();
289                     for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
290                     {
291                          visit_node(root, *iter, indentation + 2); //recursive
292                     }
293                }
294           }
295 };
296
297 //! find used groups
298 std::set<std::string>
299 used_groups(const std::list<t2n_procedure> &funcs) {
300      typedef std::set<std::string> Groups;
301      Groups groups;
302      for (std::list<t2n_procedure>::const_iterator it=funcs.begin();it!=funcs.end();++it)
303           // since we use std::set each group is inserted only once
304           groups.insert(it->group);
305      return groups;
306 }
307
308 void output_common_hpp(std::ostream &o, const std::list<t2n_procedure> &procs) {
309      std::set<std::string> groups(used_groups(procs));
310
311      for (std::set<std::string>::iterator it=groups.begin();it!=groups.end();++it) {
312           o << "class cmd_group_" << *it << " : public libt2n::command\n"
313             << "{\n"
314             << "private:\n"
315             << "        friend class boost::serialization::access;\n"
316             << "        template<class Archive>\n"
317             << "        void serialize(Archive & ar, const unsigned int /* version */)\n"
318             << "        {ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::command);}\n"
319             << "};\n";
320      }
321      
322      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
323           o << "class " << it->ret_classname() << " : public libt2n::result\n"
324             << "{\n"
325             << "private:\n"
326             << "        " << it->ret_type << " res;\n"
327             << "        friend class boost::serialization::access;\n"
328             << "        template<class Archive>\n"
329             << "        void serialize(Archive & ar, const unsigned int /* version */)\n"
330             << "        {\n"
331             << "                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::result);\n"
332             << "                ar & BOOST_SERIALIZATION_NVP(res);\n"
333             << "        }\n"
334             << "public:\n"
335             << "        " << it->ret_classname() << "() {}\n"
336             << "        " << it->ret_classname() << "(const " << it->ret_type << " &_res) : res(_res) {}\n"
337             << "        " << it->ret_type << " get_data() { return res; }\n"
338             << "};\n";
339      }
340      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
341           o << "class " << it->cmd_classname() << " : public " << "cmd_group_" << it->group << "\n"
342             << "{\n"
343             << "private:\n";
344           for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
345                o << "   " << ait->second.noref() << " " << ait->first << ";\n";
346           }
347           o << "        friend class boost::serialization::access;\n"
348             << "        template<class Archive>\n"
349             << "        void serialize(Archive & ar, const unsigned int /* version */)\n"
350             << "        {\n"
351             << "                ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(cmd_group_" << it->group << ");\n";
352           for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
353                o << "           ar & BOOST_SERIALIZATION_NVP(" << ait->first << ");\n";
354           }
355
356           // default constructor
357           o << "        }\n"
358             << "\n"
359             << "public:\n"
360             << "        " << it->cmd_classname() << "() {}\n";
361
362           // constructor taking all arguments
363           o << "        " << it->cmd_classname() << "(";
364           for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
365                if (ait!=it->args.begin()) o << ", ";
366                o << ait->second << " _" << ait->first;
367           }
368           o << ") : ";
369           for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
370                if (ait!=it->args.begin()) o << ", ";
371                o << ait->first << "(_" << ait->first << ")";
372           }
373           o << " {}\n"
374             << "        libt2n::result* operator()();\n"
375             << "};\n";
376      }
377 }
378
379 void output_common_cpp(std::ostream &o, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
380      std::set<std::string> groups(used_groups(procs));
381
382      o << "#include \"" << common_hpp << "\"\n"
383        << "#include <boost/serialization/export.hpp>\n"
384        << "\n"
385        << "/* register types with boost serialization */\n";
386      for (std::set<std::string>::iterator it=groups.begin();it!=groups.end();++it) {
387           o << "BOOST_CLASS_EXPORT(cmd_group_" << *it << ")\n";
388      }
389      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
390           o << "BOOST_CLASS_EXPORT("<<it->ret_classname()<<")\n"
391             << "BOOST_CLASS_EXPORT("<<it->cmd_classname()<<")\n";
392      }
393 }
394
395 void output_client_hpp(std::ostream &o, const std::list<t2n_procedure> &procs) {
396      std::set<std::string> groups(used_groups(procs));
397
398      o << "#include <command_client.hxx>\n";
399
400      for (std::set<std::string>::iterator it=groups.begin();it!=groups.end();++it) {
401           o << "class cmd_group_" << *it << "_client : public libt2n::command_client\n"
402             << "{\n"
403             << "public:\n"
404             << "cmd_group_" << *it << "_client(libt2n::client_connection &_c,\n"
405             << "        long long _command_timeout_usec=command_timeout_usec_default,\n"
406             << "        long long _hello_timeout_usec=hello_timeout_usec_default)\n"
407             << "        : libt2n::command_client(_c,_command_timeout_usec,_hello_timeout_usec)\n"
408             << "        {}\n";
409           for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
410                if (pit->group==*it) {
411                     o << "      " << *pit << ";\n";
412                }
413           }
414           o << "};\n";
415      }
416 }
417
418 void output_client_cpp(std::ostream &o, const std::list<t2n_procedure> &procs, const std::string &common_hpp, const std::string &common_cpp, const std::string &client_hpp) {
419      std::set<std::string> groups(used_groups(procs));
420
421      o << "#include \"" << client_hpp << "\"\n"
422        << "#include \"" << common_hpp << "\"\n"
423        << "// fake\n";
424      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
425           o << "libt2n::result* " << it->cmd_classname() << "::operator()() { return NULL; }\n";
426      }
427
428      for (std::set<std::string>::iterator it=groups.begin();it!=groups.end();++it) {
429           for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
430                if (pit->group==*it) {
431                     o << pit->ret_type << " cmd_group_" << *it << "_client::" << pit->name << "(" << pit->args << ")\n"
432                       << "{\n"
433                       << "      libt2n::result_container rc;\n"
434                       << "      send_command(new " << pit->cmd_classname() << "(";
435                     for (t2n_procedure::Args::const_iterator ait=pit->args.begin();ait!=pit->args.end();++ait) {
436                          if (ait!=pit->args.begin()) o << ", ";
437                          o << ait->first;
438                     }
439                     o << "), rc);\n"
440                       << "      " << pit->ret_classname() << "* res=dynamic_cast<" << pit->ret_classname() << "*>(rc.get_result());\n"
441                       << "      if (!res) throw libt2n::t2n_communication_error(\"result object of wrong type\");\n"
442                       << "      return res->get_data();\n"
443                       << "}\n";
444                }
445           }
446      }
447
448      // include in this compilation unit to ensure the compilation unit is used
449      // see also:
450      // http://www.google.de/search?q=g%2B%2B+static+initializer+in+static+library
451      o << "#include \"" << common_cpp << "\"\n";
452 }
453
454 void output_server_hpp(std::ostream &o, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
455      o << "#include \"" << common_hpp << "\"\n";
456
457      // output function declarations
458      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it)
459        o << *it << ";\n";
460 }
461
462 void output_server_cpp(std::ostream &o, const std::list<t2n_procedure> &procs, const std::string &common_hpp, const std::string &common_cpp) {
463      o << "#include \"" << common_hpp << "\"\n";
464
465      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
466           o << *it << ";\n";
467           o << "libt2n::result* " << it->cmd_classname() << "::operator()() { return new " << it->ret_classname() << "(" << it->name << "(";
468           for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
469                if (ait!=it->args.begin()) 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 - 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      if (argc < 3) {
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             Parser parser(*it, group);
517             const std::list<t2n_procedure> &p(parser.get_procedures());
518             std::copy(p.begin(), p.end(), std::back_inserter(procedures));
519           }
520
521           std::cerr << "Procedures:" << std::endl;
522           for (std::list<t2n_procedure>::const_iterator it=procedures.begin();it!=procedures.end();++it)
523                std::cerr << *it << ";" << std::endl;
524
525           std::set<std::string> groups(used_groups(procedures));
526           std::cerr << "Used groups:" << std::endl;
527           for (std::set<std::string>::const_iterator it=groups.begin();it!=groups.end();++it)
528                std::cerr << *it << std::endl;
529
530           std::string common_hpp_fname(prefix+"common.hxx");
531           std::string common_cpp_fname(prefix+"common.cpp");
532           std::string client_hpp_fname(prefix+"client.hxx");
533           std::string client_cpp_fname(prefix+"client.cpp");
534           std::string server_hpp_fname(prefix+"server.hxx");
535           std::string server_cpp_fname(prefix+"server.cpp");
536
537           header_file common_hpp(common_hpp_fname.c_str());
538           common_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
539                      << "#include \"codegen-stubhead.hxx\"\n"
540                      << "#include \"" << group << ".hxx\"\n";
541
542           output_common_hpp(common_hpp, procedures);
543
544           cpp_file common_cpp(common_cpp_fname.c_str());
545           output_common_cpp(common_cpp, procedures, common_hpp_fname);
546
547           header_file client_hpp(client_hpp_fname.c_str());
548           client_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
549                      << "#include \"codegen-stubhead.hxx\"\n"
550                      << "#include \"" << group << ".hxx\"\n";
551           output_client_hpp(client_hpp, procedures);
552
553           cpp_file client_cpp(client_cpp_fname.c_str());
554           output_client_cpp(client_cpp, procedures, common_hpp_fname, common_cpp_fname, client_hpp_fname);
555
556           header_file server_hpp(server_hpp_fname.c_str());
557           output_server_hpp(server_hpp, procedures, common_hpp_fname);
558
559           cpp_file server_cpp(server_cpp_fname.c_str());
560           output_server_cpp(server_cpp, procedures, common_hpp_fname, common_cpp_fname);
561      }catch(const parse_error &e){
562        std::cerr << e.what() << std::endl;
563        return EXIT_FAILURE;
564      }
565      return EXIT_SUCCESS;
566 }