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