increase version
[libt2n] / codegen / main.cpp
... / ...
CommitLineData
1/*
2 Copyright (C) 2006
3 intra2net.com
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18*/
19
20#include <libxml++/libxml++.h>
21#include <cassert>
22#include <iostream>
23#include <set>
24#include <fstream>
25#include <list>
26#include <stdexcept>
27#include <boost/lexical_cast.hpp>
28#ifdef HAVE_CONFIG_H
29#include "config.h"
30#endif
31
32
33//! map group to class name
34std::string
35groupClass(const std::string &group) {
36 return std::string("cmd_group_")+group;
37}
38
39//! convert string to upper case
40std::string
41toupper(std::string s) {
42 for (unsigned i=0; i<s.length(); ++i) s[i]=toupper(s[i]);
43 return s;
44}
45
46//! replace all characters f by r in string s
47std::string
48replace(std::string s, char f, char r) {
49 for (unsigned i=0; i<s.length(); ++i) if (s[i]==f) s[i]=r;
50 return s;
51}
52
53//! strip prefix from string s
54/*!
55 \return string s without prefix or an empty string on error
56 */
57std::string
58strip(std::string s, std::string prefix)
59{
60 std::string error;
61 if ( (prefix.length()>s.length() ) || ( std::string(s,0,prefix.length())!=prefix ) ) return error;
62 return std::string(s, prefix.length(), s.length()-prefix.length());
63}
64
65//! get child element by id
66/*!
67 \return pointer to element having id or null on error
68 \todo find libxmlpp pendant
69*/
70const xmlpp::Element* get_element_by_id(const xmlpp::Element* element, const std::string &id)
71{
72 const xmlpp::Attribute* cid = element->get_attribute("id");
73 if ( cid && ( cid->get_value() == id)) return element;
74
75 //Recurse through child nodes:
76 xmlpp::Node::NodeList list = element->get_children();
77 for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
78 {
79 const xmlpp::Element* element = dynamic_cast<const xmlpp::Element*>(*iter);
80 if (element) {
81 const xmlpp::Element* match = get_element_by_id(element, id);
82 if (match) return match;
83 }
84 }
85 return NULL;
86}
87
88std::string
89get_file(const xmlpp::Element* root, const std::string &file_id)
90{
91 std::string error;
92 const xmlpp::Element* e=get_element_by_id(root, file_id);
93 if ((!e)||(!e->get_attribute("name"))) return error;
94 return e->get_attribute("name")->get_value();
95}
96
97//! get namespace by id
98/*!
99 \return namespace name or empty string on error
100*/
101std::string get_namespace(const xmlpp::Element* root, const std::string &id)
102{
103 std::string error;
104 const xmlpp::Element* element(get_element_by_id(root, id));
105 // [RP:20071024]: use "demangled" attribute instead of "name" to cover nested namespaces:
106 if ((!element)||(!element->get_attribute("demangled"))) return error;
107 return element->get_attribute("demangled")->get_value();
108}
109
110//! procedure marked for export?
111bool
112is_marked(const std::string &attrs)
113{
114 // todo: improve this
115 std::string to_match("gccxml(libt2n-");
116 std::string::size_type p(attrs.find(to_match));
117 return (p!=std::string::npos);
118}
119
120struct type_info
121{
122 std::string name;
123 std::string noref_name;
124 bool operator==(const type_info& o) {return (name==o.name) && (noref_name == o.noref_name);}
125 std::string noref() const {return noref_name.empty() ? name : noref_name;}
126 bool isVoid() const {return name=="void";}
127};
128
129std::ostream &operator<<(std::ostream &o, const type_info &t) {
130 o << t.name;
131 return o;
132}
133
134struct parse_error : public std::runtime_error
135{
136 parse_error(const std::string &file, unsigned line, const std::string &msg)
137 : std::runtime_error(file+":"+boost::lexical_cast<std::string>(line)+": error: "+msg)
138 {}
139};
140
141//! get type by id
142/*!
143 \return type name or empty string on error
144*/
145type_info get_type(const xmlpp::Element* root, const std::string &id)
146{
147 type_info error;
148 const xmlpp::Element* element(get_element_by_id(root, id));
149 if (!element) return error;
150
151 // TODO: not yet complete
152 // if we recurse - when do we stop?
153 // if it is a typedef? yes? (hmm if the typedef is in the file parsed this will not work)
154
155 // TODO: const and reference types handling is a ugly hack
156
157 std::string tag(element->get_name());
158 if (tag=="ReferenceType") {
159 assert(element->get_attribute("type"));
160 type_info ret(get_type(root, element->get_attribute("type")->get_value()));
161 if (ret==error) return error;
162 // at the moment we only support const &
163 // todo: nice error message!
164 if ((ret.noref_name=strip(ret.name,"const ")).empty()) return error;
165 ret.name=ret.name+"&";
166 return ret;
167 }else if (tag=="CvQualifiedType") {
168 assert(element->get_attribute("type"));
169 type_info ret(get_type(root, element->get_attribute("type")->get_value()));
170 if (ret==error) return error;
171 ret.name=std::string("const ")+ret.name;
172 return ret;
173 }else if (tag=="PointerType") {
174 // todo: nearly the same as reference type handling
175 assert(element->get_attribute("type"));
176 type_info ret(get_type(root, element->get_attribute("type")->get_value()));
177 if (ret==error) return error;
178 // at the moment we only support const &
179 // todo: nice error message!
180 if ((ret.noref_name=strip(ret.name,"const ")).empty()) return error;
181 ret.name=ret.name+"*";
182 return ret;
183 }
184
185 assert(element->get_attribute("name"));
186 type_info ret;
187 if (element->get_attribute("context")) {
188 ret.name=get_namespace(root, element->get_attribute("context")->get_value());
189 if (ret.name!="::")
190 ret.name+="::";
191 else
192 // do not explicitely add ::
193 ret.name="";
194 }
195 ret.name+=element->get_attribute("name")->get_value();
196 return ret;
197}
198
199struct t2n_procedure
200{
201 typedef std::list<std::pair<std::string, type_info> > Args;
202
203 type_info ret_type;
204 std::string name;
205 std::string mangled;
206 Args args;
207
208 std::string ret_classname() const {
209 return name+mangled+"_res";
210 }
211 std::string cmd_classname() const {
212 return name+mangled+"_cmd";
213 }
214 bool hasReturn() const {return !ret_type.isVoid();}
215};
216
217std::ostream &operator<<(std::ostream &o, const t2n_procedure::Args &args) {
218 for (t2n_procedure::Args::const_iterator it=args.begin();it!=args.end();++it) {
219 if (it!=args.begin()) o << ", ";
220 o << it->second << " " << it->first;
221 }
222 return o;
223}
224
225std::ostream &operator<<(std::ostream &o, const t2n_procedure &f) {
226 o << f.ret_type << " " << f.name << "(" << f.args << ")";
227 return o;
228}
229
230std::pair<std::string, unsigned>
231get_file_and_line(const xmlpp::Element* root, const xmlpp::Element* element)
232{
233 return std::pair<std::string, unsigned>(get_file(root, element->get_attribute("file")->get_value()),
234 boost::lexical_cast<unsigned>(element->get_attribute("line")->get_value())-1);
235}
236
237std::string
238get_file_and_line_as_string(const xmlpp::Element* root, const xmlpp::Element* element)
239{
240 std::pair<std::string, unsigned> fl(get_file_and_line(root,element));
241 return std::string(fl.first)+":"+boost::lexical_cast<std::string>(fl.second);
242}
243
244class Parser
245{
246public:
247 Parser(const std::string &fname) : m_fname(fname) {}
248
249 std::list<t2n_procedure> get_procedures() {
250 xmlpp::DomParser parser;
251 // parser.set_validate();
252 parser.set_substitute_entities(); //We just want the text to be resolved/unescaped automatically.
253 parser.parse_file(m_fname);
254 if(parser)
255 {
256 //Walk the tree:
257 const xmlpp::Node* pNode = parser.get_document()->get_root_node(); //deleted by DomParser.
258 const xmlpp::Element* root = dynamic_cast<const xmlpp::Element*>(pNode);
259 assert(root);
260 visit_node(root);
261 }
262 return m_procedures;
263 }
264protected:
265 std::string m_fname;
266 std::list<t2n_procedure> m_procedures;
267
268 void parse_function(const xmlpp::Element* root, const xmlpp::Node* node) {
269 const xmlpp::Element* element = dynamic_cast<const xmlpp::Element*>(node);
270 if (!element) return;
271
272 const xmlpp::Attribute* attributes = element->get_attribute("attributes");
273 const xmlpp::Attribute* name = element->get_attribute("name");
274 const xmlpp::Attribute* mangled = element->get_attribute("mangled");
275 const xmlpp::Attribute* returns = element->get_attribute("returns");
276 if ((!attributes)||(!name)||(!mangled)||(!returns)) return;
277
278 // check wether the procedure is marked (TODO: improve)
279 // attributes are speparated by spaces?
280
281 t2n_procedure f;
282 if (!is_marked(attributes->get_value())) return;
283
284 // we need the return type
285 f.ret_type=get_type(root, returns->get_value());
286 f.name=name->get_value();
287 f.mangled=mangled->get_value();
288
289 xmlpp::Node::NodeList list = node->get_children("Argument");
290 for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
291 {
292 const xmlpp::Element* arg = dynamic_cast<const xmlpp::Element*>(*iter);
293 if ( arg ) {
294 assert(arg->get_name() == "Argument");
295 assert(arg->get_attribute("name"));
296 assert(arg->get_attribute("type"));
297 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())));
298 // todo: ugly - could be any other error
299 if (f.args.back().second.name.empty()) {
300 assert(element->get_attribute("file"));
301 assert(element->get_attribute("line"));
302 std::pair<std::string, unsigned> file_and_line(get_file_and_line(root, element));
303 throw parse_error(file_and_line.first,
304 file_and_line.second,
305 std::string("type of parameter `")+f.args.back().first+"' not (yet?) supported");
306 }
307 }
308 }
309 std::cerr << get_file_and_line_as_string(root, element) << ":\texport procedure: " << f << std::endl;
310 m_procedures.push_back(f);
311 }
312
313 void visit_node(const xmlpp::Element* root, const xmlpp::Node* node = NULL, unsigned int indentation = 0)
314 {
315 if (!node) node=root;
316
317 const xmlpp::ContentNode* nodeContent = dynamic_cast<const xmlpp::ContentNode*>(node);
318 const xmlpp::TextNode* nodeText = dynamic_cast<const xmlpp::TextNode*>(node);
319 const xmlpp::CommentNode* nodeComment = dynamic_cast<const xmlpp::CommentNode*>(node);
320
321 if(nodeText && nodeText->is_white_space()) //Let's ignore the indenting - you don't always want to do this.
322 return;
323
324 std::string nodename = node->get_name();
325
326 if(!nodeText && !nodeComment && !nodename.empty()) //Let's not say "name: text".
327 {
328 if (node->get_name() == "Function") parse_function(root, node);
329 }
330 if(!nodeContent)
331 {
332 //Recurse through child nodes:
333 xmlpp::Node::NodeList list = node->get_children();
334 for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list.end(); ++iter)
335 {
336 visit_node(root, *iter, indentation + 2); //recursive
337 }
338 }
339 }
340};
341
342void output_common_hpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs) {
343 o << "class " << groupClass(group) << " : public libt2n::command\n"
344 << "{\n"
345 << "private:\n"
346 << " friend class boost::serialization::access;\n"
347 << " template<class Archive>\n"
348 << " void serialize(Archive & ar, const unsigned int /* version */)\n"
349 << " {ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::command);}\n"
350 << "};\n";
351
352 for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
353 o << "class " << it->ret_classname() << " : public libt2n::result\n"
354 << "{\n"
355 << "private:\n";
356 if (it->hasReturn())
357 o << " " << it->ret_type << " res;\n";
358 o << " friend class boost::serialization::access;\n"
359 << " template<class Archive>\n"
360 << " void serialize(Archive & ar, const unsigned int /* version */)\n"
361 << " {\n"
362 << " ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(libt2n::result);\n";
363 if (it->hasReturn())
364 o << " ar & BOOST_SERIALIZATION_NVP(res);\n";
365 o << " }\n"
366 << "public:\n"
367 << " " << it->ret_classname() << "() {}\n";
368 if (it->hasReturn()) {
369 o << " " << it->ret_classname() << "(const " << it->ret_type << " &_res) : res(_res) {}\n"
370 << " " << it->ret_type << " get_data() { return res; }\n";
371 }
372 o << "};\n";
373 }
374 for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
375 o << "class " << it->cmd_classname() << " : public " << groupClass(group) << "\n"
376 << "{\n"
377 << "private:\n";
378 for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
379 o << " " << ait->second.noref() << " " << ait->first << ";\n";
380 }
381 o << " friend class boost::serialization::access;\n"
382 << " template<class Archive>\n"
383 << " void serialize(Archive & ar, const unsigned int /* version */)\n"
384 << " {\n"
385 << " ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(" << groupClass(group) << ");\n";
386 for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
387 o << " ar & BOOST_SERIALIZATION_NVP(" << ait->first << ");\n";
388 }
389
390 // default constructor
391 o << " }\n"
392 << "\n"
393 << "public:\n"
394 << " " << it->cmd_classname() << "() {}\n";
395
396 // constructor taking all arguments
397 if (!it->args.empty()) {
398 o << " " << it->cmd_classname() << "(";
399 for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
400 if (ait!=it->args.begin()) o << ", ";
401 o << ait->second << " _" << ait->first;
402 }
403 o << ") : ";
404 for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
405 if (ait!=it->args.begin()) o << ", ";
406 // pointers are const pointers and must be dereferenced
407 o << ait->first << "(" << ((ait->second.name.find_first_of('*')!=std::string::npos) ? "*" : "" ) << "_" << ait->first << ")";
408 }
409 o << " {}\n";
410 }
411 o << " libt2n::result* operator()();\n"
412 << "};\n";
413 }
414}
415
416void output_common_cpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
417 o << "#include \"" << common_hpp << "\"\n"
418 << "#include <boost/serialization/export.hpp>\n"
419 << "\n"
420 << "/* register types with boost serialization */\n";
421 o << "BOOST_CLASS_EXPORT(" << groupClass(group) << ")\n";
422 for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
423 o << "BOOST_CLASS_EXPORT("<<it->ret_classname()<<")\n"
424 << "BOOST_CLASS_EXPORT("<<it->cmd_classname()<<")\n";
425 }
426}
427
428void output_client_hpp(std::ostream &o, const std::string &group, const std::list<t2n_procedure> &procs) {
429 o << "#include <command_client.hxx>\n";
430
431 o << "class " << groupClass(group) << "_client : public libt2n::command_client\n"
432 << "{\n"
433 << "public:\n"
434 << groupClass(group) << "_client(libt2n::client_connection &_c,\n"
435 << " long long _command_timeout_usec=command_timeout_usec_default,\n"
436 << " long long _hello_timeout_usec=hello_timeout_usec_default)\n"
437 << " : libt2n::command_client(_c,_command_timeout_usec,_hello_timeout_usec)\n"
438 << " {}\n";
439 for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
440 o << " " << *pit << ";\n";
441 }
442 o << "};\n";
443}
444
445void 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) {
446 o << "#include \"" << client_hpp << "\"\n"
447 << "#include \"" << common_hpp << "\"\n"
448 << "// fake\n";
449 for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
450 o << "libt2n::result* " << it->cmd_classname() << "::operator()() { return NULL; }\n";
451 }
452
453 for (std::list<t2n_procedure>::const_iterator pit=procs.begin();pit!=procs.end();++pit) {
454 o << pit->ret_type << " " << groupClass(group) << "_client::" << pit->name << "(" << pit->args << ")\n"
455 << "{\n"
456 << " libt2n::result_container rc;\n"
457 << " send_command(new " << pit->cmd_classname() << "(";
458 for (t2n_procedure::Args::const_iterator ait=pit->args.begin();ait!=pit->args.end();++ait) {
459 if (ait!=pit->args.begin()) o << ", ";
460 o << ait->first;
461 }
462 o << "), rc);\n"
463 << " " << pit->ret_classname() << "* res=dynamic_cast<" << pit->ret_classname() << "*>(rc.get_result());\n"
464 << " if (!res) throw libt2n::t2n_communication_error(\"result object of wrong type\");\n";
465 if (pit->hasReturn())
466 o << " return res->get_data();\n";
467 o << "}\n";
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
476void output_server_hpp(std::ostream &o, const std::string & /* group */, const std::list<t2n_procedure> &procs, const std::string &common_hpp) {
477 o << "#include \"" << common_hpp << "\"\n";
478
479 // output function declarations
480 for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it)
481 o << *it << ";\n";
482}
483
484void 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) {
485 o << "#include \"" << common_hpp << "\"\n";
486
487 for (std::list<t2n_procedure>::const_iterator it=procs.begin();it!=procs.end();++it) {
488 o << *it << ";\n";
489 o << "libt2n::result* " << it->cmd_classname() << "::operator()() { ";
490
491 if (it->hasReturn())
492 o << "return new " << it->ret_classname() << "(";
493
494 // output function name and args
495 o << it->name << "(";
496 for (t2n_procedure::Args::const_iterator ait=it->args.begin();ait!=it->args.end();++ait) {
497 if (ait!=it->args.begin()) o << ", ";
498 // get pointer
499 if (ait->second.name.find_first_of('*')!=std::string::npos)
500 o << '&';
501 o << ait->first;
502 }
503
504 if (it->hasReturn())
505 o << "));";
506 else
507 o << "); return new " << it->ret_classname() << "();";
508
509 o << " }\n";
510 }
511 o << "#include \"" << common_cpp << "\"\n";
512}
513
514struct header_file : public std::ofstream
515{
516 header_file(const char* fname) : std::ofstream(fname) {
517 std::cerr << "create header: '" << fname << "'" << std::endl;
518 std::string macro(replace(toupper(fname),'.','_'));
519 *this << "// automatically generated code (generated by libt2n-codegen " << VERSION << ") - do not edit\n" << std::endl;
520 *this << "#ifndef " << macro << "\n"
521 << "#define " << macro << "\n";
522 }
523 ~header_file() {
524 *this << "#endif" << std::endl;
525 }
526};
527
528struct cpp_file : public std::ofstream
529{
530 cpp_file(const char* fname) : std::ofstream(fname) {
531 std::cerr << "create cpp: '" << fname << "'" << std::endl;
532 *this << "// automatically generated code - do not edit\n" << std::endl;
533 }
534};
535
536int
537main(int argc, char* argv[])
538{
539 // todo: maybe use getopt
540 if ((argc>1)&&(std::string(argv[1])=="--version")) {
541 std::cerr << VERSION << std::endl;
542 return 0;
543 }
544 if (argc < 3)
545 {
546 std::cerr << "Usage: " << argv[0] << "default-group gccxml-file1 gccxml-file2 ... " << std::endl;
547 return 1;
548 }
549
550 try{
551 std::string group(argv[1]);
552 std::list<std::string> xmlfiles;
553 for (int i=2;i<argc;++i)
554 xmlfiles.push_back(argv[i]);
555
556 std::string prefix=group+"_";
557 std::list<t2n_procedure> procedures;
558 for (std::list<std::string>::iterator it=xmlfiles.begin();it!=xmlfiles.end();++it) {
559 std::cerr << "Parse " << *it << std::endl;
560 Parser parser(*it);
561 const std::list<t2n_procedure> &p(parser.get_procedures());
562 std::copy(p.begin(), p.end(), std::back_inserter(procedures));
563 }
564
565 std::cerr << "All procedures:" << std::endl;
566 for (std::list<t2n_procedure>::const_iterator it=procedures.begin();it!=procedures.end();++it)
567 std::cerr << *it << ";" << std::endl;
568
569 std::string common_hpp_fname(prefix+"common.hxx");
570 std::string common_cpp_fname(prefix+"common.cpp");
571 std::string client_hpp_fname(prefix+"client.hxx");
572 std::string client_cpp_fname(prefix+"client.cpp");
573 std::string server_hpp_fname(prefix+"server.hxx");
574 std::string server_cpp_fname(prefix+"server.cpp");
575
576 header_file common_hpp(common_hpp_fname.c_str());
577 common_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
578 << "#include \"codegen-stubhead.hxx\"\n"
579 << "#include \"" << group << ".hxx\"\n";
580
581 output_common_hpp(common_hpp, group, procedures);
582
583 cpp_file common_cpp(common_cpp_fname.c_str());
584 output_common_cpp(common_cpp, group, procedures, common_hpp_fname);
585
586 header_file client_hpp(client_hpp_fname.c_str());
587 client_hpp << "// boost serialization is picky about order of include files => we have to include this one first\n"
588 << "#include \"codegen-stubhead.hxx\"\n"
589 << "#include \"" << group << ".hxx\"\n";
590 output_client_hpp(client_hpp, group, procedures);
591
592 cpp_file client_cpp(client_cpp_fname.c_str());
593 output_client_cpp(client_cpp, group, procedures, common_hpp_fname, common_cpp_fname, client_hpp_fname);
594
595 header_file server_hpp(server_hpp_fname.c_str());
596 output_server_hpp(server_hpp, group, procedures, common_hpp_fname);
597
598 cpp_file server_cpp(server_cpp_fname.c_str());
599 output_server_cpp(server_cpp, group, procedures, common_hpp_fname, common_cpp_fname);
600 }catch(const parse_error &e){
601 std::cerr << e.what() << std::endl;
602 return EXIT_FAILURE;
603 }
604 return EXIT_SUCCESS;
605}