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