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