ec974036bac336b9fdeba37d059cf6411bde973b
[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 //! get child element by id
37 /*!
38   \return pointer to element having id or null on error
39   \todo find libxmlpp pendant
40 */
41 const xmlpp::Element* get_element_by_id(const xmlpp::Element* element, const std::string &id)
42 {
43      const xmlpp::Attribute* cid = element->get_attribute("id");
44      if ( cid && ( cid->get_value() == id)) return element;
45
46      //Recurse through child nodes:
47      xmlpp::Node::NodeList list = element->get_children();
48      for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
49      {
50           const xmlpp::Element* element = dynamic_cast<const xmlpp::Element*>(*iter);
51           if (element) {
52                const xmlpp::Element* match = get_element_by_id(element, id);
53                if (match) return match;
54           }
55      }
56      return NULL;
57 }
58
59 std::string
60 get_file(const xmlpp::Element* root, const std::string &file_id)
61 {
62      std::string error;
63      const xmlpp::Element* e=get_element_by_id(root, file_id);
64      if ((!e)||(!e->get_attribute("name"))) return error;
65      return e->get_attribute("name")->get_value();
66 }
67
68 //! get namespace by id
69 /*!
70   \return namespace name or empty string on error
71 */
72 std::string get_namespace(const xmlpp::Element* root, const std::string &id)
73 {
74      std::string error;
75      const xmlpp::Element* element(get_element_by_id(root, id));
76      if ((!element)||(!element->get_attribute("name"))) return error;
77      return element->get_attribute("name")->get_value();
78 }
79
80 //! extract group from attributes
81 std::string
82 extract_group(const std::string &attrs)
83 {
84      // todo: improve this
85      std::string error;
86      std::string to_match("gccxml(libt2n-");
87      std::string::size_type p(attrs.find(to_match));
88      if (p==std::string::npos) return error;
89      std::string group(attrs, p+to_match.length(), attrs.length());
90      p=group.find_first_of(')');
91      assert(p!=std::string::npos);
92      return std::string(group,0,p);
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      type_info ret_type;
171      std::string name;
172      std::string mangled;
173      Args  args;
174
175      std::string ret_classname() const {
176           return name+mangled+"_res";
177      }
178      std::string cmd_classname() const {
179           return name+mangled+"_cmd";
180      }
181 };
182
183 std::ostream &operator<<(std::ostream &o, const t2n_procedure::Args &args) {
184      for (t2n_procedure::Args::const_iterator it=args.begin();it!=args.end();++it) {
185           if (it!=args.begin()) o << ", ";
186           o << it->second << " " << it->first;
187      }
188      return o;
189 }
190
191 std::ostream &operator<<(std::ostream &o, const t2n_procedure &f) {
192      o << f.ret_type << " " << f.name << "(" << f.args << ")";
193      return o;
194 }
195
196 class Parser
197 {
198 public:
199      Parser(const std::string &fname) : m_fname(fname) {}
200
201      std::list<t2n_procedure> get_procedures() {
202           xmlpp::DomParser parser;
203           //    parser.set_validate();
204           parser.set_substitute_entities(); //We just want the text to be resolved/unescaped automatically.
205           parser.parse_file(m_fname);
206           if(parser)
207           {
208                //Walk the tree:
209                const xmlpp::Node* pNode = parser.get_document()->get_root_node(); //deleted by DomParser.
210                const xmlpp::Element* root = dynamic_cast<const xmlpp::Element*>(pNode);
211                assert(root);
212                visit_node(root);
213           }
214           return m_procedures;
215      }
216 protected:
217      std::string m_fname;
218      std::list<t2n_procedure> m_procedures;
219
220      void parse_function(const xmlpp::Element* root, const xmlpp::Node* node) {
221           const xmlpp::Element* element = dynamic_cast<const xmlpp::Element*>(node);
222           if (!element) return;
223
224           const xmlpp::Attribute* attributes = element->get_attribute("attributes");
225           const xmlpp::Attribute* name = element->get_attribute("name");
226           const xmlpp::Attribute* mangled = element->get_attribute("mangled");
227           const xmlpp::Attribute* returns = element->get_attribute("returns");
228           if ((!attributes)||(!name)||(!mangled)||(!returns)) return;
229
230           // check wether the procedure is marked (TODO: improve)
231           // attributes are speparated by spaces?
232
233           t2n_procedure f;
234           if (extract_group(attributes->get_value()).empty()) return;
235
236           // we need the return type
237           f.ret_type=get_type(root, returns->get_value());
238           f.name=name->get_value();
239           f.mangled=mangled->get_value();
240
241           xmlpp::Node::NodeList list = node->get_children("Argument");
242           for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
243           {
244                const xmlpp::Element* arg = dynamic_cast<const xmlpp::Element*>(*iter);
245                if ( arg ) {
246                     assert(arg->get_name() == "Argument");
247                     assert(arg->get_attribute("name"));
248                     assert(arg->get_attribute("type"));
249                     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())));
250                     // todo: ugly - could be any other error
251                     if (f.args.back().second.name.empty()) {
252                          assert(element->get_attribute("file"));
253                          assert(element->get_attribute("line"));
254                          throw parse_error(get_file(root, element->get_attribute("file")->get_value()),
255                                            boost::lexical_cast<unsigned>(element->get_attribute("line")->get_value())-1,
256                                            std::string("type of parameter `")+f.args.back().first+"' not (yet?) supported");
257                     }
258                }
259           }
260           std::cerr << "Found function: " << f << std::endl;
261           m_procedures.push_back(f);
262      }
263
264      void visit_node(const xmlpp::Element* root, const xmlpp::Node* node = NULL, unsigned int indentation = 0)
265           {
266                if (!node) node=root;
267           
268                const xmlpp::ContentNode* nodeContent = dynamic_cast<const xmlpp::ContentNode*>(node);
269                const xmlpp::TextNode* nodeText = dynamic_cast<const xmlpp::TextNode*>(node);
270                const xmlpp::CommentNode* nodeComment = dynamic_cast<const xmlpp::CommentNode*>(node);
271
272                if(nodeText && nodeText->is_white_space()) //Let's ignore the indenting - you don't always want to do this.
273                     return;
274     
275                std::string nodename = node->get_name();
276
277                if(!nodeText && !nodeComment && !nodename.empty()) //Let's not say "name: text".
278                {
279                     if (node->get_name() == "Function") parse_function(root, node);
280                }
281                if(!nodeContent)
282                {
283                     //Recurse through child nodes:
284                     xmlpp::Node::NodeList list = node->get_children();
285                     for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
286                     {
287                          visit_node(root, *iter, indentation + 2); //recursive
288                     }
289                }
290           }
291 };
292
293 void output_common_hpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs) {
294     o << "class cmd_group_" << group << " : public libt2n::command\n"
295       << "{\n"
296       << "private:\n"
297       << "      friend class boost::serialization::access;\n"
298       << "      template<class Archive>\n"
299       << "      void serialize(Archive & ar, const unsigned int /* version */)\n"
300       << "      {ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::command);}\n"
301       << "};\n";
302      
303     for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
304         o << "class " << it->ret_classname() << " : public libt2n::result\n"
305           << "{\n"
306           << "private:\n"
307           << "  " << it->ret_type << " res;\n"
308           << "  friend class boost::serialization::access;\n"
309           << "  template<class Archive>\n"
310           << "  void serialize(Archive & ar, const unsigned int /* version */)\n"
311           << "  {\n"
312           << "          ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::result);\n"
313           << "          ar & BOOST_SERIALIZATION_NVP(res);\n"
314           << "  }\n"
315           << "public:\n"
316           << "  " << it->ret_classname() << "() {}\n"
317           << "  " << it->ret_classname() << "(const " << it->ret_type << " &_res) : res(_res) {}\n"
318           << "  " << it->ret_type << " get_data() { return res; }\n"
319           << "};\n";
320     }
321     for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
322         o << "class " << it->cmd_classname() << " : public " << "cmd_group_" << group << "\n"
323           << "{\n"
324           << "private:\n";
325         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
326             o << "      " << ait->second.noref() << " " << ait->first << ";\n";
327         }
328         o << "  friend class boost::serialization::access;\n"
329           << "  template<class Archive>\n"
330           << "  void serialize(Archive & ar, const unsigned int /* version */)\n"
331           << "  {\n"
332           << "          ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(cmd_group_" << group << ");\n";
333         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
334             o << "              ar & BOOST_SERIALIZATION_NVP(" << ait->first << ");\n";
335         }
336         
337         // default constructor
338         o << "  }\n"
339           << "\n"
340           << "public:\n"
341           << "  " << it->cmd_classname() << "() {}\n";
342         
343         // constructor taking all arguments
344         o << "  " << it->cmd_classname() << "(";
345         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
346             if (ait!=it->args.begin()) o << ", ";
347             o << ait->second << " _" << ait->first;
348         }
349         o << ") : ";
350         for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
351             if (ait!=it->args.begin()) o << ", ";
352             o << ait->first << "(_" << ait->first << ")";
353         }
354         o << " {}\n"
355           << "  libt2n::result* operator()();\n"
356           << "};\n";
357     }
358 }
359
360 void output_common_cpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
361      o << "#include \"" << common_hpp << "\"\n"
362        << "#include <boost/serialization/export.hpp>\n"
363        << "\n"
364        << "/* register types with boost serialization */\n";
365      o << "BOOST_CLASS_EXPORT(cmd_group_" << group << ")\n";
366      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
367           o << "BOOST_CLASS_EXPORT("<<it->ret_classname()<<")\n"
368             << "BOOST_CLASS_EXPORT("<<it->cmd_classname()<<")\n";
369      }
370 }
371
372 void output_client_hpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs) {
373      o << "#include <command_client.hxx>\n";
374
375      o << "class cmd_group_" << group << "_client : public libt2n::command_client\n"
376        << "{\n"
377        << "public:\n"
378        << "cmd_group_" << group << "_client(libt2n::client_connection &_c,\n"
379        << "     long long _command_timeout_usec=command_timeout_usec_default,\n"
380        << "     long long _hello_timeout_usec=hello_timeout_usec_default)\n"
381        << "     : libt2n::command_client(_c,_command_timeout_usec,_hello_timeout_usec)\n"
382        << "     {}\n";
383      for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
384          o << " " << *pit << ";\n";
385      }
386      o << "};\n";
387 }
388
389 void output_client_cpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs, const std::string &common_hpp, const std::string &common_cpp, const std::string &client_hpp) {
390      o << "#include \"" << client_hpp << "\"\n"
391        << "#include \"" << common_hpp << "\"\n"
392        << "// fake\n";
393      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
394           o << "libt2n::result* " << it->cmd_classname() << "::operator()() { return NULL; }\n";
395      }
396
397      for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
398          o << pit->ret_type << " cmd_group_" << group << "_client::" << pit->name << "(" << pit->args << ")\n"
399            << "{\n"
400            << " libt2n::result_container rc;\n"
401            << " send_command(new " << pit->cmd_classname() << "(";
402          for (t2n_procedure::Args::const_iterator ait=pit->args.begin();ait!=pit->args.end();++ait) {
403              if (ait!=pit->args.begin()) o << ", ";
404              o << ait->first;
405          }
406          o << "), rc);\n"
407            << " " << pit->ret_classname() << "* res=dynamic_cast<" << pit->ret_classname() << "*>(rc.get_result());\n"
408            << " if (!res) throw libt2n::t2n_communication_error(\"result object of wrong type\");\n"
409            << " return res->get_data();\n"
410            << "}\n";
411      }
412
413      // include in this compilation unit to ensure the compilation unit is used
414      // see also:
415      // http://www.google.de/search?q=g%2B%2B+static+initializer+in+static+library
416      o << "#include \"" << common_cpp << "\"\n";
417 }
418
419 void output_server_hpp(std::ostream &o, const std::string & /* group */, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
420      o << "#include \"" << common_hpp << "\"\n";
421
422      // output function declarations
423      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it)
424        o << *it << ";\n";
425 }
426
427 void output_server_cpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs, const std::string &common_hpp, const std::string &common_cpp) {
428      o << "#include \"" << common_hpp << "\"\n";
429
430      for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
431           o << *it << ";\n";
432           o << "libt2n::result* " << it->cmd_classname() << "::operator()() { return new " << it->ret_classname() << "(" << it->name << "(";
433           for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
434                if (ait!=it->args.begin()) o << ", ";
435                o << ait->first;
436           }
437           o << ")); }\n";
438      }
439      o << "#include \"" << common_cpp << "\"\n";
440 }
441
442 struct header_file : public std::ofstream
443 {
444      header_file(const char* fname) : std::ofstream(fname) {
445           std::cerr << "create header: '" << fname << "'" << std::endl;
446           std::string macro(replace(toupper(fname),'.','_'));
447           *this << "// automatically generated code - do not edit\n" << std::endl;
448           *this << "#ifndef " << macro << "\n"
449                 << "#define " << macro << "\n";
450      }
451      ~header_file() {
452           *this << "#endif" << std::endl;
453      }
454 };
455
456 struct cpp_file : public std::ofstream
457 {
458      cpp_file(const char* fname) : std::ofstream(fname) {
459           std::cerr << "create cpp: '" << fname << "'" << std::endl;
460           *this << "// automatically generated code - do not edit\n" << std::endl;
461      }
462 };
463
464 int
465 main(int argc, char* argv[])
466 {
467      if (argc < 3) {
468           std::cerr << "Usage: " << argv[0] << "default-group gccxml-file1 gccxml-file2 ... " << std::endl;
469           return 1;
470      }
471
472      try{
473           std::string group(argv[1]);
474           std::list<std::string> xmlfiles;
475           for (int i=2;i<argc;++i)
476             xmlfiles.push_back(argv[i]);
477
478           std::string prefix=group+"_";
479           std::list<t2n_procedure> procedures;
480           for (std::list<std::string>::iterator it=xmlfiles.begin();it!=xmlfiles.end();++it) {
481               std::cerr << "Parse " << *it << std::endl;
482               Parser parser(*it);
483               const std::list<t2n_procedure> &p(parser.get_procedures());
484               std::copy(p.begin(), p.end(), std::back_inserter(procedures));
485           }
486
487           std::cerr << "Procedures:" << std::endl;
488           for (std::list<t2n_procedure>::const_iterator it=procedures.begin();it!=procedures.end();++it)
489                std::cerr << *it << ";" << std::endl;
490
491           std::string common_hpp_fname(prefix+"common.hxx");
492           std::string common_cpp_fname(prefix+"common.cpp");
493           std::string client_hpp_fname(prefix+"client.hxx");
494           std::string client_cpp_fname(prefix+"client.cpp");
495           std::string server_hpp_fname(prefix+"server.hxx");
496           std::string server_cpp_fname(prefix+"server.cpp");
497
498           header_file common_hpp(common_hpp_fname.c_str());
499           common_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
500                      << "#include \"codegen-stubhead.hxx\"\n"
501                      << "#include \"" << group << ".hxx\"\n";
502
503           output_common_hpp(common_hpp, group, procedures);
504
505           cpp_file common_cpp(common_cpp_fname.c_str());
506           output_common_cpp(common_cpp, group, procedures, common_hpp_fname);
507
508           header_file client_hpp(client_hpp_fname.c_str());
509           client_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
510                      << "#include \"codegen-stubhead.hxx\"\n"
511                      << "#include \"" << group << ".hxx\"\n";
512           output_client_hpp(client_hpp, group, procedures);
513
514           cpp_file client_cpp(client_cpp_fname.c_str());
515           output_client_cpp(client_cpp, group, procedures, common_hpp_fname, common_cpp_fname, client_hpp_fname);
516
517           header_file server_hpp(server_hpp_fname.c_str());
518           output_server_hpp(server_hpp, group, procedures, common_hpp_fname);
519
520           cpp_file server_cpp(server_cpp_fname.c_str());
521           output_server_cpp(server_cpp, group, procedures, common_hpp_fname, common_cpp_fname);
522      }catch(const parse_error &e){
523        std::cerr << e.what() << std::endl;
524        return EXIT_FAILURE;
525      }
526      return EXIT_SUCCESS;
527 }