binding_generator.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. #!python
  2. import json
  3. # comment.
  4. classes = []
  5. def generate_bindings(path):
  6. global classes
  7. classes = json.load(open(path))
  8. icalls = set()
  9. for c in classes:
  10. # print c['name']
  11. used_classes = get_used_classes(c)
  12. header = generate_class_header(used_classes, c)
  13. impl = generate_class_implementation(icalls, used_classes, c)
  14. header_file = open("include/" + strip_name(c["name"]) + ".hpp", "w+")
  15. header_file.write(header)
  16. source_file = open("src/" + strip_name(c["name"]) + ".cpp", "w+")
  17. source_file.write(impl)
  18. icall_header_file = open("src/__icalls.hpp", "w+")
  19. icall_header_file.write(generate_icall_header(icalls))
  20. icall_source_file = open("src/__icalls.cpp", "w+")
  21. icall_source_file.write(generate_icall_implementation(icalls))
  22. def is_reference_type(t):
  23. for c in classes:
  24. if c['name'] != t:
  25. continue
  26. if c['is_reference']:
  27. return True
  28. return False
  29. def make_gdnative_type(t):
  30. if is_enum(t):
  31. return remove_enum_prefix(t) + " "
  32. elif is_class_type(t):
  33. if is_reference_type(t):
  34. return "Ref<" + strip_name(t) + "> "
  35. else:
  36. return strip_name(t) + " *"
  37. else:
  38. if t == "int":
  39. return "int64_t "
  40. if t == "float" or t == "real":
  41. return "double "
  42. return strip_name(t) + " "
  43. def generate_class_header(used_classes, c):
  44. source = []
  45. source.append("#ifndef GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  46. source.append("#define GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  47. source.append("")
  48. source.append("")
  49. source.append("#include <gdnative/gdnative.h>")
  50. source.append("#include <stdint.h>")
  51. source.append("")
  52. source.append("#include <CoreTypes.hpp>")
  53. source.append("#include <Ref.hpp>")
  54. class_name = strip_name(c["name"])
  55. included = []
  56. for used_class in used_classes:
  57. if is_enum(used_class) and is_nested_type(used_class):
  58. used_class_name = remove_enum_prefix(extract_nested_type(used_class))
  59. if used_class_name not in included:
  60. included.append(used_class_name)
  61. source.append("#include <" + used_class_name + ".hpp>")
  62. elif is_enum(used_class) and is_nested_type(used_class) and not is_nested_type(used_class, class_name):
  63. used_class_name = remove_enum_prefix(used_class)
  64. if used_class_name not in included:
  65. included.append(used_class_name)
  66. source.append("#include <" + used_class_name + ".hpp>")
  67. source.append("")
  68. if c["base_class"] != "":
  69. source.append("#include <" + strip_name(c["base_class"]) + ".hpp>")
  70. source.append("namespace godot {")
  71. source.append("")
  72. for used_type in used_classes:
  73. if is_enum(used_type) or is_nested_type(used_type, class_name):
  74. continue
  75. else:
  76. source.append("class " + strip_name(used_type) + ";")
  77. source.append("")
  78. # generate the class definition here
  79. source.append("class " + class_name + ("" if c["base_class"] == "" else (" : public " + strip_name(c["base_class"])) ) + " {")
  80. source.append("public:")
  81. source.append("")
  82. # ___get_class_name
  83. source.append("\tstatic inline char *___get_class_name() { return (char *) \"" + strip_name(c["name"]) + "\"; }")
  84. enum_values = []
  85. source.append("\n\t// enums")
  86. for enum in c["enums"]:
  87. source.append("\tenum " + strip_name(enum["name"]) + " {")
  88. for value in enum["values"]:
  89. source.append("\t\t" + remove_nested_type_prefix(value) + " = " + str(enum["values"][value]) + ",")
  90. enum_values.append(value)
  91. source.append("\t};")
  92. source.append("\n\t// constants")
  93. for name in c["constants"]:
  94. if name not in enum_values:
  95. source.append("\tconst static int " + name + " = " + str(c["constants"][name]) + ";")
  96. if c["instanciable"]:
  97. source.append("\tstatic void *operator new(size_t);")
  98. source.append("\tstatic void operator delete(void *);")
  99. source.append("\n\t// methods")
  100. for method in c["methods"]:
  101. method_signature = ""
  102. method_signature += "static " if c["singleton"] else ""
  103. method_signature += make_gdnative_type(method["return_type"])
  104. method_signature += escape_cpp(method["name"]) + "("
  105. has_default_argument = False
  106. for i, argument in enumerate(method["arguments"]):
  107. method_signature += "const " + make_gdnative_type(argument["type"])
  108. method_signature += escape_cpp(argument["name"])
  109. # default arguments
  110. def escape_default_arg(_type, default_value):
  111. if _type == "Color":
  112. return "Color(" + default_value + ")"
  113. if _type == "bool" or _type == "int":
  114. return default_value.lower()
  115. if _type == "Array":
  116. return "Array()"
  117. if _type in ["PoolVector2Array", "PoolStringArray", "PoolVector3Array", "PoolColorArray"]:
  118. return _type + "()"
  119. if _type == "Vector2":
  120. return "Vector2" + default_value
  121. if _type == "Vector3":
  122. return "Vector3" + default_value
  123. if _type == "Transform":
  124. return "Transform()"
  125. if _type == "Transform2D":
  126. return "Transform2D()"
  127. if _type == "Rect2":
  128. return "Rect2" + default_value
  129. if _type == "Variant":
  130. return "Variant()" if default_value == "Null" else default_value
  131. if _type == "String":
  132. return "\"" + default_value + "\""
  133. if _type == "RID":
  134. return "RID()"
  135. if default_value == "Null" or default_value == "[Object:null]":
  136. return "nullptr"
  137. return default_value
  138. if argument["has_default_value"] or has_default_argument:
  139. method_signature += " = " + escape_default_arg(argument["type"], argument["default_value"])
  140. has_default_argument = True
  141. if i != len(method["arguments"]) - 1:
  142. method_signature += ", "
  143. if method["has_varargs"]:
  144. if len(method["arguments"]) > 0:
  145. method_signature += ", "
  146. method_signature += "const Array& __var_args = Array()"
  147. method_signature += ")" + (" const" if method["is_const"] and not c["singleton"] else "")
  148. source.append("\t" + method_signature + ";")
  149. source.append("};")
  150. source.append("")
  151. source.append("}")
  152. source.append("")
  153. source.append("#endif")
  154. return "\n".join(source)
  155. def generate_class_implementation(icalls, used_classes, c):
  156. class_name = strip_name(c["name"])
  157. source = []
  158. source.append("#include <" + class_name + ".hpp>")
  159. source.append("")
  160. source.append("")
  161. source.append("#include <CoreTypes.hpp>")
  162. source.append("#include <Ref.hpp>")
  163. source.append("#include <Godot.hpp>")
  164. source.append("")
  165. source.append("#include \"__icalls.hpp\"")
  166. source.append("")
  167. source.append("")
  168. for used_class in used_classes:
  169. if is_enum(used_class):
  170. continue
  171. else:
  172. source.append("#include <" + strip_name(used_class) + ".hpp>")
  173. source.append("")
  174. source.append("")
  175. source.append("namespace godot {")
  176. core_object_name = ("___static_object_" + strip_name(c["name"])) if c["singleton"] else "this"
  177. source.append("")
  178. source.append("")
  179. if c["singleton"]:
  180. source.append("static godot_object *" + core_object_name + ";")
  181. source.append("")
  182. source.append("")
  183. # FIXME Test if inlining has a huge impact on binary size
  184. source.append("static inline void ___singleton_init()")
  185. source.append("{")
  186. source.append("\tif (" + core_object_name + " == nullptr) {")
  187. source.append("\t\t" + core_object_name + " = godot_global_get_singleton((char *) \"" + strip_name(c["name"]) + "\");")
  188. source.append("\t}")
  189. source.append("}")
  190. source.append("")
  191. source.append("")
  192. if c["instanciable"]:
  193. source.append("void *" + strip_name(c["name"]) + "::operator new(size_t)")
  194. source.append("{")
  195. source.append("\treturn godot_get_class_constructor((char *)\"" + c["name"] + "\")();")
  196. source.append("}")
  197. source.append("void " + strip_name(c["name"]) + "::operator delete(void *ptr)")
  198. source.append("{")
  199. source.append("\tgodot_object_destroy((godot_object *)ptr);")
  200. source.append("}")
  201. for method in c["methods"]:
  202. method_signature = ""
  203. method_signature += make_gdnative_type(method["return_type"])
  204. method_signature += strip_name(c["name"]) + "::" + escape_cpp(method["name"]) + "("
  205. for i, argument in enumerate(method["arguments"]):
  206. method_signature += "const " + make_gdnative_type(argument["type"])
  207. method_signature += escape_cpp(argument["name"])
  208. if i != len(method["arguments"]) - 1:
  209. method_signature += ", "
  210. if method["has_varargs"]:
  211. if len(method["arguments"]) > 0:
  212. method_signature += ", "
  213. method_signature += "const Array& __var_args"
  214. method_signature += ")" + (" const" if method["is_const"] and not c["singleton"] else "")
  215. source.append(method_signature + " {")
  216. if c["singleton"]:
  217. source.append("\t___singleton_init();")
  218. source.append("\tstatic godot_method_bind *mb = NULL;")
  219. source.append("\tif (mb == NULL) {")
  220. source.append("\t\tmb = godot_method_bind_get_method(\"" + c["name"] +"\", \"" + method["name"] + "\");")
  221. source.append("\t}")
  222. return_statement = ""
  223. if method["return_type"] != "void":
  224. if is_class_type(method["return_type"]):
  225. if is_enum(method["return_type"]):
  226. return_statement += "return (" + remove_enum_prefix(method["return_type"]) + ") "
  227. elif is_reference_type(method["return_type"]):
  228. return_statement += "return Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor(";
  229. else:
  230. return_statement += "return " + ("(" + strip_name(method["return_type"]) + " *) " if is_class_type(method["return_type"]) else "")
  231. else:
  232. return_statement += "return "
  233. def get_icall_type_name(name):
  234. if is_enum(name):
  235. return "int"
  236. if is_class_type(name):
  237. return "Object"
  238. return name
  239. if method["has_varargs"]:
  240. if len(method["arguments"]) != 0:
  241. source.append("\tVariant __given_args[" + str(len(method["arguments"])) + "];")
  242. for i, argument in enumerate(method["arguments"]):
  243. source.append("\tgodot_variant_new_nil((godot_variant *) &__given_args[" + str(i) + "]);")
  244. source.append("")
  245. for i, argument in enumerate(method["arguments"]):
  246. source.append("\t__given_args[" + str(i) + "] = " + escape_cpp(argument["name"]) + ";")
  247. source.append("")
  248. size = ""
  249. if method["has_varargs"]:
  250. size = "(__var_args.size() + " + str(len(method["arguments"])) + ")"
  251. else:
  252. size = "(" + str(len(method["arguments"])) + ")"
  253. source.append("\tgodot_variant **__args = (godot_variant **) alloca(sizeof(godot_variant *) * " + size + ");")
  254. source.append("")
  255. for i, argument in enumerate(method["arguments"]):
  256. source.append("\t__args[" + str(i) + "] = (godot_variant *) &__given_args[" + str(i) + "];")
  257. source.append("")
  258. if method["has_varargs"]:
  259. source.append("\tfor (int i = 0; i < __var_args.size(); i++) {")
  260. source.append("\t\t__args[i + " + str(len(method["arguments"])) + "] = (godot_variant *) &((Array &) __var_args)[i];")
  261. source.append("\t}")
  262. source.append("")
  263. source.append("\tVariant __result;")
  264. source.append("\t*(godot_variant *) &__result = godot_method_bind_call(mb, (godot_object *) " + core_object_name + ", (const godot_variant **) __args, " + size + ", nullptr);")
  265. source.append("")
  266. for i, argument in enumerate(method["arguments"]):
  267. source.append("\tgodot_variant_destroy((godot_variant *) &__given_args[" + str(i) + "]);")
  268. source.append("")
  269. if method["return_type"] != "void":
  270. cast = ""
  271. if is_class_type(method["return_type"]):
  272. if is_reference_type(method["return_type"]):
  273. cast += "Ref<" + stip_name(method["return_type"]) + ">::__internal_constructor(__result);"
  274. else:
  275. cast += "(" + strip_name(method["return_type"]) + " *) (Object *) __result;"
  276. else:
  277. cast += "__result;"
  278. source.append("\treturn " + cast)
  279. else:
  280. args = []
  281. for arg in method["arguments"]:
  282. args.append(get_icall_type_name(arg["type"]))
  283. icall_ret_type = get_icall_type_name(method["return_type"])
  284. icall_sig = tuple((icall_ret_type, tuple(args)))
  285. icalls.add(icall_sig)
  286. icall_name = get_icall_name(icall_sig)
  287. return_statement += icall_name + "(mb, (godot_object *) " + core_object_name
  288. for arg in method["arguments"]:
  289. return_statement += ", " + escape_cpp(arg["name"]) + (".ptr()" if is_reference_type(arg["type"]) else "")
  290. return_statement += ")"
  291. source.append("\t" + return_statement + (")" if is_reference_type(method["return_type"]) else "") + ";")
  292. source.append("}")
  293. source.append("")
  294. source.append("}")
  295. return "\n".join(source)
  296. def generate_icall_header(icalls):
  297. source = []
  298. source.append("#ifndef GODOT_CPP__ICALLS_HPP")
  299. source.append("#define GODOT_CPP__ICALLS_HPP")
  300. source.append("")
  301. source.append("#include <gdnative/gdnative.h>")
  302. source.append("#include <stdint.h>")
  303. source.append("")
  304. source.append("#include <CoreTypes.hpp>")
  305. source.append("#include <Object.hpp>")
  306. source.append("")
  307. source.append("")
  308. source.append("namespace godot {")
  309. source.append("")
  310. for icall in icalls:
  311. ret_type = icall[0]
  312. args = icall[1]
  313. method_signature = ""
  314. method_signature += return_type(ret_type) + get_icall_name(icall) + "(godot_method_bind *mb, godot_object *inst"
  315. for arg in args:
  316. method_signature += ", const "
  317. if is_core_type(arg):
  318. method_signature += arg + "&"
  319. elif is_primitive(arg):
  320. method_signature += arg
  321. else:
  322. method_signature += "Object *"
  323. method_signature += ");"
  324. source.append(method_signature)
  325. source.append("")
  326. source.append("}")
  327. source.append("")
  328. source.append("#endif")
  329. return "\n".join(source)
  330. def generate_icall_implementation(icalls):
  331. source = []
  332. source.append("#include \"__icalls.hpp\"")
  333. source.append("")
  334. source.append("#include <gdnative/gdnative.h>")
  335. source.append("#include <stdint.h>")
  336. source.append("")
  337. source.append("#include <CoreTypes.hpp>")
  338. source.append("#include <Object.hpp>")
  339. source.append("")
  340. source.append("")
  341. source.append("namespace godot {")
  342. source.append("")
  343. for icall in icalls:
  344. ret_type = icall[0]
  345. args = icall[1]
  346. method_signature = ""
  347. method_signature += return_type(ret_type) + get_icall_name(icall) + "(godot_method_bind *mb, godot_object *inst"
  348. for i, arg in enumerate(args):
  349. method_signature += ", const "
  350. if is_core_type(arg):
  351. method_signature += arg + "& "
  352. elif is_primitive(arg):
  353. method_signature += arg + " "
  354. else:
  355. method_signature += "Object *"
  356. method_signature += "arg" + str(i)
  357. method_signature += ")"
  358. source.append(method_signature + " {")
  359. if ret_type != "void":
  360. source.append("\t" + return_type(ret_type) + "ret;")
  361. if is_class_type(ret_type):
  362. source.append("\tret = nullptr;")
  363. source.append("\tconst void *args[" + ("1" if len(args) == 0 else "") + "] = {")
  364. for i, arg in enumerate(args):
  365. wrapped_argument = "\t\t"
  366. if is_primitive(arg) or is_core_type(arg):
  367. wrapped_argument += "(void *) &arg" + str(i)
  368. else:
  369. wrapped_argument += "(void *) arg" + str(i)
  370. wrapped_argument += ","
  371. source.append(wrapped_argument)
  372. source.append("\t};")
  373. source.append("")
  374. source.append("\tgodot_method_bind_ptrcall(mb, inst, args, " + ("nullptr" if ret_type == "void" else "&ret") + ");")
  375. if ret_type != "void":
  376. source.append("\treturn ret;")
  377. source.append("}")
  378. source.append("}")
  379. source.append("")
  380. return "\n".join(source)
  381. def return_type(t):
  382. if is_class_type(t):
  383. return "Object *"
  384. if t == "int":
  385. return "int64_t "
  386. if t == "float" or t == "real":
  387. return "double "
  388. return t + " "
  389. def get_icall_name(sig):
  390. ret_type = sig[0]
  391. args = sig[1]
  392. name = "___godot_icall_"
  393. name += strip_name(ret_type)
  394. for arg in args:
  395. name += "_" + strip_name(arg)
  396. return name
  397. def get_used_classes(c):
  398. classes = []
  399. for method in c["methods"]:
  400. if is_class_type(method["return_type"]) and not (method["return_type"] in classes):
  401. classes.append(method["return_type"])
  402. for arg in method["arguments"]:
  403. if is_class_type(arg["type"]) and not (arg["type"] in classes):
  404. classes.append(arg["type"])
  405. return classes
  406. def strip_name(name):
  407. if name[0] == '_':
  408. return name[1:]
  409. return name
  410. def extract_nested_type(nested_type):
  411. return strip_name(nested_type[:nested_type.find("::")])
  412. def remove_nested_type_prefix(name):
  413. return name if name.find("::") == -1 else strip_name(name[name.find("::") + 2:])
  414. def remove_enum_prefix(name):
  415. return strip_name(name[name.find("enum.") + 5:])
  416. def is_nested_type(name, type = ""):
  417. return name.find(type + "::") != -1
  418. def is_enum(name):
  419. return name.find("enum.") == 0
  420. def is_class_type(name):
  421. return not is_core_type(name) and not is_primitive(name)
  422. def is_core_type(name):
  423. core_types = ["Array",
  424. "Basis",
  425. "Color",
  426. "Dictionary",
  427. "Error",
  428. "NodePath",
  429. "Plane",
  430. "PoolByteArray",
  431. "PoolIntArray",
  432. "PoolRealArray",
  433. "PoolStringArray",
  434. "PoolVector2Array",
  435. "PoolVector3Array",
  436. "PoolColorArray",
  437. "Quat",
  438. "Rect2",
  439. "Rect3",
  440. "RID",
  441. "String",
  442. "Transform",
  443. "Transform2D",
  444. "Variant",
  445. "Vector2",
  446. "Vector3"]
  447. return name in core_types
  448. def is_primitive(name):
  449. core_types = ["int", "bool", "real", "float", "void"]
  450. return name in core_types
  451. def escape_cpp(name):
  452. escapes = {
  453. "class": "_class",
  454. "char": "_char",
  455. "short": "_short",
  456. "bool": "_bool",
  457. "int": "_int",
  458. "default": "_default",
  459. "case": "_case",
  460. "switch": "_switch",
  461. "export": "_export",
  462. "template": "_template",
  463. "new": "new_"
  464. }
  465. if name in escapes:
  466. return escapes[name]
  467. return name