2
0

bindings_generator.cpp 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074
  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_VARARG_RET "vararg_ret"
  72. #define C_LOCAL_PTRCALL_ARGS "call_args"
  73. #define C_MACRO_OBJECT_CONSTRUCT "GODOTSHARP_INSTANCE_OBJECT"
  74. #define C_NS_MONOUTILS "GDMonoUtils"
  75. #define C_NS_MONOINTERNALS "GDMonoInternals"
  76. #define C_METHOD_TIE_MANAGED_TO_UNMANAGED C_NS_MONOINTERNALS "::tie_managed_to_unmanaged"
  77. #define C_METHOD_UNMANAGED_GET_MANAGED C_NS_MONOUTILS "::unmanaged_get_managed"
  78. #define C_NS_MONOMARSHAL "GDMonoMarshal"
  79. #define C_METHOD_MANAGED_TO_VARIANT C_NS_MONOMARSHAL "::mono_object_to_variant"
  80. #define C_METHOD_MANAGED_FROM_VARIANT C_NS_MONOMARSHAL "::variant_to_mono_object"
  81. #define C_METHOD_MONOSTR_TO_GODOT C_NS_MONOMARSHAL "::mono_string_to_godot"
  82. #define C_METHOD_MONOSTR_FROM_GODOT C_NS_MONOMARSHAL "::mono_string_from_godot"
  83. #define C_METHOD_MONOARRAY_TO(m_type) C_NS_MONOMARSHAL "::mono_array_to_" #m_type
  84. #define C_METHOD_MONOARRAY_FROM(m_type) C_NS_MONOMARSHAL "::" #m_type "_to_mono_array"
  85. #define BINDINGS_GENERATOR_VERSION UINT32_C(9)
  86. const char *BindingsGenerator::TypeInterface::DEFAULT_VARARG_C_IN("\t%0 %1_in = %1;\n");
  87. static String fix_doc_description(const String &p_bbcode) {
  88. // This seems to be the correct way to do this. It's the same EditorHelp does.
  89. return p_bbcode.dedent()
  90. .replace("\t", "")
  91. .replace("\r", "")
  92. .strip_edges();
  93. }
  94. static String snake_to_pascal_case(const String &p_identifier, bool p_input_is_upper = false) {
  95. String ret;
  96. Vector<String> parts = p_identifier.split("_", true);
  97. for (int i = 0; i < parts.size(); i++) {
  98. String part = parts[i];
  99. if (part.length()) {
  100. part[0] = _find_upper(part[0]);
  101. if (p_input_is_upper) {
  102. for (int j = 1; j < part.length(); j++)
  103. part[j] = _find_lower(part[j]);
  104. }
  105. ret += part;
  106. } else {
  107. if (i == 0 || i == (parts.size() - 1)) {
  108. // Preserve underscores at the beginning and end
  109. ret += "_";
  110. } else {
  111. // Preserve contiguous underscores
  112. if (parts[i - 1].length()) {
  113. ret += "__";
  114. } else {
  115. ret += "_";
  116. }
  117. }
  118. }
  119. }
  120. return ret;
  121. }
  122. static String snake_to_camel_case(const String &p_identifier, bool p_input_is_upper = false) {
  123. String ret;
  124. Vector<String> parts = p_identifier.split("_", true);
  125. for (int i = 0; i < parts.size(); i++) {
  126. String part = parts[i];
  127. if (part.length()) {
  128. if (i != 0) {
  129. part[0] = _find_upper(part[0]);
  130. }
  131. if (p_input_is_upper) {
  132. for (int j = i != 0 ? 1 : 0; j < part.length(); j++)
  133. part[j] = _find_lower(part[j]);
  134. }
  135. ret += part;
  136. } else {
  137. if (i == 0 || i == (parts.size() - 1)) {
  138. // Preserve underscores at the beginning and end
  139. ret += "_";
  140. } else {
  141. // Preserve contiguous underscores
  142. if (parts[i - 1].length()) {
  143. ret += "__";
  144. } else {
  145. ret += "_";
  146. }
  147. }
  148. }
  149. }
  150. return ret;
  151. }
  152. String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterface *p_itype) {
  153. // Based on the version in EditorHelp
  154. if (p_bbcode.empty())
  155. return String();
  156. DocData *doc = EditorHelp::get_doc_data();
  157. String bbcode = p_bbcode;
  158. StringBuilder xml_output;
  159. xml_output.append("<para>");
  160. List<String> tag_stack;
  161. bool code_tag = false;
  162. int pos = 0;
  163. while (pos < bbcode.length()) {
  164. int brk_pos = bbcode.find("[", pos);
  165. if (brk_pos < 0)
  166. brk_pos = bbcode.length();
  167. if (brk_pos > pos) {
  168. String text = bbcode.substr(pos, brk_pos - pos);
  169. if (code_tag || tag_stack.size() > 0) {
  170. xml_output.append(text.xml_escape());
  171. } else {
  172. Vector<String> lines = text.split("\n");
  173. for (int i = 0; i < lines.size(); i++) {
  174. if (i != 0)
  175. xml_output.append("<para>");
  176. xml_output.append(lines[i].xml_escape());
  177. if (i != lines.size() - 1)
  178. xml_output.append("</para>\n");
  179. }
  180. }
  181. }
  182. if (brk_pos == bbcode.length())
  183. break; // nothing else to add
  184. int brk_end = bbcode.find("]", brk_pos + 1);
  185. if (brk_end == -1) {
  186. String text = bbcode.substr(brk_pos, bbcode.length() - brk_pos);
  187. if (code_tag || tag_stack.size() > 0) {
  188. xml_output.append(text.xml_escape());
  189. } else {
  190. Vector<String> lines = text.split("\n");
  191. for (int i = 0; i < lines.size(); i++) {
  192. if (i != 0)
  193. xml_output.append("<para>");
  194. xml_output.append(lines[i].xml_escape());
  195. if (i != lines.size() - 1)
  196. xml_output.append("</para>\n");
  197. }
  198. }
  199. break;
  200. }
  201. String tag = bbcode.substr(brk_pos + 1, brk_end - brk_pos - 1);
  202. if (tag.begins_with("/")) {
  203. bool tag_ok = tag_stack.size() && tag_stack.front()->get() == tag.substr(1, tag.length());
  204. if (!tag_ok) {
  205. xml_output.append("[");
  206. pos = brk_pos + 1;
  207. continue;
  208. }
  209. tag_stack.pop_front();
  210. pos = brk_end + 1;
  211. code_tag = false;
  212. if (tag == "/url") {
  213. xml_output.append("</a>");
  214. } else if (tag == "/code") {
  215. xml_output.append("</c>");
  216. } else if (tag == "/codeblock") {
  217. xml_output.append("</code>");
  218. }
  219. } else if (code_tag) {
  220. xml_output.append("[");
  221. pos = brk_pos + 1;
  222. } else if (tag.begins_with("method ") || tag.begins_with("member ") || tag.begins_with("signal ") || tag.begins_with("enum ") || tag.begins_with("constant ")) {
  223. String link_target = tag.substr(tag.find(" ") + 1, tag.length());
  224. String link_tag = tag.substr(0, tag.find(" "));
  225. Vector<String> link_target_parts = link_target.split(".");
  226. if (link_target_parts.size() <= 0 || link_target_parts.size() > 2) {
  227. ERR_PRINTS("Invalid reference format: '" + tag + "'.");
  228. xml_output.append("<c>");
  229. xml_output.append(tag);
  230. xml_output.append("</c>");
  231. pos = brk_end + 1;
  232. continue;
  233. }
  234. const TypeInterface *target_itype;
  235. StringName target_cname;
  236. if (link_target_parts.size() == 2) {
  237. target_itype = _get_type_or_null(TypeReference(link_target_parts[0]));
  238. if (!target_itype) {
  239. target_itype = _get_type_or_null(TypeReference("_" + link_target_parts[0]));
  240. }
  241. target_cname = link_target_parts[1];
  242. } else {
  243. target_itype = p_itype;
  244. target_cname = link_target_parts[0];
  245. }
  246. if (link_tag == "method") {
  247. if (!target_itype || !target_itype->is_object_type) {
  248. if (OS::get_singleton()->is_stdout_verbose()) {
  249. if (target_itype) {
  250. OS::get_singleton()->print("Cannot resolve method reference for non-Godot.Object type in documentation: %s\n", link_target.utf8().get_data());
  251. } else {
  252. OS::get_singleton()->print("Cannot resolve type from method reference in documentation: %s\n", link_target.utf8().get_data());
  253. }
  254. }
  255. // TODO Map what we can
  256. xml_output.append("<c>");
  257. xml_output.append(link_target);
  258. xml_output.append("</c>");
  259. } else {
  260. const MethodInterface *target_imethod = target_itype->find_method_by_name(target_cname);
  261. if (target_imethod) {
  262. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  263. xml_output.append(target_itype->proxy_name);
  264. xml_output.append(".");
  265. xml_output.append(target_imethod->proxy_name);
  266. xml_output.append("\"/>");
  267. }
  268. }
  269. } else if (link_tag == "member") {
  270. if (!target_itype || !target_itype->is_object_type) {
  271. if (OS::get_singleton()->is_stdout_verbose()) {
  272. if (target_itype) {
  273. OS::get_singleton()->print("Cannot resolve member reference for non-Godot.Object type in documentation: %s\n", link_target.utf8().get_data());
  274. } else {
  275. OS::get_singleton()->print("Cannot resolve type from member reference in documentation: %s\n", link_target.utf8().get_data());
  276. }
  277. }
  278. // TODO Map what we can
  279. xml_output.append("<c>");
  280. xml_output.append(link_target);
  281. xml_output.append("</c>");
  282. } else {
  283. const PropertyInterface *target_iprop = target_itype->find_property_by_name(target_cname);
  284. if (target_iprop) {
  285. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  286. xml_output.append(target_itype->proxy_name);
  287. xml_output.append(".");
  288. xml_output.append(target_iprop->proxy_name);
  289. xml_output.append("\"/>");
  290. }
  291. }
  292. } else if (link_tag == "signal") {
  293. // We do not declare signals in any way in C#, so there is nothing to reference
  294. xml_output.append("<c>");
  295. xml_output.append(link_target);
  296. xml_output.append("</c>");
  297. } else if (link_tag == "enum") {
  298. StringName search_cname = !target_itype ? target_cname :
  299. StringName(target_itype->name + "." + (String)target_cname);
  300. const Map<StringName, TypeInterface>::Element *enum_match = enum_types.find(search_cname);
  301. if (!enum_match && search_cname != target_cname) {
  302. enum_match = enum_types.find(target_cname);
  303. }
  304. if (enum_match) {
  305. const TypeInterface &target_enum_itype = enum_match->value();
  306. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  307. xml_output.append(target_enum_itype.proxy_name); // Includes nesting class if any
  308. xml_output.append("\"/>");
  309. } else {
  310. ERR_PRINTS("Cannot resolve enum reference in documentation: '" + link_target + "'.");
  311. xml_output.append("<c>");
  312. xml_output.append(link_target);
  313. xml_output.append("</c>");
  314. }
  315. } else if (link_tag == "const") {
  316. if (!target_itype || !target_itype->is_object_type) {
  317. if (OS::get_singleton()->is_stdout_verbose()) {
  318. if (target_itype) {
  319. OS::get_singleton()->print("Cannot resolve constant reference for non-Godot.Object type in documentation: %s\n", link_target.utf8().get_data());
  320. } else {
  321. OS::get_singleton()->print("Cannot resolve type from constant reference in documentation: %s\n", link_target.utf8().get_data());
  322. }
  323. }
  324. // TODO Map what we can
  325. xml_output.append("<c>");
  326. xml_output.append(link_target);
  327. xml_output.append("</c>");
  328. } else if (!target_itype && target_cname == name_cache.type_at_GlobalScope) {
  329. String target_name = (String)target_cname;
  330. // Try to find as a global constant
  331. const ConstantInterface *target_iconst = find_constant_by_name(target_name, global_constants);
  332. if (target_iconst) {
  333. // Found global constant
  334. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "." BINDINGS_GLOBAL_SCOPE_CLASS ".");
  335. xml_output.append(target_iconst->proxy_name);
  336. xml_output.append("\"/>");
  337. } else {
  338. // Try to find as global enum constant
  339. const EnumInterface *target_ienum = NULL;
  340. for (const List<EnumInterface>::Element *E = global_enums.front(); E; E = E->next()) {
  341. target_ienum = &E->get();
  342. target_iconst = find_constant_by_name(target_name, target_ienum->constants);
  343. if (target_iconst)
  344. break;
  345. }
  346. if (target_iconst) {
  347. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  348. xml_output.append(target_ienum->cname);
  349. xml_output.append(".");
  350. xml_output.append(target_iconst->proxy_name);
  351. xml_output.append("\"/>");
  352. } else {
  353. ERR_PRINTS("Cannot resolve global constant reference in documentation: '" + link_target + "'.");
  354. xml_output.append("<c>");
  355. xml_output.append(link_target);
  356. xml_output.append("</c>");
  357. }
  358. }
  359. } else {
  360. String target_name = (String)target_cname;
  361. // Try to find the constant in the current class
  362. const ConstantInterface *target_iconst = find_constant_by_name(target_name, target_itype->constants);
  363. if (target_iconst) {
  364. // Found constant in current class
  365. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  366. xml_output.append(target_itype->proxy_name);
  367. xml_output.append(".");
  368. xml_output.append(target_iconst->proxy_name);
  369. xml_output.append("\"/>");
  370. } else {
  371. // Try to find as enum constant in the current class
  372. const EnumInterface *target_ienum = NULL;
  373. for (const List<EnumInterface>::Element *E = target_itype->enums.front(); E; E = E->next()) {
  374. target_ienum = &E->get();
  375. target_iconst = find_constant_by_name(target_name, target_ienum->constants);
  376. if (target_iconst)
  377. break;
  378. }
  379. if (target_iconst) {
  380. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  381. xml_output.append(target_itype->proxy_name);
  382. xml_output.append(".");
  383. xml_output.append(target_ienum->cname);
  384. xml_output.append(".");
  385. xml_output.append(target_iconst->proxy_name);
  386. xml_output.append("\"/>");
  387. } else {
  388. ERR_PRINTS("Cannot resolve constant reference in documentation: '" + link_target + "'.");
  389. xml_output.append("<c>");
  390. xml_output.append(link_target);
  391. xml_output.append("</c>");
  392. }
  393. }
  394. }
  395. }
  396. pos = brk_end + 1;
  397. } else if (doc->class_list.has(tag)) {
  398. if (tag == "Array" || tag == "Dictionary") {
  399. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE_COLLECTIONS ".");
  400. xml_output.append(tag);
  401. xml_output.append("\"/>");
  402. } else if (tag == "bool" || tag == "int") {
  403. xml_output.append("<see cref=\"");
  404. xml_output.append(tag);
  405. xml_output.append("\"/>");
  406. } else if (tag == "float") {
  407. xml_output.append("<see cref=\""
  408. #ifdef REAL_T_IS_DOUBLE
  409. "double"
  410. #else
  411. "float"
  412. #endif
  413. "\"/>");
  414. } else if (tag == "Variant") {
  415. // We use System.Object for Variant, so there is no Variant type in C#
  416. xml_output.append("<c>Variant</c>");
  417. } else if (tag == "String") {
  418. xml_output.append("<see cref=\"string\"/>");
  419. } else if (tag == "Nil") {
  420. xml_output.append("<see langword=\"null\"/>");
  421. } else if (tag.begins_with("@")) {
  422. // @GlobalScope, @GDScript, etc
  423. xml_output.append("<c>");
  424. xml_output.append(tag);
  425. xml_output.append("</c>");
  426. } else if (tag == "PoolByteArray") {
  427. xml_output.append("<see cref=\"byte\"/>");
  428. } else if (tag == "PoolIntArray") {
  429. xml_output.append("<see cref=\"int\"/>");
  430. } else if (tag == "PoolRealArray") {
  431. #ifdef REAL_T_IS_DOUBLE
  432. xml_output.append("<see cref=\"double\"/>");
  433. #else
  434. xml_output.append("<see cref=\"float\"/>");
  435. #endif
  436. } else if (tag == "PoolStringArray") {
  437. xml_output.append("<see cref=\"string\"/>");
  438. } else if (tag == "PoolVector2Array") {
  439. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Vector2\"/>");
  440. } else if (tag == "PoolVector3Array") {
  441. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Vector3\"/>");
  442. } else if (tag == "PoolColorArray") {
  443. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Color\"/>");
  444. } else {
  445. const TypeInterface *target_itype = _get_type_or_null(TypeReference(tag));
  446. if (!target_itype) {
  447. target_itype = _get_type_or_null(TypeReference("_" + tag));
  448. }
  449. if (target_itype) {
  450. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  451. xml_output.append(target_itype->proxy_name);
  452. xml_output.append("\"/>");
  453. } else {
  454. ERR_PRINTS("Cannot resolve type reference in documentation: '" + tag + "'.");
  455. xml_output.append("<c>");
  456. xml_output.append(tag);
  457. xml_output.append("</c>");
  458. }
  459. }
  460. pos = brk_end + 1;
  461. } else if (tag == "b") {
  462. // bold is not supported in xml comments
  463. pos = brk_end + 1;
  464. tag_stack.push_front(tag);
  465. } else if (tag == "i") {
  466. // italics is not supported in xml comments
  467. pos = brk_end + 1;
  468. tag_stack.push_front(tag);
  469. } else if (tag == "code") {
  470. xml_output.append("<c>");
  471. code_tag = true;
  472. pos = brk_end + 1;
  473. tag_stack.push_front(tag);
  474. } else if (tag == "codeblock") {
  475. xml_output.append("<code>");
  476. code_tag = true;
  477. pos = brk_end + 1;
  478. tag_stack.push_front(tag);
  479. } else if (tag == "center") {
  480. // center is alignment not supported in xml comments
  481. pos = brk_end + 1;
  482. tag_stack.push_front(tag);
  483. } else if (tag == "br") {
  484. xml_output.append("\n"); // FIXME: Should use <para> instead. Luckily this tag isn't used for now.
  485. pos = brk_end + 1;
  486. } else if (tag == "u") {
  487. // underline is not supported in xml comments
  488. pos = brk_end + 1;
  489. tag_stack.push_front(tag);
  490. } else if (tag == "s") {
  491. // strikethrough is not supported in xml comments
  492. pos = brk_end + 1;
  493. tag_stack.push_front(tag);
  494. } else if (tag == "url") {
  495. int end = bbcode.find("[", brk_end);
  496. if (end == -1)
  497. end = bbcode.length();
  498. String url = bbcode.substr(brk_end + 1, end - brk_end - 1);
  499. xml_output.append("<a href=\"");
  500. xml_output.append(url);
  501. xml_output.append("\">");
  502. xml_output.append(url);
  503. pos = brk_end + 1;
  504. tag_stack.push_front(tag);
  505. } else if (tag.begins_with("url=")) {
  506. String url = tag.substr(4, tag.length());
  507. xml_output.append("<a href=\"");
  508. xml_output.append(url);
  509. xml_output.append("\">");
  510. pos = brk_end + 1;
  511. tag_stack.push_front("url");
  512. } else if (tag == "img") {
  513. int end = bbcode.find("[", brk_end);
  514. if (end == -1)
  515. end = bbcode.length();
  516. String image = bbcode.substr(brk_end + 1, end - brk_end - 1);
  517. // Not supported. Just append the bbcode.
  518. xml_output.append("[img]");
  519. xml_output.append(image);
  520. xml_output.append("[/img]");
  521. pos = end;
  522. tag_stack.push_front(tag);
  523. } else if (tag.begins_with("color=")) {
  524. // Not supported.
  525. pos = brk_end + 1;
  526. tag_stack.push_front("color");
  527. } else if (tag.begins_with("font=")) {
  528. // Not supported.
  529. pos = brk_end + 1;
  530. tag_stack.push_front("font");
  531. } else {
  532. xml_output.append("["); // ignore
  533. pos = brk_pos + 1;
  534. }
  535. }
  536. xml_output.append("</para>");
  537. return xml_output.as_string();
  538. }
  539. int BindingsGenerator::_determine_enum_prefix(const EnumInterface &p_ienum) {
  540. CRASH_COND(p_ienum.constants.empty());
  541. const ConstantInterface &front_iconstant = p_ienum.constants.front()->get();
  542. Vector<String> front_parts = front_iconstant.name.split("_", /* p_allow_empty: */ true);
  543. int candidate_len = front_parts.size() - 1;
  544. if (candidate_len == 0)
  545. return 0;
  546. for (const List<ConstantInterface>::Element *E = p_ienum.constants.front()->next(); E; E = E->next()) {
  547. const ConstantInterface &iconstant = E->get();
  548. Vector<String> parts = iconstant.name.split("_", /* p_allow_empty: */ true);
  549. int i;
  550. for (i = 0; i < candidate_len && i < parts.size(); i++) {
  551. if (front_parts[i] != parts[i]) {
  552. // HARDCODED: Some Flag enums have the prefix 'FLAG_' for everything except 'FLAGS_DEFAULT' (same for 'METHOD_FLAG_' and'METHOD_FLAGS_DEFAULT').
  553. bool hardcoded_exc = (i == candidate_len - 1 && ((front_parts[i] == "FLAGS" && parts[i] == "FLAG") || (front_parts[i] == "FLAG" && parts[i] == "FLAGS")));
  554. if (!hardcoded_exc)
  555. break;
  556. }
  557. }
  558. candidate_len = i;
  559. if (candidate_len == 0)
  560. return 0;
  561. }
  562. return candidate_len;
  563. }
  564. void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumInterface &p_ienum, int p_prefix_length) {
  565. if (p_prefix_length > 0) {
  566. for (List<ConstantInterface>::Element *E = p_ienum.constants.front(); E; E = E->next()) {
  567. int curr_prefix_length = p_prefix_length;
  568. ConstantInterface &curr_const = E->get();
  569. String constant_name = curr_const.name;
  570. Vector<String> parts = constant_name.split("_", /* p_allow_empty: */ true);
  571. if (parts.size() <= curr_prefix_length)
  572. continue;
  573. if (parts[curr_prefix_length][0] >= '0' && parts[curr_prefix_length][0] <= '9') {
  574. // The name of enum constants may begin with a numeric digit when strip from the enum prefix,
  575. // so we make the prefix for this constant one word shorter in those cases.
  576. for (curr_prefix_length = curr_prefix_length - 1; curr_prefix_length > 0; curr_prefix_length--) {
  577. if (parts[curr_prefix_length][0] < '0' || parts[curr_prefix_length][0] > '9')
  578. break;
  579. }
  580. }
  581. constant_name = "";
  582. for (int i = curr_prefix_length; i < parts.size(); i++) {
  583. if (i > curr_prefix_length)
  584. constant_name += "_";
  585. constant_name += parts[i];
  586. }
  587. curr_const.proxy_name = snake_to_pascal_case(constant_name, true);
  588. }
  589. }
  590. }
  591. void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) {
  592. for (const List<MethodInterface>::Element *E = p_itype.methods.front(); E; E = E->next()) {
  593. const MethodInterface &imethod = E->get();
  594. if (imethod.is_virtual)
  595. continue;
  596. const TypeInterface *return_type = _get_type_or_placeholder(imethod.return_type);
  597. String im_sig = "IntPtr " CS_PARAM_METHODBIND ", ";
  598. String im_unique_sig = imethod.return_type.cname.operator String() + ",IntPtr,IntPtr";
  599. im_sig += "IntPtr " CS_PARAM_INSTANCE;
  600. // Get arguments information
  601. int i = 0;
  602. for (const List<ArgumentInterface>::Element *F = imethod.arguments.front(); F; F = F->next()) {
  603. const TypeInterface *arg_type = _get_type_or_placeholder(F->get().type);
  604. im_sig += ", ";
  605. im_sig += arg_type->im_type_in;
  606. im_sig += " arg";
  607. im_sig += itos(i + 1);
  608. im_unique_sig += ",";
  609. im_unique_sig += get_unique_sig(*arg_type);
  610. i++;
  611. }
  612. // godot_icall_{argc}_{icallcount}
  613. String icall_method = ICALL_PREFIX;
  614. icall_method += itos(imethod.arguments.size());
  615. icall_method += "_";
  616. icall_method += itos(method_icalls.size());
  617. InternalCall im_icall = InternalCall(p_itype.api_type, icall_method, return_type->im_type_out, im_sig, im_unique_sig);
  618. List<InternalCall>::Element *match = method_icalls.find(im_icall);
  619. if (match) {
  620. if (p_itype.api_type != ClassDB::API_EDITOR)
  621. match->get().editor_only = false;
  622. method_icalls_map.insert(&E->get(), &match->get());
  623. } else {
  624. List<InternalCall>::Element *added = method_icalls.push_back(im_icall);
  625. method_icalls_map.insert(&E->get(), &added->get());
  626. }
  627. }
  628. }
  629. void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
  630. // Constants (in partial GD class)
  631. p_output.append("\n#pragma warning disable CS1591 // Disable warning: "
  632. "'Missing XML comment for publicly visible type or member'\n");
  633. p_output.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  634. p_output.append(INDENT1 "public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n" INDENT1 "{");
  635. for (const List<ConstantInterface>::Element *E = global_constants.front(); E; E = E->next()) {
  636. const ConstantInterface &iconstant = E->get();
  637. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  638. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), NULL);
  639. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  640. if (summary_lines.size()) {
  641. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  642. for (int i = 0; i < summary_lines.size(); i++) {
  643. p_output.append(INDENT2 "/// ");
  644. p_output.append(summary_lines[i]);
  645. p_output.append("\n");
  646. }
  647. p_output.append(INDENT2 "/// </summary>");
  648. }
  649. }
  650. p_output.append(MEMBER_BEGIN "public const int ");
  651. p_output.append(iconstant.proxy_name);
  652. p_output.append(" = ");
  653. p_output.append(itos(iconstant.value));
  654. p_output.append(";");
  655. }
  656. if (!global_constants.empty())
  657. p_output.append("\n");
  658. p_output.append(INDENT1 CLOSE_BLOCK); // end of GD class
  659. // Enums
  660. for (List<EnumInterface>::Element *E = global_enums.front(); E; E = E->next()) {
  661. const EnumInterface &ienum = E->get();
  662. CRASH_COND(ienum.constants.empty());
  663. String enum_proxy_name = ienum.cname.operator String();
  664. bool enum_in_static_class = false;
  665. if (enum_proxy_name.find(".") > 0) {
  666. enum_in_static_class = true;
  667. String enum_class_name = enum_proxy_name.get_slicec('.', 0);
  668. enum_proxy_name = enum_proxy_name.get_slicec('.', 1);
  669. CRASH_COND(enum_class_name != "Variant"); // Hard-coded...
  670. _log("Declaring global enum '%s' inside static class '%s'\n", enum_proxy_name.utf8().get_data(), enum_class_name.utf8().get_data());
  671. p_output.append("\n" INDENT1 "public static partial class ");
  672. p_output.append(enum_class_name);
  673. p_output.append("\n" INDENT1 OPEN_BLOCK);
  674. }
  675. p_output.append("\n" INDENT1 "public enum ");
  676. p_output.append(enum_proxy_name);
  677. p_output.append("\n" INDENT1 OPEN_BLOCK);
  678. for (const List<ConstantInterface>::Element *F = ienum.constants.front(); F; F = F->next()) {
  679. const ConstantInterface &iconstant = F->get();
  680. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  681. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), NULL);
  682. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  683. if (summary_lines.size()) {
  684. p_output.append(INDENT2 "/// <summary>\n");
  685. for (int i = 0; i < summary_lines.size(); i++) {
  686. p_output.append(INDENT2 "/// ");
  687. p_output.append(summary_lines[i]);
  688. p_output.append("\n");
  689. }
  690. p_output.append(INDENT2 "/// </summary>\n");
  691. }
  692. }
  693. p_output.append(INDENT2);
  694. p_output.append(iconstant.proxy_name);
  695. p_output.append(" = ");
  696. p_output.append(itos(iconstant.value));
  697. p_output.append(F != ienum.constants.back() ? ",\n" : "\n");
  698. }
  699. p_output.append(INDENT1 CLOSE_BLOCK);
  700. if (enum_in_static_class)
  701. p_output.append(INDENT1 CLOSE_BLOCK);
  702. }
  703. p_output.append(CLOSE_BLOCK); // end of namespace
  704. p_output.append("\n#pragma warning restore CS1591\n");
  705. }
  706. Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir, Vector<String> &r_compile_items) {
  707. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  708. ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
  709. if (!DirAccess::exists(p_proj_dir)) {
  710. Error err = da->make_dir_recursive(p_proj_dir);
  711. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Cannot create directory '" + p_proj_dir + "'.");
  712. }
  713. da->change_dir(p_proj_dir);
  714. da->make_dir("Core");
  715. da->make_dir("ObjectType");
  716. String core_dir = path::join(p_proj_dir, "Core");
  717. String obj_type_dir = path::join(p_proj_dir, "ObjectType");
  718. // Generate source file for global scope constants and enums
  719. {
  720. StringBuilder constants_source;
  721. _generate_global_constants(constants_source);
  722. String output_file = path::join(core_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_constants.cs");
  723. Error save_err = _save_file(output_file, constants_source);
  724. if (save_err != OK)
  725. return save_err;
  726. r_compile_items.push_back(output_file);
  727. }
  728. for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
  729. const TypeInterface &itype = E.get();
  730. if (itype.api_type == ClassDB::API_EDITOR)
  731. continue;
  732. String output_file = path::join(obj_type_dir, itype.proxy_name + ".cs");
  733. Error err = _generate_cs_type(itype, output_file);
  734. if (err == ERR_SKIP)
  735. continue;
  736. if (err != OK)
  737. return err;
  738. r_compile_items.push_back(output_file);
  739. }
  740. // Generate sources from compressed files
  741. Map<String, GodotCsCompressedFile> compressed_files;
  742. get_compressed_files(compressed_files);
  743. for (Map<String, GodotCsCompressedFile>::Element *E = compressed_files.front(); E; E = E->next()) {
  744. const String &file_name = E->key();
  745. const GodotCsCompressedFile &file_data = E->value();
  746. String output_file = path::join(core_dir, file_name);
  747. Vector<uint8_t> data;
  748. data.resize(file_data.uncompressed_size);
  749. Compression::decompress(data.ptrw(), file_data.uncompressed_size, file_data.data, file_data.compressed_size, Compression::MODE_DEFLATE);
  750. String output_dir = output_file.get_base_dir();
  751. if (!DirAccess::exists(output_dir)) {
  752. Error err = da->make_dir_recursive(ProjectSettings::get_singleton()->globalize_path(output_dir));
  753. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  754. }
  755. FileAccessRef file = FileAccess::open(output_file, FileAccess::WRITE);
  756. ERR_FAIL_COND_V(!file, ERR_FILE_CANT_WRITE);
  757. file->store_buffer(data.ptr(), data.size());
  758. file->close();
  759. r_compile_items.push_back(output_file);
  760. }
  761. StringBuilder cs_icalls_content;
  762. cs_icalls_content.append("using System;\n"
  763. "using System.Runtime.CompilerServices;\n"
  764. "\n");
  765. cs_icalls_content.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  766. cs_icalls_content.append(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS "\n" INDENT1 OPEN_BLOCK);
  767. cs_icalls_content.append(MEMBER_BEGIN "internal static ulong godot_api_hash = ");
  768. cs_icalls_content.append(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + ";\n");
  769. cs_icalls_content.append(MEMBER_BEGIN "internal static uint bindings_version = ");
  770. cs_icalls_content.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n");
  771. cs_icalls_content.append(MEMBER_BEGIN "internal static uint cs_glue_version = ");
  772. cs_icalls_content.append(String::num_uint64(CS_GLUE_VERSION) + ";\n");
  773. #define ADD_INTERNAL_CALL(m_icall) \
  774. if (!m_icall.editor_only) { \
  775. cs_icalls_content.append(MEMBER_BEGIN "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \
  776. cs_icalls_content.append(INDENT2 "internal extern static "); \
  777. cs_icalls_content.append(m_icall.im_type_out + " "); \
  778. cs_icalls_content.append(m_icall.name + "("); \
  779. cs_icalls_content.append(m_icall.im_sig + ");\n"); \
  780. }
  781. for (const List<InternalCall>::Element *E = core_custom_icalls.front(); E; E = E->next())
  782. ADD_INTERNAL_CALL(E->get());
  783. for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next())
  784. ADD_INTERNAL_CALL(E->get());
  785. #undef ADD_INTERNAL_CALL
  786. cs_icalls_content.append(INDENT1 CLOSE_BLOCK CLOSE_BLOCK);
  787. String internal_methods_file = path::join(core_dir, BINDINGS_CLASS_NATIVECALLS ".cs");
  788. Error err = _save_file(internal_methods_file, cs_icalls_content);
  789. if (err != OK)
  790. return err;
  791. r_compile_items.push_back(internal_methods_file);
  792. return OK;
  793. }
  794. Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir, Vector<String> &r_compile_items) {
  795. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  796. ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
  797. if (!DirAccess::exists(p_proj_dir)) {
  798. Error err = da->make_dir_recursive(p_proj_dir);
  799. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  800. }
  801. da->change_dir(p_proj_dir);
  802. da->make_dir("Core");
  803. da->make_dir("ObjectType");
  804. String core_dir = path::join(p_proj_dir, "Core");
  805. String obj_type_dir = path::join(p_proj_dir, "ObjectType");
  806. for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
  807. const TypeInterface &itype = E.get();
  808. if (itype.api_type != ClassDB::API_EDITOR)
  809. continue;
  810. String output_file = path::join(obj_type_dir, itype.proxy_name + ".cs");
  811. Error err = _generate_cs_type(itype, output_file);
  812. if (err == ERR_SKIP)
  813. continue;
  814. if (err != OK)
  815. return err;
  816. r_compile_items.push_back(output_file);
  817. }
  818. StringBuilder cs_icalls_content;
  819. cs_icalls_content.append("using System;\n"
  820. "using System.Runtime.CompilerServices;\n"
  821. "\n");
  822. cs_icalls_content.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  823. cs_icalls_content.append(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS_EDITOR "\n" INDENT1 OPEN_BLOCK);
  824. cs_icalls_content.append(INDENT2 "internal static ulong godot_api_hash = ");
  825. cs_icalls_content.append(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + ";\n");
  826. cs_icalls_content.append(INDENT2 "internal static uint bindings_version = ");
  827. cs_icalls_content.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n");
  828. cs_icalls_content.append(INDENT2 "internal static uint cs_glue_version = ");
  829. cs_icalls_content.append(String::num_uint64(CS_GLUE_VERSION) + ";\n");
  830. cs_icalls_content.append("\n");
  831. #define ADD_INTERNAL_CALL(m_icall) \
  832. if (m_icall.editor_only) { \
  833. cs_icalls_content.append(INDENT2 "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \
  834. cs_icalls_content.append(INDENT2 "internal extern static "); \
  835. cs_icalls_content.append(m_icall.im_type_out + " "); \
  836. cs_icalls_content.append(m_icall.name + "("); \
  837. cs_icalls_content.append(m_icall.im_sig + ");\n"); \
  838. }
  839. for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next())
  840. ADD_INTERNAL_CALL(E->get());
  841. for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next())
  842. ADD_INTERNAL_CALL(E->get());
  843. #undef ADD_INTERNAL_CALL
  844. cs_icalls_content.append(INDENT1 CLOSE_BLOCK CLOSE_BLOCK);
  845. String internal_methods_file = path::join(core_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs");
  846. Error err = _save_file(internal_methods_file, cs_icalls_content);
  847. if (err != OK)
  848. return err;
  849. r_compile_items.push_back(internal_methods_file);
  850. return OK;
  851. }
  852. Error BindingsGenerator::generate_cs_api(const String &p_output_dir) {
  853. String output_dir = path::abspath(path::realpath(p_output_dir));
  854. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  855. ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
  856. if (!DirAccess::exists(output_dir)) {
  857. Error err = da->make_dir_recursive(output_dir);
  858. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  859. }
  860. Error proj_err;
  861. // Generate GodotSharp source files
  862. String core_proj_dir = output_dir.plus_file(CORE_API_ASSEMBLY_NAME);
  863. Vector<String> core_compile_items;
  864. proj_err = generate_cs_core_project(core_proj_dir, core_compile_items);
  865. if (proj_err != OK) {
  866. ERR_PRINT("Generation of the Core API C# project failed.");
  867. return proj_err;
  868. }
  869. // Generate GodotSharpEditor source files
  870. String editor_proj_dir = output_dir.plus_file(EDITOR_API_ASSEMBLY_NAME);
  871. Vector<String> editor_compile_items;
  872. proj_err = generate_cs_editor_project(editor_proj_dir, editor_compile_items);
  873. if (proj_err != OK) {
  874. ERR_PRINT("Generation of the Editor API C# project failed.");
  875. return proj_err;
  876. }
  877. // Generate solution
  878. if (!CSharpProject::generate_api_solution(output_dir,
  879. core_proj_dir, core_compile_items, editor_proj_dir, editor_compile_items)) {
  880. return ERR_CANT_CREATE;
  881. }
  882. _log("The solution for the Godot API was generated successfully\n");
  883. return OK;
  884. }
  885. // FIXME: There are some members that hide other inherited members.
  886. // - In the case of both members being the same kind, the new one must be declared
  887. // explicitly as 'new' to avoid the warning (and we must print a message about it).
  888. // - In the case of both members being of a different kind, then the new one must
  889. // be renamed to avoid the name collision (and we must print a warning about it).
  890. // - Csc warning e.g.:
  891. // ObjectType/LineEdit.cs(140,38): warning CS0108: 'LineEdit.FocusMode' hides inherited member 'Control.FocusMode'. Use the new keyword if hiding was intended.
  892. Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const String &p_output_file) {
  893. CRASH_COND(!itype.is_object_type);
  894. bool is_derived_type = itype.base_name != StringName();
  895. if (!is_derived_type) {
  896. // Some Godot.Object assertions
  897. CRASH_COND(itype.cname != name_cache.type_Object);
  898. CRASH_COND(!itype.is_instantiable);
  899. CRASH_COND(itype.api_type != ClassDB::API_CORE);
  900. CRASH_COND(itype.is_reference);
  901. CRASH_COND(itype.is_singleton);
  902. }
  903. List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls;
  904. _log("Generating %s.cs...\n", itype.proxy_name.utf8().get_data());
  905. String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); // Used only for derived types
  906. StringBuilder output;
  907. output.append("using System;\n"); // IntPtr
  908. output.append("using System.Diagnostics;\n"); // DebuggerBrowsable
  909. output.append("\n"
  910. "#pragma warning disable CS1591 // Disable warning: "
  911. "'Missing XML comment for publicly visible type or member'\n"
  912. "#pragma warning disable CS1573 // Disable warning: "
  913. "'Parameter has no matching param tag in the XML comment'\n");
  914. output.append("\nnamespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  915. const DocData::ClassDoc *class_doc = itype.class_doc;
  916. if (class_doc && class_doc->description.size()) {
  917. String xml_summary = bbcode_to_xml(fix_doc_description(class_doc->description), &itype);
  918. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  919. if (summary_lines.size()) {
  920. output.append(INDENT1 "/// <summary>\n");
  921. for (int i = 0; i < summary_lines.size(); i++) {
  922. output.append(INDENT1 "/// ");
  923. output.append(summary_lines[i]);
  924. output.append("\n");
  925. }
  926. output.append(INDENT1 "/// </summary>\n");
  927. }
  928. }
  929. output.append(INDENT1 "public ");
  930. if (itype.is_singleton) {
  931. output.append("static partial class ");
  932. } else {
  933. output.append(itype.is_instantiable ? "partial class " : "abstract partial class ");
  934. }
  935. output.append(itype.proxy_name);
  936. if (itype.is_singleton) {
  937. output.append("\n");
  938. } else if (is_derived_type) {
  939. if (obj_types.has(itype.base_name)) {
  940. output.append(" : ");
  941. output.append(obj_types[itype.base_name].proxy_name);
  942. output.append("\n");
  943. } else {
  944. ERR_PRINTS("Base type '" + itype.base_name.operator String() + "' does not exist, for class '" + itype.name + "'.");
  945. return ERR_INVALID_DATA;
  946. }
  947. }
  948. output.append(INDENT1 "{");
  949. if (class_doc) {
  950. // Add constants
  951. for (const List<ConstantInterface>::Element *E = itype.constants.front(); E; E = E->next()) {
  952. const ConstantInterface &iconstant = E->get();
  953. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  954. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
  955. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  956. if (summary_lines.size()) {
  957. output.append(MEMBER_BEGIN "/// <summary>\n");
  958. for (int i = 0; i < summary_lines.size(); i++) {
  959. output.append(INDENT2 "/// ");
  960. output.append(summary_lines[i]);
  961. output.append("\n");
  962. }
  963. output.append(INDENT2 "/// </summary>");
  964. }
  965. }
  966. output.append(MEMBER_BEGIN "public const int ");
  967. output.append(iconstant.proxy_name);
  968. output.append(" = ");
  969. output.append(itos(iconstant.value));
  970. output.append(";");
  971. }
  972. if (itype.constants.size())
  973. output.append("\n");
  974. // Add enums
  975. for (const List<EnumInterface>::Element *E = itype.enums.front(); E; E = E->next()) {
  976. const EnumInterface &ienum = E->get();
  977. ERR_FAIL_COND_V(ienum.constants.empty(), ERR_BUG);
  978. output.append(MEMBER_BEGIN "public enum ");
  979. output.append(ienum.cname.operator String());
  980. output.append(MEMBER_BEGIN OPEN_BLOCK);
  981. for (const List<ConstantInterface>::Element *F = ienum.constants.front(); F; F = F->next()) {
  982. const ConstantInterface &iconstant = F->get();
  983. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  984. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
  985. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  986. if (summary_lines.size()) {
  987. output.append(INDENT3 "/// <summary>\n");
  988. for (int i = 0; i < summary_lines.size(); i++) {
  989. output.append(INDENT3 "/// ");
  990. output.append(summary_lines[i]);
  991. output.append("\n");
  992. }
  993. output.append(INDENT3 "/// </summary>\n");
  994. }
  995. }
  996. output.append(INDENT3);
  997. output.append(iconstant.proxy_name);
  998. output.append(" = ");
  999. output.append(itos(iconstant.value));
  1000. output.append(F != ienum.constants.back() ? ",\n" : "\n");
  1001. }
  1002. output.append(INDENT2 CLOSE_BLOCK);
  1003. }
  1004. // Add properties
  1005. for (const List<PropertyInterface>::Element *E = itype.properties.front(); E; E = E->next()) {
  1006. const PropertyInterface &iprop = E->get();
  1007. Error prop_err = _generate_cs_property(itype, iprop, output);
  1008. ERR_FAIL_COND_V_MSG(prop_err != OK, prop_err,
  1009. "Failed to generate property '" + iprop.cname.operator String() +
  1010. "' for class '" + itype.name + "'.");
  1011. }
  1012. }
  1013. // TODO: BINDINGS_NATIVE_NAME_FIELD should be StringName, once we support it in C#
  1014. if (itype.is_singleton) {
  1015. // Add the type name and the singleton pointer as static fields
  1016. output.append(MEMBER_BEGIN "private static Godot.Object singleton;\n");
  1017. output.append(MEMBER_BEGIN "public static Godot.Object Singleton\n" INDENT2 "{\n" INDENT3
  1018. "get\n" INDENT3 "{\n" INDENT4 "if (singleton == null)\n" INDENT5
  1019. "singleton = Engine.GetSingleton(typeof(");
  1020. output.append(itype.proxy_name);
  1021. output.append(").Name);\n" INDENT4 "return singleton;\n" INDENT3 "}\n" INDENT2 "}\n");
  1022. output.append(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \"");
  1023. output.append(itype.name);
  1024. output.append("\";\n");
  1025. output.append(INDENT2 "internal static IntPtr " BINDINGS_PTR_FIELD " = ");
  1026. output.append(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS);
  1027. output.append("." ICALL_PREFIX);
  1028. output.append(itype.name);
  1029. output.append(SINGLETON_ICALL_SUFFIX "();\n");
  1030. } else if (is_derived_type) {
  1031. // Add member fields
  1032. output.append(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \"");
  1033. output.append(itype.name);
  1034. output.append("\";\n");
  1035. // Add default constructor
  1036. if (itype.is_instantiable) {
  1037. output.append(MEMBER_BEGIN "public ");
  1038. output.append(itype.proxy_name);
  1039. output.append("() : this(");
  1040. output.append(itype.memory_own ? "true" : "false");
  1041. // The default constructor may also be called by the engine when instancing existing native objects
  1042. // The engine will initialize the pointer field of the managed side before calling the constructor
  1043. // This is why we only allocate a new native object from the constructor if the pointer field is not set
  1044. output.append(")\n" OPEN_BLOCK_L2 "if (" BINDINGS_PTR_FIELD " == IntPtr.Zero)\n" INDENT4 BINDINGS_PTR_FIELD " = ");
  1045. output.append(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS);
  1046. output.append("." + ctor_method);
  1047. output.append("(this);\n" CLOSE_BLOCK_L2);
  1048. } else {
  1049. // Hide the constructor
  1050. output.append(MEMBER_BEGIN "internal ");
  1051. output.append(itype.proxy_name);
  1052. output.append("() {}\n");
  1053. }
  1054. // Add.. em.. trick constructor. Sort of.
  1055. output.append(MEMBER_BEGIN "internal ");
  1056. output.append(itype.proxy_name);
  1057. output.append("(bool " CS_FIELD_MEMORYOWN ") : base(" CS_FIELD_MEMORYOWN ") {}\n");
  1058. }
  1059. int method_bind_count = 0;
  1060. for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) {
  1061. const MethodInterface &imethod = E->get();
  1062. Error method_err = _generate_cs_method(itype, imethod, method_bind_count, output);
  1063. ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
  1064. "Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'.");
  1065. }
  1066. if (itype.is_singleton) {
  1067. InternalCall singleton_icall = InternalCall(itype.api_type, ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX, "IntPtr");
  1068. if (!find_icall_by_name(singleton_icall.name, custom_icalls))
  1069. custom_icalls.push_back(singleton_icall);
  1070. }
  1071. if (is_derived_type && itype.is_instantiable) {
  1072. InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj");
  1073. if (!find_icall_by_name(ctor_icall.name, custom_icalls))
  1074. custom_icalls.push_back(ctor_icall);
  1075. }
  1076. output.append(INDENT1 CLOSE_BLOCK /* class */
  1077. CLOSE_BLOCK /* namespace */);
  1078. output.append("\n"
  1079. "#pragma warning restore CS1591\n"
  1080. "#pragma warning restore CS1573\n");
  1081. return _save_file(p_output_file, output);
  1082. }
  1083. Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInterface &p_itype, const PropertyInterface &p_iprop, StringBuilder &p_output) {
  1084. const MethodInterface *setter = p_itype.find_method_by_name(p_iprop.setter);
  1085. // Search it in base types too
  1086. const TypeInterface *current_type = &p_itype;
  1087. while (!setter && current_type->base_name != StringName()) {
  1088. OrderedHashMap<StringName, TypeInterface>::Element base_match = obj_types.find(current_type->base_name);
  1089. ERR_FAIL_COND_V(!base_match, ERR_BUG);
  1090. current_type = &base_match.get();
  1091. setter = current_type->find_method_by_name(p_iprop.setter);
  1092. }
  1093. const MethodInterface *getter = p_itype.find_method_by_name(p_iprop.getter);
  1094. // Search it in base types too
  1095. current_type = &p_itype;
  1096. while (!getter && current_type->base_name != StringName()) {
  1097. OrderedHashMap<StringName, TypeInterface>::Element base_match = obj_types.find(current_type->base_name);
  1098. ERR_FAIL_COND_V(!base_match, ERR_BUG);
  1099. current_type = &base_match.get();
  1100. getter = current_type->find_method_by_name(p_iprop.getter);
  1101. }
  1102. ERR_FAIL_COND_V(!setter && !getter, ERR_BUG);
  1103. if (setter) {
  1104. int setter_argc = p_iprop.index != -1 ? 2 : 1;
  1105. ERR_FAIL_COND_V(setter->arguments.size() != setter_argc, ERR_BUG);
  1106. }
  1107. if (getter) {
  1108. int getter_argc = p_iprop.index != -1 ? 1 : 0;
  1109. ERR_FAIL_COND_V(getter->arguments.size() != getter_argc, ERR_BUG);
  1110. }
  1111. if (getter && setter) {
  1112. ERR_FAIL_COND_V(getter->return_type.cname != setter->arguments.back()->get().type.cname, ERR_BUG);
  1113. }
  1114. const TypeReference &proptype_name = getter ? getter->return_type : setter->arguments.back()->get().type;
  1115. const TypeInterface *prop_itype = _get_type_or_null(proptype_name);
  1116. ERR_FAIL_NULL_V(prop_itype, ERR_BUG); // Property type not found
  1117. if (p_iprop.prop_doc && p_iprop.prop_doc->description.size()) {
  1118. String xml_summary = bbcode_to_xml(fix_doc_description(p_iprop.prop_doc->description), &p_itype);
  1119. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1120. if (summary_lines.size()) {
  1121. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  1122. for (int i = 0; i < summary_lines.size(); i++) {
  1123. p_output.append(INDENT2 "/// ");
  1124. p_output.append(summary_lines[i]);
  1125. p_output.append("\n");
  1126. }
  1127. p_output.append(INDENT2 "/// </summary>");
  1128. }
  1129. }
  1130. p_output.append(MEMBER_BEGIN "public ");
  1131. if (p_itype.is_singleton)
  1132. p_output.append("static ");
  1133. p_output.append(prop_itype->cs_type);
  1134. p_output.append(" ");
  1135. p_output.append(p_iprop.proxy_name);
  1136. p_output.append("\n" INDENT2 OPEN_BLOCK);
  1137. if (getter) {
  1138. p_output.append(INDENT3 "get\n"
  1139. // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
  1140. "#pragma warning disable CS0618 // Disable warning about obsolete method\n"
  1141. OPEN_BLOCK_L3);
  1142. p_output.append("return ");
  1143. p_output.append(getter->proxy_name + "(");
  1144. if (p_iprop.index != -1) {
  1145. const ArgumentInterface &idx_arg = getter->arguments.front()->get();
  1146. if (idx_arg.type.cname != name_cache.type_int) {
  1147. // Assume the index parameter is an enum
  1148. const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type);
  1149. CRASH_COND(idx_arg_type == NULL);
  1150. p_output.append("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index));
  1151. } else {
  1152. p_output.append(itos(p_iprop.index));
  1153. }
  1154. }
  1155. p_output.append(");\n"
  1156. CLOSE_BLOCK_L3
  1157. // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
  1158. "#pragma warning restore CS0618\n");
  1159. }
  1160. if (setter) {
  1161. p_output.append(INDENT3 "set\n"
  1162. // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
  1163. "#pragma warning disable CS0618 // Disable warning about obsolete method\n"
  1164. OPEN_BLOCK_L3);
  1165. p_output.append(setter->proxy_name + "(");
  1166. if (p_iprop.index != -1) {
  1167. const ArgumentInterface &idx_arg = setter->arguments.front()->get();
  1168. if (idx_arg.type.cname != name_cache.type_int) {
  1169. // Assume the index parameter is an enum
  1170. const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type);
  1171. CRASH_COND(idx_arg_type == NULL);
  1172. p_output.append("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index) + ", ");
  1173. } else {
  1174. p_output.append(itos(p_iprop.index) + ", ");
  1175. }
  1176. }
  1177. p_output.append("value);\n"
  1178. CLOSE_BLOCK_L3
  1179. // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
  1180. "#pragma warning restore CS0618\n");
  1181. }
  1182. p_output.append(CLOSE_BLOCK_L2);
  1183. return OK;
  1184. }
  1185. Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, int &p_method_bind_count, StringBuilder &p_output) {
  1186. const TypeInterface *return_type = _get_type_or_placeholder(p_imethod.return_type);
  1187. String method_bind_field = "method_bind_" + itos(p_method_bind_count);
  1188. String arguments_sig;
  1189. String cs_in_statements;
  1190. String icall_params = method_bind_field + ", ";
  1191. icall_params += sformat(p_itype.cs_in, "this");
  1192. StringBuilder default_args_doc;
  1193. // Retrieve information from the arguments
  1194. for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) {
  1195. const ArgumentInterface &iarg = F->get();
  1196. const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
  1197. // Add the current arguments to the signature
  1198. // If the argument has a default value which is not a constant, we will make it Nullable
  1199. {
  1200. if (F != p_imethod.arguments.front())
  1201. arguments_sig += ", ";
  1202. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
  1203. arguments_sig += "Nullable<";
  1204. arguments_sig += arg_type->cs_type;
  1205. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
  1206. arguments_sig += "> ";
  1207. else
  1208. arguments_sig += " ";
  1209. arguments_sig += iarg.name;
  1210. if (iarg.default_argument.size()) {
  1211. if (iarg.def_param_mode != ArgumentInterface::CONSTANT)
  1212. arguments_sig += " = null";
  1213. else
  1214. arguments_sig += " = " + sformat(iarg.default_argument, arg_type->cs_type);
  1215. }
  1216. }
  1217. icall_params += ", ";
  1218. if (iarg.default_argument.size() && iarg.def_param_mode != ArgumentInterface::CONSTANT) {
  1219. // The default value of an argument must be constant. Otherwise we make it Nullable and do the following:
  1220. // Type arg_in = arg.HasValue ? arg.Value : <non-const default value>;
  1221. String arg_in = iarg.name;
  1222. arg_in += "_in";
  1223. cs_in_statements += arg_type->cs_type;
  1224. cs_in_statements += " ";
  1225. cs_in_statements += arg_in;
  1226. cs_in_statements += " = ";
  1227. cs_in_statements += iarg.name;
  1228. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
  1229. cs_in_statements += ".HasValue ? ";
  1230. else
  1231. cs_in_statements += " != null ? ";
  1232. cs_in_statements += iarg.name;
  1233. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
  1234. cs_in_statements += ".Value : ";
  1235. else
  1236. cs_in_statements += " : ";
  1237. String def_arg = sformat(iarg.default_argument, arg_type->cs_type);
  1238. cs_in_statements += def_arg;
  1239. cs_in_statements += ";\n" INDENT3;
  1240. icall_params += arg_type->cs_in.empty() ? arg_in : sformat(arg_type->cs_in, arg_in);
  1241. // Apparently the name attribute must not include the @
  1242. String param_tag_name = iarg.name.begins_with("@") ? iarg.name.substr(1, iarg.name.length()) : iarg.name;
  1243. default_args_doc.append(INDENT2 "/// <param name=\"" + param_tag_name + "\">If the parameter is null, then the default value is " + def_arg + "</param>\n");
  1244. } else {
  1245. icall_params += arg_type->cs_in.empty() ? iarg.name : sformat(arg_type->cs_in, iarg.name);
  1246. }
  1247. }
  1248. // Generate method
  1249. {
  1250. if (!p_imethod.is_virtual && !p_imethod.requires_object_call) {
  1251. p_output.append(MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]" MEMBER_BEGIN "private static IntPtr ");
  1252. p_output.append(method_bind_field + " = Object." ICALL_GET_METHODBIND "(" BINDINGS_NATIVE_NAME_FIELD ", \"");
  1253. p_output.append(p_imethod.name);
  1254. p_output.append("\");\n");
  1255. }
  1256. if (p_imethod.method_doc && p_imethod.method_doc->description.size()) {
  1257. String xml_summary = bbcode_to_xml(fix_doc_description(p_imethod.method_doc->description), &p_itype);
  1258. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1259. if (summary_lines.size() || default_args_doc.get_string_length()) {
  1260. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  1261. for (int i = 0; i < summary_lines.size(); i++) {
  1262. p_output.append(INDENT2 "/// ");
  1263. p_output.append(summary_lines[i]);
  1264. p_output.append("\n");
  1265. }
  1266. p_output.append(default_args_doc.as_string());
  1267. p_output.append(INDENT2 "/// </summary>");
  1268. }
  1269. }
  1270. if (!p_imethod.is_internal) {
  1271. p_output.append(MEMBER_BEGIN "[GodotMethod(\"");
  1272. p_output.append(p_imethod.name);
  1273. p_output.append("\")]");
  1274. }
  1275. if (p_imethod.is_deprecated) {
  1276. if (p_imethod.deprecation_message.empty())
  1277. WARN_PRINTS("An empty deprecation message is discouraged. Method: '" + p_imethod.proxy_name + "'.");
  1278. p_output.append(MEMBER_BEGIN "[Obsolete(\"");
  1279. p_output.append(p_imethod.deprecation_message);
  1280. p_output.append("\")]");
  1281. }
  1282. p_output.append(MEMBER_BEGIN);
  1283. p_output.append(p_imethod.is_internal ? "internal " : "public ");
  1284. if (p_itype.is_singleton) {
  1285. p_output.append("static ");
  1286. } else if (p_imethod.is_virtual) {
  1287. p_output.append("virtual ");
  1288. }
  1289. p_output.append(return_type->cs_type + " ");
  1290. p_output.append(p_imethod.proxy_name + "(");
  1291. p_output.append(arguments_sig + ")\n" OPEN_BLOCK_L2);
  1292. if (p_imethod.is_virtual) {
  1293. // Godot virtual method must be overridden, therefore we return a default value by default.
  1294. if (return_type->cname == name_cache.type_void) {
  1295. p_output.append("return;\n" CLOSE_BLOCK_L2);
  1296. } else {
  1297. p_output.append("return default(");
  1298. p_output.append(return_type->cs_type);
  1299. p_output.append(");\n" CLOSE_BLOCK_L2);
  1300. }
  1301. return OK; // Won't increment method bind count
  1302. }
  1303. if (p_imethod.requires_object_call) {
  1304. // Fallback to Godot's object.Call(string, params)
  1305. p_output.append(CS_METHOD_CALL "(\"");
  1306. p_output.append(p_imethod.name);
  1307. p_output.append("\"");
  1308. for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) {
  1309. p_output.append(", ");
  1310. p_output.append(F->get().name);
  1311. }
  1312. p_output.append(");\n" CLOSE_BLOCK_L2);
  1313. return OK; // Won't increment method bind count
  1314. }
  1315. const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&p_imethod);
  1316. ERR_FAIL_NULL_V(match, ERR_BUG);
  1317. const InternalCall *im_icall = match->value();
  1318. String im_call = im_icall->editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS;
  1319. im_call += "." + im_icall->name + "(" + icall_params + ")";
  1320. if (p_imethod.arguments.size())
  1321. p_output.append(cs_in_statements);
  1322. if (return_type->cname == name_cache.type_void) {
  1323. p_output.append(im_call + ";\n");
  1324. } else if (return_type->cs_out.empty()) {
  1325. p_output.append("return " + im_call + ";\n");
  1326. } else {
  1327. p_output.append(sformat(return_type->cs_out, im_call, return_type->cs_type, return_type->im_type_out));
  1328. p_output.append("\n");
  1329. }
  1330. p_output.append(CLOSE_BLOCK_L2);
  1331. }
  1332. p_method_bind_count++;
  1333. return OK;
  1334. }
  1335. Error BindingsGenerator::generate_glue(const String &p_output_dir) {
  1336. bool dir_exists = DirAccess::exists(p_output_dir);
  1337. ERR_FAIL_COND_V_MSG(!dir_exists, ERR_FILE_BAD_PATH, "The output directory does not exist.");
  1338. StringBuilder output;
  1339. output.append("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
  1340. output.append("#include \"" GLUE_HEADER_FILE "\"\n");
  1341. output.append("\n#ifdef MONO_GLUE_ENABLED\n");
  1342. generated_icall_funcs.clear();
  1343. for (OrderedHashMap<StringName, TypeInterface>::Element type_elem = obj_types.front(); type_elem; type_elem = type_elem.next()) {
  1344. const TypeInterface &itype = type_elem.get();
  1345. bool is_derived_type = itype.base_name != StringName();
  1346. if (!is_derived_type) {
  1347. // Some Object assertions
  1348. CRASH_COND(itype.cname != name_cache.type_Object);
  1349. CRASH_COND(!itype.is_instantiable);
  1350. CRASH_COND(itype.api_type != ClassDB::API_CORE);
  1351. CRASH_COND(itype.is_reference);
  1352. CRASH_COND(itype.is_singleton);
  1353. }
  1354. List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls;
  1355. OS::get_singleton()->print("Generating %s...\n", itype.name.utf8().get_data());
  1356. String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); // Used only for derived types
  1357. for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) {
  1358. const MethodInterface &imethod = E->get();
  1359. Error method_err = _generate_glue_method(itype, imethod, output);
  1360. ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
  1361. "Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'.");
  1362. }
  1363. if (itype.is_singleton) {
  1364. String singleton_icall_name = ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX;
  1365. InternalCall singleton_icall = InternalCall(itype.api_type, singleton_icall_name, "IntPtr");
  1366. if (!find_icall_by_name(singleton_icall.name, custom_icalls))
  1367. custom_icalls.push_back(singleton_icall);
  1368. output.append("Object* ");
  1369. output.append(singleton_icall_name);
  1370. output.append("() " OPEN_BLOCK "\treturn Engine::get_singleton()->get_singleton_object(\"");
  1371. output.append(itype.proxy_name);
  1372. output.append("\");\n" CLOSE_BLOCK "\n");
  1373. }
  1374. if (is_derived_type && itype.is_instantiable) {
  1375. InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj");
  1376. if (!find_icall_by_name(ctor_icall.name, custom_icalls))
  1377. custom_icalls.push_back(ctor_icall);
  1378. output.append("Object* ");
  1379. output.append(ctor_method);
  1380. output.append("(MonoObject* obj) " OPEN_BLOCK
  1381. "\t" C_MACRO_OBJECT_CONSTRUCT "(instance, \"");
  1382. output.append(itype.name);
  1383. output.append("\");\n"
  1384. "\t" C_METHOD_TIE_MANAGED_TO_UNMANAGED "(obj, instance);\n"
  1385. "\treturn instance;\n" CLOSE_BLOCK "\n");
  1386. }
  1387. }
  1388. output.append("namespace GodotSharpBindings\n" OPEN_BLOCK "\n");
  1389. output.append("uint64_t get_core_api_hash() { return ");
  1390. output.append(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + "U; }\n");
  1391. output.append("#ifdef TOOLS_ENABLED\n"
  1392. "uint64_t get_editor_api_hash() { return ");
  1393. output.append(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + "U; }\n");
  1394. output.append("#endif // TOOLS_ENABLED\n");
  1395. output.append("uint32_t get_bindings_version() { return ");
  1396. output.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + "; }\n");
  1397. output.append("\nvoid register_generated_icalls() " OPEN_BLOCK);
  1398. output.append("\tgodot_register_glue_header_icalls();\n");
  1399. #define ADD_INTERNAL_CALL_REGISTRATION(m_icall) \
  1400. { \
  1401. output.append("\tmono_add_internal_call("); \
  1402. output.append("\"" BINDINGS_NAMESPACE "."); \
  1403. output.append(m_icall.editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); \
  1404. output.append("::"); \
  1405. output.append(m_icall.name); \
  1406. output.append("\", (void*)"); \
  1407. output.append(m_icall.name); \
  1408. output.append(");\n"); \
  1409. }
  1410. bool tools_sequence = false;
  1411. for (const List<InternalCall>::Element *E = core_custom_icalls.front(); E; E = E->next()) {
  1412. if (tools_sequence) {
  1413. if (!E->get().editor_only) {
  1414. tools_sequence = false;
  1415. output.append("#endif\n");
  1416. }
  1417. } else {
  1418. if (E->get().editor_only) {
  1419. output.append("#ifdef TOOLS_ENABLED\n");
  1420. tools_sequence = true;
  1421. }
  1422. }
  1423. ADD_INTERNAL_CALL_REGISTRATION(E->get());
  1424. }
  1425. if (tools_sequence) {
  1426. tools_sequence = false;
  1427. output.append("#endif\n");
  1428. }
  1429. output.append("#ifdef TOOLS_ENABLED\n");
  1430. for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next())
  1431. ADD_INTERNAL_CALL_REGISTRATION(E->get());
  1432. output.append("#endif // TOOLS_ENABLED\n");
  1433. for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next()) {
  1434. if (tools_sequence) {
  1435. if (!E->get().editor_only) {
  1436. tools_sequence = false;
  1437. output.append("#endif\n");
  1438. }
  1439. } else {
  1440. if (E->get().editor_only) {
  1441. output.append("#ifdef TOOLS_ENABLED\n");
  1442. tools_sequence = true;
  1443. }
  1444. }
  1445. ADD_INTERNAL_CALL_REGISTRATION(E->get());
  1446. }
  1447. if (tools_sequence) {
  1448. tools_sequence = false;
  1449. output.append("#endif\n");
  1450. }
  1451. #undef ADD_INTERNAL_CALL_REGISTRATION
  1452. output.append(CLOSE_BLOCK "\n} // namespace GodotSharpBindings\n");
  1453. output.append("\n#endif // MONO_GLUE_ENABLED\n");
  1454. Error save_err = _save_file(path::join(p_output_dir, "mono_glue.gen.cpp"), output);
  1455. if (save_err != OK)
  1456. return save_err;
  1457. OS::get_singleton()->print("Mono glue generated successfully\n");
  1458. return OK;
  1459. }
  1460. uint32_t BindingsGenerator::get_version() {
  1461. return BINDINGS_GENERATOR_VERSION;
  1462. }
  1463. Error BindingsGenerator::_save_file(const String &p_path, const StringBuilder &p_content) {
  1464. FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE);
  1465. ERR_FAIL_COND_V_MSG(!file, ERR_FILE_CANT_WRITE, "Cannot open file: '" + p_path + "'.");
  1466. file->store_string(p_content.as_string());
  1467. file->close();
  1468. return OK;
  1469. }
  1470. Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, StringBuilder &p_output) {
  1471. if (p_imethod.is_virtual)
  1472. return OK; // Ignore
  1473. bool ret_void = p_imethod.return_type.cname == name_cache.type_void;
  1474. const TypeInterface *return_type = _get_type_or_placeholder(p_imethod.return_type);
  1475. String argc_str = itos(p_imethod.arguments.size());
  1476. String c_func_sig = "MethodBind* " CS_PARAM_METHODBIND ", " + p_itype.c_type_in + " " CS_PARAM_INSTANCE;
  1477. String c_in_statements;
  1478. String c_args_var_content;
  1479. // Get arguments information
  1480. int i = 0;
  1481. for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) {
  1482. const ArgumentInterface &iarg = F->get();
  1483. const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
  1484. String c_param_name = "arg" + itos(i + 1);
  1485. if (p_imethod.is_vararg) {
  1486. if (i < p_imethod.arguments.size() - 1) {
  1487. c_in_statements += sformat(arg_type->c_in.size() ? arg_type->c_in : TypeInterface::DEFAULT_VARARG_C_IN, "Variant", c_param_name);
  1488. c_in_statements += "\t" C_LOCAL_PTRCALL_ARGS ".set(";
  1489. c_in_statements += itos(i);
  1490. c_in_statements += sformat(", &%s_in);\n", c_param_name);
  1491. }
  1492. } else {
  1493. if (i > 0)
  1494. c_args_var_content += ", ";
  1495. if (arg_type->c_in.size())
  1496. c_in_statements += sformat(arg_type->c_in, arg_type->c_type, c_param_name);
  1497. c_args_var_content += sformat(arg_type->c_arg_in, c_param_name);
  1498. }
  1499. c_func_sig += ", ";
  1500. c_func_sig += arg_type->c_type_in;
  1501. c_func_sig += " ";
  1502. c_func_sig += c_param_name;
  1503. i++;
  1504. }
  1505. const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&p_imethod);
  1506. ERR_FAIL_NULL_V(match, ERR_BUG);
  1507. const InternalCall *im_icall = match->value();
  1508. String icall_method = im_icall->name;
  1509. if (!generated_icall_funcs.find(im_icall)) {
  1510. generated_icall_funcs.push_back(im_icall);
  1511. if (im_icall->editor_only)
  1512. p_output.append("#ifdef TOOLS_ENABLED\n");
  1513. // Generate icall function
  1514. p_output.append(ret_void ? "void " : return_type->c_type_out + " ");
  1515. p_output.append(icall_method);
  1516. p_output.append("(");
  1517. p_output.append(c_func_sig);
  1518. p_output.append(") " OPEN_BLOCK);
  1519. String fail_ret = ret_void ? "" : ", " + (return_type->c_type_out.ends_with("*") ? "NULL" : return_type->c_type_out + "()");
  1520. if (!ret_void) {
  1521. String ptrcall_return_type;
  1522. String initialization;
  1523. if (p_imethod.is_vararg && return_type->cname != name_cache.type_Variant) {
  1524. // VarArg methods always return Variant, but there are some cases in which MethodInfo provides
  1525. // a specific return type. We trust this information is valid. We need a temporary local to keep
  1526. // the Variant alive until the method returns. Otherwise, if the returned Variant holds a RefPtr,
  1527. // it could be deleted too early. This is the case with GDScript.new() which returns OBJECT.
  1528. // Alternatively, we could just return Variant, but that would result in a worse API.
  1529. p_output.append("\tVariant " C_LOCAL_VARARG_RET ";\n");
  1530. }
  1531. if (return_type->is_object_type) {
  1532. ptrcall_return_type = return_type->is_reference ? "Ref<Reference>" : return_type->c_type;
  1533. initialization = return_type->is_reference ? "" : " = NULL";
  1534. } else {
  1535. ptrcall_return_type = return_type->c_type;
  1536. }
  1537. p_output.append("\t" + ptrcall_return_type);
  1538. p_output.append(" " C_LOCAL_RET);
  1539. p_output.append(initialization + ";\n");
  1540. p_output.append("\tERR_FAIL_NULL_V(" CS_PARAM_INSTANCE);
  1541. p_output.append(fail_ret);
  1542. p_output.append(");\n");
  1543. } else {
  1544. p_output.append("\tERR_FAIL_NULL(" CS_PARAM_INSTANCE ");\n");
  1545. }
  1546. if (p_imethod.arguments.size()) {
  1547. if (p_imethod.is_vararg) {
  1548. String vararg_arg = "arg" + argc_str;
  1549. String real_argc_str = itos(p_imethod.arguments.size() - 1); // Arguments count without vararg
  1550. p_output.append("\tint vararg_length = mono_array_length(");
  1551. p_output.append(vararg_arg);
  1552. p_output.append(");\n\tint total_length = ");
  1553. p_output.append(real_argc_str);
  1554. p_output.append(" + vararg_length;\n"
  1555. "\tArgumentsVector<Variant> varargs(vararg_length);\n"
  1556. "\tArgumentsVector<const Variant *> " C_LOCAL_PTRCALL_ARGS "(total_length);\n");
  1557. p_output.append(c_in_statements);
  1558. p_output.append("\tfor (int i = 0; i < vararg_length; i++) " OPEN_BLOCK
  1559. "\t\tMonoObject* elem = mono_array_get(");
  1560. p_output.append(vararg_arg);
  1561. p_output.append(", MonoObject*, i);\n"
  1562. "\t\tvarargs.set(i, GDMonoMarshal::mono_object_to_variant(elem));\n"
  1563. "\t\t" C_LOCAL_PTRCALL_ARGS ".set(");
  1564. p_output.append(real_argc_str);
  1565. p_output.append(" + i, &varargs.get(i));\n\t" CLOSE_BLOCK);
  1566. } else {
  1567. p_output.append(c_in_statements);
  1568. p_output.append("\tconst void* " C_LOCAL_PTRCALL_ARGS "[");
  1569. p_output.append(argc_str + "] = { ");
  1570. p_output.append(c_args_var_content + " };\n");
  1571. }
  1572. }
  1573. if (p_imethod.is_vararg) {
  1574. p_output.append("\tVariant::CallError vcall_error;\n\t");
  1575. if (!ret_void) {
  1576. // See the comment on the C_LOCAL_VARARG_RET declaration
  1577. if (return_type->cname != name_cache.type_Variant) {
  1578. p_output.append(C_LOCAL_VARARG_RET " = ");
  1579. } else {
  1580. p_output.append(C_LOCAL_RET " = ");
  1581. }
  1582. }
  1583. p_output.append(CS_PARAM_METHODBIND "->call(" CS_PARAM_INSTANCE ", ");
  1584. p_output.append(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ".ptr()" : "NULL");
  1585. p_output.append(", total_length, vcall_error);\n");
  1586. // See the comment on the C_LOCAL_VARARG_RET declaration
  1587. if (return_type->cname != name_cache.type_Variant) {
  1588. p_output.append("\t" C_LOCAL_RET " = " C_LOCAL_VARARG_RET ";\n");
  1589. }
  1590. } else {
  1591. p_output.append("\t" CS_PARAM_METHODBIND "->ptrcall(" CS_PARAM_INSTANCE ", ");
  1592. p_output.append(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ", " : "NULL, ");
  1593. p_output.append(!ret_void ? "&" C_LOCAL_RET ");\n" : "NULL);\n");
  1594. }
  1595. if (!ret_void) {
  1596. if (return_type->c_out.empty())
  1597. p_output.append("\treturn " C_LOCAL_RET ";\n");
  1598. else
  1599. p_output.append(sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET, return_type->name));
  1600. }
  1601. p_output.append(CLOSE_BLOCK "\n");
  1602. if (im_icall->editor_only)
  1603. p_output.append("#endif // TOOLS_ENABLED\n");
  1604. }
  1605. return OK;
  1606. }
  1607. const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_null(const TypeReference &p_typeref) {
  1608. const Map<StringName, TypeInterface>::Element *builtin_type_match = builtin_types.find(p_typeref.cname);
  1609. if (builtin_type_match)
  1610. return &builtin_type_match->get();
  1611. const OrderedHashMap<StringName, TypeInterface>::Element obj_type_match = obj_types.find(p_typeref.cname);
  1612. if (obj_type_match)
  1613. return &obj_type_match.get();
  1614. if (p_typeref.is_enum) {
  1615. const Map<StringName, TypeInterface>::Element *enum_match = enum_types.find(p_typeref.cname);
  1616. if (enum_match)
  1617. return &enum_match->get();
  1618. // Enum not found. Most likely because none of its constants were bound, so it's empty. That's fine. Use int instead.
  1619. const Map<StringName, TypeInterface>::Element *int_match = builtin_types.find(name_cache.type_int);
  1620. ERR_FAIL_NULL_V(int_match, NULL);
  1621. return &int_match->get();
  1622. }
  1623. return NULL;
  1624. }
  1625. const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_placeholder(const TypeReference &p_typeref) {
  1626. const TypeInterface *found = _get_type_or_null(p_typeref);
  1627. if (found)
  1628. return found;
  1629. ERR_PRINTS(String() + "Type not found. Creating placeholder: '" + p_typeref.cname.operator String() + "'.");
  1630. const Map<StringName, TypeInterface>::Element *match = placeholder_types.find(p_typeref.cname);
  1631. if (match)
  1632. return &match->get();
  1633. TypeInterface placeholder;
  1634. TypeInterface::create_placeholder_type(placeholder, p_typeref.cname);
  1635. return &placeholder_types.insert(placeholder.cname, placeholder)->get();
  1636. }
  1637. StringName BindingsGenerator::_get_int_type_name_from_meta(GodotTypeInfo::Metadata p_meta) {
  1638. switch (p_meta) {
  1639. case GodotTypeInfo::METADATA_INT_IS_INT8:
  1640. return "sbyte";
  1641. break;
  1642. case GodotTypeInfo::METADATA_INT_IS_INT16:
  1643. return "short";
  1644. break;
  1645. case GodotTypeInfo::METADATA_INT_IS_INT32:
  1646. return "int";
  1647. break;
  1648. case GodotTypeInfo::METADATA_INT_IS_INT64:
  1649. return "long";
  1650. break;
  1651. case GodotTypeInfo::METADATA_INT_IS_UINT8:
  1652. return "byte";
  1653. break;
  1654. case GodotTypeInfo::METADATA_INT_IS_UINT16:
  1655. return "ushort";
  1656. break;
  1657. case GodotTypeInfo::METADATA_INT_IS_UINT32:
  1658. return "uint";
  1659. break;
  1660. case GodotTypeInfo::METADATA_INT_IS_UINT64:
  1661. return "ulong";
  1662. break;
  1663. default:
  1664. // Assume INT32
  1665. return "int";
  1666. }
  1667. }
  1668. StringName BindingsGenerator::_get_float_type_name_from_meta(GodotTypeInfo::Metadata p_meta) {
  1669. switch (p_meta) {
  1670. case GodotTypeInfo::METADATA_REAL_IS_FLOAT:
  1671. return "float";
  1672. break;
  1673. case GodotTypeInfo::METADATA_REAL_IS_DOUBLE:
  1674. return "double";
  1675. break;
  1676. default:
  1677. // Assume real_t (float or double depending of REAL_T_IS_DOUBLE)
  1678. #ifdef REAL_T_IS_DOUBLE
  1679. return "double";
  1680. #else
  1681. return "float";
  1682. #endif
  1683. }
  1684. }
  1685. void BindingsGenerator::_populate_object_type_interfaces() {
  1686. obj_types.clear();
  1687. List<StringName> class_list;
  1688. ClassDB::get_class_list(&class_list);
  1689. class_list.sort_custom<StringName::AlphCompare>();
  1690. while (class_list.size()) {
  1691. StringName type_cname = class_list.front()->get();
  1692. ClassDB::APIType api_type = ClassDB::get_api_type(type_cname);
  1693. if (api_type == ClassDB::API_NONE) {
  1694. class_list.pop_front();
  1695. continue;
  1696. }
  1697. if (!ClassDB::is_class_exposed(type_cname)) {
  1698. _log("Ignoring type '%s' because it's not exposed\n", String(type_cname).utf8().get_data());
  1699. class_list.pop_front();
  1700. continue;
  1701. }
  1702. if (!ClassDB::is_class_enabled(type_cname)) {
  1703. _log("Ignoring type '%s' because it's not enabled\n", String(type_cname).utf8().get_data());
  1704. class_list.pop_front();
  1705. continue;
  1706. }
  1707. ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(type_cname);
  1708. TypeInterface itype = TypeInterface::create_object_type(type_cname, api_type);
  1709. itype.base_name = ClassDB::get_parent_class(type_cname);
  1710. itype.is_singleton = Engine::get_singleton()->has_singleton(itype.proxy_name);
  1711. itype.is_instantiable = class_info->creation_func && !itype.is_singleton;
  1712. itype.is_reference = ClassDB::is_parent_class(type_cname, name_cache.type_Reference);
  1713. itype.memory_own = itype.is_reference;
  1714. itype.c_out = "\treturn ";
  1715. itype.c_out += C_METHOD_UNMANAGED_GET_MANAGED;
  1716. itype.c_out += itype.is_reference ? "(%1.ptr());\n" : "(%1);\n";
  1717. itype.cs_in = itype.is_singleton ? BINDINGS_PTR_FIELD : "Object." CS_SMETHOD_GETINSTANCE "(%0)";
  1718. itype.c_type = "Object*";
  1719. itype.c_type_in = itype.c_type;
  1720. itype.c_type_out = "MonoObject*";
  1721. itype.cs_type = itype.proxy_name;
  1722. itype.im_type_in = "IntPtr";
  1723. itype.im_type_out = itype.proxy_name;
  1724. // Populate properties
  1725. List<PropertyInfo> property_list;
  1726. ClassDB::get_property_list(type_cname, &property_list, true);
  1727. Map<StringName, StringName> accessor_methods;
  1728. for (const List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
  1729. const PropertyInfo &property = E->get();
  1730. if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_CATEGORY)
  1731. continue;
  1732. PropertyInterface iprop;
  1733. iprop.cname = property.name;
  1734. iprop.setter = ClassDB::get_property_setter(type_cname, iprop.cname);
  1735. iprop.getter = ClassDB::get_property_getter(type_cname, iprop.cname);
  1736. if (iprop.setter != StringName())
  1737. accessor_methods[iprop.setter] = iprop.cname;
  1738. if (iprop.getter != StringName())
  1739. accessor_methods[iprop.getter] = iprop.cname;
  1740. bool valid = false;
  1741. iprop.index = ClassDB::get_property_index(type_cname, iprop.cname, &valid);
  1742. ERR_FAIL_COND(!valid);
  1743. iprop.proxy_name = escape_csharp_keyword(snake_to_pascal_case(iprop.cname));
  1744. // Prevent the property and its enclosing type from sharing the same name
  1745. if (iprop.proxy_name == itype.proxy_name) {
  1746. _log("Name of property '%s' is ambiguous with the name of its enclosing class '%s'. Renaming property to '%s_'\n",
  1747. iprop.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), iprop.proxy_name.utf8().get_data());
  1748. iprop.proxy_name += "_";
  1749. }
  1750. iprop.proxy_name = iprop.proxy_name.replace("/", "__"); // Some members have a slash...
  1751. iprop.prop_doc = NULL;
  1752. for (int i = 0; i < itype.class_doc->properties.size(); i++) {
  1753. const DocData::PropertyDoc &prop_doc = itype.class_doc->properties[i];
  1754. if (prop_doc.name == iprop.cname) {
  1755. iprop.prop_doc = &prop_doc;
  1756. break;
  1757. }
  1758. }
  1759. itype.properties.push_back(iprop);
  1760. }
  1761. // Populate methods
  1762. List<MethodInfo> virtual_method_list;
  1763. ClassDB::get_virtual_methods(type_cname, &virtual_method_list, true);
  1764. List<MethodInfo> method_list;
  1765. ClassDB::get_method_list(type_cname, &method_list, true);
  1766. method_list.sort();
  1767. for (List<MethodInfo>::Element *E = method_list.front(); E; E = E->next()) {
  1768. const MethodInfo &method_info = E->get();
  1769. int argc = method_info.arguments.size();
  1770. if (method_info.name.empty())
  1771. continue;
  1772. String cname = method_info.name;
  1773. if (blacklisted_methods.find(itype.cname) && blacklisted_methods[itype.cname].find(cname))
  1774. continue;
  1775. MethodInterface imethod;
  1776. imethod.name = method_info.name;
  1777. imethod.cname = cname;
  1778. if (method_info.flags & METHOD_FLAG_VIRTUAL)
  1779. imethod.is_virtual = true;
  1780. PropertyInfo return_info = method_info.return_val;
  1781. MethodBind *m = imethod.is_virtual ? NULL : ClassDB::get_method(type_cname, method_info.name);
  1782. imethod.is_vararg = m && m->is_vararg();
  1783. if (!m && !imethod.is_virtual) {
  1784. ERR_FAIL_COND_MSG(!virtual_method_list.find(method_info),
  1785. "Missing MethodBind for non-virtual method: '" + itype.name + "." + imethod.name + "'.");
  1786. // A virtual method without the virtual flag. This is a special case.
  1787. // There is no method bind, so let's fallback to Godot's object.Call(string, params)
  1788. imethod.requires_object_call = true;
  1789. // The method Object.free is registered as a virtual method, but without the virtual flag.
  1790. // This is because this method is not supposed to be overridden, but called.
  1791. // We assume the return type is void.
  1792. imethod.return_type.cname = name_cache.type_void;
  1793. // Actually, more methods like this may be added in the future,
  1794. // which could actually will return something different.
  1795. // Let's put this to notify us if that ever happens.
  1796. if (itype.cname != name_cache.type_Object || imethod.name != "free") {
  1797. ERR_PRINTS("Notification: New unexpected virtual non-overridable method found."
  1798. " We only expected Object.free, but found '" +
  1799. itype.name + "." + imethod.name + "'.");
  1800. }
  1801. } else if (return_info.type == Variant::INT && return_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
  1802. imethod.return_type.cname = return_info.class_name;
  1803. imethod.return_type.is_enum = true;
  1804. } else if (return_info.class_name != StringName()) {
  1805. imethod.return_type.cname = return_info.class_name;
  1806. if (!imethod.is_virtual && ClassDB::is_parent_class(return_info.class_name, name_cache.type_Reference) && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE) {
  1807. /* clang-format off */
  1808. ERR_PRINTS("Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'."
  1809. " Are you returning a reference type by pointer? Method: '" + itype.name + "." + imethod.name + "'.");
  1810. /* clang-format on */
  1811. ERR_FAIL();
  1812. }
  1813. } else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  1814. imethod.return_type.cname = return_info.hint_string;
  1815. } else if (return_info.type == Variant::NIL && return_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
  1816. imethod.return_type.cname = name_cache.type_Variant;
  1817. } else if (return_info.type == Variant::NIL) {
  1818. imethod.return_type.cname = name_cache.type_void;
  1819. } else {
  1820. if (return_info.type == Variant::INT) {
  1821. imethod.return_type.cname = _get_int_type_name_from_meta(m ? m->get_argument_meta(-1) : GodotTypeInfo::METADATA_NONE);
  1822. } else if (return_info.type == Variant::REAL) {
  1823. imethod.return_type.cname = _get_float_type_name_from_meta(m ? m->get_argument_meta(-1) : GodotTypeInfo::METADATA_NONE);
  1824. } else {
  1825. imethod.return_type.cname = Variant::get_type_name(return_info.type);
  1826. }
  1827. }
  1828. for (int i = 0; i < argc; i++) {
  1829. PropertyInfo arginfo = method_info.arguments[i];
  1830. ArgumentInterface iarg;
  1831. iarg.name = arginfo.name;
  1832. if (arginfo.type == Variant::INT && arginfo.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
  1833. iarg.type.cname = arginfo.class_name;
  1834. iarg.type.is_enum = true;
  1835. } else if (arginfo.class_name != StringName()) {
  1836. iarg.type.cname = arginfo.class_name;
  1837. } else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  1838. iarg.type.cname = arginfo.hint_string;
  1839. } else if (arginfo.type == Variant::NIL) {
  1840. iarg.type.cname = name_cache.type_Variant;
  1841. } else {
  1842. if (arginfo.type == Variant::INT) {
  1843. iarg.type.cname = _get_int_type_name_from_meta(m ? m->get_argument_meta(i) : GodotTypeInfo::METADATA_NONE);
  1844. } else if (arginfo.type == Variant::REAL) {
  1845. iarg.type.cname = _get_float_type_name_from_meta(m ? m->get_argument_meta(i) : GodotTypeInfo::METADATA_NONE);
  1846. } else {
  1847. iarg.type.cname = Variant::get_type_name(arginfo.type);
  1848. }
  1849. }
  1850. iarg.name = escape_csharp_keyword(snake_to_camel_case(iarg.name));
  1851. if (m && m->has_default_argument(i)) {
  1852. _default_argument_from_variant(m->get_default_argument(i), iarg);
  1853. }
  1854. imethod.add_argument(iarg);
  1855. }
  1856. if (imethod.is_vararg) {
  1857. ArgumentInterface ivararg;
  1858. ivararg.type.cname = name_cache.type_VarArg;
  1859. ivararg.name = "@args";
  1860. imethod.add_argument(ivararg);
  1861. }
  1862. imethod.proxy_name = escape_csharp_keyword(snake_to_pascal_case(imethod.name));
  1863. // Prevent the method and its enclosing type from sharing the same name
  1864. if (imethod.proxy_name == itype.proxy_name) {
  1865. _log("Name of method '%s' is ambiguous with the name of its enclosing class '%s'. Renaming method to '%s_'\n",
  1866. imethod.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), imethod.proxy_name.utf8().get_data());
  1867. imethod.proxy_name += "_";
  1868. }
  1869. Map<StringName, StringName>::Element *accessor = accessor_methods.find(imethod.cname);
  1870. if (accessor) {
  1871. const PropertyInterface *accessor_property = itype.find_property_by_name(accessor->value());
  1872. // We only deprecate an accessor method if it's in the same class as the property. It's easier this way, but also
  1873. // we don't know if an accessor method in a different class could have other purposes, so better leave those untouched.
  1874. imethod.is_deprecated = true;
  1875. imethod.deprecation_message = imethod.proxy_name + " is deprecated. Use the " + accessor_property->proxy_name + " property instead.";
  1876. }
  1877. if (itype.class_doc) {
  1878. for (int i = 0; i < itype.class_doc->methods.size(); i++) {
  1879. if (itype.class_doc->methods[i].name == imethod.name) {
  1880. imethod.method_doc = &itype.class_doc->methods[i];
  1881. break;
  1882. }
  1883. }
  1884. }
  1885. if (!imethod.is_virtual && imethod.name[0] == '_') {
  1886. for (const List<PropertyInterface>::Element *F = itype.properties.front(); F; F = F->next()) {
  1887. const PropertyInterface &iprop = F->get();
  1888. if (iprop.setter == imethod.name || iprop.getter == imethod.name) {
  1889. imethod.is_internal = true;
  1890. itype.methods.push_back(imethod);
  1891. break;
  1892. }
  1893. }
  1894. } else {
  1895. itype.methods.push_back(imethod);
  1896. }
  1897. }
  1898. // Populate enums and constants
  1899. List<String> constants;
  1900. ClassDB::get_integer_constant_list(type_cname, &constants, true);
  1901. const HashMap<StringName, List<StringName> > &enum_map = class_info->enum_map;
  1902. const StringName *k = NULL;
  1903. while ((k = enum_map.next(k))) {
  1904. StringName enum_proxy_cname = *k;
  1905. String enum_proxy_name = enum_proxy_cname.operator String();
  1906. if (itype.find_property_by_proxy_name(enum_proxy_cname)) {
  1907. // We have several conflicts between enums and PascalCase properties,
  1908. // so we append 'Enum' to the enum name in those cases.
  1909. enum_proxy_name += "Enum";
  1910. enum_proxy_cname = StringName(enum_proxy_name);
  1911. }
  1912. EnumInterface ienum(enum_proxy_cname);
  1913. const List<StringName> &enum_constants = enum_map.get(*k);
  1914. for (const List<StringName>::Element *E = enum_constants.front(); E; E = E->next()) {
  1915. const StringName &constant_cname = E->get();
  1916. String constant_name = constant_cname.operator String();
  1917. int *value = class_info->constant_map.getptr(constant_cname);
  1918. ERR_FAIL_NULL(value);
  1919. constants.erase(constant_name);
  1920. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value);
  1921. iconstant.const_doc = NULL;
  1922. for (int i = 0; i < itype.class_doc->constants.size(); i++) {
  1923. const DocData::ConstantDoc &const_doc = itype.class_doc->constants[i];
  1924. if (const_doc.name == iconstant.name) {
  1925. iconstant.const_doc = &const_doc;
  1926. break;
  1927. }
  1928. }
  1929. ienum.constants.push_back(iconstant);
  1930. }
  1931. int prefix_length = _determine_enum_prefix(ienum);
  1932. _apply_prefix_to_enum_constants(ienum, prefix_length);
  1933. itype.enums.push_back(ienum);
  1934. TypeInterface enum_itype;
  1935. enum_itype.is_enum = true;
  1936. enum_itype.name = itype.name + "." + String(*k);
  1937. enum_itype.cname = StringName(enum_itype.name);
  1938. enum_itype.proxy_name = itype.proxy_name + "." + enum_proxy_name;
  1939. TypeInterface::postsetup_enum_type(enum_itype);
  1940. enum_types.insert(enum_itype.cname, enum_itype);
  1941. }
  1942. for (const List<String>::Element *E = constants.front(); E; E = E->next()) {
  1943. const String &constant_name = E->get();
  1944. int *value = class_info->constant_map.getptr(StringName(E->get()));
  1945. ERR_FAIL_NULL(value);
  1946. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value);
  1947. iconstant.const_doc = NULL;
  1948. for (int i = 0; i < itype.class_doc->constants.size(); i++) {
  1949. const DocData::ConstantDoc &const_doc = itype.class_doc->constants[i];
  1950. if (const_doc.name == iconstant.name) {
  1951. iconstant.const_doc = &const_doc;
  1952. break;
  1953. }
  1954. }
  1955. itype.constants.push_back(iconstant);
  1956. }
  1957. obj_types.insert(itype.cname, itype);
  1958. class_list.pop_front();
  1959. }
  1960. }
  1961. void BindingsGenerator::_default_argument_from_variant(const Variant &p_val, ArgumentInterface &r_iarg) {
  1962. r_iarg.default_argument = p_val;
  1963. switch (p_val.get_type()) {
  1964. case Variant::NIL:
  1965. // Either Object type or Variant
  1966. r_iarg.default_argument = "null";
  1967. break;
  1968. // Atomic types
  1969. case Variant::BOOL:
  1970. r_iarg.default_argument = bool(p_val) ? "true" : "false";
  1971. break;
  1972. case Variant::INT:
  1973. if (r_iarg.type.cname != name_cache.type_int) {
  1974. r_iarg.default_argument = "(%s)" + r_iarg.default_argument;
  1975. }
  1976. break;
  1977. case Variant::REAL:
  1978. #ifndef REAL_T_IS_DOUBLE
  1979. r_iarg.default_argument += "f";
  1980. #endif
  1981. break;
  1982. case Variant::STRING:
  1983. case Variant::NODE_PATH:
  1984. r_iarg.default_argument = "\"" + r_iarg.default_argument + "\"";
  1985. break;
  1986. case Variant::TRANSFORM:
  1987. if (p_val.operator Transform() == Transform())
  1988. r_iarg.default_argument.clear();
  1989. r_iarg.default_argument = "new %s(" + r_iarg.default_argument + ")";
  1990. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  1991. break;
  1992. case Variant::PLANE:
  1993. case Variant::AABB:
  1994. case Variant::COLOR:
  1995. r_iarg.default_argument = "new Color(1, 1, 1, 1)";
  1996. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  1997. break;
  1998. case Variant::VECTOR2:
  1999. case Variant::RECT2:
  2000. case Variant::VECTOR3:
  2001. r_iarg.default_argument = "new %s" + r_iarg.default_argument;
  2002. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2003. break;
  2004. case Variant::OBJECT:
  2005. if (p_val.is_zero()) {
  2006. r_iarg.default_argument = "null";
  2007. break;
  2008. }
  2009. FALLTHROUGH;
  2010. case Variant::DICTIONARY:
  2011. case Variant::_RID:
  2012. r_iarg.default_argument = "new %s()";
  2013. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  2014. break;
  2015. case Variant::ARRAY:
  2016. case Variant::POOL_BYTE_ARRAY:
  2017. case Variant::POOL_INT_ARRAY:
  2018. case Variant::POOL_REAL_ARRAY:
  2019. case Variant::POOL_STRING_ARRAY:
  2020. case Variant::POOL_VECTOR2_ARRAY:
  2021. case Variant::POOL_VECTOR3_ARRAY:
  2022. case Variant::POOL_COLOR_ARRAY:
  2023. r_iarg.default_argument = "new %s {}";
  2024. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  2025. break;
  2026. case Variant::TRANSFORM2D:
  2027. case Variant::BASIS:
  2028. case Variant::QUAT:
  2029. r_iarg.default_argument = Variant::get_type_name(p_val.get_type()) + ".Identity";
  2030. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2031. break;
  2032. default: {
  2033. }
  2034. }
  2035. if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "null")
  2036. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  2037. }
  2038. void BindingsGenerator::_populate_builtin_type_interfaces() {
  2039. builtin_types.clear();
  2040. TypeInterface itype;
  2041. #define INSERT_STRUCT_TYPE(m_type, m_type_in) \
  2042. { \
  2043. itype = TypeInterface::create_value_type(String(#m_type)); \
  2044. itype.c_in = "\t%0 %1_in = MARSHALLED_IN(" #m_type ", %1);\n"; \
  2045. itype.c_out = "\treturn MARSHALLED_OUT(" #m_type ", %1);\n"; \
  2046. itype.c_arg_in = "&%s_in"; \
  2047. itype.c_type_in = "GDMonoMarshal::M_" #m_type "*"; \
  2048. itype.c_type_out = "GDMonoMarshal::M_" #m_type; \
  2049. itype.cs_in = "ref %s"; \
  2050. itype.cs_out = "return (%1)%0;"; \
  2051. itype.im_type_out = itype.cs_type; \
  2052. builtin_types.insert(itype.cname, itype); \
  2053. }
  2054. INSERT_STRUCT_TYPE(Vector2, "real_t*")
  2055. INSERT_STRUCT_TYPE(Rect2, "real_t*")
  2056. INSERT_STRUCT_TYPE(Transform2D, "real_t*")
  2057. INSERT_STRUCT_TYPE(Vector3, "real_t*")
  2058. INSERT_STRUCT_TYPE(Basis, "real_t*")
  2059. INSERT_STRUCT_TYPE(Quat, "real_t*")
  2060. INSERT_STRUCT_TYPE(Transform, "real_t*")
  2061. INSERT_STRUCT_TYPE(AABB, "real_t*")
  2062. INSERT_STRUCT_TYPE(Color, "real_t*")
  2063. INSERT_STRUCT_TYPE(Plane, "real_t*")
  2064. #undef INSERT_STRUCT_TYPE
  2065. // bool
  2066. itype = TypeInterface::create_value_type(String("bool"));
  2067. {
  2068. // MonoBoolean <---> bool
  2069. itype.c_in = "\t%0 %1_in = (%0)%1;\n";
  2070. itype.c_out = "\treturn (%0)%1;\n";
  2071. itype.c_type = "bool";
  2072. itype.c_type_in = "MonoBoolean";
  2073. itype.c_type_out = itype.c_type_in;
  2074. itype.c_arg_in = "&%s_in";
  2075. }
  2076. itype.im_type_in = itype.name;
  2077. itype.im_type_out = itype.name;
  2078. builtin_types.insert(itype.cname, itype);
  2079. // Integer types
  2080. {
  2081. // C interface for 'uint32_t' is the same as that of enums. Remember to apply
  2082. // any of the changes done here to 'TypeInterface::postsetup_enum_type' as well.
  2083. #define INSERT_INT_TYPE(m_name, m_c_type_in_out, m_c_type) \
  2084. { \
  2085. itype = TypeInterface::create_value_type(String(m_name)); \
  2086. { \
  2087. itype.c_in = "\t%0 %1_in = (%0)%1;\n"; \
  2088. itype.c_out = "\treturn (%0)%1;\n"; \
  2089. itype.c_type = #m_c_type; \
  2090. itype.c_arg_in = "&%s_in"; \
  2091. } \
  2092. itype.c_type_in = #m_c_type_in_out; \
  2093. itype.c_type_out = itype.c_type_in; \
  2094. itype.im_type_in = itype.name; \
  2095. itype.im_type_out = itype.name; \
  2096. builtin_types.insert(itype.cname, itype); \
  2097. }
  2098. // The expected type for all integers in ptrcall is 'int64_t', so that's what we use for 'c_type'
  2099. INSERT_INT_TYPE("sbyte", int8_t, int64_t);
  2100. INSERT_INT_TYPE("short", int16_t, int64_t);
  2101. INSERT_INT_TYPE("int", int32_t, int64_t);
  2102. INSERT_INT_TYPE("long", int64_t, int64_t);
  2103. INSERT_INT_TYPE("byte", uint8_t, int64_t);
  2104. INSERT_INT_TYPE("ushort", uint16_t, int64_t);
  2105. INSERT_INT_TYPE("uint", uint32_t, int64_t);
  2106. INSERT_INT_TYPE("ulong", uint64_t, int64_t);
  2107. }
  2108. // Floating point types
  2109. {
  2110. // float
  2111. itype = TypeInterface();
  2112. itype.name = "float";
  2113. itype.cname = itype.name;
  2114. itype.proxy_name = "float";
  2115. {
  2116. // The expected type for 'float' in ptrcall is 'double'
  2117. itype.c_in = "\t%0 %1_in = (%0)%1;\n";
  2118. itype.c_out = "\treturn (%0)%1;\n";
  2119. itype.c_type = "double";
  2120. itype.c_type_in = "float";
  2121. itype.c_type_out = "float";
  2122. itype.c_arg_in = "&%s_in";
  2123. }
  2124. itype.cs_type = itype.proxy_name;
  2125. itype.im_type_in = itype.proxy_name;
  2126. itype.im_type_out = itype.proxy_name;
  2127. builtin_types.insert(itype.cname, itype);
  2128. // double
  2129. itype = TypeInterface();
  2130. itype.name = "double";
  2131. itype.cname = itype.name;
  2132. itype.proxy_name = "double";
  2133. itype.c_type = "double";
  2134. itype.c_type_in = "double";
  2135. itype.c_type_out = "double";
  2136. itype.c_arg_in = "&%s";
  2137. itype.cs_type = itype.proxy_name;
  2138. itype.im_type_in = itype.proxy_name;
  2139. itype.im_type_out = itype.proxy_name;
  2140. builtin_types.insert(itype.cname, itype);
  2141. }
  2142. // String
  2143. itype = TypeInterface();
  2144. itype.name = "String";
  2145. itype.cname = itype.name;
  2146. itype.proxy_name = "string";
  2147. itype.c_in = "\t%0 %1_in = " C_METHOD_MONOSTR_TO_GODOT "(%1);\n";
  2148. itype.c_out = "\treturn " C_METHOD_MONOSTR_FROM_GODOT "(%1);\n";
  2149. itype.c_arg_in = "&%s_in";
  2150. itype.c_type = itype.name;
  2151. itype.c_type_in = "MonoString*";
  2152. itype.c_type_out = "MonoString*";
  2153. itype.cs_type = itype.proxy_name;
  2154. itype.im_type_in = itype.proxy_name;
  2155. itype.im_type_out = itype.proxy_name;
  2156. builtin_types.insert(itype.cname, itype);
  2157. // NodePath
  2158. itype = TypeInterface();
  2159. itype.name = "NodePath";
  2160. itype.cname = itype.name;
  2161. itype.proxy_name = "NodePath";
  2162. itype.c_out = "\treturn memnew(NodePath(%1));\n";
  2163. itype.c_type = itype.name;
  2164. itype.c_type_in = itype.c_type + "*";
  2165. itype.c_type_out = itype.c_type + "*";
  2166. itype.cs_type = itype.proxy_name;
  2167. itype.cs_in = "NodePath." CS_SMETHOD_GETINSTANCE "(%0)";
  2168. itype.cs_out = "return new %1(%0);";
  2169. itype.im_type_in = "IntPtr";
  2170. itype.im_type_out = "IntPtr";
  2171. builtin_types.insert(itype.cname, itype);
  2172. // RID
  2173. itype = TypeInterface();
  2174. itype.name = "RID";
  2175. itype.cname = itype.name;
  2176. itype.proxy_name = "RID";
  2177. itype.c_out = "\treturn memnew(RID(%1));\n";
  2178. itype.c_type = itype.name;
  2179. itype.c_type_in = itype.c_type + "*";
  2180. itype.c_type_out = itype.c_type + "*";
  2181. itype.cs_type = itype.proxy_name;
  2182. itype.cs_in = "RID." CS_SMETHOD_GETINSTANCE "(%0)";
  2183. itype.cs_out = "return new %1(%0);";
  2184. itype.im_type_in = "IntPtr";
  2185. itype.im_type_out = "IntPtr";
  2186. builtin_types.insert(itype.cname, itype);
  2187. // Variant
  2188. itype = TypeInterface();
  2189. itype.name = "Variant";
  2190. itype.cname = itype.name;
  2191. itype.proxy_name = "object";
  2192. itype.c_in = "\t%0 %1_in = " C_METHOD_MANAGED_TO_VARIANT "(%1);\n";
  2193. itype.c_out = "\treturn " C_METHOD_MANAGED_FROM_VARIANT "(%1);\n";
  2194. itype.c_arg_in = "&%s_in";
  2195. itype.c_type = itype.name;
  2196. itype.c_type_in = "MonoObject*";
  2197. itype.c_type_out = "MonoObject*";
  2198. itype.cs_type = itype.proxy_name;
  2199. itype.im_type_in = "object";
  2200. itype.im_type_out = itype.proxy_name;
  2201. builtin_types.insert(itype.cname, itype);
  2202. // VarArg (fictitious type to represent variable arguments)
  2203. itype = TypeInterface();
  2204. itype.name = "VarArg";
  2205. itype.cname = itype.name;
  2206. itype.proxy_name = "object[]";
  2207. itype.c_in = "\t%0 %1_in = " C_METHOD_MONOARRAY_TO(Array) "(%1);\n";
  2208. itype.c_arg_in = "&%s_in";
  2209. itype.c_type = "Array";
  2210. itype.c_type_in = "MonoArray*";
  2211. itype.cs_type = "params object[]";
  2212. itype.im_type_in = "object[]";
  2213. builtin_types.insert(itype.cname, itype);
  2214. #define INSERT_ARRAY_FULL(m_name, m_type, m_proxy_t) \
  2215. { \
  2216. itype = TypeInterface(); \
  2217. itype.name = #m_name; \
  2218. itype.cname = itype.name; \
  2219. itype.proxy_name = #m_proxy_t "[]"; \
  2220. itype.c_in = "\t%0 %1_in = " C_METHOD_MONOARRAY_TO(m_type) "(%1);\n"; \
  2221. itype.c_out = "\treturn " C_METHOD_MONOARRAY_FROM(m_type) "(%1);\n"; \
  2222. itype.c_arg_in = "&%s_in"; \
  2223. itype.c_type = #m_type; \
  2224. itype.c_type_in = "MonoArray*"; \
  2225. itype.c_type_out = "MonoArray*"; \
  2226. itype.cs_type = itype.proxy_name; \
  2227. itype.im_type_in = itype.proxy_name; \
  2228. itype.im_type_out = itype.proxy_name; \
  2229. builtin_types.insert(itype.name, itype); \
  2230. }
  2231. #define INSERT_ARRAY(m_type, m_proxy_t) INSERT_ARRAY_FULL(m_type, m_type, m_proxy_t)
  2232. INSERT_ARRAY(PoolIntArray, int);
  2233. INSERT_ARRAY_FULL(PoolByteArray, PoolByteArray, byte);
  2234. #ifdef REAL_T_IS_DOUBLE
  2235. INSERT_ARRAY(PoolRealArray, double);
  2236. #else
  2237. INSERT_ARRAY(PoolRealArray, float);
  2238. #endif
  2239. INSERT_ARRAY(PoolStringArray, string);
  2240. INSERT_ARRAY(PoolColorArray, Color);
  2241. INSERT_ARRAY(PoolVector2Array, Vector2);
  2242. INSERT_ARRAY(PoolVector3Array, Vector3);
  2243. #undef INSERT_ARRAY
  2244. // Array
  2245. itype = TypeInterface();
  2246. itype.name = "Array";
  2247. itype.cname = itype.name;
  2248. itype.proxy_name = itype.name;
  2249. itype.c_out = "\treturn memnew(Array(%1));\n";
  2250. itype.c_type = itype.name;
  2251. itype.c_type_in = itype.c_type + "*";
  2252. itype.c_type_out = itype.c_type + "*";
  2253. itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
  2254. itype.cs_in = "%0." CS_SMETHOD_GETINSTANCE "()";
  2255. itype.cs_out = "return new " + itype.cs_type + "(%0);";
  2256. itype.im_type_in = "IntPtr";
  2257. itype.im_type_out = "IntPtr";
  2258. builtin_types.insert(itype.cname, itype);
  2259. // Dictionary
  2260. itype = TypeInterface();
  2261. itype.name = "Dictionary";
  2262. itype.cname = itype.name;
  2263. itype.proxy_name = itype.name;
  2264. itype.c_out = "\treturn memnew(Dictionary(%1));\n";
  2265. itype.c_type = itype.name;
  2266. itype.c_type_in = itype.c_type + "*";
  2267. itype.c_type_out = itype.c_type + "*";
  2268. itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
  2269. itype.cs_in = "%0." CS_SMETHOD_GETINSTANCE "()";
  2270. itype.cs_out = "return new " + itype.cs_type + "(%0);";
  2271. itype.im_type_in = "IntPtr";
  2272. itype.im_type_out = "IntPtr";
  2273. builtin_types.insert(itype.cname, itype);
  2274. // void (fictitious type to represent the return type of methods that do not return anything)
  2275. itype = TypeInterface();
  2276. itype.name = "void";
  2277. itype.cname = itype.name;
  2278. itype.proxy_name = itype.name;
  2279. itype.c_type = itype.name;
  2280. itype.c_type_in = itype.c_type;
  2281. itype.c_type_out = itype.c_type;
  2282. itype.cs_type = itype.proxy_name;
  2283. itype.im_type_in = itype.proxy_name;
  2284. itype.im_type_out = itype.proxy_name;
  2285. builtin_types.insert(itype.cname, itype);
  2286. }
  2287. void BindingsGenerator::_populate_global_constants() {
  2288. int global_constants_count = GlobalConstants::get_global_constant_count();
  2289. if (global_constants_count > 0) {
  2290. Map<String, DocData::ClassDoc>::Element *match = EditorHelp::get_doc_data()->class_list.find("@GlobalScope");
  2291. CRASH_COND_MSG(!match, "Could not find '@GlobalScope' in DocData.");
  2292. const DocData::ClassDoc &global_scope_doc = match->value();
  2293. for (int i = 0; i < global_constants_count; i++) {
  2294. String constant_name = GlobalConstants::get_global_constant_name(i);
  2295. const DocData::ConstantDoc *const_doc = NULL;
  2296. for (int j = 0; j < global_scope_doc.constants.size(); j++) {
  2297. const DocData::ConstantDoc &curr_const_doc = global_scope_doc.constants[j];
  2298. if (curr_const_doc.name == constant_name) {
  2299. const_doc = &curr_const_doc;
  2300. break;
  2301. }
  2302. }
  2303. int constant_value = GlobalConstants::get_global_constant_value(i);
  2304. StringName enum_name = GlobalConstants::get_global_constant_enum(i);
  2305. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), constant_value);
  2306. iconstant.const_doc = const_doc;
  2307. if (enum_name != StringName()) {
  2308. EnumInterface ienum(enum_name);
  2309. List<EnumInterface>::Element *enum_match = global_enums.find(ienum);
  2310. if (enum_match) {
  2311. enum_match->get().constants.push_back(iconstant);
  2312. } else {
  2313. ienum.constants.push_back(iconstant);
  2314. global_enums.push_back(ienum);
  2315. }
  2316. } else {
  2317. global_constants.push_back(iconstant);
  2318. }
  2319. }
  2320. for (List<EnumInterface>::Element *E = global_enums.front(); E; E = E->next()) {
  2321. EnumInterface &ienum = E->get();
  2322. TypeInterface enum_itype;
  2323. enum_itype.is_enum = true;
  2324. enum_itype.name = ienum.cname.operator String();
  2325. enum_itype.cname = ienum.cname;
  2326. enum_itype.proxy_name = enum_itype.name;
  2327. TypeInterface::postsetup_enum_type(enum_itype);
  2328. enum_types.insert(enum_itype.cname, enum_itype);
  2329. int prefix_length = _determine_enum_prefix(ienum);
  2330. // HARDCODED: The Error enum have the prefix 'ERR_' for everything except 'OK' and 'FAILED'.
  2331. if (ienum.cname == name_cache.enum_Error) {
  2332. if (prefix_length > 0) { // Just in case it ever changes
  2333. ERR_PRINTS("Prefix for enum '" _STR(Error) "' is not empty.");
  2334. }
  2335. prefix_length = 1; // 'ERR_'
  2336. }
  2337. _apply_prefix_to_enum_constants(ienum, prefix_length);
  2338. }
  2339. }
  2340. // HARDCODED
  2341. List<StringName> hardcoded_enums;
  2342. hardcoded_enums.push_back("Vector3.Axis");
  2343. for (List<StringName>::Element *E = hardcoded_enums.front(); E; E = E->next()) {
  2344. // These enums are not generated and must be written manually (e.g.: Vector3.Axis)
  2345. // Here, we assume core types do not begin with underscore
  2346. TypeInterface enum_itype;
  2347. enum_itype.is_enum = true;
  2348. enum_itype.name = E->get().operator String();
  2349. enum_itype.cname = E->get();
  2350. enum_itype.proxy_name = enum_itype.name;
  2351. TypeInterface::postsetup_enum_type(enum_itype);
  2352. enum_types.insert(enum_itype.cname, enum_itype);
  2353. }
  2354. }
  2355. void BindingsGenerator::_initialize_blacklisted_methods() {
  2356. blacklisted_methods["Object"].push_back("to_string"); // there is already ToString
  2357. blacklisted_methods["Object"].push_back("_to_string"); // override ToString instead
  2358. blacklisted_methods["Object"].push_back("_init"); // never called in C# (TODO: implement it)
  2359. }
  2360. void BindingsGenerator::_log(const char *p_format, ...) {
  2361. if (log_print_enabled) {
  2362. va_list list;
  2363. va_start(list, p_format);
  2364. OS::get_singleton()->print("%s", str_format(p_format, list).utf8().get_data());
  2365. va_end(list);
  2366. }
  2367. }
  2368. void BindingsGenerator::_initialize() {
  2369. EditorHelp::generate_doc();
  2370. enum_types.clear();
  2371. _initialize_blacklisted_methods();
  2372. _populate_object_type_interfaces();
  2373. _populate_builtin_type_interfaces();
  2374. _populate_global_constants();
  2375. // Generate internal calls (after populating type interfaces and global constants)
  2376. core_custom_icalls.clear();
  2377. editor_custom_icalls.clear();
  2378. for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next())
  2379. _generate_method_icalls(E.get());
  2380. }
  2381. void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) {
  2382. const int NUM_OPTIONS = 2;
  2383. String generate_all_glue_option = "--generate-mono-glue";
  2384. String generate_cs_glue_option = "--generate-mono-cs-glue";
  2385. String generate_cpp_glue_option = "--generate-mono-cpp-glue";
  2386. String glue_dir_path;
  2387. String cs_dir_path;
  2388. String cpp_dir_path;
  2389. int options_left = NUM_OPTIONS;
  2390. const List<String>::Element *elem = p_cmdline_args.front();
  2391. while (elem && options_left) {
  2392. if (elem->get() == generate_all_glue_option) {
  2393. const List<String>::Element *path_elem = elem->next();
  2394. if (path_elem) {
  2395. glue_dir_path = path_elem->get();
  2396. elem = elem->next();
  2397. } else {
  2398. ERR_PRINTS(generate_all_glue_option + ": No output directory specified (expected path to '{GODOT_ROOT}/modules/mono/glue').");
  2399. }
  2400. --options_left;
  2401. } else if (elem->get() == generate_cs_glue_option) {
  2402. const List<String>::Element *path_elem = elem->next();
  2403. if (path_elem) {
  2404. cs_dir_path = path_elem->get();
  2405. elem = elem->next();
  2406. } else {
  2407. ERR_PRINTS(generate_cs_glue_option + ": No output directory specified.");
  2408. }
  2409. --options_left;
  2410. } else if (elem->get() == generate_cpp_glue_option) {
  2411. const List<String>::Element *path_elem = elem->next();
  2412. if (path_elem) {
  2413. cpp_dir_path = path_elem->get();
  2414. elem = elem->next();
  2415. } else {
  2416. ERR_PRINTS(generate_cpp_glue_option + ": No output directory specified.");
  2417. }
  2418. --options_left;
  2419. }
  2420. elem = elem->next();
  2421. }
  2422. if (glue_dir_path.length() || cs_dir_path.length() || cpp_dir_path.length()) {
  2423. BindingsGenerator bindings_generator;
  2424. bindings_generator.set_log_print_enabled(true);
  2425. if (glue_dir_path.length()) {
  2426. if (bindings_generator.generate_glue(glue_dir_path) != OK)
  2427. ERR_PRINTS(generate_all_glue_option + ": Failed to generate the C++ glue.");
  2428. if (bindings_generator.generate_cs_api(glue_dir_path.plus_file("Managed/Generated")) != OK)
  2429. ERR_PRINTS(generate_all_glue_option + ": Failed to generate the C# API.");
  2430. }
  2431. if (cs_dir_path.length()) {
  2432. if (bindings_generator.generate_cs_api(cs_dir_path) != OK)
  2433. ERR_PRINTS(generate_cs_glue_option + ": Failed to generate the C# API.");
  2434. }
  2435. if (cpp_dir_path.length()) {
  2436. if (bindings_generator.generate_glue(cpp_dir_path) != OK)
  2437. ERR_PRINTS(generate_cpp_glue_option + ": Failed to generate the C++ glue.");
  2438. }
  2439. // Exit once done
  2440. ::exit(0);
  2441. }
  2442. }
  2443. #endif