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