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