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