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