binding_generator.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880
  1. #!/usr/bin/env python
  2. import json
  3. import re
  4. import shutil
  5. from pathlib import Path
  6. def print_file_list(api_filepath, output_dir, headers=False, sources=False):
  7. api = {}
  8. end = ";"
  9. with open(api_filepath) as api_file:
  10. api = json.load(api_file)
  11. include_gen_folder = Path(output_dir) / "gen" / "include" / "godot_cpp"
  12. source_gen_folder = Path(output_dir) / "gen" / "src"
  13. for builtin_class in api["builtin_classes"]:
  14. if is_pod_type(builtin_class["name"]):
  15. continue
  16. if is_included_type(builtin_class["name"]):
  17. continue
  18. header_filename = include_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".hpp")
  19. source_filename = source_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".cpp")
  20. if headers:
  21. print(str(header_filename.as_posix()), end=end)
  22. if sources:
  23. print(str(source_filename.as_posix()), end=end)
  24. for engine_class in api["classes"]:
  25. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  26. if engine_class["name"] == "ClassDB":
  27. continue
  28. header_filename = include_gen_folder / "classes" / (camel_to_snake(engine_class["name"]) + ".hpp")
  29. source_filename = source_gen_folder / "classes" / (camel_to_snake(engine_class["name"]) + ".cpp")
  30. if headers:
  31. print(str(header_filename.as_posix()), end=end)
  32. if sources:
  33. print(str(source_filename.as_posix()), end=end)
  34. utility_functions_header_path = include_gen_folder / "variant" / "utility_functions.hpp"
  35. utility_functions_source_path = source_gen_folder / "variant" / "utility_functions.cpp"
  36. global_constants_header_path = include_gen_folder / "classes" / "global_constants.hpp"
  37. if headers:
  38. print(str(utility_functions_header_path.as_posix()), end=end)
  39. print(str(global_constants_header_path.as_posix()), end=end)
  40. if sources:
  41. print(str(utility_functions_source_path.as_posix()), end=end)
  42. def generate_bindings(api_filepath, use_template_get_node, output_dir="."):
  43. api = None
  44. target_dir = Path(output_dir) / "gen"
  45. with open(api_filepath) as api_file:
  46. api = json.load(api_file)
  47. shutil.rmtree(target_dir, ignore_errors=True)
  48. target_dir.mkdir(parents=True)
  49. generate_global_constants(api, target_dir)
  50. generate_global_constant_binds(api, target_dir)
  51. generate_builtin_bindings(api, target_dir, "float_64")
  52. generate_engine_classes_bindings(api, target_dir, use_template_get_node)
  53. generate_utility_functions(api, target_dir)
  54. builtin_classes = []
  55. # Key is class name, value is boolean where True means the class is refcounted.
  56. engine_classes = {}
  57. singletons = []
  58. def generate_builtin_bindings(api, output_dir, build_config):
  59. global builtin_classes
  60. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  61. source_gen_folder = Path(output_dir) / "src" / "variant"
  62. include_gen_folder.mkdir(parents=True, exist_ok=True)
  63. source_gen_folder.mkdir(parents=True, exist_ok=True)
  64. # Store types beforehand.
  65. for builtin_api in api["builtin_classes"]:
  66. if is_pod_type(builtin_api["name"]):
  67. continue
  68. builtin_classes.append(builtin_api["name"])
  69. builtin_sizes = {}
  70. for size_list in api["builtin_class_sizes"]:
  71. if size_list["build_configuration"] == build_config:
  72. for size in size_list["sizes"]:
  73. builtin_sizes[size["name"]] = size["size"]
  74. break
  75. # Create a file for Variant size, since that class isn't generated.
  76. variant_size_filename = include_gen_folder / "variant_size.hpp"
  77. with variant_size_filename.open("+w") as variant_size_file:
  78. variant_size_source = []
  79. add_header("variant_size.hpp", variant_size_source)
  80. header_guard = "GODOT_CPP_VARIANT_SIZE_HPP"
  81. variant_size_source.append(f"#ifndef {header_guard}")
  82. variant_size_source.append(f"#define {header_guard}")
  83. variant_size_source.append(f'#define GODOT_CPP_VARIANT_SIZE {builtin_sizes["Variant"]}')
  84. variant_size_source.append(f"#endif // ! {header_guard}")
  85. variant_size_file.write("\n".join(variant_size_source))
  86. for builtin_api in api["builtin_classes"]:
  87. if is_pod_type(builtin_api["name"]):
  88. continue
  89. if is_included_type(builtin_api["name"]):
  90. continue
  91. size = builtin_sizes[builtin_api["name"]]
  92. header_filename = include_gen_folder / (camel_to_snake(builtin_api["name"]) + ".hpp")
  93. source_filename = source_gen_folder / (camel_to_snake(builtin_api["name"]) + ".cpp")
  94. # Check used classes for header include
  95. used_classes = set()
  96. fully_used_classes = set()
  97. class_name = builtin_api["name"]
  98. if "constructors" in builtin_api:
  99. for constructor in builtin_api["constructors"]:
  100. if "arguments" in constructor:
  101. for argument in constructor["arguments"]:
  102. if is_included(argument["type"], class_name):
  103. if "default_value" in argument and argument["type"] != "Variant":
  104. fully_used_classes.add(argument["type"])
  105. else:
  106. used_classes.add(argument["type"])
  107. if "methods" in builtin_api:
  108. for method in builtin_api["methods"]:
  109. if "arguments" in method:
  110. for argument in method["arguments"]:
  111. if is_included(argument["type"], class_name):
  112. if "default_value" in argument and argument["type"] != "Variant":
  113. fully_used_classes.add(argument["type"])
  114. else:
  115. used_classes.add(argument["type"])
  116. if "return_type" in method:
  117. if is_included(method["return_type"], class_name):
  118. used_classes.add(method["return_type"])
  119. if "members" in builtin_api:
  120. for member in builtin_api["members"]:
  121. if is_included(member["type"], class_name):
  122. used_classes.add(member["type"])
  123. if "indexing_return_type" in builtin_api:
  124. if is_included(builtin_api["indexing_return_type"], class_name):
  125. used_classes.add(builtin_api["indexing_return_type"])
  126. if "operators" in builtin_api:
  127. for operator in builtin_api["operators"]:
  128. if "right_type" in operator:
  129. # FIXME Temporary workaround for incorrect JSON
  130. if operator["right_type"] == "Nil":
  131. used_classes.add("Variant")
  132. elif is_included(operator["right_type"], class_name):
  133. used_classes.add(operator["right_type"])
  134. for type_name in fully_used_classes:
  135. if type_name in used_classes:
  136. used_classes.remove(type_name)
  137. with header_filename.open("w+") as header_file:
  138. header_file.write(generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes))
  139. with source_filename.open("w+") as source_file:
  140. source_file.write(generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes))
  141. # Create a header with all builtin types for convenience.
  142. builtin_header_filename = include_gen_folder / "builtin_types.hpp"
  143. with builtin_header_filename.open("w+") as builtin_header_file:
  144. builtin_header = []
  145. add_header("builtin_types.hpp", builtin_header)
  146. builtin_header.append("#ifndef GODOT_CPP_BUILTIN_TYPES_HPP")
  147. builtin_header.append("#define GODOT_CPP_BUILTIN_TYPES_HPP")
  148. builtin_header.append("")
  149. for builtin in builtin_classes:
  150. builtin_header.append(f"#include <godot_cpp/variant/{camel_to_snake(builtin)}.hpp>")
  151. builtin_header.append("")
  152. builtin_header.append("#endif // ! GODOT_CPP_BUILTIN_TYPES_HPP")
  153. builtin_header_file.write("\n".join(builtin_header))
  154. def generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes):
  155. result = []
  156. class_name = builtin_api["name"]
  157. snake_class_name = camel_to_snake(class_name).upper()
  158. header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
  159. add_header(f"{snake_class_name.lower()}.hpp", result)
  160. result.append(f"#ifndef {header_guard}")
  161. result.append(f"#define {header_guard}")
  162. result.append("")
  163. result.append("#include <godot_cpp/core/defs.hpp>")
  164. result.append("")
  165. # Special cases.
  166. if class_name == "String":
  167. result.append("#include <godot_cpp/variant/char_string.hpp>")
  168. result.append("#include <godot_cpp/variant/char_utils.hpp>")
  169. result.append("#include <godot_cpp/variant/ucaps.hpp>")
  170. if class_name == "Array":
  171. result.append("#include <godot_cpp/variant/array_helpers.hpp>")
  172. for include in fully_used_classes:
  173. result.append(f"#include <godot_cpp/{get_include_path(include)}>")
  174. if len(fully_used_classes) > 0:
  175. result.append("")
  176. result.append(f"#include <godot/gdnative_interface.h>")
  177. result.append("")
  178. result.append("namespace godot {")
  179. result.append("")
  180. for type_name in used_classes:
  181. result.append(f"class {type_name};")
  182. if len(used_classes) > 0:
  183. result.append("")
  184. result.append(f"class {class_name} {{")
  185. result.append(f"\tstatic constexpr size_t {snake_class_name}_SIZE = {size};")
  186. result.append(f"\tuint8_t opaque[{snake_class_name}_SIZE] = {{}};")
  187. result.append(
  188. f"\t_FORCE_INLINE_ GDNativeTypePtr _native_ptr() const {{ return const_cast<uint8_t (*)[{snake_class_name}_SIZE]>(&opaque); }}"
  189. )
  190. result.append("")
  191. result.append("\tfriend class Variant;")
  192. result.append("")
  193. result.append("\tstatic struct _MethodBindings {")
  194. if "constructors" in builtin_api:
  195. for constructor in builtin_api["constructors"]:
  196. result.append(f'\t\tGDNativePtrConstructor constructor_{constructor["index"]};')
  197. if builtin_api["has_destructor"]:
  198. result.append("\t\tGDNativePtrDestructor destructor;")
  199. if "methods" in builtin_api:
  200. for method in builtin_api["methods"]:
  201. result.append(f'\t\tGDNativePtrBuiltInMethod method_{method["name"]};')
  202. if "members" in builtin_api:
  203. for member in builtin_api["members"]:
  204. result.append(f'\t\tGDNativePtrSetter member_{member["name"]}_setter;')
  205. result.append(f'\t\tGDNativePtrGetter member_{member["name"]}_getter;')
  206. if "indexing_return_type" in builtin_api:
  207. result.append(f"\t\tGDNativePtrIndexedSetter indexed_setter;")
  208. result.append(f"\t\tGDNativePtrIndexedGetter indexed_getter;")
  209. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  210. result.append(f"\t\tGDNativePtrKeyedSetter keyed_setter;")
  211. result.append(f"\t\tGDNativePtrKeyedGetter keyed_getter;")
  212. result.append(f"\t\tGDNativePtrKeyedChecker keyed_checker;")
  213. if "operators" in builtin_api:
  214. for operator in builtin_api["operators"]:
  215. if "right_type" in operator:
  216. result.append(
  217. f'\t\tGDNativePtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]};'
  218. )
  219. else:
  220. result.append(f'\t\tGDNativePtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])};')
  221. result.append("\t} _method_bindings;")
  222. result.append("")
  223. result.append("\tstatic void init_bindings();")
  224. result.append("")
  225. result.append("public:")
  226. copy_constructor_index = -1
  227. if "constructors" in builtin_api:
  228. for constructor in builtin_api["constructors"]:
  229. method_signature = f"\t{class_name}("
  230. if "arguments" in constructor:
  231. method_signature += make_function_parameters(
  232. constructor["arguments"], include_default=True, for_builtin=True
  233. )
  234. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  235. copy_constructor_index = constructor["index"]
  236. method_signature += ");"
  237. result.append(method_signature)
  238. # Move constructor.
  239. result.append(f"\t{class_name}({class_name} &&other);")
  240. # Special cases.
  241. if class_name == "String" or class_name == "StringName" or class_name == "NodePath":
  242. result.append(f"\t{class_name}(const char *from);")
  243. result.append(f"\t{class_name}(const wchar_t *from);")
  244. result.append(f"\t{class_name}(const char16_t *from);")
  245. result.append(f"\t{class_name}(const char32_t *from);")
  246. if "constants" in builtin_api:
  247. axis_constants_count = 0
  248. for constant in builtin_api["constants"]:
  249. # Special case: Vector3.Axis is the only enum in the bindings.
  250. # It's technically not supported by Variant but works for direct access.
  251. if class_name == "Vector3" and constant["name"].startswith("AXIS"):
  252. if axis_constants_count == 0:
  253. result.append("\tenum Axis {")
  254. result.append(f'\t\t{constant["name"]} = {constant["value"]},')
  255. axis_constants_count += 1
  256. if axis_constants_count == 3:
  257. result.append("\t};")
  258. else:
  259. result.append(f'\tstatic const {correct_type(constant["type"])} {constant["name"]};')
  260. if builtin_api["has_destructor"]:
  261. result.append(f"\t~{class_name}();")
  262. method_list = []
  263. if "methods" in builtin_api:
  264. for method in builtin_api["methods"]:
  265. method_list.append(method["name"])
  266. vararg = method["is_vararg"]
  267. if vararg:
  268. result.append("\ttemplate<class... Args>")
  269. method_signature = "\t"
  270. if "is_static" in method and method["is_static"]:
  271. method_signature += "static "
  272. if "return_type" in method:
  273. method_signature += f'{correct_type(method["return_type"])} '
  274. else:
  275. method_signature += "void "
  276. method_signature += f'{method["name"]}('
  277. method_arguments = []
  278. if "arguments" in method:
  279. method_arguments = method["arguments"]
  280. method_signature += make_function_parameters(
  281. method_arguments, include_default=True, for_builtin=True, is_vararg=vararg
  282. )
  283. method_signature += ")"
  284. if method["is_const"]:
  285. method_signature += " const"
  286. method_signature += ";"
  287. result.append(method_signature)
  288. # Special cases.
  289. if class_name == "String":
  290. result.append("\tstatic String utf8(const char *from, int len = -1);")
  291. result.append("\tvoid parse_utf8(const char *from, int len = -1);")
  292. result.append("\tstatic String utf16(const char16_t *from, int len = -1);")
  293. result.append("\tvoid parse_utf16(const char16_t *from, int len = -1);")
  294. result.append("\tCharString utf8() const;")
  295. result.append("\tCharString ascii() const;")
  296. result.append("\tChar16String utf16() const;")
  297. result.append("\tChar32String utf32() const;")
  298. result.append("\tCharWideString wide_string() const;")
  299. if "members" in builtin_api:
  300. for member in builtin_api["members"]:
  301. if f'get_{member["name"]}' not in method_list:
  302. result.append(f'\t{correct_type(member["type"])} get_{member["name"]}() const;')
  303. if f'set_{member["name"]}' not in method_list:
  304. result.append(f'\tvoid set_{member["name"]}({type_for_parameter(member["type"])}value);')
  305. if "operators" in builtin_api:
  306. for operator in builtin_api["operators"]:
  307. if operator["name"] not in ["in", "xor"]:
  308. if "right_type" in operator:
  309. result.append(
  310. f'\t{correct_type(operator["return_type"])} operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const;'
  311. )
  312. else:
  313. result.append(
  314. f'\t{correct_type(operator["return_type"])} operator{operator["name"].replace("unary", "")}() const;'
  315. )
  316. # Copy assignment.
  317. if copy_constructor_index >= 0:
  318. result.append(f"\t{class_name} &operator=(const {class_name} &other);")
  319. # Move assignment.
  320. result.append(f"\t{class_name} &operator=({class_name} &&other);")
  321. # Special cases.
  322. if class_name == "String":
  323. result.append("String &operator=(const char *p_str);")
  324. result.append("String &operator=(const wchar_t *p_str);")
  325. result.append("String &operator=(const char16_t *p_str);")
  326. result.append("String &operator=(const char32_t *p_str);")
  327. result.append("bool operator==(const char *p_str) const;")
  328. result.append("bool operator==(const wchar_t *p_str) const;")
  329. result.append("bool operator==(const char16_t *p_str) const;")
  330. result.append("bool operator==(const char32_t *p_str) const;")
  331. result.append("bool operator!=(const char *p_str) const;")
  332. result.append("bool operator!=(const wchar_t *p_str) const;")
  333. result.append("bool operator!=(const char16_t *p_str) const;")
  334. result.append("bool operator!=(const char32_t *p_str) const;")
  335. result.append(f"\tconst char32_t &operator[](int p_index) const;")
  336. result.append(f"\tchar32_t &operator[](int p_index);")
  337. result.append(f"\tconst char32_t *ptr() const;")
  338. result.append(f"\tchar32_t *ptrw();")
  339. if class_name == "Array":
  340. result.append("\ttemplate <class... Args>")
  341. result.append("\tstatic Array make(Args... args) {")
  342. result.append("\t\treturn helpers::append_all(Array(), args...);")
  343. result.append("\t}")
  344. if is_packed_array(class_name):
  345. return_type = correct_type(builtin_api["indexing_return_type"])
  346. if class_name == "PackedByteArray":
  347. return_type = "uint8_t"
  348. elif class_name == "PackedInt32Array":
  349. return_type = "int32_t"
  350. elif class_name == "PackedFloat32Array":
  351. return_type = "float"
  352. result.append(f"\tconst " + return_type + f" &operator[](int p_index) const;")
  353. result.append(f"\t" + return_type + f" &operator[](int p_index);")
  354. result.append(f"\tconst " + return_type + f" *ptr() const;")
  355. result.append(f"\t" + return_type + f" *ptrw();")
  356. if class_name == "Array":
  357. result.append(f"\tconst Variant &operator[](int p_index) const;")
  358. result.append(f"\tVariant &operator[](int p_index);")
  359. if class_name == "Dictionary":
  360. result.append(f"\tconst Variant &operator[](const Variant &p_key) const;")
  361. result.append(f"\tVariant &operator[](const Variant &p_key);")
  362. result.append("};")
  363. if class_name == "String":
  364. result.append("")
  365. result.append("bool operator==(const char *p_chr, const String &p_str);")
  366. result.append("bool operator==(const wchar_t *p_chr, const String &p_str);")
  367. result.append("bool operator==(const char16_t *p_chr, const String &p_str);")
  368. result.append("bool operator==(const char32_t *p_chr, const String &p_str);")
  369. result.append("bool operator!=(const char *p_chr, const String &p_str);")
  370. result.append("bool operator!=(const wchar_t *p_chr, const String &p_str);")
  371. result.append("bool operator!=(const char16_t *p_chr, const String &p_str);")
  372. result.append("bool operator!=(const char32_t *p_chr, const String &p_str);")
  373. result.append("String operator+(const char *p_chr, const String &p_str);")
  374. result.append("String operator+(const wchar_t *p_chr, const String &p_str);")
  375. result.append("String operator+(const char16_t *p_chr, const String &p_str);")
  376. result.append("String operator+(const char32_t *p_chr, const String &p_str);")
  377. result.append("")
  378. result.append("} // namespace godot")
  379. result.append(f"#endif // ! {header_guard}")
  380. return "\n".join(result)
  381. def generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes):
  382. result = []
  383. class_name = builtin_api["name"]
  384. snake_class_name = camel_to_snake(class_name)
  385. enum_type_name = f"GDNATIVE_VARIANT_TYPE_{snake_class_name.upper()}"
  386. add_header(f"{snake_class_name}.cpp", result)
  387. result.append("")
  388. result.append(f"#include <godot_cpp/variant/{snake_class_name}.hpp>")
  389. result.append("")
  390. result.append("#include <godot_cpp/core/binder_common.hpp>")
  391. result.append("")
  392. result.append("#include <godot_cpp/godot.hpp>")
  393. result.append("")
  394. # Only used since the "fully used" is included in header already.
  395. for include in used_classes:
  396. result.append(f"#include <godot_cpp/{get_include_path(include)}>")
  397. if len(used_classes) > 0:
  398. result.append("")
  399. result.append("#include <godot_cpp/core/builtin_ptrcall.hpp>")
  400. result.append("")
  401. result.append("#include <utility>")
  402. result.append("")
  403. result.append("namespace godot {")
  404. result.append("")
  405. result.append(f"{class_name}::_MethodBindings {class_name}::_method_bindings;")
  406. result.append("")
  407. result.append(f"void {class_name}::init_bindings() {{")
  408. if "constructors" in builtin_api:
  409. for constructor in builtin_api["constructors"]:
  410. result.append(
  411. f'\t_method_bindings.constructor_{constructor["index"]} = internal::gdn_interface->variant_get_ptr_constructor({enum_type_name}, {constructor["index"]});'
  412. )
  413. if builtin_api["has_destructor"]:
  414. result.append(
  415. f"\t_method_bindings.destructor = internal::gdn_interface->variant_get_ptr_destructor({enum_type_name});"
  416. )
  417. if "methods" in builtin_api:
  418. for method in builtin_api["methods"]:
  419. # TODO: Add error check for hash mismatch.
  420. result.append(
  421. f'\t_method_bindings.method_{method["name"]} = internal::gdn_interface->variant_get_ptr_builtin_method({enum_type_name}, "{method["name"]}", {method["hash"]});'
  422. )
  423. if "members" in builtin_api:
  424. for member in builtin_api["members"]:
  425. result.append(
  426. f'\t_method_bindings.member_{member["name"]}_setter = internal::gdn_interface->variant_get_ptr_setter({enum_type_name}, "{member["name"]}");'
  427. )
  428. result.append(
  429. f'\t_method_bindings.member_{member["name"]}_getter = internal::gdn_interface->variant_get_ptr_getter({enum_type_name}, "{member["name"]}");'
  430. )
  431. if "indexing_return_type" in builtin_api:
  432. result.append(
  433. f"\t_method_bindings.indexed_setter = internal::gdn_interface->variant_get_ptr_indexed_setter({enum_type_name});"
  434. )
  435. result.append(
  436. f"\t_method_bindings.indexed_getter = internal::gdn_interface->variant_get_ptr_indexed_getter({enum_type_name});"
  437. )
  438. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  439. result.append(
  440. f"\t_method_bindings.keyed_setter = internal::gdn_interface->variant_get_ptr_keyed_setter({enum_type_name});"
  441. )
  442. result.append(
  443. f"\t_method_bindings.keyed_getter = internal::gdn_interface->variant_get_ptr_keyed_getter({enum_type_name});"
  444. )
  445. result.append(
  446. f"\t_method_bindings.keyed_checker = internal::gdn_interface->variant_get_ptr_keyed_checker({enum_type_name});"
  447. )
  448. if "operators" in builtin_api:
  449. for operator in builtin_api["operators"]:
  450. if "right_type" in operator:
  451. result.append(
  452. f'\t_method_bindings.operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]} = internal::gdn_interface->variant_get_ptr_operator_evaluator(GDNATIVE_VARIANT_OP_{get_operator_id_name(operator["name"]).upper()}, {enum_type_name}, GDNATIVE_VARIANT_TYPE_{camel_to_snake(operator["right_type"]).upper()});'
  453. )
  454. else:
  455. result.append(
  456. f'\t_method_bindings.operator_{get_operator_id_name(operator["name"])} = internal::gdn_interface->variant_get_ptr_operator_evaluator(GDNATIVE_VARIANT_OP_{get_operator_id_name(operator["name"]).upper()}, {enum_type_name}, GDNATIVE_VARIANT_TYPE_NIL);'
  457. )
  458. result.append("}")
  459. result.append("")
  460. copy_constructor_index = -1
  461. if "constructors" in builtin_api:
  462. for constructor in builtin_api["constructors"]:
  463. method_signature = f"{class_name}::{class_name}("
  464. if "arguments" in constructor:
  465. method_signature += make_function_parameters(
  466. constructor["arguments"], include_default=False, for_builtin=True
  467. )
  468. method_signature += ") {"
  469. result.append(method_signature)
  470. method_call = (
  471. f'\tinternal::_call_builtin_constructor(_method_bindings.constructor_{constructor["index"]}, &opaque'
  472. )
  473. if "arguments" in constructor:
  474. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  475. copy_constructor_index = constructor["index"]
  476. method_call += ", "
  477. arguments = []
  478. for argument in constructor["arguments"]:
  479. (encode, arg_name) = get_encoded_arg(
  480. argument["name"],
  481. argument["type"],
  482. argument["meta"] if "meta" in argument else None,
  483. )
  484. result += encode
  485. arguments.append(arg_name)
  486. method_call += ", ".join(arguments)
  487. method_call += ");"
  488. result.append(method_call)
  489. result.append("}")
  490. result.append("")
  491. # Move constructor.
  492. result.append(f"{class_name}::{class_name}({class_name} &&other) {{")
  493. if needs_copy_instead_of_move(class_name) and copy_constructor_index >= 0:
  494. result.append(
  495. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, &other);"
  496. )
  497. else:
  498. result.append("\tstd::swap(opaque, other.opaque);")
  499. result.append("}")
  500. result.append("")
  501. if builtin_api["has_destructor"]:
  502. result.append(f"{class_name}::~{class_name}() {{")
  503. result.append("\t_method_bindings.destructor(&opaque);")
  504. result.append("}")
  505. result.append("")
  506. method_list = []
  507. if "methods" in builtin_api:
  508. for method in builtin_api["methods"]:
  509. method_list.append(method["name"])
  510. if "is_vararg" in method and method["is_vararg"]:
  511. # Done in the header because of the template.
  512. continue
  513. method_signature = make_signature(class_name, method, for_builtin=True)
  514. result.append(method_signature + "{")
  515. method_call = "\t"
  516. if "return_type" in method:
  517. method_call += f'return internal::_call_builtin_method_ptr_ret<{correct_type(method["return_type"])}>('
  518. else:
  519. method_call += f"internal::_call_builtin_method_ptr_no_ret("
  520. method_call += f'_method_bindings.method_{method["name"]}, '
  521. if "is_static" in method and method["is_static"]:
  522. method_call += "nullptr"
  523. else:
  524. method_call += "(GDNativeTypePtr)&opaque"
  525. if "arguments" in method:
  526. arguments = []
  527. method_call += ", "
  528. for argument in method["arguments"]:
  529. (encode, arg_name) = get_encoded_arg(
  530. argument["name"],
  531. argument["type"],
  532. argument["meta"] if "meta" in argument else None,
  533. )
  534. result += encode
  535. arguments.append(arg_name)
  536. method_call += ", ".join(arguments)
  537. method_call += ");"
  538. result.append(method_call)
  539. result.append("}")
  540. result.append("")
  541. if "members" in builtin_api:
  542. for member in builtin_api["members"]:
  543. if f'get_{member["name"]}' not in method_list:
  544. result.append(f'{correct_type(member["type"])} {class_name}::get_{member["name"]}() const {{')
  545. result.append(
  546. f'\treturn internal::_call_builtin_ptr_getter<{correct_type(member["type"])}>(_method_bindings.member_{member["name"]}_getter, (const GDNativeTypePtr)&opaque);'
  547. )
  548. result.append("}")
  549. if f'set_{member["name"]}' not in method_list:
  550. result.append(f'void {class_name}::set_{member["name"]}({type_for_parameter(member["type"])}value) {{')
  551. (encode, arg_name) = get_encoded_arg("value", member["type"], None)
  552. result += encode
  553. result.append(
  554. f'\t_method_bindings.member_{member["name"]}_setter((const GDNativeTypePtr)&opaque, (const GDNativeTypePtr){arg_name});'
  555. )
  556. result.append("}")
  557. result.append("")
  558. if "operators" in builtin_api:
  559. for operator in builtin_api["operators"]:
  560. if operator["name"] not in ["in", "xor"]:
  561. if "right_type" in operator:
  562. result.append(
  563. f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const {{'
  564. )
  565. (encode, arg_name) = get_encoded_arg("other", operator["right_type"], None)
  566. result += encode
  567. result.append(
  568. f'\treturn internal::_call_builtin_operator_ptr<{get_gdnative_type(correct_type(operator["return_type"]))}>(_method_bindings.operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]}, (const GDNativeTypePtr)&opaque, (const GDNativeTypePtr){arg_name});'
  569. )
  570. result.append("}")
  571. else:
  572. result.append(
  573. f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"].replace("unary", "")}() const {{'
  574. )
  575. result.append(
  576. f'\treturn internal::_call_builtin_operator_ptr<{get_gdnative_type(correct_type(operator["return_type"]))}>(_method_bindings.operator_{get_operator_id_name(operator["name"])}, (const GDNativeTypePtr)&opaque, (const GDNativeTypePtr)nullptr);'
  577. )
  578. result.append("}")
  579. result.append("")
  580. # Copy assignment.
  581. if copy_constructor_index >= 0:
  582. result.append(f"{class_name} &{class_name}::operator=(const {class_name} &other) {{")
  583. if builtin_api["has_destructor"]:
  584. result.append("\t_method_bindings.destructor(&opaque);")
  585. (encode, arg_name) = get_encoded_arg(
  586. "other",
  587. class_name,
  588. None,
  589. )
  590. result += encode
  591. result.append(
  592. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, {arg_name});"
  593. )
  594. result.append("\treturn *this;")
  595. result.append("}")
  596. result.append("")
  597. # Move assignment.
  598. result.append(f"{class_name} &{class_name}::operator=({class_name} &&other) {{")
  599. if needs_copy_instead_of_move(class_name) and copy_constructor_index >= 0:
  600. result.append(
  601. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, &other);"
  602. )
  603. else:
  604. result.append("\tstd::swap(opaque, other.opaque);")
  605. result.append("\treturn *this;")
  606. result.append("}")
  607. result.append("")
  608. result.append("} //namespace godot")
  609. return "\n".join(result)
  610. def generate_engine_classes_bindings(api, output_dir, use_template_get_node):
  611. global engine_classes
  612. global singletons
  613. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  614. source_gen_folder = Path(output_dir) / "src" / "classes"
  615. include_gen_folder.mkdir(parents=True, exist_ok=True)
  616. source_gen_folder.mkdir(parents=True, exist_ok=True)
  617. # First create map of classes and singletons.
  618. for class_api in api["classes"]:
  619. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  620. if class_api["name"] == "ClassDB":
  621. continue
  622. engine_classes[class_api["name"]] = class_api["is_refcounted"]
  623. for native_struct in api["native_structures"]:
  624. engine_classes[native_struct["name"]] = False
  625. for singleton in api["singletons"]:
  626. singletons.append(singleton["name"])
  627. for class_api in api["classes"]:
  628. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  629. if class_api["name"] == "ClassDB":
  630. continue
  631. # Check used classes for header include.
  632. used_classes = set()
  633. fully_used_classes = set()
  634. class_name = class_api["name"]
  635. header_filename = include_gen_folder / (camel_to_snake(class_api["name"]) + ".hpp")
  636. source_filename = source_gen_folder / (camel_to_snake(class_api["name"]) + ".cpp")
  637. if "methods" in class_api:
  638. for method in class_api["methods"]:
  639. if "arguments" in method:
  640. for argument in method["arguments"]:
  641. type_name = argument["type"]
  642. if type_name.startswith("const "):
  643. type_name = type_name[6:]
  644. if type_name.endswith("*"):
  645. type_name = type_name[:-1]
  646. if is_included(type_name, class_name):
  647. if is_enum(type_name):
  648. fully_used_classes.add(get_enum_class(type_name))
  649. elif "default_value" in argument:
  650. fully_used_classes.add(type_name)
  651. else:
  652. used_classes.add(type_name)
  653. if is_refcounted(type_name):
  654. fully_used_classes.add("Ref")
  655. if "return_value" in method:
  656. type_name = method["return_value"]["type"]
  657. if type_name.startswith("const "):
  658. type_name = type_name[6:]
  659. if type_name.endswith("*"):
  660. type_name = type_name[:-1]
  661. if is_included(type_name, class_name):
  662. if is_enum(type_name):
  663. fully_used_classes.add(get_enum_class(type_name))
  664. elif is_variant(type_name):
  665. fully_used_classes.add(type_name)
  666. else:
  667. used_classes.add(type_name)
  668. if is_refcounted(type_name):
  669. fully_used_classes.add("Ref")
  670. if "members" in class_api:
  671. for member in class_api["members"]:
  672. if is_included(member["type"], class_name):
  673. if is_enum(member["type"]):
  674. fully_used_classes.add(get_enum_class(member["type"]))
  675. else:
  676. used_classes.add(member["type"])
  677. if is_refcounted(member["type"]):
  678. fully_used_classes.add("Ref")
  679. if "inherits" in class_api:
  680. if is_included(class_api["inherits"], class_name):
  681. fully_used_classes.add(class_api["inherits"])
  682. if is_refcounted(class_api["name"]):
  683. fully_used_classes.add("Ref")
  684. else:
  685. fully_used_classes.add("Wrapped")
  686. for type_name in fully_used_classes:
  687. if type_name in used_classes:
  688. used_classes.remove(type_name)
  689. with header_filename.open("w+") as header_file:
  690. header_file.write(
  691. generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node)
  692. )
  693. with source_filename.open("w+") as source_file:
  694. source_file.write(
  695. generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node)
  696. )
  697. for native_struct in api["native_structures"]:
  698. struct_name = native_struct["name"]
  699. snake_struct_name = camel_to_snake(struct_name)
  700. header_filename = include_gen_folder / (snake_struct_name + ".hpp")
  701. result = []
  702. add_header(f"{snake_struct_name}.hpp", result)
  703. header_guard = f"GODOT_CPP_{snake_struct_name.upper()}_HPP"
  704. result.append(f"#ifndef {header_guard}")
  705. result.append(f"#define {header_guard}")
  706. used_classes = []
  707. expanded_format = native_struct["format"].replace("(", " ").replace(")", ";").replace(",", ";")
  708. for field in expanded_format.split(";"):
  709. field_type = field.strip().split(" ")[0].split("::")[0]
  710. if field_type != "" and not is_included_type(field_type) and not is_pod_type(field_type):
  711. if not field_type in used_classes:
  712. used_classes.append(field_type)
  713. result.append("")
  714. for included in used_classes:
  715. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  716. if len(used_classes) > 0:
  717. result.append("")
  718. result.append("namespace godot {")
  719. result.append("")
  720. result.append(f"struct {struct_name} {{")
  721. for field in native_struct["format"].split(";"):
  722. if field != "":
  723. result.append(f"\t{field};")
  724. result.append("};")
  725. result.append("")
  726. result.append(f"GDVIRTUAL_NATIVE_PTR({struct_name});")
  727. result.append("")
  728. result.append("} // namespace godot")
  729. result.append("")
  730. result.append(f"#endif // ! {header_guard}")
  731. with header_filename.open("w+") as header_file:
  732. header_file.write("\n".join(result))
  733. def generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node):
  734. global singletons
  735. result = []
  736. class_name = class_api["name"]
  737. snake_class_name = camel_to_snake(class_name).upper()
  738. is_singleton = class_name in singletons
  739. add_header(f"{snake_class_name.lower()}.hpp", result)
  740. header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
  741. result.append(f"#ifndef {header_guard}")
  742. result.append(f"#define {header_guard}")
  743. result.append("")
  744. for included in fully_used_classes:
  745. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  746. if len(fully_used_classes) > 0:
  747. result.append("")
  748. if class_name != "Object":
  749. result.append("#include <godot_cpp/core/class_db.hpp>")
  750. result.append("")
  751. result.append("#include <type_traits>")
  752. result.append("")
  753. result.append("namespace godot {")
  754. result.append("")
  755. for type_name in used_classes:
  756. result.append(f"class {type_name};")
  757. if len(used_classes) > 0:
  758. result.append("")
  759. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  760. result.append(f"class {class_name} : public {inherits} {{")
  761. result.append(f"\tGDNATIVE_CLASS({class_name}, {inherits})")
  762. result.append("")
  763. result.append("public:")
  764. result.append("")
  765. if "enums" in class_api:
  766. for enum_api in class_api["enums"]:
  767. result.append(f'\tenum {enum_api["name"]} {{')
  768. for value in enum_api["values"]:
  769. result.append(f'\t\t{value["name"]} = {value["value"]},')
  770. result.append("\t};")
  771. result.append("")
  772. if is_singleton:
  773. result.append(f"\tstatic {class_name} *get_singleton();")
  774. result.append("")
  775. if "methods" in class_api:
  776. for method in class_api["methods"]:
  777. if method["is_virtual"]:
  778. # Will be done later.
  779. continue
  780. vararg = "is_vararg" in method and method["is_vararg"]
  781. method_signature = "\t"
  782. if vararg:
  783. method_signature += "private: "
  784. method_signature += make_signature(
  785. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  786. )
  787. result.append(method_signature + ";")
  788. if vararg:
  789. # Add templated version.
  790. result += make_varargs_template(method)
  791. # Virtuals now.
  792. for method in class_api["methods"]:
  793. if not method["is_virtual"]:
  794. continue
  795. method_signature = "\t"
  796. method_signature += make_signature(
  797. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  798. )
  799. result.append(method_signature + ";")
  800. result.append("protected:")
  801. result.append("\ttemplate <class T>")
  802. result.append("\tstatic void register_virtuals() {")
  803. if class_name != "Object":
  804. result.append(f"\t\t{inherits}::register_virtuals<T>();")
  805. if "methods" in class_api:
  806. for method in class_api["methods"]:
  807. if not method["is_virtual"]:
  808. continue
  809. method_name = escape_identifier(method["name"])
  810. result.append(
  811. f"\t\tif constexpr (!std::is_same_v<decltype(&{class_name}::{method_name}),decltype(&T::{method_name})>) {{"
  812. )
  813. result.append(f"\t\t\tBIND_VIRTUAL_METHOD(T, {method_name});")
  814. result.append("\t\t}")
  815. result.append("\t}")
  816. result.append("")
  817. result.append("public:")
  818. # Special cases.
  819. if class_name == "Object":
  820. result.append("")
  821. result.append("\ttemplate<class T>")
  822. result.append("\tstatic T *cast_to(Object *p_object);")
  823. result.append("\tvirtual ~Object() = default;")
  824. elif use_template_get_node and class_name == "Node":
  825. result.append("\ttemplate<class T>")
  826. result.append(
  827. "\tT *get_node(const NodePath &p_path) const { return Object::cast_to<T>(get_node_internal(p_path)); }"
  828. )
  829. result.append("")
  830. result.append("};")
  831. result.append("")
  832. result.append("} // namespace godot")
  833. result.append("")
  834. if "enums" in class_api and class_name != "Object":
  835. for enum_api in class_api["enums"]:
  836. result.append(f'VARIANT_ENUM_CAST({class_name}, {class_name}::{enum_api["name"]});')
  837. result.append("")
  838. result.append(f"#endif // ! {header_guard}")
  839. return "\n".join(result)
  840. def generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node):
  841. global singletons
  842. result = []
  843. class_name = class_api["name"]
  844. snake_class_name = camel_to_snake(class_name)
  845. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  846. is_singleton = class_name in singletons
  847. add_header(f"{snake_class_name}.cpp", result)
  848. result.append(f"#include <godot_cpp/classes/{snake_class_name}.hpp>")
  849. result.append("")
  850. result.append(f"#include <godot_cpp/core/engine_ptrcall.hpp>")
  851. result.append(f"#include <godot_cpp/core/error_macros.hpp>")
  852. result.append("")
  853. for included in used_classes:
  854. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  855. if len(used_classes) > 0:
  856. result.append(f"")
  857. result.append("namespace godot {")
  858. result.append("")
  859. if is_singleton:
  860. result.append(f"{class_name} *{class_name}::get_singleton() {{")
  861. result.append(
  862. f'\tstatic GDNativeObjectPtr singleton_obj = internal::gdn_interface->global_get_singleton("{class_name}");'
  863. )
  864. result.append("#ifdef DEBUG_ENABLED")
  865. result.append("\tERR_FAIL_COND_V(singleton_obj == nullptr, nullptr);")
  866. result.append("#endif // DEBUG_ENABLED")
  867. result.append(
  868. f"\tstatic {class_name} *singleton = reinterpret_cast<{class_name} *>(internal::gdn_interface->object_get_instance_binding(singleton_obj, internal::token, &{class_name}::___binding_callbacks));"
  869. )
  870. result.append("\treturn singleton;")
  871. result.append("}")
  872. result.append("")
  873. if "methods" in class_api:
  874. for method in class_api["methods"]:
  875. if method["is_virtual"]:
  876. # Will be done later
  877. continue
  878. vararg = "is_vararg" in method and method["is_vararg"]
  879. # Method signature.
  880. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  881. result.append(method_signature + " {")
  882. # Method body.
  883. result.append(
  884. f'\tstatic GDNativeMethodBindPtr ___method_bind = internal::gdn_interface->classdb_get_method_bind("{class_name}", "{method["name"]}", {method["hash"]});'
  885. )
  886. method_call = "\t"
  887. has_return = "return_value" in method and method["return_value"]["type"] != "void"
  888. if has_return:
  889. result.append(
  890. f'\tCHECK_METHOD_BIND_RET(___method_bind, {get_default_value_for_type(method["return_value"]["type"])});'
  891. )
  892. else:
  893. result.append(f"\tCHECK_METHOD_BIND(___method_bind);")
  894. is_ref = False
  895. if not vararg:
  896. if has_return:
  897. return_type = method["return_value"]["type"]
  898. meta_type = method["return_value"]["meta"] if "meta" in method["return_value"] else None
  899. if is_pod_type(return_type) or is_variant(return_type) or is_enum(return_type):
  900. method_call += f"return internal::_call_native_mb_ret<{get_gdnative_type(correct_type(return_type, meta_type))}>(___method_bind, _owner"
  901. elif is_refcounted(return_type):
  902. method_call += f"return Ref<{return_type}>::___internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, _owner"
  903. is_ref = True
  904. else:
  905. method_call += f"return internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, _owner"
  906. else:
  907. method_call += f"internal::_call_native_mb_no_ret(___method_bind, _owner"
  908. if "arguments" in method:
  909. method_call += ", "
  910. arguments = []
  911. for argument in method["arguments"]:
  912. (encode, arg_name) = get_encoded_arg(
  913. argument["name"],
  914. argument["type"],
  915. argument["meta"] if "meta" in argument else None,
  916. )
  917. result += encode
  918. arguments.append(arg_name)
  919. method_call += ", ".join(arguments)
  920. else: # vararg.
  921. result.append("\tGDNativeCallError error;")
  922. result.append("\tVariant ret;")
  923. method_call += "internal::gdn_interface->object_method_bind_call(___method_bind, _owner, (const GDNativeVariantPtr *)args, arg_count, &ret, &error"
  924. if is_ref:
  925. method_call += ")" # Close Ref<> constructor.
  926. method_call += ");"
  927. result.append(method_call)
  928. if vararg and ("return_value" in method and method["return_value"]["type"] != "void"):
  929. result.append("\treturn ret;")
  930. result.append("}")
  931. result.append("")
  932. # Virtuals now.
  933. for method in class_api["methods"]:
  934. if not method["is_virtual"]:
  935. continue
  936. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  937. method_signature += " {"
  938. if "return_value" in method and correct_type(method["return_value"]["type"]) != "void":
  939. result.append(method_signature)
  940. result.append(f'\treturn {get_default_value_for_type(method["return_value"]["type"])};')
  941. result.append("}")
  942. else:
  943. method_signature += "}"
  944. result.append(method_signature)
  945. result.append("")
  946. result.append("")
  947. result.append("} // namespace godot ")
  948. return "\n".join(result)
  949. def generate_global_constants(api, output_dir):
  950. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  951. source_gen_folder = Path(output_dir) / "src" / "classes"
  952. include_gen_folder.mkdir(parents=True, exist_ok=True)
  953. source_gen_folder.mkdir(parents=True, exist_ok=True)
  954. # Generate header
  955. header = []
  956. add_header("global_constants.hpp", header)
  957. header_filename = include_gen_folder / "global_constants.hpp"
  958. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_HPP"
  959. header.append(f"#ifndef {header_guard}")
  960. header.append(f"#define {header_guard}")
  961. header.append("")
  962. header.append("namespace godot {")
  963. header.append("")
  964. for constant in api["global_constants"]:
  965. header.append(f'\tconst int {escape_identifier(constant["name"])} = {constant["value"]};')
  966. header.append("")
  967. for enum_def in api["global_enums"]:
  968. if enum_def["name"].startswith("Variant."):
  969. continue
  970. header.append(f'\tenum {enum_def["name"]} {{')
  971. for value in enum_def["values"]:
  972. header.append(f'\t\t{value["name"]} = {value["value"]},')
  973. header.append("\t};")
  974. header.append("")
  975. header.append("} // namespace godot")
  976. header.append("")
  977. header.append(f"#endif // ! {header_guard}")
  978. with header_filename.open("w+") as header_file:
  979. header_file.write("\n".join(header))
  980. def generate_global_constant_binds(api, output_dir):
  981. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  982. source_gen_folder = Path(output_dir) / "src" / "classes"
  983. include_gen_folder.mkdir(parents=True, exist_ok=True)
  984. source_gen_folder.mkdir(parents=True, exist_ok=True)
  985. # Generate header
  986. header = []
  987. add_header("global_constants_binds.hpp", header)
  988. header_filename = include_gen_folder / "global_constants_binds.hpp"
  989. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_BINDS_HPP"
  990. header.append(f"#ifndef {header_guard}")
  991. header.append(f"#define {header_guard}")
  992. header.append("")
  993. header.append("#include <godot_cpp/classes/global_constants.hpp>")
  994. header.append("#include <godot_cpp/core/binder_common.hpp>")
  995. header.append("")
  996. for enum_def in api["global_enums"]:
  997. if enum_def["name"].startswith("Variant."):
  998. continue
  999. header.append(f'VARIANT_ENUM_CAST(, godot::{enum_def["name"]});')
  1000. header.append("")
  1001. header.append(f"#endif // ! {header_guard}")
  1002. with header_filename.open("w+") as header_file:
  1003. header_file.write("\n".join(header))
  1004. def generate_utility_functions(api, output_dir):
  1005. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  1006. source_gen_folder = Path(output_dir) / "src" / "variant"
  1007. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1008. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1009. # Generate header.
  1010. header = []
  1011. add_header("utility_functions.hpp", header)
  1012. header_filename = include_gen_folder / "utility_functions.hpp"
  1013. header_guard = "GODOT_CPP_UTILITY_FUNCTIONS_HPP"
  1014. header.append(f"#ifndef {header_guard}")
  1015. header.append(f"#define {header_guard}")
  1016. header.append("")
  1017. header.append("#include <godot_cpp/variant/builtin_types.hpp>")
  1018. header.append("#include <godot_cpp/variant/variant.hpp>")
  1019. header.append("")
  1020. header.append("#include <array>")
  1021. header.append("")
  1022. header.append("namespace godot {")
  1023. header.append("")
  1024. header.append("class UtilityFunctions {")
  1025. header.append("public:")
  1026. for function in api["utility_functions"]:
  1027. vararg = "is_vararg" in function and function["is_vararg"]
  1028. function_signature = "\t"
  1029. function_signature += make_signature("UtilityFunctions", function, for_header=True, static=True)
  1030. header.append(function_signature + ";")
  1031. if vararg:
  1032. # Add templated version.
  1033. header += make_varargs_template(function, static=True)
  1034. header.append("};")
  1035. header.append("")
  1036. header.append("} // namespace godot")
  1037. header.append("")
  1038. header.append(f"#endif // ! {header_guard}")
  1039. with header_filename.open("w+") as header_file:
  1040. header_file.write("\n".join(header))
  1041. # Generate source.
  1042. source = []
  1043. add_header("utility_functions.cpp", source)
  1044. source_filename = source_gen_folder / "utility_functions.cpp"
  1045. source.append("#include <godot_cpp/variant/utility_functions.hpp>")
  1046. source.append("")
  1047. source.append("#include <godot_cpp/core/error_macros.hpp>")
  1048. source.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  1049. source.append("")
  1050. source.append("namespace godot {")
  1051. source.append("")
  1052. for function in api["utility_functions"]:
  1053. vararg = "is_vararg" in function and function["is_vararg"]
  1054. function_signature = make_signature("UtilityFunctions", function)
  1055. source.append(function_signature + " {")
  1056. # Function body.
  1057. source.append(
  1058. f'\tstatic GDNativePtrUtilityFunction ___function = internal::gdn_interface->variant_get_ptr_utility_function("{function["name"]}", {function["hash"]});'
  1059. )
  1060. has_return = "return_type" in function and function["return_type"] != "void"
  1061. if has_return:
  1062. source.append(
  1063. f'\tCHECK_METHOD_BIND_RET(___function, {get_default_value_for_type(function["return_type"])});'
  1064. )
  1065. else:
  1066. source.append(f"\tCHECK_METHOD_BIND(___function);")
  1067. function_call = "\t"
  1068. if not vararg:
  1069. if has_return:
  1070. function_call += "return "
  1071. if function["return_type"] == "Object":
  1072. function_call += "internal::_call_utility_ret_obj(___function"
  1073. else:
  1074. function_call += f'internal::_call_utility_ret<{get_gdnative_type(correct_type(function["return_type"]))}>(___function'
  1075. else:
  1076. function_call += "internal::_call_utility_no_ret(___function"
  1077. if "arguments" in function:
  1078. function_call += ", "
  1079. arguments = []
  1080. for argument in function["arguments"]:
  1081. (encode, arg_name) = get_encoded_arg(
  1082. argument["name"],
  1083. argument["type"],
  1084. argument["meta"] if "meta" in argument else None,
  1085. )
  1086. source += encode
  1087. arguments.append(arg_name)
  1088. function_call += ", ".join(arguments)
  1089. else:
  1090. source.append("\tVariant ret;")
  1091. function_call += "___function(&ret, (const GDNativeVariantPtr *)args, arg_count"
  1092. function_call += ");"
  1093. source.append(function_call)
  1094. if vararg and has_return:
  1095. source.append("\treturn ret;")
  1096. source.append("}")
  1097. source.append("")
  1098. source.append("} // namespace godot")
  1099. with source_filename.open("w+") as source_file:
  1100. source_file.write("\n".join(source))
  1101. # Helper functions.
  1102. def camel_to_snake(name):
  1103. name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
  1104. name = re.sub("([a-z0-9])([A-Z])", r"\1_\2", name)
  1105. return name.replace("2_D", "2D").replace("3_D", "3D").lower()
  1106. def make_function_parameters(parameters, include_default=False, for_builtin=False, is_vararg=False):
  1107. signature = []
  1108. for index, par in enumerate(parameters):
  1109. parameter = type_for_parameter(par["type"], par["meta"] if "meta" in par else None)
  1110. parameter_name = escape_identifier(par["name"])
  1111. if len(parameter_name) == 0:
  1112. parameter_name = "arg_" + str(index + 1)
  1113. parameter += parameter_name
  1114. if include_default and "default_value" in par and (not for_builtin or par["type"] != "Variant"):
  1115. parameter += " = "
  1116. if is_enum(par["type"]):
  1117. parameter_type = correct_type(par["type"])
  1118. if parameter_type == "void":
  1119. parameter_type = "Variant"
  1120. parameter += f"({parameter_type})"
  1121. parameter += correct_default_value(par["default_value"], par["type"])
  1122. signature.append(parameter)
  1123. if is_vararg:
  1124. signature.append("const Args&... args")
  1125. return ", ".join(signature)
  1126. def type_for_parameter(type_name, meta=None):
  1127. if type_name == "void":
  1128. return "Variant "
  1129. elif is_pod_type(type_name) and type_name != "Nil" or is_enum(type_name):
  1130. return f"{correct_type(type_name, meta)} "
  1131. elif is_variant(type_name) or is_refcounted(type_name):
  1132. return f"const {correct_type(type_name)} &"
  1133. else:
  1134. return f"{correct_type(type_name)}"
  1135. def get_include_path(type_name):
  1136. base_dir = ""
  1137. if type_name == "Object":
  1138. base_dir = "core"
  1139. elif is_variant(type_name):
  1140. base_dir = "variant"
  1141. else:
  1142. base_dir = "classes"
  1143. return f"{base_dir}/{camel_to_snake(type_name)}.hpp"
  1144. def get_encoded_arg(arg_name, type_name, type_meta):
  1145. result = []
  1146. name = escape_identifier(arg_name)
  1147. arg_type = correct_type(type_name)
  1148. if is_pod_type(arg_type):
  1149. result.append(f"\t{get_gdnative_type(arg_type)} {name}_encoded;")
  1150. result.append(f"\tPtrToArg<{correct_type(type_name)}>::encode({name}, &{name}_encoded);")
  1151. name = f"&{name}_encoded"
  1152. elif is_engine_class(type_name):
  1153. name = f"{name}->_owner"
  1154. else:
  1155. name = f"&{name}"
  1156. return (result, name)
  1157. def make_signature(
  1158. class_name, function_data, for_header=False, use_template_get_node=True, for_builtin=False, static=False
  1159. ):
  1160. function_signature = ""
  1161. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1162. if for_header:
  1163. if "is_virtual" in function_data and function_data["is_virtual"]:
  1164. function_signature += "virtual "
  1165. if is_vararg:
  1166. function_signature += "private: "
  1167. if static:
  1168. function_signature += "static "
  1169. return_type = "void"
  1170. return_meta = None
  1171. if "return_type" in function_data:
  1172. return_type = correct_type(function_data["return_type"])
  1173. elif "return_value" in function_data:
  1174. return_type = function_data["return_value"]["type"]
  1175. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1176. function_signature += correct_type(
  1177. return_type,
  1178. return_meta,
  1179. )
  1180. if not function_signature.endswith("*"):
  1181. function_signature += " "
  1182. if not for_header:
  1183. function_signature += f"{class_name}::"
  1184. function_signature += escape_identifier(function_data["name"])
  1185. if is_vararg or (
  1186. not for_builtin and use_template_get_node and class_name == "Node" and function_data["name"] == "get_node"
  1187. ):
  1188. function_signature += "_internal"
  1189. function_signature += "("
  1190. arguments = function_data["arguments"] if "arguments" in function_data else []
  1191. if not is_vararg:
  1192. function_signature += make_function_parameters(arguments, for_header, for_builtin, is_vararg)
  1193. else:
  1194. function_signature += "const Variant **args, GDNativeInt arg_count"
  1195. function_signature += ")"
  1196. if "is_const" in function_data and function_data["is_const"]:
  1197. function_signature += " const"
  1198. return function_signature
  1199. def make_varargs_template(function_data, static=False):
  1200. result = []
  1201. function_signature = "\tpublic: template<class... Args> "
  1202. if static:
  1203. function_signature += "static "
  1204. return_type = "void"
  1205. return_meta = None
  1206. if "return_type" in function_data:
  1207. return_type = correct_type(function_data["return_type"])
  1208. elif "return_value" in function_data:
  1209. return_type = function_data["return_value"]["type"]
  1210. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1211. function_signature += correct_type(
  1212. return_type,
  1213. return_meta,
  1214. )
  1215. if not function_signature.endswith("*"):
  1216. function_signature += " "
  1217. function_signature += f'{escape_identifier(function_data["name"])}'
  1218. method_arguments = []
  1219. if "arguments" in function_data:
  1220. method_arguments = function_data["arguments"]
  1221. function_signature += "("
  1222. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1223. function_signature += make_function_parameters(method_arguments, include_default=True, is_vararg=is_vararg)
  1224. function_signature += ")"
  1225. if "is_const" in function_data and function_data["is_const"]:
  1226. function_signature += " const"
  1227. function_signature += " {"
  1228. result.append(function_signature)
  1229. args_array = f"\t\tstd::array<Variant, {len(method_arguments)} + sizeof...(Args)> variant_args {{ "
  1230. for argument in method_arguments:
  1231. if argument["type"] == "Variant":
  1232. args_array += argument["name"]
  1233. else:
  1234. args_array += f'Variant({argument["name"]})'
  1235. args_array += ", "
  1236. args_array += "Variant(args)... };"
  1237. result.append(args_array)
  1238. result.append(f"\t\tstd::array<const Variant *, {len(method_arguments)} + sizeof...(Args)> call_args;")
  1239. result.append("\t\tfor(size_t i = 0; i < variant_args.size(); i++) {")
  1240. result.append("\t\t\tcall_args[i] = &variant_args[i];")
  1241. result.append("\t\t}")
  1242. call_line = "\t\t"
  1243. if return_type != "void":
  1244. call_line += "return "
  1245. call_line += f'{escape_identifier(function_data["name"])}_internal(call_args.data(), variant_args.size());'
  1246. result.append(call_line)
  1247. result.append("\t}")
  1248. return result
  1249. # Engine idiosyncrasies.
  1250. def is_pod_type(type_name):
  1251. """
  1252. Those are types for which no class should be generated.
  1253. """
  1254. return type_name in [
  1255. "Nil",
  1256. "void",
  1257. "bool",
  1258. "real_t",
  1259. "float",
  1260. "double",
  1261. "int",
  1262. "int8_t",
  1263. "uint8_t",
  1264. "int16_t",
  1265. "uint16_t",
  1266. "int32_t",
  1267. "int64_t",
  1268. "uint32_t",
  1269. "uint64_t",
  1270. ]
  1271. def is_included_type(type_name):
  1272. """
  1273. Those are types for which we already have a class file implemented.
  1274. """
  1275. return type_name in [
  1276. "AABB",
  1277. "Basis",
  1278. "Color",
  1279. "ObjectID",
  1280. "Plane",
  1281. "Quaternion",
  1282. "Rect2",
  1283. "Rect2i",
  1284. "Transform2D",
  1285. "Transform3D",
  1286. "Vector2",
  1287. "Vector2i",
  1288. "Vector3",
  1289. "Vector3i",
  1290. ]
  1291. def is_packed_array(type_name):
  1292. """
  1293. Those are types for which we add our extra packed array functions.
  1294. """
  1295. return type_name in [
  1296. "PackedByteArray",
  1297. "PackedColorArray",
  1298. "PackedFloat32Array",
  1299. "PackedFloat64Array",
  1300. "PackedInt32Array",
  1301. "PackedInt64Array",
  1302. "PackedStringArray",
  1303. "PackedVector2Array",
  1304. "PackedVector3Array",
  1305. ]
  1306. def needs_copy_instead_of_move(type_name):
  1307. """
  1308. Those are types which need initialised data or we'll get warning spam so need a copy instead of move.
  1309. """
  1310. return type_name in [
  1311. "Dictionary",
  1312. ]
  1313. def is_enum(type_name):
  1314. return type_name.startswith("enum::")
  1315. def get_enum_class(enum_name: str):
  1316. if "." in enum_name:
  1317. return enum_name.replace("enum::", "").split(".")[0]
  1318. else:
  1319. return "GlobalConstants"
  1320. def get_enum_name(enum_name: str):
  1321. return enum_name.replace("enum::", "").split(".")[-1]
  1322. def is_variant(type_name):
  1323. return type_name == "Variant" or type_name in builtin_classes or type_name == "Nil"
  1324. def is_engine_class(type_name):
  1325. global engine_classes
  1326. return type_name == "Object" or type_name in engine_classes
  1327. def is_refcounted(type_name):
  1328. return type_name in engine_classes and engine_classes[type_name]
  1329. def is_included(type_name, current_type):
  1330. """
  1331. Check if a builtin type should be included.
  1332. This removes Variant and POD types from inclusion, and the current type.
  1333. """
  1334. to_include = get_enum_class(type_name) if is_enum(type_name) else type_name
  1335. if to_include == current_type or is_pod_type(to_include):
  1336. return False
  1337. if to_include == "GlobalConstants" or to_include == "UtilityFunctions":
  1338. return True
  1339. return is_engine_class(to_include) or is_variant(to_include)
  1340. def correct_default_value(value, type_name):
  1341. value_map = {
  1342. "null": "nullptr",
  1343. '""': "String()",
  1344. '&""': "StringName()",
  1345. "[]": "Array()",
  1346. "{}": "Dictionary()",
  1347. "Transform2D(1, 0, 0, 1, 0, 0)": "Transform2D()", # Default transform.
  1348. "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)": "Transform3D()", # Default transform.
  1349. }
  1350. if value in value_map:
  1351. return value_map[value]
  1352. if value == "":
  1353. return f"{type_name}()"
  1354. return value
  1355. def correct_type(type_name, meta=None):
  1356. type_conversion = {"float": "double", "int": "int64_t", "Nil": "Variant"}
  1357. if meta != None:
  1358. if "int" in meta:
  1359. return f"{meta}_t"
  1360. elif meta in type_conversion:
  1361. return type_conversion[type_name]
  1362. else:
  1363. return meta
  1364. if type_name in type_conversion:
  1365. return type_conversion[type_name]
  1366. if is_enum(type_name):
  1367. base_class = get_enum_class(type_name)
  1368. if base_class == "GlobalConstants":
  1369. return f"{get_enum_name(type_name)}"
  1370. return f"{base_class}::{get_enum_name(type_name)}"
  1371. if is_refcounted(type_name):
  1372. return f"Ref<{type_name}>"
  1373. if type_name == "Object" or is_engine_class(type_name):
  1374. return f"{type_name} *"
  1375. if type_name.endswith("*"):
  1376. return f"{type_name[:-1]} *"
  1377. return type_name
  1378. def get_gdnative_type(type_name):
  1379. type_conversion_map = {
  1380. "bool": "int8_t",
  1381. "uint8_t": "int64_t",
  1382. "int8_t": "int64_t",
  1383. "uint16_t": "int64_t",
  1384. "int16_t": "int64_t",
  1385. "uint32_t": "int64_t",
  1386. "int32_t": "int64_t",
  1387. "int": "int64_t",
  1388. "float": "double",
  1389. }
  1390. if type_name in type_conversion_map:
  1391. return type_conversion_map[type_name]
  1392. return type_name
  1393. def escape_identifier(id):
  1394. cpp_keywords_map = {
  1395. "class": "_class",
  1396. "char": "_char",
  1397. "short": "_short",
  1398. "bool": "_bool",
  1399. "int": "_int",
  1400. "default": "_default",
  1401. "case": "_case",
  1402. "switch": "_switch",
  1403. "export": "_export",
  1404. "template": "_template",
  1405. "new": "new_",
  1406. "operator": "_operator",
  1407. "typeof": "type_of",
  1408. "typename": "type_name",
  1409. }
  1410. if id in cpp_keywords_map:
  1411. return cpp_keywords_map[id]
  1412. return id
  1413. def get_operator_id_name(op):
  1414. op_id_map = {
  1415. "==": "equal",
  1416. "!=": "not_equal",
  1417. "<": "less",
  1418. "<=": "less_equal",
  1419. ">": "greater",
  1420. ">=": "greater_equal",
  1421. "+": "add",
  1422. "-": "subtract",
  1423. "*": "multiply",
  1424. "/": "divide",
  1425. "unary-": "negate",
  1426. "unary+": "positive",
  1427. "%": "module",
  1428. "<<": "shift_left",
  1429. ">>": "shift_right",
  1430. "&": "bit_and",
  1431. "|": "bit_or",
  1432. "^": "bit_xor",
  1433. "~": "bit_negate",
  1434. "and": "and",
  1435. "or": "or",
  1436. "xor": "xor",
  1437. "not": "not",
  1438. "and": "and",
  1439. "in": "in",
  1440. }
  1441. return op_id_map[op]
  1442. def get_default_value_for_type(type_name):
  1443. if type_name == "int":
  1444. return "0"
  1445. if type_name == "float":
  1446. return "0.0"
  1447. if type_name == "bool":
  1448. return "false"
  1449. if is_enum(type_name):
  1450. return f"{correct_type(type_name)}(0)"
  1451. if is_variant(type_name):
  1452. return f"{type_name}()"
  1453. if is_refcounted(type_name):
  1454. return f"Ref<{type_name}>()"
  1455. return "nullptr"
  1456. header = """\
  1457. /*************************************************************************/
  1458. /* $filename */
  1459. /*************************************************************************/
  1460. /* This file is part of: */
  1461. /* GODOT ENGINE */
  1462. /* https://godotengine.org */
  1463. /*************************************************************************/
  1464. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  1465. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  1466. /* */
  1467. /* Permission is hereby granted, free of charge, to any person obtaining */
  1468. /* a copy of this software and associated documentation files (the */
  1469. /* "Software"), to deal in the Software without restriction, including */
  1470. /* without limitation the rights to use, copy, modify, merge, publish, */
  1471. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1472. /* permit persons to whom the Software is furnished to do so, subject to */
  1473. /* the following conditions: */
  1474. /* */
  1475. /* The above copyright notice and this permission notice shall be */
  1476. /* included in all copies or substantial portions of the Software. */
  1477. /* */
  1478. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1479. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1480. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  1481. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1482. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1483. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1484. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1485. /*************************************************************************/
  1486. """
  1487. def add_header(filename, lines):
  1488. desired_length = len(header.split("\n")[0])
  1489. pad_spaces = desired_length - 6 - len(filename)
  1490. for num, line in enumerate(header.split("\n")):
  1491. if num == 1:
  1492. new_line = f"/* {filename}{' ' * pad_spaces}*/"
  1493. lines.append(new_line)
  1494. else:
  1495. lines.append(line)
  1496. lines.append("// THIS FILE IS GENERATED. EDITS WILL BE LOST.")
  1497. lines.append("")