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