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