*include stdio.h in a couple files for MinGW GCC 4.4.0
[supertux.git] / tools / miniswig / create_wrapper.cpp
1 #include <config.h>
2
3 #include "tree.hpp"
4 #include "create_wrapper.hpp"
5 #include "globals.hpp"
6
7 #include <stdio.h>
8 #include <iostream>
9 #include <sstream>
10 #include <stdexcept>
11
12 void
13 WrapperCreator::create_wrapper(Namespace* ns)
14 {
15     std::string fromfile = original_file != "" ? original_file : inputfile;
16
17     if(selected_namespace != "") {
18         ns_prefix = selected_namespace;
19         ns_prefix += "::";
20     }
21
22     // hpp file
23     hppout
24         << "/**\n"
25         << " * WARNING: This file is automatically generated from:\n"
26         << " *  '" << fromfile << "'\n"
27         << " * DO NOT CHANGE\n"
28         << " */\n"
29         << "#ifndef __" << modulename << "_WRAPPER_H__\n"
30         << "#define __" << modulename << "_WRAPPER_H__\n"
31         << "\n"
32         << "#include <squirrel.h>\n"
33         << "\n"
34         << "namespace Scripting\n"
35         << "{\n"
36         << "\n";
37
38     hppout << "void register_" << modulename << "_wrapper(HSQUIRRELVM v);\n"
39            << "\n";
40
41     for(std::vector<AtomicType*>::iterator i = ns->types.begin();
42             i != ns->types.end(); ++i) {
43         AtomicType* type = *i;
44         Class* _class = dynamic_cast<Class*> (type);
45         if(_class == 0)
46             continue;
47
48         hppout << "class " << _class->name << ";\n";
49         hppout << "void create_squirrel_instance(HSQUIRRELVM v, "
50                << ns_prefix << _class->name
51                << "* object, bool setup_releasehook = false);\n";
52     }
53     hppout <<"\n"
54            << "}\n"
55            << "\n"
56            << "#endif\n";
57
58     // cpp header
59     out << "/**\n"
60         << " * WARNING: This file is automatically generated from:\n"
61         << " *  '" << fromfile << "'\n"
62         << " * DO NOT CHANGE\n"
63         << " */\n"
64         << "#include <config.h>\n"
65         << "\n"
66         << "#include <new>\n"
67         << "#include <assert.h>\n"
68         << "#include <string>\n"
69         << "#include <sstream>\n"
70         << "#include <squirrel.h>\n"
71         << "#include \"squirrel_error.hpp\"\n"
72         << "#include \"wrapper.interface.hpp\"\n"
73         << "\n"
74         << "namespace Scripting\n"
75         << "{\n"
76         << "namespace Wrapper\n"
77         << "{\n"
78         << "\n";
79
80     for(std::vector<AtomicType*>::iterator i = ns->types.begin();
81             i != ns->types.end(); ++i) {
82         AtomicType* type = *i;
83         Class* _class = dynamic_cast<Class*> (type);
84         if(_class != 0)
85             create_class_wrapper(_class);
86     }
87     for(std::vector<Function*>::iterator i = ns->functions.begin();
88             i != ns->functions.end(); ++i) {
89         create_function_wrapper(0, *i);
90     }
91
92     out << "} // end of namespace Wrapper\n";
93
94     for(std::vector<AtomicType*>::iterator i = ns->types.begin();
95             i != ns->types.end(); ++i) {
96         AtomicType* type = *i;
97         Class* _class = dynamic_cast<Class*> (type);
98         if(_class != 0)
99             create_squirrel_instance(_class);
100     }
101
102     out << "void register_" << modulename << "_wrapper(HSQUIRRELVM v)\n"
103         << "{\n"
104         << ind << "using namespace Wrapper;\n"
105         << "\n";
106
107     create_register_constants_code(ns);
108     create_register_functions_code(ns);
109     create_register_classes_code(ns);
110
111     out << "}\n"
112         << "\n"
113         << "} // end of namespace Scripting\n";
114 }
115
116 void
117 WrapperCreator::create_register_function_code(Function* function, Class* _class)
118 {
119     if(function->type == Function::DESTRUCTOR)
120         return;
121
122     out << ind << "sq_pushstring(v, \"" << function->name << "\", -1);\n";
123     out << ind << "sq_newclosure(v, &"
124         << (_class != 0 ? _class->name + "_" : "") << function->name
125         << "_wrapper, 0);\n";
126
127     if(function->custom) {
128       out << ind << "sq_setparamscheck(v, SQ_MATCHTYPEMASKSTRING, " << function->parameter_spec << ");\n";
129     } else {
130       out << ind << "sq_setparamscheck(v, SQ_MATCHTYPEMASKSTRING, \"";
131
132       out << "x|t";
133
134       if(!function->parameters.empty())
135         {
136           std::vector<Parameter>::iterator p = function->parameters.begin();
137           
138           // Skip the first parameter since its a HSQUIRRELVM that is
139           // handled internally
140           if (function->suspend) {
141             ++p;
142           } else if (p->type.atomic_type == HSQUIRRELVMType::instance()) {
143             ++p;
144           }
145
146           for(; p != function->parameters.end(); ++p) {
147             if(p->type.atomic_type == &BasicType::INT) {
148               out << "i";
149             } else if(p->type.atomic_type == &BasicType::FLOAT) {
150               out << "n";
151             } else if(p->type.atomic_type == &BasicType::BOOL) {
152               out << "b";
153             } else if(p->type.atomic_type == StringType::instance()) {
154               out << "s";
155             } else {
156               out << ".";
157             }
158           }
159       }
160       out << "\");\n";
161     }
162
163     create_register_slot_code("function", function->name);
164     out << "\n";
165 }
166
167 void
168 WrapperCreator::create_register_functions_code(Namespace* ns)
169 {
170     for(std::vector<Function*>::iterator i = ns->functions.begin();
171             i != ns->functions.end(); ++i) {
172         Function* function = *i;
173         create_register_function_code(function, 0);
174     }
175 }
176
177 void
178 WrapperCreator::create_register_classes_code(Namespace* ns)
179 {
180     for(std::vector<AtomicType*>::iterator i = ns->types.begin();
181             i != ns->types.end(); ++i) {
182         AtomicType* type = *i;
183         Class* _class = dynamic_cast<Class*> (type);
184         if(_class == 0)
185             continue;
186         if(_class->super_classes.size() > 0)
187             continue;
188
189         create_register_class_code(_class);
190     }
191 }
192
193 void
194 WrapperCreator::create_register_class_code(Class* _class)
195 {
196     out << ind << "// Register class " << _class->name << "\n";
197     out << ind << "sq_pushstring(v, \""
198         << _class->name << "\", -1);\n";
199
200     if(_class->super_classes.size() > 0) {
201         if(_class->super_classes.size() > 1) {
202             std::ostringstream msg;
203             msg << "Multiple inheritance not supported (at class '"
204                 << _class->name << "')";
205             throw std::runtime_error(msg.str());
206         }
207
208         out << ind << "sq_pushstring(v, \""
209             << _class->super_classes[0]->name << "\", -1);\n";
210         out << ind << "sq_get(v, -3);\n";
211     }
212     out << ind << "if(sq_newclass(v, "
213         << (_class->super_classes.size() > 0 ? "SQTrue" : "SQFalse")
214         << ") < 0) {\n";
215     out << ind << ind << "std::ostringstream msg;\n";
216     out << ind << ind << "msg << \"Couldn't create new class '"
217         << _class->name << "'\";\n";
218     out << ind << ind << "throw SquirrelError(v, msg.str());\n";
219     out << ind << "}\n";
220
221     for(std::vector<ClassMember*>::iterator i = _class->members.begin();
222             i != _class->members.end(); ++i) {
223         ClassMember* member = *i;
224         if(member->visibility != ClassMember::PUBLIC)
225             continue;
226         Function* function = dynamic_cast<Function*> (member);
227         if(function) {
228             create_register_function_code(function, _class);
229         }
230         Field* field = dynamic_cast<Field*> (member);
231         if(field) {
232             create_register_constant_code(field);
233         }
234     }
235
236     create_register_slot_code("class", _class->name);
237     out << "\n";
238
239     for(std::vector<Class*>::iterator i = _class->sub_classes.begin();
240             i != _class->sub_classes.end(); ++i) {
241         Class* _class = *i;
242         create_register_class_code(_class);
243     }
244 }
245
246 void
247 WrapperCreator::create_register_constants_code(Namespace* ns)
248 {
249     for(std::vector<Field*>::iterator i = ns->fields.begin();
250             i != ns->fields.end(); ++i) {
251         Field* field = *i;
252         create_register_constant_code(field);
253     }
254 }
255
256 void
257 WrapperCreator::create_register_constant_code(Field* field)
258 {
259     if(!field->has_const_value)
260         return;
261     out << ind << "sq_pushstring(v, \"" << field->name << "\", -1);\n";
262     if(field->type->atomic_type == &BasicType::INT) {
263         out << ind << "sq_pushinteger(v, " << field->const_int_value << ");\n";
264     } else if(field->type->atomic_type == &BasicType::FLOAT) {
265         out << ind << "sq_pushfloat(v, " << field->const_float_value << ");\n";
266     } else if(field->type->atomic_type == StringType::instance()) {
267         out << ind << "sq_pushstring(v, \""
268             << field->const_string_value << "\", -1);\n";
269     } else {
270       throw std::runtime_error("Constant is not int, float or string");
271     }
272     create_register_slot_code("constant", field->name);
273     out << "\n";
274 }
275
276 void
277 WrapperCreator::create_register_slot_code(const std::string& what,
278                                           const std::string& name)
279 {
280     out << ind << "if(SQ_FAILED(sq_createslot(v, -3))) {\n";
281     out << ind << ind << "throw SquirrelError(v, \""
282         << "Couldn't register " << what << " '" << name << "'\");\n";
283     out << ind << "}\n";
284 }
285
286 void
287 WrapperCreator::create_function_wrapper(Class* _class, Function* function)
288 {
289     if(function->type == Function::DESTRUCTOR)
290         assert(false);
291
292     std::string ns_prefix;
293     if(selected_namespace != "")
294         ns_prefix = selected_namespace + "::";
295     if(function->type == Function::CONSTRUCTOR)
296         function->name = "constructor";
297
298     out << "static SQInteger ";
299     if(_class != 0) {
300         out << _class->name << "_";
301     }
302     out << function->name << "_wrapper(HSQUIRRELVM vm)\n"
303         << "{\n";
304     // avoid warning...
305     if(_class == 0 && function->parameters.empty()
306             && function->return_type.is_void()
307             && function->type != Function::CONSTRUCTOR) {
308         out << ind << "(void) vm;\n";
309     }
310
311     // retrieve pointer to class instance
312     if(_class != 0 && function->type != Function::CONSTRUCTOR) {
313         out << ind << "SQUserPointer data;\n";
314         out << ind << "if(SQ_FAILED(sq_getinstanceup(vm, 1, &data, 0)) || !data) {\n";
315         out << ind << ind << "sq_throwerror(vm, _SC(\"'" << function->name << "' called without instance\"));\n";
316         out << ind << ind << "return SQ_ERROR;\n";
317         out << ind << "}\n";
318         out << ind << ns_prefix <<  _class->name << "* _this = reinterpret_cast<" << ns_prefix << _class->name << "*> (data);\n";
319     }
320
321     // custom function?
322     if(function->custom) {
323         if(function->type != Function::FUNCTION) 
324             throw std::runtime_error(
325                     "custom not allow constructor+destructor yet");
326         if(function->return_type.atomic_type != SQIntegerType::instance())
327             throw std::runtime_error("custom function '" + function->name + "' has to return SQInteger");
328         if(function->parameters.size() != 1)
329             throw std::runtime_error(
330                     "custom function '" + function->name + "' must have 1 HSQUIRRELVM parameter");
331
332         out << ind << "return ";
333         if(_class != 0)
334             out << "_this->";
335         else
336             out << ns_prefix;
337         out << function->name << "(vm);\n";
338         out << "}\n";
339         out << "\n";
340         return;
341     }
342
343     // declare and retrieve arguments
344     int i = 0;
345     int arg_offset = 2;
346     for(std::vector<Parameter>::iterator p = function->parameters.begin();
347             p != function->parameters.end(); ++p) {
348         if(i == 0 && p->type.atomic_type == HSQUIRRELVMType::instance()) {
349             out << ind << "HSQUIRRELVM arg0 = vm;\n";
350             arg_offset--;
351         } else {
352             char argname[64];
353             snprintf(argname, sizeof(argname), "arg%d", i);
354             prepare_argument(p->type, i + arg_offset, argname);
355         }
356         ++i;
357     }
358
359     // call function
360     out << "\n";
361     out << ind << "try {\n";
362     out << ind << ind;
363     if(!function->return_type.is_void()) {
364         function->return_type.write_c_type(out);
365         out << " return_value = ";
366     }
367     if(_class != 0) {
368         if(function->type == Function::CONSTRUCTOR) {
369             out << ns_prefix << _class->name << "* _this = new " << ns_prefix;
370         } else {
371             out << "_this->";
372         }
373     } else {
374         out << ns_prefix;
375     }
376     if(function->type == Function::CONSTRUCTOR) {
377         out << _class->name << "(";
378     } else {
379         out << function->name << "(";
380     }
381     for(size_t i = 0; i < function->parameters.size(); ++i) {
382         if(i != 0)
383             out << ", ";
384         const Parameter param = function->parameters[i];
385         if(param.type.ref == 0 && param.type.pointer == 0) {
386             if(param.type.atomic_type == &BasicType::INT)
387                 out << "static_cast<int> (arg" << i << ")";
388             else if(param.type.atomic_type == &BasicType::FLOAT)
389                 out << "static_cast<float> (arg" << i << ")";
390             else if(param.type.atomic_type == &BasicType::BOOL)
391                 out << "arg" << i << " == SQTrue";
392             else
393                 out << "arg" << i;
394         } else {
395             out << "arg" << i;
396         }
397     }
398     out << ");\n";
399     if(function->type == Function::CONSTRUCTOR) {
400         out << ind << "if(SQ_FAILED(sq_setinstanceup(vm, 1, _this))) {\n";
401         out << ind << ind << "sq_throwerror(vm, _SC(\"Couldn't setup instance of '" << _class->name << "' class\"));\n";
402         out << ind << ind << "return SQ_ERROR;\n";
403         out << ind << "}\n";
404         out << ind << "sq_setreleasehook(vm, 1, "
405             << _class->name << "_release_hook);\n";
406     }
407     out << "\n";
408     // push return value back on stack and return
409     if(function->suspend) {
410         if(!function->return_type.is_void()) {
411             std::stringstream msg;
412             msg << "Function '" << function->name << "' declared as suspend"
413                 << " but has a return value.";
414             throw std::runtime_error(msg.str());
415         }
416         out << ind << ind << "return sq_suspendvm(vm);\n";
417     } else if(function->return_type.is_void()) {
418         out << ind << ind << "return 0;\n";
419     } else {
420         push_to_stack(function->return_type, "return_value");
421         out << ind << ind << "return 1;\n";
422     }
423
424     out << "\n";
425     out << ind << "} catch(std::exception& e) {\n";
426     out << ind << ind << "sq_throwerror(vm, e.what());\n";
427     out << ind << ind << "return SQ_ERROR;\n";
428     out << ind << "} catch(...) {\n";
429     out << ind << ind << "sq_throwerror(vm, _SC(\"Unexpected exception while executing function '" << function->name << "'\"));\n";
430     out << ind << ind << "return SQ_ERROR;\n";
431     out << ind << "}\n";
432     out << "\n";
433
434     out << "}\n";
435     out << "\n";
436 }
437
438 void
439 WrapperCreator::prepare_argument(const Type& type, size_t index,
440         const std::string& var)
441 {
442     if(type.ref > 0 && type.atomic_type != StringType::instance())
443         throw std::runtime_error("References not handled yet");
444     if(type.pointer > 0)
445         throw std::runtime_error("Pointers not handled yet");
446     if(type.atomic_type == &BasicType::INT) {
447         out << ind << "SQInteger " << var << ";\n";
448         out << ind << "if(SQ_FAILED(sq_getinteger(vm, " << index << ", &" << var << "))) {\n";
449         out << ind << ind << "sq_throwerror(vm, _SC(\"Argument " << (index-1) << " not an integer\"));\n";
450         out << ind << ind << "return SQ_ERROR;\n";
451         out << ind << "}\n";
452     } else if(type.atomic_type == &BasicType::FLOAT) {
453         out << ind << "SQFloat " << var << ";\n";
454         out << ind << "if(SQ_FAILED(sq_getfloat(vm, " << index << ", &" << var << "))) {\n";
455         out << ind << ind << "sq_throwerror(vm, _SC(\"Argument " << (index-1) << " not a float\"));\n";
456         out << ind << ind << "return SQ_ERROR;\n";
457         out << ind << "}\n";
458     } else if(type.atomic_type == &BasicType::BOOL) {
459         out << ind << "SQBool " << var << ";\n";
460         out << ind << "if(SQ_FAILED(sq_getbool(vm, " << index << ", &" << var << "))) {\n";
461         out << ind << ind << "sq_throwerror(vm, _SC(\"Argument " << (index-1) << " not a bool\"));\n";
462         out << ind << ind << "return SQ_ERROR;\n";
463         out << ind << "}\n";
464     } else if(type.atomic_type == StringType::instance()) {
465         out << ind << "const SQChar* " << var << ";\n";
466         out << ind << "if(SQ_FAILED(sq_getstring(vm, " << index << ", &" << var << "))) {\n";
467         out << ind << ind << "sq_throwerror(vm, _SC(\"Argument " << (index-1) << " not a string\"));\n";
468         out << ind << ind << "return SQ_ERROR;\n";
469         out << ind << "}\n";
470     } else {
471         std::ostringstream msg;
472         msg << "Type '" << type.atomic_type->name << "' not supported yet.";
473         throw std::runtime_error(msg.str());
474     }
475 }
476
477 void
478 WrapperCreator::push_to_stack(const Type& type, const std::string& var)
479 {
480     if(type.ref > 0 && type.atomic_type != StringType::instance())
481         throw std::runtime_error("References not handled yet");
482     if(type.pointer > 0)
483         throw std::runtime_error("Pointers not handled yet");
484     out << ind << ind;
485     if(type.atomic_type == &BasicType::INT) {
486         out << "sq_pushinteger(vm, " << var << ");\n";
487     } else if(type.atomic_type == &BasicType::FLOAT) {
488         out << "sq_pushfloat(vm, " << var << ");\n";
489     } else if(type.atomic_type == &BasicType::BOOL) {
490         out << "sq_pushbool(vm, " << var << ");\n";
491     } else if(type.atomic_type == StringType::instance()) {
492         out << "sq_pushstring(vm, " << var << ".c_str(), "
493             << var << ".size());\n";
494     } else {
495         std::ostringstream msg;
496         msg << "Type '" << type.atomic_type->name << "' not supported yet.";
497         throw std::runtime_error(msg.str());
498     }
499 }
500
501 void
502 WrapperCreator::create_class_wrapper(Class* _class)
503 {
504     create_class_release_hook(_class);
505     for(std::vector<ClassMember*>::iterator i = _class->members.begin();
506             i != _class->members.end(); ++i) {
507         ClassMember* member = *i;
508         if(member->visibility != ClassMember::PUBLIC)
509             continue;
510         Function* function = dynamic_cast<Function*> (member);
511         if(!function)
512             continue;
513         // don't wrap destructors
514         if(function->type == Function::DESTRUCTOR)
515             continue;
516         create_function_wrapper(_class, function);
517     }
518 }
519
520 void
521 WrapperCreator::create_squirrel_instance(Class* _class)
522 {
523     out << "void create_squirrel_instance(HSQUIRRELVM v, "
524         << ns_prefix << _class->name
525         << "* object, bool setup_releasehook)\n"
526         << "{\n"
527         << ind << "using namespace Wrapper;\n"
528         << "\n"
529         << ind << "sq_pushroottable(v);\n"
530         << ind << "sq_pushstring(v, \"" << _class->name << "\", -1);\n"
531         << ind << "if(SQ_FAILED(sq_get(v, -2))) {\n"
532         << ind << ind << "std::ostringstream msg;\n"
533         << ind << ind << "msg << \"Couldn't resolved squirrel type '"
534         << _class->name << "'\";\n"
535         << ind << ind << "throw SquirrelError(v, msg.str());\n"
536         << ind << "}\n"
537         << "\n"
538         << ind << "if(SQ_FAILED(sq_createinstance(v, -1)) || "
539         << "SQ_FAILED(sq_setinstanceup(v, -1, object))) {\n"
540         << ind << ind << "std::ostringstream msg;\n"
541         << ind << ind << "msg << \"Couldn't setup squirrel instance for "
542         << "object of type '" << _class->name << "'\";\n"
543         << ind << ind << "throw SquirrelError(v, msg.str());\n"
544         << ind << "}\n"
545         << ind << "sq_remove(v, -2); // remove object name\n"
546         << "\n"
547         << ind << "if(setup_releasehook) {\n"
548         << ind << ind << "sq_setreleasehook(v, -1, "
549         << _class->name << "_release_hook);\n"
550         << ind << "}\n"
551         << "\n"
552         << ind << "sq_remove(v, -2); // remove root table\n"
553         << "}\n"
554         << "\n";
555 }
556
557 void
558 WrapperCreator::create_class_release_hook(Class* _class)
559 {
560     out << "static SQInteger " << _class->name << "_release_hook(SQUserPointer ptr, SQInteger )\n"
561         << "{\n"
562         << ind << ns_prefix << _class->name
563         << "* _this = reinterpret_cast<" << ns_prefix << _class->name
564         << "*> (ptr);\n"
565         << ind << "delete _this;\n"
566         << ind << "return 0;\n"
567         << "}\n"
568         << "\n";
569 }