d0c91319252901ac3d83dcd24637522999284487
[supertux.git] / tools / miniswig / create_wrapper.cpp
1 #include "tree.hpp"
2 #include <iostream>
3 #include <sstream>
4 #include <stdexcept>
5 #include "create_wrapper.hpp"
6 #include "globals.hpp"
7
8 void
9 WrapperCreator::create_wrapper(Namespace* ns)
10 {
11     std::string fromfile = original_file != "" ? original_file : inputfile;
12
13     if(selected_namespace != "") {
14         ns_prefix = selected_namespace;
15         ns_prefix += "::";
16     }
17
18     // hpp file
19     hppout
20         << "/**\n"
21         << " * WARNING: This file is automatically generated from:\n"
22         << " *  '" << fromfile << "'\n"
23         << " * DO NOT CHANGE\n"
24         << " */\n"
25         << "#ifndef __" << modulename << "_WRAPPER_H__\n"
26         << "#define __" << modulename << "_WRAPPER_H__\n"
27         << "\n"
28         << "#include <squirrel.h>\n"
29         << "#include \"wrapper.interface.hpp\"\n"
30         << "\n"
31         << "namespace Scripting\n"
32         << "{\n"
33         << "\n";
34
35     hppout << "void register_" << modulename << "_wrapper(HSQUIRRELVM v);\n"
36            << "\n";
37
38     for(std::vector<AtomicType*>::iterator i = ns->types.begin();
39             i != ns->types.end(); ++i) {
40         AtomicType* type = *i;
41         Class* _class = dynamic_cast<Class*> (type);                 
42         if(_class == 0)
43             continue;
44
45         hppout << "void create_squirrel_instance(HSQUIRRELVM v, "
46                << ns_prefix << _class->name
47                << "* object, bool setup_releasehook = false);\n";
48     }
49     hppout <<"\n"
50            << "}\n"
51            << "\n"
52            << "#endif\n"
53            << "\n";
54     
55     // cpp header
56     out << "/**\n"
57         << " * WARNING: This file is automatically generated from:\n"
58         << " *  '" << fromfile << "'\n"
59         << " * DO NOT CHANGE\n"
60         << " */\n"
61         << "#include <config.h>\n"
62         << "\n"
63         << "#include <new>\n"
64         << "#include <assert.h>\n"
65         << "#include <string>\n"
66         << "#include <sstream>\n"
67         << "#include <squirrel.h>\n"
68         << "#include \"squirrel_error.hpp\"\n"
69         << "#include \"wrapper.interface.hpp\"\n"
70         << "\n"
71         << "namespace Scripting\n"
72         << "{\n"
73         << "namespace Wrapper\n"
74         << "{\n"
75         << "\n";
76
77     for(std::vector<AtomicType*>::iterator i = ns->types.begin();
78             i != ns->types.end(); ++i) {
79         AtomicType* type = *i;
80         Class* _class = dynamic_cast<Class*> (type);
81         if(_class != 0)
82             create_class_wrapper(_class);
83     }
84     for(std::vector<Function*>::iterator i = ns->functions.begin();
85             i != ns->functions.end(); ++i) {
86         create_function_wrapper(0, *i);
87     }
88
89     out << "} // end of namespace Wrapper\n";
90     out << "\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         << ind << "sq_pushroottable(v);\n";
105
106     create_register_constants_code(ns);
107     create_register_functions_code(ns);
108     create_register_classes_code(ns);
109
110     out << ind << "sq_pop(v, 1);\n"
111         << "}\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 int ";
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 << ns_prefix <<  _class->name << "* _this;\n";
278         out << ind << "if(SQ_FAILED(sq_getinstanceup(vm, 1, reinterpret_cast<SQUserPointer*> (&_this), 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     }
283
284     // custom function?
285     if(function->custom) {
286         if(function->type != Function::FUNCTION)
287             throw std::runtime_error(
288                     "custom not allow constructor+destructor yet");
289         if(function->return_type.atomic_type != &BasicType::INT)
290             throw std::runtime_error("custom function has to return int");
291         if(function->parameters.size() != 1)
292             throw std::runtime_error(
293                     "custom function must have 1 HSQUIRRELVM parameter");
294
295         out << ind << "return ";
296         if(_class != 0)
297             out << "_this->";
298         else
299             out << ns_prefix;
300         out << function->name << "(vm);\n";
301         out << "}\n";
302         out << "\n";
303         return;
304     }
305     
306     // declare and retrieve arguments
307     int i = 0;
308     int arg_offset = 2;
309     for(std::vector<Parameter>::iterator p = function->parameters.begin();
310             p != function->parameters.end(); ++p) {
311         if(i == 0 && p->type.atomic_type == HSQUIRRELVMType::instance()) {
312             out << ind << "HSQUIRRELVM arg0 = vm;\n";
313             arg_offset--;
314         } else {
315             char argname[64];
316             snprintf(argname, sizeof(argname), "arg%d", i);
317             prepare_argument(p->type, i + arg_offset, argname);
318         }
319         ++i;
320     }
321     
322     // call function
323     out << ind << "\n";
324     out << ind << "try {\n";
325     out << ind << ind;
326     if(!function->return_type.is_void()) {
327         function->return_type.write_c_type(out);
328         out << " return_value = ";
329     }
330     if(_class != 0) {
331         if(function->type == Function::CONSTRUCTOR) {
332             out << ns_prefix << _class->name << "* _this = new " << ns_prefix;
333         } else {
334             out << "_this->";
335         }
336     } else {
337         out << ns_prefix;
338     }
339     if(function->type == Function::CONSTRUCTOR) {
340         out << _class->name << "(";
341     } else {
342         out << function->name << "(";
343     }
344     for(size_t i = 0; i < function->parameters.size(); ++i) {
345         if(i != 0)
346             out << ", ";
347         out << "arg" << i;
348     }
349     out << ");\n";
350     if(function->type == Function::CONSTRUCTOR) {
351         out << ind << "if(SQ_FAILED(sq_setinstanceup(vm, 1, _this))) {\n";
352         out << ind << ind << "sq_throwerror(vm, _SC(\"Couldn't setup instance of '" << _class->name << "' class\"));\n";
353         out << ind << ind << "return SQ_ERROR;\n";
354         out << ind << "}\n";
355         out << ind << "sq_setreleasehook(vm, 1, " 
356             << _class->name << "_release_hook);\n";
357     }
358     out << ind << "\n";
359     // push return value back on stack and return
360     if(function->suspend) {
361         if(!function->return_type.is_void()) {
362             std::stringstream msg;
363             msg << "Function '" << function->name << "' declared as suspend"
364                 << " but has a return value.";
365             throw std::runtime_error(msg.str());
366         }
367         out << ind << ind << "return sq_suspendvm(vm);\n";
368     } else if(function->return_type.is_void()) {
369         out << ind << ind << "return 0;\n";
370     } else {
371         push_to_stack(function->return_type, "return_value");
372         out << ind << ind << "return 1;\n";
373     }
374
375     out << ind << "\n";
376     out << ind << "} catch(std::exception& e) {\n";
377     out << ind << ind << "sq_throwerror(vm, e.what());\n";
378     out << ind << ind << "return SQ_ERROR;\n";
379     out << ind << "} catch(...) {\n";
380     out << ind << ind << "sq_throwerror(vm, _SC(\"Unexpected exception while executing function '" << function->name << "'\"));\n";
381     out << ind << ind << "return SQ_ERROR;\n";
382     out << ind << "}\n";
383     out << ind << "\n";
384     
385     out << "}\n";
386     out << "\n";
387 }
388
389 void
390 WrapperCreator::prepare_argument(const Type& type, size_t index,
391         const std::string& var)
392 {
393     if(type.ref > 0 && type.atomic_type != StringType::instance())
394         throw std::runtime_error("References not handled yet");
395     if(type.pointer > 0)
396         throw std::runtime_error("Pointers not handled yet");
397     if(type.atomic_type == &BasicType::INT) {
398         out << ind << "int " << var << ";\n";
399         out << ind << "if(SQ_FAILED(sq_getinteger(vm, " << index << ", &" << var << "))) {\n";
400         out << ind << ind << "sq_throwerror(vm, _SC(\"Argument " << (index-1) << " not an integer\"));\n";
401         out << ind << ind << "return SQ_ERROR;\n";
402         out << ind << "}\n";
403     } else if(type.atomic_type == &BasicType::FLOAT) {
404         out << ind << "float " << var << ";\n";
405         out << ind << "if(SQ_FAILED(sq_getfloat(vm, " << index << ", &" << var << "))) {\n";
406         out << ind << ind << "sq_throwerror(vm, _SC(\"Argument " << (index-1) << " not a float\"));\n";
407         out << ind << ind << "return SQ_ERROR;\n";
408         out << ind << "}\n";
409     } else if(type.atomic_type == &BasicType::BOOL) {
410         out << ind << "SQBool " << var << ";\n";
411         out << ind << "if(SQ_FAILED(sq_getbool(vm, " << index << ", &" << var << "))) {\n";
412         out << ind << ind << "sq_throwerror(vm, _SC(\"Argument " << (index-1) << " not a bool\"));\n";
413         out << ind << ind << "return SQ_ERROR;\n";
414         out << ind << "}\n";
415     } else if(type.atomic_type == StringType::instance()) {
416         out << ind << "const char* " << var << ";\n";
417         out << ind << "if(SQ_FAILED(sq_getstring(vm, " << index << ", &" << var << "))) {\n";
418         out << ind << ind << "sq_throwerror(vm, _SC(\"Argument " << (index-1) << " not a string\"));\n";
419         out << ind << ind << "return SQ_ERROR;\n";
420         out << ind << "}\n";
421     } else {
422         std::ostringstream msg;
423         msg << "Type '" << type.atomic_type->name << "' not supported yet.";
424         throw std::runtime_error(msg.str());
425     }
426 }
427
428 void
429 WrapperCreator::push_to_stack(const Type& type, const std::string& var)
430 {
431     if(type.ref > 0 && type.atomic_type != StringType::instance())
432         throw std::runtime_error("References not handled yet");
433     if(type.pointer > 0)
434         throw std::runtime_error("Pointers not handled yet");
435     out << ind << ind;
436     if(type.atomic_type == &BasicType::INT) {
437         out << "sq_pushinteger(vm, " << var << ");\n";
438     } else if(type.atomic_type == &BasicType::FLOAT) {
439         out << "sq_pushfloat(vm, " << var << ");\n";
440     } else if(type.atomic_type == &BasicType::BOOL) {
441         out << "sq_pushbool(vm, " << var << ");\n";
442     } else if(type.atomic_type == StringType::instance()) {
443         out << "sq_pushstring(vm, " << var << ".c_str(), " 
444             << var << ".size());\n";
445     } else {
446         std::ostringstream msg;
447         msg << "Type '" << type.atomic_type->name << "' not supported yet.";
448         throw std::runtime_error(msg.str());
449     }
450 }
451
452 void
453 WrapperCreator::create_class_wrapper(Class* _class)
454 {
455     create_class_release_hook(_class);
456     for(std::vector<ClassMember*>::iterator i = _class->members.begin();
457             i != _class->members.end(); ++i) {
458         ClassMember* member = *i;
459         if(member->visibility != ClassMember::PUBLIC)
460             continue;
461         Function* function = dynamic_cast<Function*> (member);
462         if(!function)
463             continue;
464         // don't wrap destructors
465         if(function->type == Function::DESTRUCTOR)
466             continue;
467         create_function_wrapper(_class, function);
468     }
469 }
470
471 void
472 WrapperCreator::create_squirrel_instance(Class* _class)
473 {
474     out << "void create_squirrel_instance(HSQUIRRELVM v, "
475         << ns_prefix << _class->name 
476         << "* object, bool setup_releasehook)\n"
477         << "{\n"
478         << ind << "using namespace Wrapper;\n"
479         << "\n"
480         << ind << "sq_pushroottable(v);\n"
481         << ind << "sq_pushstring(v, \"" << _class->name << "\", -1);\n"
482         << ind << "if(SQ_FAILED(sq_get(v, -2))) {\n"
483         << ind << ind << "std::ostringstream msg;\n"
484         << ind << ind << "msg << \"Couldn't resolved squirrel type '"
485         << _class->name << "'\";\n"
486         << ind << ind << "throw SquirrelError(v, msg.str());\n"
487         << ind << "}\n"
488         << "\n"
489         << ind << "if(SQ_FAILED(sq_createinstance(v, -1)) || "
490         << "SQ_FAILED(sq_setinstanceup(v, -1, object))) {\n"
491         << ind << ind << "std::ostringstream msg;\n"
492         << ind << ind << "msg << \"Couldn't setup squirrel instance for "
493         << "object of type '" << _class->name << "'\";\n"
494         << ind << ind << "throw SquirrelError(v, msg.str());\n"
495         << ind << "}\n"
496         << ind << "sq_remove(v, -2); // remove object name\n"
497         << "\n"
498         << ind << "if(setup_releasehook) {\n"
499         << ind << ind << "sq_setreleasehook(v, -1, "
500         << _class->name << "_release_hook);\n"
501         << ind << "}\n"
502         << "\n"
503         << ind << "sq_remove(v, -2); // remove root table\n"
504         << "}\n"
505         << "\n";
506 }
507
508 void
509 WrapperCreator::create_class_release_hook(Class* _class)
510 {
511     out << "static int " << _class->name << "_release_hook(SQUserPointer ptr, int )\n"
512         << "{\n"
513         << ind << ns_prefix << _class->name 
514         << "* _this = reinterpret_cast<" << ns_prefix << _class->name 
515         << "*> (ptr);\n"
516         << ind << "delete _this;\n"
517         << ind << "return 0;\n"
518         << "}\n"
519         << "\n";
520 }
521