bindings_generator.cpp 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453
  1. /*************************************************************************/
  2. /* bindings_generator.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "bindings_generator.h"
  31. #ifdef DEBUG_METHODS_ENABLED
  32. #include "core/engine.h"
  33. #include "core/global_constants.h"
  34. #include "core/io/compression.h"
  35. #include "core/os/dir_access.h"
  36. #include "core/os/file_access.h"
  37. #include "core/os/os.h"
  38. #include "core/ucaps.h"
  39. #include "../glue/cs_compressed.gen.h"
  40. #include "../glue/cs_glue_version.gen.h"
  41. #include "../godotsharp_defs.h"
  42. #include "../mono_gd/gd_mono_marshal.h"
  43. #include "../utils/path_utils.h"
  44. #include "../utils/string_utils.h"
  45. #include "csharp_project.h"
  46. #define CS_INDENT " " // 4 whitespaces
  47. #define INDENT1 CS_INDENT
  48. #define INDENT2 INDENT1 INDENT1
  49. #define INDENT3 INDENT2 INDENT1
  50. #define INDENT4 INDENT3 INDENT1
  51. #define INDENT5 INDENT4 INDENT1
  52. #define MEMBER_BEGIN "\n" INDENT2
  53. #define OPEN_BLOCK "{\n"
  54. #define CLOSE_BLOCK "}\n"
  55. #define OPEN_BLOCK_L2 INDENT2 OPEN_BLOCK INDENT3
  56. #define OPEN_BLOCK_L3 INDENT3 OPEN_BLOCK INDENT4
  57. #define OPEN_BLOCK_L4 INDENT4 OPEN_BLOCK INDENT5
  58. #define CLOSE_BLOCK_L2 INDENT2 CLOSE_BLOCK
  59. #define CLOSE_BLOCK_L3 INDENT3 CLOSE_BLOCK
  60. #define CLOSE_BLOCK_L4 INDENT4 CLOSE_BLOCK
  61. #define CS_FIELD_MEMORYOWN "memoryOwn"
  62. #define CS_PARAM_METHODBIND "method"
  63. #define CS_PARAM_INSTANCE "ptr"
  64. #define CS_SMETHOD_GETINSTANCE "GetPtr"
  65. #define CS_METHOD_CALL "Call"
  66. #define GLUE_HEADER_FILE "glue_header.h"
  67. #define ICALL_PREFIX "godot_icall_"
  68. #define SINGLETON_ICALL_SUFFIX "_get_singleton"
  69. #define ICALL_GET_METHODBIND ICALL_PREFIX "Object_ClassDB_get_method"
  70. #define C_LOCAL_RET "ret"
  71. #define C_LOCAL_PTRCALL_ARGS "call_args"
  72. #define C_MACRO_OBJECT_CONSTRUCT "GODOTSHARP_INSTANCE_OBJECT"
  73. #define C_NS_MONOUTILS "GDMonoUtils"
  74. #define C_NS_MONOINTERNALS "GDMonoInternals"
  75. #define C_METHOD_TIE_MANAGED_TO_UNMANAGED C_NS_MONOINTERNALS "::tie_managed_to_unmanaged"
  76. #define C_METHOD_UNMANAGED_GET_MANAGED C_NS_MONOUTILS "::unmanaged_get_managed"
  77. #define C_NS_MONOMARSHAL "GDMonoMarshal"
  78. #define C_METHOD_MANAGED_TO_VARIANT C_NS_MONOMARSHAL "::mono_object_to_variant"
  79. #define C_METHOD_MANAGED_FROM_VARIANT C_NS_MONOMARSHAL "::variant_to_mono_object"
  80. #define C_METHOD_MONOSTR_TO_GODOT C_NS_MONOMARSHAL "::mono_string_to_godot"
  81. #define C_METHOD_MONOSTR_FROM_GODOT C_NS_MONOMARSHAL "::mono_string_from_godot"
  82. #define C_METHOD_MONOARRAY_TO(m_type) C_NS_MONOMARSHAL "::mono_array_to_" #m_type
  83. #define C_METHOD_MONOARRAY_FROM(m_type) C_NS_MONOMARSHAL "::" #m_type "_to_mono_array"
  84. #define BINDINGS_GENERATOR_VERSION UINT32_C(5)
  85. const char *BindingsGenerator::TypeInterface::DEFAULT_VARARG_C_IN = "\t%0 %1_in = %1;\n";
  86. bool BindingsGenerator::verbose_output = false;
  87. BindingsGenerator *BindingsGenerator::singleton = NULL;
  88. static String snake_to_pascal_case(const String &p_identifier, bool p_input_is_upper = false) {
  89. String ret;
  90. Vector<String> parts = p_identifier.split("_", true);
  91. for (int i = 0; i < parts.size(); i++) {
  92. String part = parts[i];
  93. if (part.length()) {
  94. part[0] = _find_upper(part[0]);
  95. if (p_input_is_upper) {
  96. for (int j = 1; j < part.length(); j++)
  97. part[j] = _find_lower(part[j]);
  98. }
  99. ret += part;
  100. } else {
  101. if (i == 0 || i == (parts.size() - 1)) {
  102. // Preserve underscores at the beginning and end
  103. ret += "_";
  104. } else {
  105. // Preserve contiguous underscores
  106. if (parts[i - 1].length()) {
  107. ret += "__";
  108. } else {
  109. ret += "_";
  110. }
  111. }
  112. }
  113. }
  114. return ret;
  115. }
  116. static String snake_to_camel_case(const String &p_identifier, bool p_input_is_upper = false) {
  117. String ret;
  118. Vector<String> parts = p_identifier.split("_", true);
  119. for (int i = 0; i < parts.size(); i++) {
  120. String part = parts[i];
  121. if (part.length()) {
  122. if (i != 0) {
  123. part[0] = _find_upper(part[0]);
  124. }
  125. if (p_input_is_upper) {
  126. for (int j = i != 0 ? 1 : 0; j < part.length(); j++)
  127. part[j] = _find_lower(part[j]);
  128. }
  129. ret += part;
  130. } else {
  131. if (i == 0 || i == (parts.size() - 1)) {
  132. // Preserve underscores at the beginning and end
  133. ret += "_";
  134. } else {
  135. // Preserve contiguous underscores
  136. if (parts[i - 1].length()) {
  137. ret += "__";
  138. } else {
  139. ret += "_";
  140. }
  141. }
  142. }
  143. }
  144. return ret;
  145. }
  146. int BindingsGenerator::_determine_enum_prefix(const EnumInterface &p_ienum) {
  147. CRASH_COND(p_ienum.constants.empty());
  148. const ConstantInterface &front_iconstant = p_ienum.constants.front()->get();
  149. Vector<String> front_parts = front_iconstant.name.split("_", /* p_allow_empty: */ true);
  150. int candidate_len = front_parts.size() - 1;
  151. if (candidate_len == 0)
  152. return 0;
  153. for (const List<ConstantInterface>::Element *E = p_ienum.constants.front()->next(); E; E = E->next()) {
  154. const ConstantInterface &iconstant = E->get();
  155. Vector<String> parts = iconstant.name.split("_", /* p_allow_empty: */ true);
  156. int i;
  157. for (i = 0; i < candidate_len && i < parts.size(); i++) {
  158. if (front_parts[i] != parts[i]) {
  159. // HARDCODED: Some Flag enums have the prefix 'FLAG_' for everything except 'FLAGS_DEFAULT' (same for 'METHOD_FLAG_' and'METHOD_FLAGS_DEFAULT').
  160. bool hardcoded_exc = (i == candidate_len - 1 && ((front_parts[i] == "FLAGS" && parts[i] == "FLAG") || (front_parts[i] == "FLAG" && parts[i] == "FLAGS")));
  161. if (!hardcoded_exc)
  162. break;
  163. }
  164. }
  165. candidate_len = i;
  166. if (candidate_len == 0)
  167. return 0;
  168. }
  169. return candidate_len;
  170. }
  171. void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumInterface &p_ienum, int p_prefix_length) {
  172. if (p_prefix_length > 0) {
  173. for (List<ConstantInterface>::Element *E = p_ienum.constants.front(); E; E = E->next()) {
  174. int curr_prefix_length = p_prefix_length;
  175. ConstantInterface &curr_const = E->get();
  176. String constant_name = curr_const.name;
  177. Vector<String> parts = constant_name.split("_", /* p_allow_empty: */ true);
  178. if (parts.size() <= curr_prefix_length)
  179. continue;
  180. if (parts[curr_prefix_length][0] >= '0' && parts[curr_prefix_length][0] <= '9') {
  181. // The name of enum constants may begin with a numeric digit when strip from the enum prefix,
  182. // so we make the prefix for this constant one word shorter in those cases.
  183. for (curr_prefix_length = curr_prefix_length - 1; curr_prefix_length > 0; curr_prefix_length--) {
  184. if (parts[curr_prefix_length][0] < '0' || parts[curr_prefix_length][0] > '9')
  185. break;
  186. }
  187. }
  188. constant_name = "";
  189. for (int i = curr_prefix_length; i < parts.size(); i++) {
  190. if (i > curr_prefix_length)
  191. constant_name += "_";
  192. constant_name += parts[i];
  193. }
  194. curr_const.proxy_name = snake_to_pascal_case(constant_name, true);
  195. }
  196. }
  197. }
  198. void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) {
  199. for (const List<MethodInterface>::Element *E = p_itype.methods.front(); E; E = E->next()) {
  200. const MethodInterface &imethod = E->get();
  201. if (imethod.is_virtual)
  202. continue;
  203. const TypeInterface *return_type = _get_type_or_placeholder(imethod.return_type);
  204. String im_sig = "IntPtr " CS_PARAM_METHODBIND ", ";
  205. String im_unique_sig = imethod.return_type.cname.operator String() + ",IntPtr,IntPtr";
  206. im_sig += "IntPtr " CS_PARAM_INSTANCE;
  207. // Get arguments information
  208. int i = 0;
  209. for (const List<ArgumentInterface>::Element *F = imethod.arguments.front(); F; F = F->next()) {
  210. const TypeInterface *arg_type = _get_type_or_placeholder(F->get().type);
  211. im_sig += ", ";
  212. im_sig += arg_type->im_type_in;
  213. im_sig += " arg";
  214. im_sig += itos(i + 1);
  215. im_unique_sig += ",";
  216. im_unique_sig += get_unique_sig(*arg_type);
  217. i++;
  218. }
  219. // godot_icall_{argc}_{icallcount}
  220. String icall_method = ICALL_PREFIX;
  221. icall_method += itos(imethod.arguments.size());
  222. icall_method += "_";
  223. icall_method += itos(method_icalls.size());
  224. InternalCall im_icall = InternalCall(p_itype.api_type, icall_method, return_type->im_type_out, im_sig, im_unique_sig);
  225. List<InternalCall>::Element *match = method_icalls.find(im_icall);
  226. if (match) {
  227. if (p_itype.api_type != ClassDB::API_EDITOR)
  228. match->get().editor_only = false;
  229. method_icalls_map.insert(&E->get(), &match->get());
  230. } else {
  231. List<InternalCall>::Element *added = method_icalls.push_back(im_icall);
  232. method_icalls_map.insert(&E->get(), &added->get());
  233. }
  234. }
  235. }
  236. void BindingsGenerator::_generate_global_constants(List<String> &p_output) {
  237. // Constants (in partial GD class)
  238. p_output.push_back("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  239. p_output.push_back(INDENT1 "public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n" INDENT1 "{");
  240. for (const List<ConstantInterface>::Element *E = global_constants.front(); E; E = E->next()) {
  241. const ConstantInterface &iconstant = E->get();
  242. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  243. p_output.push_back(MEMBER_BEGIN "/// <summary>\n");
  244. Vector<String> description_lines = iconstant.const_doc->description.split("\n");
  245. for (int i = 0; i < description_lines.size(); i++) {
  246. String description_line = description_lines[i].strip_edges();
  247. if (description_line.size()) {
  248. p_output.push_back(INDENT2 "/// ");
  249. p_output.push_back(description_line.xml_escape());
  250. p_output.push_back("\n");
  251. }
  252. }
  253. p_output.push_back(INDENT2 "/// </summary>");
  254. }
  255. p_output.push_back(MEMBER_BEGIN "public const int ");
  256. p_output.push_back(iconstant.proxy_name);
  257. p_output.push_back(" = ");
  258. p_output.push_back(itos(iconstant.value));
  259. p_output.push_back(";");
  260. }
  261. if (!global_constants.empty())
  262. p_output.push_back("\n");
  263. p_output.push_back(INDENT1 CLOSE_BLOCK); // end of GD class
  264. // Enums
  265. for (List<EnumInterface>::Element *E = global_enums.front(); E; E = E->next()) {
  266. const EnumInterface &ienum = E->get();
  267. CRASH_COND(ienum.constants.empty());
  268. String enum_proxy_name = ienum.cname.operator String();
  269. bool enum_in_static_class = false;
  270. if (enum_proxy_name.find(".") > 0) {
  271. enum_in_static_class = true;
  272. String enum_class_name = enum_proxy_name.get_slicec('.', 0);
  273. enum_proxy_name = enum_proxy_name.get_slicec('.', 1);
  274. CRASH_COND(enum_class_name != "Variant"); // Hard-coded...
  275. if (verbose_output) {
  276. WARN_PRINTS("Declaring global enum `" + enum_proxy_name + "` inside static class `" + enum_class_name + "`");
  277. }
  278. p_output.push_back("\n" INDENT1 "public static partial class ");
  279. p_output.push_back(enum_class_name);
  280. p_output.push_back("\n" INDENT1 OPEN_BLOCK);
  281. }
  282. p_output.push_back("\n" INDENT1 "public enum ");
  283. p_output.push_back(enum_proxy_name);
  284. p_output.push_back("\n" INDENT1 OPEN_BLOCK);
  285. for (const List<ConstantInterface>::Element *E = ienum.constants.front(); E; E = E->next()) {
  286. const ConstantInterface &iconstant = E->get();
  287. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  288. p_output.push_back(INDENT2 "/// <summary>\n");
  289. Vector<String> description_lines = iconstant.const_doc->description.split("\n");
  290. for (int i = 0; i < description_lines.size(); i++) {
  291. String description_line = description_lines[i].strip_edges();
  292. if (description_line.size()) {
  293. p_output.push_back(INDENT2 "/// ");
  294. p_output.push_back(description_line.xml_escape());
  295. p_output.push_back("\n");
  296. }
  297. }
  298. p_output.push_back(INDENT2 "/// </summary>\n");
  299. }
  300. p_output.push_back(INDENT2);
  301. p_output.push_back(iconstant.proxy_name);
  302. p_output.push_back(" = ");
  303. p_output.push_back(itos(iconstant.value));
  304. p_output.push_back(E != ienum.constants.back() ? ",\n" : "\n");
  305. }
  306. p_output.push_back(INDENT1 CLOSE_BLOCK);
  307. if (enum_in_static_class)
  308. p_output.push_back(INDENT1 CLOSE_BLOCK);
  309. }
  310. p_output.push_back(CLOSE_BLOCK); // end of namespace
  311. }
  312. Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir, DotNetSolution &r_solution, bool p_verbose_output) {
  313. verbose_output = p_verbose_output;
  314. String proj_dir = p_solution_dir.plus_file(CORE_API_ASSEMBLY_NAME);
  315. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  316. ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
  317. if (!DirAccess::exists(proj_dir)) {
  318. Error err = da->make_dir_recursive(proj_dir);
  319. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  320. }
  321. da->change_dir(proj_dir);
  322. da->make_dir("Core");
  323. da->make_dir("ObjectType");
  324. String core_dir = path_join(proj_dir, "Core");
  325. String obj_type_dir = path_join(proj_dir, "ObjectType");
  326. Vector<String> compile_items;
  327. // Generate source file for global scope constants and enums
  328. {
  329. List<String> constants_source;
  330. _generate_global_constants(constants_source);
  331. String output_file = path_join(core_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_constants.cs");
  332. Error save_err = _save_file(output_file, constants_source);
  333. if (save_err != OK)
  334. return save_err;
  335. compile_items.push_back(output_file);
  336. }
  337. for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
  338. const TypeInterface &itype = E.get();
  339. if (itype.api_type == ClassDB::API_EDITOR)
  340. continue;
  341. String output_file = path_join(obj_type_dir, itype.proxy_name + ".cs");
  342. Error err = _generate_cs_type(itype, output_file);
  343. if (err == ERR_SKIP)
  344. continue;
  345. if (err != OK)
  346. return err;
  347. compile_items.push_back(output_file);
  348. }
  349. // Generate sources from compressed files
  350. Map<String, CompressedFile> compressed_files;
  351. get_compressed_files(compressed_files);
  352. for (Map<String, CompressedFile>::Element *E = compressed_files.front(); E; E = E->next()) {
  353. const String &file_name = E->key();
  354. const CompressedFile &file_data = E->value();
  355. String output_file = path_join(core_dir, file_name);
  356. Vector<uint8_t> data;
  357. data.resize(file_data.uncompressed_size);
  358. Compression::decompress(data.ptrw(), file_data.uncompressed_size, file_data.data, file_data.compressed_size, Compression::MODE_DEFLATE);
  359. String output_dir = output_file.get_base_dir();
  360. if (!DirAccess::exists(output_dir)) {
  361. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  362. ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
  363. Error err = da->make_dir_recursive(ProjectSettings::get_singleton()->globalize_path(output_dir));
  364. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  365. }
  366. FileAccessRef file = FileAccess::open(output_file, FileAccess::WRITE);
  367. ERR_FAIL_COND_V(!file, ERR_FILE_CANT_WRITE);
  368. file->store_buffer(data.ptr(), data.size());
  369. file->close();
  370. compile_items.push_back(output_file);
  371. }
  372. List<String> cs_icalls_content;
  373. cs_icalls_content.push_back("using System;\n"
  374. "using System.Runtime.CompilerServices;\n"
  375. "\n");
  376. cs_icalls_content.push_back("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  377. cs_icalls_content.push_back(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS "\n" INDENT1 OPEN_BLOCK);
  378. cs_icalls_content.push_back(MEMBER_BEGIN "internal static ulong godot_api_hash = ");
  379. cs_icalls_content.push_back(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + ";\n");
  380. cs_icalls_content.push_back(MEMBER_BEGIN "internal static uint bindings_version = ");
  381. cs_icalls_content.push_back(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n");
  382. cs_icalls_content.push_back(MEMBER_BEGIN "internal static uint cs_glue_version = ");
  383. cs_icalls_content.push_back(String::num_uint64(CS_GLUE_VERSION) + ";\n");
  384. #define ADD_INTERNAL_CALL(m_icall) \
  385. if (!m_icall.editor_only) { \
  386. cs_icalls_content.push_back(MEMBER_BEGIN "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \
  387. cs_icalls_content.push_back(INDENT2 "internal extern static "); \
  388. cs_icalls_content.push_back(m_icall.im_type_out + " "); \
  389. cs_icalls_content.push_back(m_icall.name + "("); \
  390. cs_icalls_content.push_back(m_icall.im_sig + ");\n"); \
  391. }
  392. for (const List<InternalCall>::Element *E = core_custom_icalls.front(); E; E = E->next())
  393. ADD_INTERNAL_CALL(E->get());
  394. for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next())
  395. ADD_INTERNAL_CALL(E->get());
  396. #undef ADD_INTERNAL_CALL
  397. cs_icalls_content.push_back(INDENT1 CLOSE_BLOCK CLOSE_BLOCK);
  398. String internal_methods_file = path_join(core_dir, BINDINGS_CLASS_NATIVECALLS ".cs");
  399. Error err = _save_file(internal_methods_file, cs_icalls_content);
  400. if (err != OK)
  401. return err;
  402. compile_items.push_back(internal_methods_file);
  403. String guid = CSharpProject::generate_core_api_project(proj_dir, compile_items);
  404. DotNetSolution::ProjectInfo proj_info;
  405. proj_info.guid = guid;
  406. proj_info.relpath = String(CORE_API_ASSEMBLY_NAME).plus_file(CORE_API_ASSEMBLY_NAME ".csproj");
  407. proj_info.configs.push_back("Debug");
  408. proj_info.configs.push_back("Release");
  409. r_solution.add_new_project(CORE_API_ASSEMBLY_NAME, proj_info);
  410. if (verbose_output)
  411. OS::get_singleton()->print("The solution and C# project for the Core API was generated successfully\n");
  412. return OK;
  413. }
  414. Error BindingsGenerator::generate_cs_editor_project(const String &p_solution_dir, DotNetSolution &r_solution, bool p_verbose_output) {
  415. verbose_output = p_verbose_output;
  416. String proj_dir = p_solution_dir.plus_file(EDITOR_API_ASSEMBLY_NAME);
  417. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  418. ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
  419. if (!DirAccess::exists(proj_dir)) {
  420. Error err = da->make_dir_recursive(proj_dir);
  421. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  422. }
  423. da->change_dir(proj_dir);
  424. da->make_dir("Core");
  425. da->make_dir("ObjectType");
  426. String core_dir = path_join(proj_dir, "Core");
  427. String obj_type_dir = path_join(proj_dir, "ObjectType");
  428. Vector<String> compile_items;
  429. for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
  430. const TypeInterface &itype = E.get();
  431. if (itype.api_type != ClassDB::API_EDITOR)
  432. continue;
  433. String output_file = path_join(obj_type_dir, itype.proxy_name + ".cs");
  434. Error err = _generate_cs_type(itype, output_file);
  435. if (err == ERR_SKIP)
  436. continue;
  437. if (err != OK)
  438. return err;
  439. compile_items.push_back(output_file);
  440. }
  441. List<String> cs_icalls_content;
  442. cs_icalls_content.push_back("using System;\n"
  443. "using System.Runtime.CompilerServices;\n"
  444. "\n");
  445. cs_icalls_content.push_back("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  446. cs_icalls_content.push_back(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS_EDITOR "\n" INDENT1 OPEN_BLOCK);
  447. cs_icalls_content.push_back(INDENT2 "internal static ulong godot_api_hash = ");
  448. cs_icalls_content.push_back(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + ";\n");
  449. cs_icalls_content.push_back(INDENT2 "internal static uint bindings_version = ");
  450. cs_icalls_content.push_back(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n");
  451. cs_icalls_content.push_back(INDENT2 "internal static uint cs_glue_version = ");
  452. cs_icalls_content.push_back(String::num_uint64(CS_GLUE_VERSION) + ";\n");
  453. cs_icalls_content.push_back("\n");
  454. #define ADD_INTERNAL_CALL(m_icall) \
  455. if (m_icall.editor_only) { \
  456. cs_icalls_content.push_back(INDENT2 "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \
  457. cs_icalls_content.push_back(INDENT2 "internal extern static "); \
  458. cs_icalls_content.push_back(m_icall.im_type_out + " "); \
  459. cs_icalls_content.push_back(m_icall.name + "("); \
  460. cs_icalls_content.push_back(m_icall.im_sig + ");\n"); \
  461. }
  462. for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next())
  463. ADD_INTERNAL_CALL(E->get());
  464. for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next())
  465. ADD_INTERNAL_CALL(E->get());
  466. #undef ADD_INTERNAL_CALL
  467. cs_icalls_content.push_back(INDENT1 CLOSE_BLOCK CLOSE_BLOCK);
  468. String internal_methods_file = path_join(core_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs");
  469. Error err = _save_file(internal_methods_file, cs_icalls_content);
  470. if (err != OK)
  471. return err;
  472. compile_items.push_back(internal_methods_file);
  473. String guid = CSharpProject::generate_editor_api_project(proj_dir, "../" CORE_API_ASSEMBLY_NAME "/" CORE_API_ASSEMBLY_NAME ".csproj", compile_items);
  474. DotNetSolution::ProjectInfo proj_info;
  475. proj_info.guid = guid;
  476. proj_info.relpath = String(EDITOR_API_ASSEMBLY_NAME).plus_file(EDITOR_API_ASSEMBLY_NAME ".csproj");
  477. proj_info.configs.push_back("Debug");
  478. proj_info.configs.push_back("Release");
  479. r_solution.add_new_project(EDITOR_API_ASSEMBLY_NAME, proj_info);
  480. if (verbose_output)
  481. OS::get_singleton()->print("The solution and C# project for the Editor API was generated successfully\n");
  482. return OK;
  483. }
  484. Error BindingsGenerator::generate_cs_api(const String &p_output_dir, bool p_verbose_output) {
  485. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  486. ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
  487. if (!DirAccess::exists(p_output_dir)) {
  488. Error err = da->make_dir_recursive(p_output_dir);
  489. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  490. }
  491. DotNetSolution solution(API_SOLUTION_NAME);
  492. if (!solution.set_path(p_output_dir))
  493. return ERR_FILE_NOT_FOUND;
  494. Error proj_err;
  495. proj_err = generate_cs_core_project(p_output_dir, solution, p_verbose_output);
  496. if (proj_err != OK) {
  497. ERR_PRINT("Generation of the Core API C# project failed");
  498. return proj_err;
  499. }
  500. proj_err = generate_cs_editor_project(p_output_dir, solution, p_verbose_output);
  501. if (proj_err != OK) {
  502. ERR_PRINT("Generation of the Editor API C# project failed");
  503. return proj_err;
  504. }
  505. Error sln_error = solution.save();
  506. if (sln_error != OK) {
  507. ERR_PRINT("Failed to save API solution");
  508. return sln_error;
  509. }
  510. return OK;
  511. }
  512. // FIXME: There are some members that hide other inherited members.
  513. // - In the case of both members being the same kind, the new one must be declared
  514. // explicitly as `new` to avoid the warning (and we must print a message about it).
  515. // - In the case of both members being of a different kind, then the new one must
  516. // be renamed to avoid the name collision (and we must print a warning about it).
  517. // - Csc warning e.g.:
  518. // ObjectType/LineEdit.cs(140,38): warning CS0108: 'LineEdit.FocusMode' hides inherited member 'Control.FocusMode'. Use the new keyword if hiding was intended.
  519. Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const String &p_output_file) {
  520. CRASH_COND(!itype.is_object_type);
  521. bool is_derived_type = itype.base_name != StringName();
  522. if (!is_derived_type) {
  523. // Some Godot.Object assertions
  524. CRASH_COND(itype.cname != name_cache.type_Object);
  525. CRASH_COND(!itype.is_instantiable);
  526. CRASH_COND(itype.api_type != ClassDB::API_CORE);
  527. CRASH_COND(itype.is_reference);
  528. CRASH_COND(itype.is_singleton);
  529. }
  530. List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls;
  531. if (verbose_output)
  532. OS::get_singleton()->print(String("Generating " + itype.proxy_name + ".cs...\n").utf8());
  533. String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); // Used only for derived types
  534. List<String> output;
  535. output.push_back("using System;\n"); // IntPtr
  536. output.push_back("using System.Diagnostics;\n"); // DebuggerBrowsable
  537. output.push_back("\n#pragma warning disable CS1591 // Disable warning: "
  538. "'Missing XML comment for publicly visible type or member'\n");
  539. output.push_back("\nnamespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  540. const DocData::ClassDoc *class_doc = itype.class_doc;
  541. if (class_doc && class_doc->description.size()) {
  542. output.push_back(INDENT1 "/// <summary>\n");
  543. Vector<String> description_lines = class_doc->description.split("\n");
  544. for (int i = 0; i < description_lines.size(); i++) {
  545. String description_line = description_lines[i].strip_edges();
  546. if (description_line.size()) {
  547. output.push_back(INDENT1 "/// ");
  548. output.push_back(description_line.xml_escape());
  549. output.push_back("\n");
  550. }
  551. }
  552. output.push_back(INDENT1 "/// </summary>\n");
  553. }
  554. output.push_back(INDENT1 "public ");
  555. if (itype.is_singleton) {
  556. output.push_back("static partial class ");
  557. } else {
  558. output.push_back(itype.is_instantiable ? "partial class " : "abstract partial class ");
  559. }
  560. output.push_back(itype.proxy_name);
  561. if (itype.is_singleton) {
  562. output.push_back("\n");
  563. } else if (is_derived_type) {
  564. if (obj_types.has(itype.base_name)) {
  565. output.push_back(" : ");
  566. output.push_back(obj_types[itype.base_name].proxy_name);
  567. output.push_back("\n");
  568. } else {
  569. ERR_PRINTS("Base type '" + itype.base_name.operator String() + "' does not exist, for class " + itype.name);
  570. return ERR_INVALID_DATA;
  571. }
  572. }
  573. output.push_back(INDENT1 "{");
  574. if (class_doc) {
  575. // Add constants
  576. for (const List<ConstantInterface>::Element *E = itype.constants.front(); E; E = E->next()) {
  577. const ConstantInterface &iconstant = E->get();
  578. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  579. output.push_back(MEMBER_BEGIN "/// <summary>\n");
  580. Vector<String> description_lines = iconstant.const_doc->description.split("\n");
  581. for (int i = 0; i < description_lines.size(); i++) {
  582. String description_line = description_lines[i].strip_edges();
  583. if (description_line.size()) {
  584. output.push_back(INDENT2 "/// ");
  585. output.push_back(description_line.xml_escape());
  586. output.push_back("\n");
  587. }
  588. }
  589. output.push_back(INDENT2 "/// </summary>");
  590. }
  591. output.push_back(MEMBER_BEGIN "public const int ");
  592. output.push_back(iconstant.proxy_name);
  593. output.push_back(" = ");
  594. output.push_back(itos(iconstant.value));
  595. output.push_back(";");
  596. }
  597. if (itype.constants.size())
  598. output.push_back("\n");
  599. // Add enums
  600. for (const List<EnumInterface>::Element *E = itype.enums.front(); E; E = E->next()) {
  601. const EnumInterface &ienum = E->get();
  602. ERR_FAIL_COND_V(ienum.constants.empty(), ERR_BUG);
  603. output.push_back(MEMBER_BEGIN "public enum ");
  604. output.push_back(ienum.cname.operator String());
  605. output.push_back(MEMBER_BEGIN OPEN_BLOCK);
  606. for (const List<ConstantInterface>::Element *E = ienum.constants.front(); E; E = E->next()) {
  607. const ConstantInterface &iconstant = E->get();
  608. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  609. output.push_back(INDENT3 "/// <summary>\n");
  610. Vector<String> description_lines = iconstant.const_doc->description.split("\n");
  611. for (int i = 0; i < description_lines.size(); i++) {
  612. String description_line = description_lines[i].strip_edges();
  613. if (description_line.size()) {
  614. output.push_back(INDENT3 "/// ");
  615. output.push_back(description_line.xml_escape());
  616. output.push_back("\n");
  617. }
  618. }
  619. output.push_back(INDENT3 "/// </summary>\n");
  620. }
  621. output.push_back(INDENT3);
  622. output.push_back(iconstant.proxy_name);
  623. output.push_back(" = ");
  624. output.push_back(itos(iconstant.value));
  625. output.push_back(E != ienum.constants.back() ? ",\n" : "\n");
  626. }
  627. output.push_back(INDENT2 CLOSE_BLOCK);
  628. }
  629. // Add properties
  630. for (const List<PropertyInterface>::Element *E = itype.properties.front(); E; E = E->next()) {
  631. const PropertyInterface &iprop = E->get();
  632. Error prop_err = _generate_cs_property(itype, iprop, output);
  633. if (prop_err != OK) {
  634. ERR_EXPLAIN("Failed to generate property '" + iprop.cname.operator String() +
  635. "' for class '" + itype.name + "'");
  636. ERR_FAIL_V(prop_err);
  637. }
  638. }
  639. }
  640. if (itype.is_singleton) {
  641. // Add the type name and the singleton pointer as static fields
  642. output.push_back(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \"");
  643. output.push_back(itype.name);
  644. output.push_back("\";\n");
  645. output.push_back(INDENT2 "internal static IntPtr " BINDINGS_PTR_FIELD " = ");
  646. output.push_back(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS);
  647. output.push_back("." ICALL_PREFIX);
  648. output.push_back(itype.name);
  649. output.push_back(SINGLETON_ICALL_SUFFIX "();\n");
  650. } else if (is_derived_type) {
  651. // Add member fields
  652. output.push_back(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \"");
  653. output.push_back(itype.name);
  654. output.push_back("\";\n");
  655. // Add default constructor
  656. if (itype.is_instantiable) {
  657. output.push_back(MEMBER_BEGIN "public ");
  658. output.push_back(itype.proxy_name);
  659. output.push_back("() : this(");
  660. output.push_back(itype.memory_own ? "true" : "false");
  661. // The default constructor may also be called by the engine when instancing existing native objects
  662. // The engine will initialize the pointer field of the managed side before calling the constructor
  663. // This is why we only allocate a new native object from the constructor if the pointer field is not set
  664. output.push_back(")\n" OPEN_BLOCK_L2 "if (" BINDINGS_PTR_FIELD " == IntPtr.Zero)\n" INDENT4 BINDINGS_PTR_FIELD " = ");
  665. output.push_back(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS);
  666. output.push_back("." + ctor_method);
  667. output.push_back("(this);\n" CLOSE_BLOCK_L2);
  668. } else {
  669. // Hide the constructor
  670. output.push_back(MEMBER_BEGIN "internal ");
  671. output.push_back(itype.proxy_name);
  672. output.push_back("() {}\n");
  673. }
  674. // Add.. em.. trick constructor. Sort of.
  675. output.push_back(MEMBER_BEGIN "internal ");
  676. output.push_back(itype.proxy_name);
  677. output.push_back("(bool " CS_FIELD_MEMORYOWN ") : base(" CS_FIELD_MEMORYOWN ") {}\n");
  678. }
  679. int method_bind_count = 0;
  680. for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) {
  681. const MethodInterface &imethod = E->get();
  682. Error method_err = _generate_cs_method(itype, imethod, method_bind_count, output);
  683. if (method_err != OK) {
  684. ERR_EXPLAIN("Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'");
  685. ERR_FAIL_V(method_err);
  686. }
  687. }
  688. if (itype.is_singleton) {
  689. InternalCall singleton_icall = InternalCall(itype.api_type, ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX, "IntPtr");
  690. if (!find_icall_by_name(singleton_icall.name, custom_icalls))
  691. custom_icalls.push_back(singleton_icall);
  692. }
  693. if (is_derived_type && itype.is_instantiable) {
  694. InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj");
  695. if (!find_icall_by_name(ctor_icall.name, custom_icalls))
  696. custom_icalls.push_back(ctor_icall);
  697. }
  698. output.push_back(INDENT1 CLOSE_BLOCK /* class */
  699. CLOSE_BLOCK /* namespace */);
  700. output.push_back("\n#pragma warning restore CS1591\n");
  701. return _save_file(p_output_file, output);
  702. }
  703. Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInterface &p_itype, const PropertyInterface &p_iprop, List<String> &p_output) {
  704. const MethodInterface *setter = p_itype.find_method_by_name(p_iprop.setter);
  705. // Search it in base types too
  706. const TypeInterface *current_type = &p_itype;
  707. while (!setter && current_type->base_name != StringName()) {
  708. OrderedHashMap<StringName, TypeInterface>::Element base_match = obj_types.find(current_type->base_name);
  709. ERR_FAIL_COND_V(!base_match, ERR_BUG);
  710. current_type = &base_match.get();
  711. setter = current_type->find_method_by_name(p_iprop.setter);
  712. }
  713. const MethodInterface *getter = p_itype.find_method_by_name(p_iprop.getter);
  714. // Search it in base types too
  715. current_type = &p_itype;
  716. while (!getter && current_type->base_name != StringName()) {
  717. OrderedHashMap<StringName, TypeInterface>::Element base_match = obj_types.find(current_type->base_name);
  718. ERR_FAIL_COND_V(!base_match, ERR_BUG);
  719. current_type = &base_match.get();
  720. getter = current_type->find_method_by_name(p_iprop.getter);
  721. }
  722. ERR_FAIL_COND_V(!setter && !getter, ERR_BUG);
  723. if (setter) {
  724. int setter_argc = p_iprop.index != -1 ? 2 : 1;
  725. ERR_FAIL_COND_V(setter->arguments.size() != setter_argc, ERR_BUG);
  726. }
  727. if (getter) {
  728. int getter_argc = p_iprop.index != -1 ? 1 : 0;
  729. ERR_FAIL_COND_V(getter->arguments.size() != getter_argc, ERR_BUG);
  730. }
  731. if (getter && setter) {
  732. ERR_FAIL_COND_V(getter->return_type.cname != setter->arguments.back()->get().type.cname, ERR_BUG);
  733. }
  734. const TypeReference &proptype_name = getter ? getter->return_type : setter->arguments.back()->get().type;
  735. const TypeInterface *prop_itype = _get_type_or_null(proptype_name);
  736. ERR_FAIL_NULL_V(prop_itype, ERR_BUG); // Property type not found
  737. String prop_proxy_name = escape_csharp_keyword(snake_to_pascal_case(p_iprop.cname));
  738. // Prevent property and enclosing type from sharing the same name
  739. if (prop_proxy_name == p_itype.proxy_name) {
  740. if (verbose_output) {
  741. WARN_PRINTS("Name of property `" + prop_proxy_name + "` is ambiguous with the name of its class `" +
  742. p_itype.proxy_name + "`. Renaming property to `" + prop_proxy_name + "_`");
  743. }
  744. prop_proxy_name += "_";
  745. }
  746. if (p_iprop.prop_doc && p_iprop.prop_doc->description.size()) {
  747. p_output.push_back(MEMBER_BEGIN "/// <summary>\n");
  748. Vector<String> description_lines = p_iprop.prop_doc->description.split("\n");
  749. for (int i = 0; i < description_lines.size(); i++) {
  750. String description_line = description_lines[i].strip_edges();
  751. if (description_line.size()) {
  752. p_output.push_back(INDENT2 "/// ");
  753. p_output.push_back(description_line.xml_escape());
  754. p_output.push_back("\n");
  755. }
  756. }
  757. p_output.push_back(INDENT2 "/// </summary>");
  758. }
  759. p_output.push_back(MEMBER_BEGIN "public ");
  760. if (p_itype.is_singleton)
  761. p_output.push_back("static ");
  762. p_output.push_back(prop_itype->cs_type);
  763. p_output.push_back(" ");
  764. p_output.push_back(prop_proxy_name.replace("/", "__"));
  765. p_output.push_back("\n" INDENT2 OPEN_BLOCK);
  766. if (getter) {
  767. p_output.push_back(INDENT3 "get\n" OPEN_BLOCK_L3);
  768. p_output.push_back("return ");
  769. p_output.push_back(getter->proxy_name + "(");
  770. if (p_iprop.index != -1) {
  771. const ArgumentInterface &idx_arg = getter->arguments.front()->get();
  772. if (idx_arg.type.cname != name_cache.type_int) {
  773. // Assume the index parameter is an enum
  774. const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type);
  775. CRASH_COND(idx_arg_type == NULL);
  776. p_output.push_back("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index));
  777. } else {
  778. p_output.push_back(itos(p_iprop.index));
  779. }
  780. }
  781. p_output.push_back(");\n" CLOSE_BLOCK_L3);
  782. }
  783. if (setter) {
  784. p_output.push_back(INDENT3 "set\n" OPEN_BLOCK_L3);
  785. p_output.push_back(setter->proxy_name + "(");
  786. if (p_iprop.index != -1) {
  787. const ArgumentInterface &idx_arg = setter->arguments.front()->get();
  788. if (idx_arg.type.cname != name_cache.type_int) {
  789. // Assume the index parameter is an enum
  790. const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type);
  791. CRASH_COND(idx_arg_type == NULL);
  792. p_output.push_back("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index) + ", ");
  793. } else {
  794. p_output.push_back(itos(p_iprop.index) + ", ");
  795. }
  796. }
  797. p_output.push_back("value);\n" CLOSE_BLOCK_L3);
  798. }
  799. p_output.push_back(CLOSE_BLOCK_L2);
  800. return OK;
  801. }
  802. Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, int &p_method_bind_count, List<String> &p_output) {
  803. const TypeInterface *return_type = _get_type_or_placeholder(p_imethod.return_type);
  804. String method_bind_field = "method_bind_" + itos(p_method_bind_count);
  805. String arguments_sig;
  806. String cs_in_statements;
  807. String icall_params = method_bind_field + ", ";
  808. icall_params += sformat(p_itype.cs_in, "this");
  809. List<String> default_args_doc;
  810. // Retrieve information from the arguments
  811. for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) {
  812. const ArgumentInterface &iarg = F->get();
  813. const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
  814. // Add the current arguments to the signature
  815. // If the argument has a default value which is not a constant, we will make it Nullable
  816. {
  817. if (F != p_imethod.arguments.front())
  818. arguments_sig += ", ";
  819. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
  820. arguments_sig += "Nullable<";
  821. arguments_sig += arg_type->cs_type;
  822. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
  823. arguments_sig += "> ";
  824. else
  825. arguments_sig += " ";
  826. arguments_sig += iarg.name;
  827. if (iarg.default_argument.size()) {
  828. if (iarg.def_param_mode != ArgumentInterface::CONSTANT)
  829. arguments_sig += " = null";
  830. else
  831. arguments_sig += " = " + sformat(iarg.default_argument, arg_type->cs_type);
  832. }
  833. }
  834. icall_params += ", ";
  835. if (iarg.default_argument.size() && iarg.def_param_mode != ArgumentInterface::CONSTANT) {
  836. // The default value of an argument must be constant. Otherwise we make it Nullable and do the following:
  837. // Type arg_in = arg.HasValue ? arg.Value : <non-const default value>;
  838. String arg_in = iarg.name;
  839. arg_in += "_in";
  840. cs_in_statements += arg_type->cs_type;
  841. cs_in_statements += " ";
  842. cs_in_statements += arg_in;
  843. cs_in_statements += " = ";
  844. cs_in_statements += iarg.name;
  845. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
  846. cs_in_statements += ".HasValue ? ";
  847. else
  848. cs_in_statements += " != null ? ";
  849. cs_in_statements += iarg.name;
  850. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
  851. cs_in_statements += ".Value : ";
  852. else
  853. cs_in_statements += " : ";
  854. String def_arg = sformat(iarg.default_argument, arg_type->cs_type);
  855. cs_in_statements += def_arg;
  856. cs_in_statements += ";\n" INDENT3;
  857. icall_params += arg_type->cs_in.empty() ? arg_in : sformat(arg_type->cs_in, arg_in);
  858. default_args_doc.push_back(INDENT2 "/// <param name=\"" + iarg.name + "\">If the param is null, then the default value is " + def_arg + "</param>\n");
  859. } else {
  860. icall_params += arg_type->cs_in.empty() ? iarg.name : sformat(arg_type->cs_in, iarg.name);
  861. }
  862. }
  863. // Generate method
  864. {
  865. if (!p_imethod.is_virtual && !p_imethod.requires_object_call) {
  866. p_output.push_back(MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]" MEMBER_BEGIN "private static IntPtr ");
  867. p_output.push_back(method_bind_field + " = Object." ICALL_GET_METHODBIND "(" BINDINGS_NATIVE_NAME_FIELD ", \"");
  868. p_output.push_back(p_imethod.name);
  869. p_output.push_back("\");\n");
  870. }
  871. if (p_imethod.method_doc && p_imethod.method_doc->description.size()) {
  872. p_output.push_back(MEMBER_BEGIN "/// <summary>\n");
  873. Vector<String> description_lines = p_imethod.method_doc->description.split("\n");
  874. for (int i = 0; i < description_lines.size(); i++) {
  875. String description_line = description_lines[i].strip_edges();
  876. if (description_line.size()) {
  877. p_output.push_back(INDENT2 "/// ");
  878. p_output.push_back(description_line.xml_escape());
  879. p_output.push_back("\n");
  880. }
  881. }
  882. for (List<String>::Element *E = default_args_doc.front(); E; E = E->next()) {
  883. p_output.push_back(E->get().xml_escape());
  884. }
  885. p_output.push_back(INDENT2 "/// </summary>");
  886. }
  887. if (!p_imethod.is_internal) {
  888. p_output.push_back(MEMBER_BEGIN "[GodotMethod(\"");
  889. p_output.push_back(p_imethod.name);
  890. p_output.push_back("\")]");
  891. }
  892. p_output.push_back(MEMBER_BEGIN);
  893. p_output.push_back(p_imethod.is_internal ? "internal " : "public ");
  894. if (p_itype.is_singleton) {
  895. p_output.push_back("static ");
  896. } else if (p_imethod.is_virtual) {
  897. p_output.push_back("virtual ");
  898. }
  899. p_output.push_back(return_type->cs_type + " ");
  900. p_output.push_back(p_imethod.proxy_name + "(");
  901. p_output.push_back(arguments_sig + ")\n" OPEN_BLOCK_L2);
  902. if (p_imethod.is_virtual) {
  903. // Godot virtual method must be overridden, therefore we return a default value by default.
  904. if (return_type->cname == name_cache.type_void) {
  905. p_output.push_back("return;\n" CLOSE_BLOCK_L2);
  906. } else {
  907. p_output.push_back("return default(");
  908. p_output.push_back(return_type->cs_type);
  909. p_output.push_back(");\n" CLOSE_BLOCK_L2);
  910. }
  911. return OK; // Won't increment method bind count
  912. }
  913. if (p_imethod.requires_object_call) {
  914. // Fallback to Godot's object.Call(string, params)
  915. p_output.push_back(CS_METHOD_CALL "(\"");
  916. p_output.push_back(p_imethod.name);
  917. p_output.push_back("\"");
  918. for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) {
  919. p_output.push_back(", ");
  920. p_output.push_back(F->get().name);
  921. }
  922. p_output.push_back(");\n" CLOSE_BLOCK_L2);
  923. return OK; // Won't increment method bind count
  924. }
  925. const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&p_imethod);
  926. ERR_FAIL_NULL_V(match, ERR_BUG);
  927. const InternalCall *im_icall = match->value();
  928. String im_call = im_icall->editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS;
  929. im_call += "." + im_icall->name + "(" + icall_params + ")";
  930. if (p_imethod.arguments.size())
  931. p_output.push_back(cs_in_statements);
  932. if (return_type->cname == name_cache.type_void) {
  933. p_output.push_back(im_call + ";\n");
  934. } else if (return_type->cs_out.empty()) {
  935. p_output.push_back("return " + im_call + ";\n");
  936. } else {
  937. p_output.push_back(sformat(return_type->cs_out, im_call, return_type->cs_type, return_type->im_type_out));
  938. p_output.push_back("\n");
  939. }
  940. p_output.push_back(CLOSE_BLOCK_L2);
  941. }
  942. p_method_bind_count++;
  943. return OK;
  944. }
  945. Error BindingsGenerator::generate_glue(const String &p_output_dir) {
  946. verbose_output = true;
  947. bool dir_exists = DirAccess::exists(p_output_dir);
  948. ERR_EXPLAIN("The output directory does not exist.");
  949. ERR_FAIL_COND_V(!dir_exists, ERR_FILE_BAD_PATH);
  950. List<String> output;
  951. output.push_back("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
  952. output.push_back("#include \"" GLUE_HEADER_FILE "\"\n");
  953. output.push_back("\n#ifdef MONO_GLUE_ENABLED\n");
  954. generated_icall_funcs.clear();
  955. for (OrderedHashMap<StringName, TypeInterface>::Element type_elem = obj_types.front(); type_elem; type_elem = type_elem.next()) {
  956. const TypeInterface &itype = type_elem.get();
  957. bool is_derived_type = itype.base_name != StringName();
  958. if (!is_derived_type) {
  959. // Some Object assertions
  960. CRASH_COND(itype.cname != name_cache.type_Object);
  961. CRASH_COND(!itype.is_instantiable);
  962. CRASH_COND(itype.api_type != ClassDB::API_CORE);
  963. CRASH_COND(itype.is_reference);
  964. CRASH_COND(itype.is_singleton);
  965. }
  966. List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls;
  967. OS::get_singleton()->print(String("Generating " + itype.name + "...\n").utf8());
  968. String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); // Used only for derived types
  969. for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) {
  970. const MethodInterface &imethod = E->get();
  971. Error method_err = _generate_glue_method(itype, imethod, output);
  972. if (method_err != OK) {
  973. ERR_EXPLAIN("Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'");
  974. ERR_FAIL_V(method_err);
  975. }
  976. }
  977. if (itype.is_singleton) {
  978. String singleton_icall_name = ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX;
  979. InternalCall singleton_icall = InternalCall(itype.api_type, singleton_icall_name, "IntPtr");
  980. if (!find_icall_by_name(singleton_icall.name, custom_icalls))
  981. custom_icalls.push_back(singleton_icall);
  982. output.push_back("Object* ");
  983. output.push_back(singleton_icall_name);
  984. output.push_back("() " OPEN_BLOCK "\treturn Engine::get_singleton()->get_singleton_object(\"");
  985. output.push_back(itype.proxy_name);
  986. output.push_back("\");\n" CLOSE_BLOCK "\n");
  987. }
  988. if (is_derived_type && itype.is_instantiable) {
  989. InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj");
  990. if (!find_icall_by_name(ctor_icall.name, custom_icalls))
  991. custom_icalls.push_back(ctor_icall);
  992. output.push_back("Object* ");
  993. output.push_back(ctor_method);
  994. output.push_back("(MonoObject* obj) " OPEN_BLOCK
  995. "\t" C_MACRO_OBJECT_CONSTRUCT "(instance, \"");
  996. output.push_back(itype.name);
  997. output.push_back("\");\n"
  998. "\t" C_METHOD_TIE_MANAGED_TO_UNMANAGED "(obj, instance);\n"
  999. "\treturn instance;\n" CLOSE_BLOCK "\n");
  1000. }
  1001. }
  1002. output.push_back("namespace GodotSharpBindings\n" OPEN_BLOCK "\n");
  1003. output.push_back("uint64_t get_core_api_hash() { return ");
  1004. output.push_back(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + "U; }\n");
  1005. output.push_back("#ifdef TOOLS_ENABLED\n"
  1006. "uint64_t get_editor_api_hash() { return ");
  1007. output.push_back(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + "U; }\n");
  1008. output.push_back("#endif // TOOLS_ENABLED\n");
  1009. output.push_back("uint32_t get_bindings_version() { return ");
  1010. output.push_back(String::num_uint64(BINDINGS_GENERATOR_VERSION) + "; }\n");
  1011. output.push_back("\nvoid register_generated_icalls() " OPEN_BLOCK);
  1012. output.push_back("\tgodot_register_glue_header_icalls();\n");
  1013. #define ADD_INTERNAL_CALL_REGISTRATION(m_icall) \
  1014. { \
  1015. output.push_back("\tmono_add_internal_call("); \
  1016. output.push_back("\"" BINDINGS_NAMESPACE "."); \
  1017. output.push_back(m_icall.editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); \
  1018. output.push_back("::"); \
  1019. output.push_back(m_icall.name); \
  1020. output.push_back("\", (void*)"); \
  1021. output.push_back(m_icall.name); \
  1022. output.push_back(");\n"); \
  1023. }
  1024. bool tools_sequence = false;
  1025. for (const List<InternalCall>::Element *E = core_custom_icalls.front(); E; E = E->next()) {
  1026. if (tools_sequence) {
  1027. if (!E->get().editor_only) {
  1028. tools_sequence = false;
  1029. output.push_back("#endif\n");
  1030. }
  1031. } else {
  1032. if (E->get().editor_only) {
  1033. output.push_back("#ifdef TOOLS_ENABLED\n");
  1034. tools_sequence = true;
  1035. }
  1036. }
  1037. ADD_INTERNAL_CALL_REGISTRATION(E->get());
  1038. }
  1039. if (tools_sequence) {
  1040. tools_sequence = false;
  1041. output.push_back("#endif\n");
  1042. }
  1043. output.push_back("#ifdef TOOLS_ENABLED\n");
  1044. for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next())
  1045. ADD_INTERNAL_CALL_REGISTRATION(E->get());
  1046. output.push_back("#endif // TOOLS_ENABLED\n");
  1047. for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next()) {
  1048. if (tools_sequence) {
  1049. if (!E->get().editor_only) {
  1050. tools_sequence = false;
  1051. output.push_back("#endif\n");
  1052. }
  1053. } else {
  1054. if (E->get().editor_only) {
  1055. output.push_back("#ifdef TOOLS_ENABLED\n");
  1056. tools_sequence = true;
  1057. }
  1058. }
  1059. ADD_INTERNAL_CALL_REGISTRATION(E->get());
  1060. }
  1061. if (tools_sequence) {
  1062. tools_sequence = false;
  1063. output.push_back("#endif\n");
  1064. }
  1065. #undef ADD_INTERNAL_CALL_REGISTRATION
  1066. output.push_back(CLOSE_BLOCK "\n} // namespace GodotSharpBindings\n");
  1067. output.push_back("\n#endif // MONO_GLUE_ENABLED\n");
  1068. Error save_err = _save_file(path_join(p_output_dir, "mono_glue.gen.cpp"), output);
  1069. if (save_err != OK)
  1070. return save_err;
  1071. OS::get_singleton()->print("Mono glue generated successfully\n");
  1072. return OK;
  1073. }
  1074. uint32_t BindingsGenerator::get_version() {
  1075. return BINDINGS_GENERATOR_VERSION;
  1076. }
  1077. Error BindingsGenerator::_save_file(const String &p_path, const List<String> &p_content) {
  1078. FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE);
  1079. ERR_EXPLAIN("Cannot open file: " + p_path);
  1080. ERR_FAIL_COND_V(!file, ERR_FILE_CANT_WRITE);
  1081. for (const List<String>::Element *E = p_content.front(); E; E = E->next()) {
  1082. file->store_string(E->get());
  1083. }
  1084. file->close();
  1085. return OK;
  1086. }
  1087. Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, List<String> &p_output) {
  1088. if (p_imethod.is_virtual)
  1089. return OK; // Ignore
  1090. bool ret_void = p_imethod.return_type.cname == name_cache.type_void;
  1091. const TypeInterface *return_type = _get_type_or_placeholder(p_imethod.return_type);
  1092. String argc_str = itos(p_imethod.arguments.size());
  1093. String c_func_sig = "MethodBind* " CS_PARAM_METHODBIND ", " + p_itype.c_type_in + " " CS_PARAM_INSTANCE;
  1094. String c_in_statements;
  1095. String c_args_var_content;
  1096. // Get arguments information
  1097. int i = 0;
  1098. for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) {
  1099. const ArgumentInterface &iarg = F->get();
  1100. const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
  1101. String c_param_name = "arg" + itos(i + 1);
  1102. if (p_imethod.is_vararg) {
  1103. if (i < p_imethod.arguments.size() - 1) {
  1104. c_in_statements += sformat(arg_type->c_in.size() ? arg_type->c_in : TypeInterface::DEFAULT_VARARG_C_IN, "Variant", c_param_name);
  1105. c_in_statements += "\t" C_LOCAL_PTRCALL_ARGS ".set(";
  1106. c_in_statements += itos(i);
  1107. c_in_statements += sformat(", &%s_in);\n", c_param_name);
  1108. }
  1109. } else {
  1110. if (i > 0)
  1111. c_args_var_content += ", ";
  1112. if (arg_type->c_in.size())
  1113. c_in_statements += sformat(arg_type->c_in, arg_type->c_type, c_param_name);
  1114. c_args_var_content += sformat(arg_type->c_arg_in, c_param_name);
  1115. }
  1116. c_func_sig += ", ";
  1117. c_func_sig += arg_type->c_type_in;
  1118. c_func_sig += " ";
  1119. c_func_sig += c_param_name;
  1120. i++;
  1121. }
  1122. const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&p_imethod);
  1123. ERR_FAIL_NULL_V(match, ERR_BUG);
  1124. const InternalCall *im_icall = match->value();
  1125. String icall_method = im_icall->name;
  1126. if (!generated_icall_funcs.find(im_icall)) {
  1127. generated_icall_funcs.push_back(im_icall);
  1128. if (im_icall->editor_only)
  1129. p_output.push_back("#ifdef TOOLS_ENABLED\n");
  1130. // Generate icall function
  1131. p_output.push_back(ret_void ? "void " : return_type->c_type_out + " ");
  1132. p_output.push_back(icall_method);
  1133. p_output.push_back("(");
  1134. p_output.push_back(c_func_sig);
  1135. p_output.push_back(") " OPEN_BLOCK);
  1136. String fail_ret = ret_void ? "" : ", " + (return_type->c_type_out.ends_with("*") ? "NULL" : return_type->c_type_out + "()");
  1137. if (!ret_void) {
  1138. String ptrcall_return_type;
  1139. String initialization;
  1140. if (return_type->is_object_type) {
  1141. ptrcall_return_type = return_type->is_reference ? "Ref<Reference>" : return_type->c_type;
  1142. initialization = return_type->is_reference ? "" : " = NULL";
  1143. } else {
  1144. ptrcall_return_type = return_type->c_type;
  1145. }
  1146. p_output.push_back("\t" + ptrcall_return_type);
  1147. p_output.push_back(" " C_LOCAL_RET);
  1148. p_output.push_back(initialization + ";\n");
  1149. p_output.push_back("\tERR_FAIL_NULL_V(" CS_PARAM_INSTANCE);
  1150. p_output.push_back(fail_ret);
  1151. p_output.push_back(");\n");
  1152. } else {
  1153. p_output.push_back("\tERR_FAIL_NULL(" CS_PARAM_INSTANCE ");\n");
  1154. }
  1155. if (p_imethod.arguments.size()) {
  1156. if (p_imethod.is_vararg) {
  1157. String err_fail_macro = ret_void ? "ERR_FAIL_COND" : "ERR_FAIL_COND_V";
  1158. String vararg_arg = "arg" + argc_str;
  1159. String real_argc_str = itos(p_imethod.arguments.size() - 1); // Arguments count without vararg
  1160. p_output.push_back("\tVector<Variant> varargs;\n"
  1161. "\tint vararg_length = mono_array_length(");
  1162. p_output.push_back(vararg_arg);
  1163. p_output.push_back(");\n\tint total_length = ");
  1164. p_output.push_back(real_argc_str);
  1165. p_output.push_back(" + vararg_length;\n\t");
  1166. p_output.push_back(err_fail_macro);
  1167. p_output.push_back("(varargs.resize(vararg_length) != OK");
  1168. p_output.push_back(fail_ret);
  1169. p_output.push_back(");\n\tVector<Variant*> " C_LOCAL_PTRCALL_ARGS ";\n\t");
  1170. p_output.push_back(err_fail_macro);
  1171. p_output.push_back("(call_args.resize(total_length) != OK");
  1172. p_output.push_back(fail_ret);
  1173. p_output.push_back(");\n");
  1174. p_output.push_back(c_in_statements);
  1175. p_output.push_back("\tfor (int i = 0; i < vararg_length; i++) " OPEN_BLOCK
  1176. "\t\tMonoObject* elem = mono_array_get(");
  1177. p_output.push_back(vararg_arg);
  1178. p_output.push_back(", MonoObject*, i);\n"
  1179. "\t\tvarargs.set(i, GDMonoMarshal::mono_object_to_variant(elem));\n"
  1180. "\t\t" C_LOCAL_PTRCALL_ARGS ".set(");
  1181. p_output.push_back(real_argc_str);
  1182. p_output.push_back(" + i, &varargs.write[i]);\n\t" CLOSE_BLOCK);
  1183. } else {
  1184. p_output.push_back(c_in_statements);
  1185. p_output.push_back("\tconst void* " C_LOCAL_PTRCALL_ARGS "[");
  1186. p_output.push_back(argc_str + "] = { ");
  1187. p_output.push_back(c_args_var_content + " };\n");
  1188. }
  1189. }
  1190. if (p_imethod.is_vararg) {
  1191. p_output.push_back("\tVariant::CallError vcall_error;\n\t");
  1192. if (!ret_void)
  1193. p_output.push_back(C_LOCAL_RET " = ");
  1194. p_output.push_back(CS_PARAM_METHODBIND "->call(" CS_PARAM_INSTANCE ", ");
  1195. p_output.push_back(p_imethod.arguments.size() ? "(const Variant**)" C_LOCAL_PTRCALL_ARGS ".ptr()" : "NULL");
  1196. p_output.push_back(", total_length, vcall_error);\n");
  1197. } else {
  1198. p_output.push_back("\t" CS_PARAM_METHODBIND "->ptrcall(" CS_PARAM_INSTANCE ", ");
  1199. p_output.push_back(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ", " : "NULL, ");
  1200. p_output.push_back(!ret_void ? "&" C_LOCAL_RET ");\n" : "NULL);\n");
  1201. }
  1202. if (!ret_void) {
  1203. if (return_type->c_out.empty())
  1204. p_output.push_back("\treturn " C_LOCAL_RET ";\n");
  1205. else
  1206. p_output.push_back(sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET, return_type->name));
  1207. }
  1208. p_output.push_back(CLOSE_BLOCK "\n");
  1209. if (im_icall->editor_only)
  1210. p_output.push_back("#endif // TOOLS_ENABLED\n");
  1211. }
  1212. return OK;
  1213. }
  1214. const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_null(const TypeReference &p_typeref) {
  1215. const Map<StringName, TypeInterface>::Element *builtin_type_match = builtin_types.find(p_typeref.cname);
  1216. if (builtin_type_match)
  1217. return &builtin_type_match->get();
  1218. const OrderedHashMap<StringName, TypeInterface>::Element obj_type_match = obj_types.find(p_typeref.cname);
  1219. if (obj_type_match)
  1220. return &obj_type_match.get();
  1221. if (p_typeref.is_enum) {
  1222. const Map<StringName, TypeInterface>::Element *enum_match = enum_types.find(p_typeref.cname);
  1223. if (enum_match)
  1224. return &enum_match->get();
  1225. // Enum not found. Most likely because none of its constants were bound, so it's empty. That's fine. Use int instead.
  1226. const Map<StringName, TypeInterface>::Element *int_match = builtin_types.find(name_cache.type_int);
  1227. ERR_FAIL_NULL_V(int_match, NULL);
  1228. return &int_match->get();
  1229. }
  1230. return NULL;
  1231. }
  1232. const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_placeholder(const TypeReference &p_typeref) {
  1233. const TypeInterface *found = _get_type_or_null(p_typeref);
  1234. if (found)
  1235. return found;
  1236. ERR_PRINTS(String() + "Type not found. Creating placeholder: " + p_typeref.cname.operator String());
  1237. const Map<StringName, TypeInterface>::Element *match = placeholder_types.find(p_typeref.cname);
  1238. if (match)
  1239. return &match->get();
  1240. TypeInterface placeholder;
  1241. TypeInterface::create_placeholder_type(placeholder, p_typeref.cname);
  1242. return &placeholder_types.insert(placeholder.cname, placeholder)->get();
  1243. }
  1244. void BindingsGenerator::_populate_object_type_interfaces() {
  1245. obj_types.clear();
  1246. List<StringName> class_list;
  1247. ClassDB::get_class_list(&class_list);
  1248. class_list.sort_custom<StringName::AlphCompare>();
  1249. while (class_list.size()) {
  1250. StringName type_cname = class_list.front()->get();
  1251. ClassDB::APIType api_type = ClassDB::get_api_type(type_cname);
  1252. if (api_type == ClassDB::API_NONE) {
  1253. class_list.pop_front();
  1254. continue;
  1255. }
  1256. if (!ClassDB::is_class_exposed(type_cname)) {
  1257. if (verbose_output)
  1258. WARN_PRINTS("Ignoring type " + type_cname.operator String() + " because it's not exposed");
  1259. class_list.pop_front();
  1260. continue;
  1261. }
  1262. if (!ClassDB::is_class_enabled(type_cname)) {
  1263. if (verbose_output)
  1264. WARN_PRINTS("Ignoring type " + type_cname.operator String() + " because it's not enabled");
  1265. class_list.pop_front();
  1266. continue;
  1267. }
  1268. ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(type_cname);
  1269. TypeInterface itype = TypeInterface::create_object_type(type_cname, api_type);
  1270. itype.base_name = ClassDB::get_parent_class(type_cname);
  1271. itype.is_singleton = Engine::get_singleton()->has_singleton(itype.proxy_name);
  1272. itype.is_instantiable = ClassDB::can_instance(type_cname) && !itype.is_singleton;
  1273. itype.is_reference = ClassDB::is_parent_class(type_cname, name_cache.type_Reference);
  1274. itype.memory_own = itype.is_reference;
  1275. itype.c_out = "\treturn ";
  1276. itype.c_out += C_METHOD_UNMANAGED_GET_MANAGED;
  1277. itype.c_out += itype.is_reference ? "(%1.ptr());\n" : "(%1);\n";
  1278. itype.cs_in = itype.is_singleton ? BINDINGS_PTR_FIELD : "Object." CS_SMETHOD_GETINSTANCE "(%0)";
  1279. itype.c_type = "Object*";
  1280. itype.c_type_in = itype.c_type;
  1281. itype.c_type_out = "MonoObject*";
  1282. itype.cs_type = itype.proxy_name;
  1283. itype.im_type_in = "IntPtr";
  1284. itype.im_type_out = itype.proxy_name;
  1285. List<PropertyInfo> property_list;
  1286. ClassDB::get_property_list(type_cname, &property_list, true);
  1287. // Populate properties
  1288. for (const List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
  1289. const PropertyInfo &property = E->get();
  1290. if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_CATEGORY)
  1291. continue;
  1292. PropertyInterface iprop;
  1293. iprop.cname = property.name;
  1294. iprop.proxy_name = escape_csharp_keyword(snake_to_pascal_case(iprop.cname));
  1295. iprop.setter = ClassDB::get_property_setter(type_cname, iprop.cname);
  1296. iprop.getter = ClassDB::get_property_getter(type_cname, iprop.cname);
  1297. bool valid = false;
  1298. iprop.index = ClassDB::get_property_index(type_cname, iprop.cname, &valid);
  1299. ERR_FAIL_COND(!valid);
  1300. // Prevent property and enclosing type from sharing the same name
  1301. if (iprop.proxy_name == itype.proxy_name) {
  1302. if (verbose_output) {
  1303. WARN_PRINTS("Name of property `" + iprop.proxy_name + "` is ambiguous with the name of its class `" +
  1304. itype.proxy_name + "`. Renaming property to `" + iprop.proxy_name + "_`");
  1305. }
  1306. iprop.proxy_name += "_";
  1307. }
  1308. iprop.prop_doc = NULL;
  1309. for (int i = 0; i < itype.class_doc->properties.size(); i++) {
  1310. const DocData::PropertyDoc &prop_doc = itype.class_doc->properties[i];
  1311. if (prop_doc.name == iprop.cname) {
  1312. iprop.prop_doc = &prop_doc;
  1313. break;
  1314. }
  1315. }
  1316. itype.properties.push_back(iprop);
  1317. }
  1318. // Populate methods
  1319. List<MethodInfo> virtual_method_list;
  1320. ClassDB::get_virtual_methods(type_cname, &virtual_method_list, true);
  1321. List<MethodInfo> method_list;
  1322. ClassDB::get_method_list(type_cname, &method_list, true);
  1323. method_list.sort();
  1324. for (List<MethodInfo>::Element *E = method_list.front(); E; E = E->next()) {
  1325. const MethodInfo &method_info = E->get();
  1326. int argc = method_info.arguments.size();
  1327. if (method_info.name.empty())
  1328. continue;
  1329. MethodInterface imethod;
  1330. imethod.name = method_info.name;
  1331. imethod.cname = imethod.name;
  1332. if (method_info.flags & METHOD_FLAG_VIRTUAL)
  1333. imethod.is_virtual = true;
  1334. PropertyInfo return_info = method_info.return_val;
  1335. MethodBind *m = imethod.is_virtual ? NULL : ClassDB::get_method(type_cname, method_info.name);
  1336. imethod.is_vararg = m && m->is_vararg();
  1337. if (!m && !imethod.is_virtual) {
  1338. if (virtual_method_list.find(method_info)) {
  1339. // A virtual method without the virtual flag. This is a special case.
  1340. // There is no method bind, so let's fallback to Godot's object.Call(string, params)
  1341. imethod.requires_object_call = true;
  1342. // The method Object.free is registered as a virtual method, but without the virtual flag.
  1343. // This is because this method is not supposed to be overridden, but called.
  1344. // We assume the return type is void.
  1345. imethod.return_type.cname = name_cache.type_void;
  1346. // Actually, more methods like this may be added in the future,
  1347. // which could actually will return something different.
  1348. // Let's put this to notify us if that ever happens.
  1349. if (itype.cname != name_cache.type_Object || imethod.name != "free") {
  1350. if (verbose_output) {
  1351. WARN_PRINTS("Notification: New unexpected virtual non-overridable method found.\n"
  1352. "We only expected Object.free, but found " +
  1353. itype.name + "." + imethod.name);
  1354. }
  1355. }
  1356. } else {
  1357. ERR_PRINTS("Missing MethodBind for non-virtual method: " + itype.name + "." + imethod.name);
  1358. }
  1359. } else if (return_info.type == Variant::INT && return_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
  1360. imethod.return_type.cname = return_info.class_name;
  1361. imethod.return_type.is_enum = true;
  1362. } else if (return_info.class_name != StringName()) {
  1363. imethod.return_type.cname = return_info.class_name;
  1364. } else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  1365. imethod.return_type.cname = return_info.hint_string;
  1366. } else if (return_info.type == Variant::NIL && return_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
  1367. imethod.return_type.cname = name_cache.type_Variant;
  1368. } else if (return_info.type == Variant::NIL) {
  1369. imethod.return_type.cname = name_cache.type_void;
  1370. } else {
  1371. imethod.return_type.cname = Variant::get_type_name(return_info.type);
  1372. }
  1373. for (int i = 0; i < argc; i++) {
  1374. PropertyInfo arginfo = method_info.arguments[i];
  1375. ArgumentInterface iarg;
  1376. iarg.name = arginfo.name;
  1377. if (arginfo.type == Variant::INT && arginfo.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
  1378. iarg.type.cname = arginfo.class_name;
  1379. iarg.type.is_enum = true;
  1380. } else if (arginfo.class_name != StringName()) {
  1381. iarg.type.cname = arginfo.class_name;
  1382. } else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  1383. iarg.type.cname = arginfo.hint_string;
  1384. } else if (arginfo.type == Variant::NIL) {
  1385. iarg.type.cname = name_cache.type_Variant;
  1386. } else {
  1387. iarg.type.cname = Variant::get_type_name(arginfo.type);
  1388. }
  1389. iarg.name = escape_csharp_keyword(snake_to_camel_case(iarg.name));
  1390. if (m && m->has_default_argument(i)) {
  1391. _default_argument_from_variant(m->get_default_argument(i), iarg);
  1392. }
  1393. imethod.add_argument(iarg);
  1394. }
  1395. if (imethod.is_vararg) {
  1396. ArgumentInterface ivararg;
  1397. ivararg.type.cname = name_cache.type_VarArg;
  1398. ivararg.name = "@args";
  1399. imethod.add_argument(ivararg);
  1400. }
  1401. imethod.proxy_name = escape_csharp_keyword(snake_to_pascal_case(imethod.name));
  1402. // Prevent naming the property and its enclosing type from sharing the same name
  1403. if (imethod.proxy_name == itype.proxy_name) {
  1404. if (verbose_output) {
  1405. WARN_PRINTS("Name of method `" + imethod.proxy_name + "` is ambiguous with the name of its class `" +
  1406. itype.proxy_name + "`. Renaming method to `" + imethod.proxy_name + "_`");
  1407. }
  1408. imethod.proxy_name += "_";
  1409. }
  1410. if (itype.class_doc) {
  1411. for (int i = 0; i < itype.class_doc->methods.size(); i++) {
  1412. if (itype.class_doc->methods[i].name == imethod.name) {
  1413. imethod.method_doc = &itype.class_doc->methods[i];
  1414. break;
  1415. }
  1416. }
  1417. }
  1418. if (!imethod.is_virtual && imethod.name[0] == '_') {
  1419. for (const List<PropertyInterface>::Element *E = itype.properties.front(); E; E = E->next()) {
  1420. const PropertyInterface &iprop = E->get();
  1421. if (iprop.setter == imethod.name || iprop.getter == imethod.name) {
  1422. imethod.is_internal = true;
  1423. itype.methods.push_back(imethod);
  1424. break;
  1425. }
  1426. }
  1427. } else {
  1428. itype.methods.push_back(imethod);
  1429. }
  1430. }
  1431. // Populate enums and constants
  1432. List<String> constant_list;
  1433. ClassDB::get_integer_constant_list(type_cname, &constant_list, true);
  1434. const HashMap<StringName, List<StringName> > &enum_map = class_info->enum_map;
  1435. const StringName *k = NULL;
  1436. while ((k = enum_map.next(k))) {
  1437. StringName enum_proxy_cname = *k;
  1438. String enum_proxy_name = enum_proxy_cname.operator String();
  1439. if (itype.find_property_by_proxy_name(enum_proxy_cname)) {
  1440. // We have several conflicts between enums and PascalCase properties,
  1441. // so we append 'Enum' to the enum name in those cases.
  1442. enum_proxy_name += "Enum";
  1443. enum_proxy_cname = StringName(enum_proxy_name);
  1444. }
  1445. EnumInterface ienum(enum_proxy_cname);
  1446. const List<StringName> &constants = enum_map.get(*k);
  1447. for (const List<StringName>::Element *E = constants.front(); E; E = E->next()) {
  1448. const StringName &constant_cname = E->get();
  1449. String constant_name = constant_cname.operator String();
  1450. int *value = class_info->constant_map.getptr(constant_cname);
  1451. ERR_FAIL_NULL(value);
  1452. constant_list.erase(constant_name);
  1453. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value);
  1454. iconstant.const_doc = NULL;
  1455. for (int i = 0; i < itype.class_doc->constants.size(); i++) {
  1456. const DocData::ConstantDoc &const_doc = itype.class_doc->constants[i];
  1457. if (const_doc.name == iconstant.name) {
  1458. iconstant.const_doc = &const_doc;
  1459. break;
  1460. }
  1461. }
  1462. ienum.constants.push_back(iconstant);
  1463. }
  1464. int prefix_length = _determine_enum_prefix(ienum);
  1465. _apply_prefix_to_enum_constants(ienum, prefix_length);
  1466. itype.enums.push_back(ienum);
  1467. TypeInterface enum_itype;
  1468. enum_itype.is_enum = true;
  1469. enum_itype.name = itype.name + "." + String(*k);
  1470. enum_itype.cname = StringName(enum_itype.name);
  1471. enum_itype.proxy_name = itype.proxy_name + "." + enum_proxy_name;
  1472. TypeInterface::postsetup_enum_type(enum_itype);
  1473. enum_types.insert(enum_itype.cname, enum_itype);
  1474. }
  1475. for (const List<String>::Element *E = constant_list.front(); E; E = E->next()) {
  1476. const String &constant_name = E->get();
  1477. int *value = class_info->constant_map.getptr(StringName(E->get()));
  1478. ERR_FAIL_NULL(value);
  1479. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value);
  1480. iconstant.const_doc = NULL;
  1481. for (int i = 0; i < itype.class_doc->constants.size(); i++) {
  1482. const DocData::ConstantDoc &const_doc = itype.class_doc->constants[i];
  1483. if (const_doc.name == iconstant.name) {
  1484. iconstant.const_doc = &const_doc;
  1485. break;
  1486. }
  1487. }
  1488. itype.constants.push_back(iconstant);
  1489. }
  1490. obj_types.insert(itype.cname, itype);
  1491. class_list.pop_front();
  1492. }
  1493. }
  1494. void BindingsGenerator::_default_argument_from_variant(const Variant &p_val, ArgumentInterface &r_iarg) {
  1495. r_iarg.default_argument = p_val;
  1496. switch (p_val.get_type()) {
  1497. case Variant::NIL:
  1498. if (ClassDB::class_exists(r_iarg.type.cname)) {
  1499. // Object type
  1500. r_iarg.default_argument = "null";
  1501. } else {
  1502. // Variant
  1503. r_iarg.default_argument = "null";
  1504. }
  1505. break;
  1506. // Atomic types
  1507. case Variant::BOOL:
  1508. r_iarg.default_argument = bool(p_val) ? "true" : "false";
  1509. break;
  1510. case Variant::INT:
  1511. if (r_iarg.type.cname != name_cache.type_int) {
  1512. r_iarg.default_argument = "(%s)" + r_iarg.default_argument;
  1513. }
  1514. break;
  1515. case Variant::REAL:
  1516. #ifndef REAL_T_IS_DOUBLE
  1517. r_iarg.default_argument += "f";
  1518. #endif
  1519. break;
  1520. case Variant::STRING:
  1521. case Variant::NODE_PATH:
  1522. r_iarg.default_argument = "\"" + r_iarg.default_argument + "\"";
  1523. break;
  1524. case Variant::TRANSFORM:
  1525. if (p_val.operator Transform() == Transform())
  1526. r_iarg.default_argument.clear();
  1527. r_iarg.default_argument = "new %s(" + r_iarg.default_argument + ")";
  1528. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  1529. break;
  1530. case Variant::PLANE:
  1531. case Variant::AABB:
  1532. case Variant::COLOR:
  1533. r_iarg.default_argument = "new Color(1, 1, 1, 1)";
  1534. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  1535. break;
  1536. case Variant::VECTOR2:
  1537. case Variant::RECT2:
  1538. case Variant::VECTOR3:
  1539. r_iarg.default_argument = "new %s" + r_iarg.default_argument;
  1540. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  1541. break;
  1542. case Variant::OBJECT:
  1543. if (p_val.is_zero()) {
  1544. r_iarg.default_argument = "null";
  1545. break;
  1546. }
  1547. case Variant::DICTIONARY:
  1548. case Variant::_RID:
  1549. r_iarg.default_argument = "new %s()";
  1550. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  1551. break;
  1552. case Variant::ARRAY:
  1553. case Variant::POOL_BYTE_ARRAY:
  1554. case Variant::POOL_INT_ARRAY:
  1555. case Variant::POOL_REAL_ARRAY:
  1556. case Variant::POOL_STRING_ARRAY:
  1557. case Variant::POOL_VECTOR2_ARRAY:
  1558. case Variant::POOL_VECTOR3_ARRAY:
  1559. case Variant::POOL_COLOR_ARRAY:
  1560. r_iarg.default_argument = "new %s {}";
  1561. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  1562. break;
  1563. case Variant::TRANSFORM2D:
  1564. case Variant::BASIS:
  1565. case Variant::QUAT:
  1566. r_iarg.default_argument = Variant::get_type_name(p_val.get_type()) + ".Identity";
  1567. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  1568. break;
  1569. default: {}
  1570. }
  1571. if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "null")
  1572. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  1573. }
  1574. void BindingsGenerator::_populate_builtin_type_interfaces() {
  1575. builtin_types.clear();
  1576. TypeInterface itype;
  1577. #define INSERT_STRUCT_TYPE(m_type, m_type_in) \
  1578. { \
  1579. itype = TypeInterface::create_value_type(String(#m_type)); \
  1580. itype.c_in = "\t%0 %1_in = MARSHALLED_IN(" #m_type ", %1);\n"; \
  1581. itype.c_out = "\treturn MARSHALLED_OUT(" #m_type ", %1);\n"; \
  1582. itype.c_arg_in = "&%s_in"; \
  1583. itype.c_type_in = "GDMonoMarshal::M_" #m_type "*"; \
  1584. itype.c_type_out = "GDMonoMarshal::M_" #m_type; \
  1585. itype.cs_in = "ref %s"; \
  1586. itype.cs_out = "return (%1)%0;"; \
  1587. itype.im_type_out = itype.cs_type; \
  1588. builtin_types.insert(itype.cname, itype); \
  1589. }
  1590. INSERT_STRUCT_TYPE(Vector2, "real_t*")
  1591. INSERT_STRUCT_TYPE(Rect2, "real_t*")
  1592. INSERT_STRUCT_TYPE(Transform2D, "real_t*")
  1593. INSERT_STRUCT_TYPE(Vector3, "real_t*")
  1594. INSERT_STRUCT_TYPE(Basis, "real_t*")
  1595. INSERT_STRUCT_TYPE(Quat, "real_t*")
  1596. INSERT_STRUCT_TYPE(Transform, "real_t*")
  1597. INSERT_STRUCT_TYPE(AABB, "real_t*")
  1598. INSERT_STRUCT_TYPE(Color, "real_t*")
  1599. INSERT_STRUCT_TYPE(Plane, "real_t*")
  1600. #undef INSERT_STRUCT_TYPE
  1601. // bool
  1602. itype = TypeInterface::create_value_type(String("bool"));
  1603. {
  1604. // MonoBoolean <---> bool
  1605. itype.c_in = "\t%0 %1_in = (%0)%1;\n";
  1606. itype.c_out = "\treturn (%0)%1;\n";
  1607. itype.c_type = "bool";
  1608. itype.c_type_in = "MonoBoolean";
  1609. itype.c_type_out = itype.c_type_in;
  1610. itype.c_arg_in = "&%s_in";
  1611. }
  1612. itype.im_type_in = itype.name;
  1613. itype.im_type_out = itype.name;
  1614. builtin_types.insert(itype.cname, itype);
  1615. // int
  1616. // C interface is the same as that of enums. Remember to apply any
  1617. // changes done here to TypeInterface::postsetup_enum_type as well
  1618. itype = TypeInterface::create_value_type(String("int"));
  1619. itype.c_arg_in = "&%s_in";
  1620. {
  1621. // The expected types for parameters and return value in ptrcall are 'int64_t' or 'uint64_t'.
  1622. itype.c_in = "\t%0 %1_in = (%0)%1;\n";
  1623. itype.c_out = "\treturn (%0)%1;\n";
  1624. itype.c_type = "int64_t";
  1625. }
  1626. itype.c_type_in = "int32_t";
  1627. itype.c_type_out = itype.c_type_in;
  1628. itype.im_type_in = itype.name;
  1629. itype.im_type_out = itype.name;
  1630. builtin_types.insert(itype.cname, itype);
  1631. // real_t
  1632. itype = TypeInterface();
  1633. itype.name = "float"; // The name is always "float" in Variant, even with REAL_T_IS_DOUBLE.
  1634. itype.cname = itype.name;
  1635. #ifdef REAL_T_IS_DOUBLE
  1636. itype.proxy_name = "double";
  1637. #else
  1638. itype.proxy_name = "float";
  1639. #endif
  1640. {
  1641. // The expected type for parameters and return value in ptrcall is 'double'.
  1642. itype.c_in = "\t%0 %1_in = (%0)%1;\n";
  1643. itype.c_out = "\treturn (%0)%1;\n";
  1644. itype.c_type = "double";
  1645. itype.c_type_in = "real_t";
  1646. itype.c_type_out = "real_t";
  1647. itype.c_arg_in = "&%s_in";
  1648. }
  1649. itype.cs_type = itype.proxy_name;
  1650. itype.im_type_in = itype.proxy_name;
  1651. itype.im_type_out = itype.proxy_name;
  1652. builtin_types.insert(itype.cname, itype);
  1653. // String
  1654. itype = TypeInterface();
  1655. itype.name = "String";
  1656. itype.cname = itype.name;
  1657. itype.proxy_name = "string";
  1658. itype.c_in = "\t%0 %1_in = " C_METHOD_MONOSTR_TO_GODOT "(%1);\n";
  1659. itype.c_out = "\treturn " C_METHOD_MONOSTR_FROM_GODOT "(%1);\n";
  1660. itype.c_arg_in = "&%s_in";
  1661. itype.c_type = itype.name;
  1662. itype.c_type_in = "MonoString*";
  1663. itype.c_type_out = "MonoString*";
  1664. itype.cs_type = itype.proxy_name;
  1665. itype.im_type_in = itype.proxy_name;
  1666. itype.im_type_out = itype.proxy_name;
  1667. builtin_types.insert(itype.cname, itype);
  1668. // NodePath
  1669. itype = TypeInterface();
  1670. itype.name = "NodePath";
  1671. itype.cname = itype.name;
  1672. itype.proxy_name = "NodePath";
  1673. itype.c_out = "\treturn memnew(NodePath(%1));\n";
  1674. itype.c_type = itype.name;
  1675. itype.c_type_in = itype.c_type + "*";
  1676. itype.c_type_out = itype.c_type + "*";
  1677. itype.cs_type = itype.proxy_name;
  1678. itype.cs_in = "NodePath." CS_SMETHOD_GETINSTANCE "(%0)";
  1679. itype.cs_out = "return new %1(%0);";
  1680. itype.im_type_in = "IntPtr";
  1681. itype.im_type_out = "IntPtr";
  1682. builtin_types.insert(itype.cname, itype);
  1683. // RID
  1684. itype = TypeInterface();
  1685. itype.name = "RID";
  1686. itype.cname = itype.name;
  1687. itype.proxy_name = "RID";
  1688. itype.c_out = "\treturn memnew(RID(%1));\n";
  1689. itype.c_type = itype.name;
  1690. itype.c_type_in = itype.c_type + "*";
  1691. itype.c_type_out = itype.c_type + "*";
  1692. itype.cs_type = itype.proxy_name;
  1693. itype.cs_in = "RID." CS_SMETHOD_GETINSTANCE "(%0)";
  1694. itype.cs_out = "return new %1(%0);";
  1695. itype.im_type_in = "IntPtr";
  1696. itype.im_type_out = "IntPtr";
  1697. builtin_types.insert(itype.cname, itype);
  1698. // Variant
  1699. itype = TypeInterface();
  1700. itype.name = "Variant";
  1701. itype.cname = itype.name;
  1702. itype.proxy_name = "object";
  1703. itype.c_in = "\t%0 %1_in = " C_METHOD_MANAGED_TO_VARIANT "(%1);\n";
  1704. itype.c_out = "\treturn " C_METHOD_MANAGED_FROM_VARIANT "(%1);\n";
  1705. itype.c_arg_in = "&%s_in";
  1706. itype.c_type = itype.name;
  1707. itype.c_type_in = "MonoObject*";
  1708. itype.c_type_out = "MonoObject*";
  1709. itype.cs_type = itype.proxy_name;
  1710. itype.im_type_in = "object";
  1711. itype.im_type_out = itype.proxy_name;
  1712. builtin_types.insert(itype.cname, itype);
  1713. // VarArg (fictitious type to represent variable arguments)
  1714. itype = TypeInterface();
  1715. itype.name = "VarArg";
  1716. itype.cname = itype.name;
  1717. itype.proxy_name = "object[]";
  1718. itype.c_in = "\t%0 %1_in = " C_METHOD_MONOARRAY_TO(Array) "(%1);\n";
  1719. itype.c_arg_in = "&%s_in";
  1720. itype.c_type = "Array";
  1721. itype.c_type_in = "MonoArray*";
  1722. itype.cs_type = "params object[]";
  1723. itype.im_type_in = "object[]";
  1724. builtin_types.insert(itype.cname, itype);
  1725. #define INSERT_ARRAY_FULL(m_name, m_type, m_proxy_t) \
  1726. { \
  1727. itype = TypeInterface(); \
  1728. itype.name = #m_name; \
  1729. itype.cname = itype.name; \
  1730. itype.proxy_name = #m_proxy_t "[]"; \
  1731. itype.c_in = "\t%0 %1_in = " C_METHOD_MONOARRAY_TO(m_type) "(%1);\n"; \
  1732. itype.c_out = "\treturn " C_METHOD_MONOARRAY_FROM(m_type) "(%1);\n"; \
  1733. itype.c_arg_in = "&%s_in"; \
  1734. itype.c_type = #m_type; \
  1735. itype.c_type_in = "MonoArray*"; \
  1736. itype.c_type_out = "MonoArray*"; \
  1737. itype.cs_type = itype.proxy_name; \
  1738. itype.im_type_in = itype.proxy_name; \
  1739. itype.im_type_out = itype.proxy_name; \
  1740. builtin_types.insert(itype.name, itype); \
  1741. }
  1742. #define INSERT_ARRAY(m_type, m_proxy_t) INSERT_ARRAY_FULL(m_type, m_type, m_proxy_t)
  1743. INSERT_ARRAY(PoolIntArray, int);
  1744. INSERT_ARRAY_FULL(PoolByteArray, PoolByteArray, byte);
  1745. #ifdef REAL_T_IS_DOUBLE
  1746. INSERT_ARRAY(PoolRealArray, double);
  1747. #else
  1748. INSERT_ARRAY(PoolRealArray, float);
  1749. #endif
  1750. INSERT_ARRAY(PoolStringArray, string);
  1751. INSERT_ARRAY(PoolColorArray, Color);
  1752. INSERT_ARRAY(PoolVector2Array, Vector2);
  1753. INSERT_ARRAY(PoolVector3Array, Vector3);
  1754. #undef INSERT_ARRAY
  1755. // Array
  1756. itype = TypeInterface();
  1757. itype.name = "Array";
  1758. itype.cname = itype.name;
  1759. itype.proxy_name = itype.name;
  1760. itype.c_out = "\treturn memnew(Array(%1));\n";
  1761. itype.c_type = itype.name;
  1762. itype.c_type_in = itype.c_type + "*";
  1763. itype.c_type_out = itype.c_type + "*";
  1764. itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
  1765. itype.cs_in = "%0." CS_SMETHOD_GETINSTANCE "()";
  1766. itype.cs_out = "return new " + itype.cs_type + "(%0);";
  1767. itype.im_type_in = "IntPtr";
  1768. itype.im_type_out = "IntPtr";
  1769. builtin_types.insert(itype.cname, itype);
  1770. // Dictionary
  1771. itype = TypeInterface();
  1772. itype.name = "Dictionary";
  1773. itype.cname = itype.name;
  1774. itype.proxy_name = itype.name;
  1775. itype.c_out = "\treturn memnew(Dictionary(%1));\n";
  1776. itype.c_type = itype.name;
  1777. itype.c_type_in = itype.c_type + "*";
  1778. itype.c_type_out = itype.c_type + "*";
  1779. itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
  1780. itype.cs_in = "%0." CS_SMETHOD_GETINSTANCE "()";
  1781. itype.cs_out = "return new " + itype.cs_type + "(%0);";
  1782. itype.im_type_in = "IntPtr";
  1783. itype.im_type_out = "IntPtr";
  1784. builtin_types.insert(itype.cname, itype);
  1785. // void (fictitious type to represent the return type of methods that do not return anything)
  1786. itype = TypeInterface();
  1787. itype.name = "void";
  1788. itype.cname = itype.name;
  1789. itype.proxy_name = itype.name;
  1790. itype.c_type = itype.name;
  1791. itype.c_type_in = itype.c_type;
  1792. itype.c_type_out = itype.c_type;
  1793. itype.cs_type = itype.proxy_name;
  1794. itype.im_type_in = itype.proxy_name;
  1795. itype.im_type_out = itype.proxy_name;
  1796. builtin_types.insert(itype.cname, itype);
  1797. }
  1798. void BindingsGenerator::_populate_global_constants() {
  1799. int global_constants_count = GlobalConstants::get_global_constant_count();
  1800. if (global_constants_count > 0) {
  1801. Map<String, DocData::ClassDoc>::Element *match = EditorHelp::get_doc_data()->class_list.find("@GlobalScope");
  1802. ERR_EXPLAIN("Could not find `@GlobalScope` in DocData");
  1803. CRASH_COND(!match);
  1804. const DocData::ClassDoc &global_scope_doc = match->value();
  1805. for (int i = 0; i < global_constants_count; i++) {
  1806. String constant_name = GlobalConstants::get_global_constant_name(i);
  1807. const DocData::ConstantDoc *const_doc = NULL;
  1808. for (int j = 0; j < global_scope_doc.constants.size(); j++) {
  1809. const DocData::ConstantDoc &curr_const_doc = global_scope_doc.constants[j];
  1810. if (curr_const_doc.name == constant_name) {
  1811. const_doc = &curr_const_doc;
  1812. break;
  1813. }
  1814. }
  1815. int constant_value = GlobalConstants::get_global_constant_value(i);
  1816. StringName enum_name = GlobalConstants::get_global_constant_enum(i);
  1817. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), constant_value);
  1818. iconstant.const_doc = const_doc;
  1819. if (enum_name != StringName()) {
  1820. EnumInterface ienum(enum_name);
  1821. List<EnumInterface>::Element *match = global_enums.find(ienum);
  1822. if (match) {
  1823. match->get().constants.push_back(iconstant);
  1824. } else {
  1825. ienum.constants.push_back(iconstant);
  1826. global_enums.push_back(ienum);
  1827. }
  1828. } else {
  1829. global_constants.push_back(iconstant);
  1830. }
  1831. }
  1832. for (List<EnumInterface>::Element *E = global_enums.front(); E; E = E->next()) {
  1833. EnumInterface &ienum = E->get();
  1834. TypeInterface enum_itype;
  1835. enum_itype.is_enum = true;
  1836. enum_itype.name = ienum.cname.operator String();
  1837. enum_itype.cname = ienum.cname;
  1838. enum_itype.proxy_name = enum_itype.name;
  1839. TypeInterface::postsetup_enum_type(enum_itype);
  1840. enum_types.insert(enum_itype.cname, enum_itype);
  1841. int prefix_length = _determine_enum_prefix(ienum);
  1842. // HARDCODED: The Error enum have the prefix 'ERR_' for everything except 'OK' and 'FAILED'.
  1843. if (ienum.cname == name_cache.enum_Error) {
  1844. if (prefix_length > 0) { // Just in case it ever changes
  1845. ERR_PRINTS("Prefix for enum 'Error' is not empty");
  1846. }
  1847. prefix_length = 1; // 'ERR_'
  1848. }
  1849. _apply_prefix_to_enum_constants(ienum, prefix_length);
  1850. }
  1851. }
  1852. // HARDCODED
  1853. List<StringName> hardcoded_enums;
  1854. hardcoded_enums.push_back("Vector3.Axis");
  1855. for (List<StringName>::Element *E = hardcoded_enums.front(); E; E = E->next()) {
  1856. // These enums are not generated and must be written manually (e.g.: Vector3.Axis)
  1857. // Here, we assume core types do not begin with underscore
  1858. TypeInterface enum_itype;
  1859. enum_itype.is_enum = true;
  1860. enum_itype.name = E->get().operator String();
  1861. enum_itype.cname = E->get();
  1862. enum_itype.proxy_name = enum_itype.name;
  1863. TypeInterface::postsetup_enum_type(enum_itype);
  1864. enum_types.insert(enum_itype.cname, enum_itype);
  1865. }
  1866. }
  1867. void BindingsGenerator::initialize() {
  1868. EditorHelp::generate_doc();
  1869. enum_types.clear();
  1870. _populate_object_type_interfaces();
  1871. _populate_builtin_type_interfaces();
  1872. _populate_global_constants();
  1873. // Generate internal calls (after populating type interfaces and global constants)
  1874. core_custom_icalls.clear();
  1875. editor_custom_icalls.clear();
  1876. for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next())
  1877. _generate_method_icalls(E.get());
  1878. }
  1879. void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) {
  1880. const int NUM_OPTIONS = 2;
  1881. int options_left = NUM_OPTIONS;
  1882. String mono_glue_option = "--generate-mono-glue";
  1883. String cs_api_option = "--generate-cs-api";
  1884. verbose_output = true;
  1885. const List<String>::Element *elem = p_cmdline_args.front();
  1886. while (elem && options_left) {
  1887. if (elem->get() == mono_glue_option) {
  1888. const List<String>::Element *path_elem = elem->next();
  1889. if (path_elem) {
  1890. if (get_singleton()->generate_glue(path_elem->get()) != OK)
  1891. ERR_PRINTS(mono_glue_option + ": Failed to generate mono glue");
  1892. elem = elem->next();
  1893. } else {
  1894. ERR_PRINTS(mono_glue_option + ": No output directory specified");
  1895. }
  1896. --options_left;
  1897. } else if (elem->get() == cs_api_option) {
  1898. const List<String>::Element *path_elem = elem->next();
  1899. if (path_elem) {
  1900. if (get_singleton()->generate_cs_api(path_elem->get()) != OK)
  1901. ERR_PRINTS(cs_api_option + ": Failed to generate the C# API");
  1902. elem = elem->next();
  1903. } else {
  1904. ERR_PRINTS(cs_api_option + ": No output directory specified");
  1905. }
  1906. --options_left;
  1907. }
  1908. elem = elem->next();
  1909. }
  1910. verbose_output = false;
  1911. if (options_left != NUM_OPTIONS)
  1912. ::exit(0);
  1913. }
  1914. #endif