bindings_generator.cpp 129 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722
  1. /*************************************************************************/
  2. /* bindings_generator.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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. #if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED)
  32. #include "core/config/engine.h"
  33. #include "core/core_constants.h"
  34. #include "core/io/compression.h"
  35. #include "core/io/dir_access.h"
  36. #include "core/io/file_access.h"
  37. #include "core/os/os.h"
  38. #include "core/string/ucaps.h"
  39. #include "main/main.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. #define CS_INDENT " " // 4 whitespaces
  46. #define INDENT1 CS_INDENT
  47. #define INDENT2 INDENT1 INDENT1
  48. #define INDENT3 INDENT2 INDENT1
  49. #define INDENT4 INDENT3 INDENT1
  50. #define INDENT5 INDENT4 INDENT1
  51. #define MEMBER_BEGIN "\n" INDENT2
  52. #define OPEN_BLOCK "{\n"
  53. #define CLOSE_BLOCK "}\n"
  54. #define OPEN_BLOCK_L2 INDENT2 OPEN_BLOCK INDENT3
  55. #define OPEN_BLOCK_L3 INDENT3 OPEN_BLOCK INDENT4
  56. #define CLOSE_BLOCK_L2 INDENT2 CLOSE_BLOCK
  57. #define CLOSE_BLOCK_L3 INDENT3 CLOSE_BLOCK
  58. #define CS_FIELD_MEMORYOWN "memoryOwn"
  59. #define CS_PARAM_METHODBIND "method"
  60. #define CS_PARAM_INSTANCE "ptr"
  61. #define CS_SMETHOD_GETINSTANCE "GetPtr"
  62. #define CS_METHOD_CALL "Call"
  63. #define GLUE_HEADER_FILE "glue_header.h"
  64. #define ICALL_PREFIX "godot_icall_"
  65. #define SINGLETON_ICALL_SUFFIX "_get_singleton"
  66. #define ICALL_GET_METHODBIND "__ClassDB_get_method"
  67. #define C_LOCAL_RET "ret"
  68. #define C_LOCAL_VARARG_RET "vararg_ret"
  69. #define C_LOCAL_PTRCALL_ARGS "call_args"
  70. #define C_MACRO_OBJECT_CONSTRUCT "GODOTSHARP_INSTANCE_OBJECT"
  71. #define C_NS_MONOUTILS "GDMonoUtils"
  72. #define C_NS_MONOINTERNALS "GDMonoInternals"
  73. #define C_METHOD_TIE_MANAGED_TO_UNMANAGED C_NS_MONOINTERNALS "::tie_managed_to_unmanaged"
  74. #define C_METHOD_UNMANAGED_GET_MANAGED C_NS_MONOUTILS "::unmanaged_get_managed"
  75. #define C_NS_MONOMARSHAL "GDMonoMarshal"
  76. #define C_METHOD_MANAGED_TO_VARIANT C_NS_MONOMARSHAL "::mono_object_to_variant"
  77. #define C_METHOD_MANAGED_FROM_VARIANT C_NS_MONOMARSHAL "::variant_to_mono_object"
  78. #define C_METHOD_MONOSTR_TO_GODOT C_NS_MONOMARSHAL "::mono_string_to_godot"
  79. #define C_METHOD_MONOSTR_FROM_GODOT C_NS_MONOMARSHAL "::mono_string_from_godot"
  80. #define C_METHOD_MONOARRAY_TO(m_type) C_NS_MONOMARSHAL "::mono_array_to_" #m_type
  81. #define C_METHOD_MONOARRAY_FROM(m_type) C_NS_MONOMARSHAL "::" #m_type "_to_mono_array"
  82. #define C_METHOD_MANAGED_TO_CALLABLE C_NS_MONOMARSHAL "::managed_to_callable"
  83. #define C_METHOD_MANAGED_FROM_CALLABLE C_NS_MONOMARSHAL "::callable_to_managed"
  84. #define C_METHOD_MANAGED_TO_SIGNAL C_NS_MONOMARSHAL "::signal_info_to_callable"
  85. #define C_METHOD_MANAGED_FROM_SIGNAL C_NS_MONOMARSHAL "::callable_to_signal_info"
  86. #define BINDINGS_GENERATOR_VERSION UINT32_C(13)
  87. const char *BindingsGenerator::TypeInterface::DEFAULT_VARARG_C_IN("\t%0 %1_in = %1;\n");
  88. static String fix_doc_description(const String &p_bbcode) {
  89. // This seems to be the correct way to do this. It's the same EditorHelp does.
  90. return p_bbcode.dedent()
  91. .replace("\t", "")
  92. .replace("\r", "")
  93. .strip_edges();
  94. }
  95. static String snake_to_pascal_case(const String &p_identifier, bool p_input_is_upper = false) {
  96. String ret;
  97. Vector<String> parts = p_identifier.split("_", true);
  98. for (int i = 0; i < parts.size(); i++) {
  99. String part = parts[i];
  100. if (part.length()) {
  101. part[0] = _find_upper(part[0]);
  102. if (p_input_is_upper) {
  103. for (int j = 1; j < part.length(); j++) {
  104. part[j] = _find_lower(part[j]);
  105. }
  106. }
  107. ret += part;
  108. } else {
  109. if (i == 0 || i == (parts.size() - 1)) {
  110. // Preserve underscores at the beginning and end
  111. ret += "_";
  112. } else {
  113. // Preserve contiguous underscores
  114. if (parts[i - 1].length()) {
  115. ret += "__";
  116. } else {
  117. ret += "_";
  118. }
  119. }
  120. }
  121. }
  122. return ret;
  123. }
  124. static String snake_to_camel_case(const String &p_identifier, bool p_input_is_upper = false) {
  125. String ret;
  126. Vector<String> parts = p_identifier.split("_", true);
  127. for (int i = 0; i < parts.size(); i++) {
  128. String part = parts[i];
  129. if (part.length()) {
  130. if (i != 0) {
  131. part[0] = _find_upper(part[0]);
  132. }
  133. if (p_input_is_upper) {
  134. for (int j = i != 0 ? 1 : 0; j < part.length(); j++) {
  135. part[j] = _find_lower(part[j]);
  136. }
  137. }
  138. ret += part;
  139. } else {
  140. if (i == 0 || i == (parts.size() - 1)) {
  141. // Preserve underscores at the beginning and end
  142. ret += "_";
  143. } else {
  144. // Preserve contiguous underscores
  145. if (parts[i - 1].length()) {
  146. ret += "__";
  147. } else {
  148. ret += "_";
  149. }
  150. }
  151. }
  152. }
  153. return ret;
  154. }
  155. String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterface *p_itype) {
  156. // Based on the version in EditorHelp
  157. if (p_bbcode.is_empty()) {
  158. return String();
  159. }
  160. DocTools *doc = EditorHelp::get_doc_data();
  161. String bbcode = p_bbcode;
  162. StringBuilder xml_output;
  163. xml_output.append("<para>");
  164. List<String> tag_stack;
  165. bool code_tag = false;
  166. int pos = 0;
  167. while (pos < bbcode.length()) {
  168. int brk_pos = bbcode.find("[", pos);
  169. if (brk_pos < 0) {
  170. brk_pos = bbcode.length();
  171. }
  172. if (brk_pos > pos) {
  173. String text = bbcode.substr(pos, brk_pos - pos);
  174. if (code_tag || tag_stack.size() > 0) {
  175. xml_output.append(text.xml_escape());
  176. } else {
  177. Vector<String> lines = text.split("\n");
  178. for (int i = 0; i < lines.size(); i++) {
  179. if (i != 0) {
  180. xml_output.append("<para>");
  181. }
  182. xml_output.append(lines[i].xml_escape());
  183. if (i != lines.size() - 1) {
  184. xml_output.append("</para>\n");
  185. }
  186. }
  187. }
  188. }
  189. if (brk_pos == bbcode.length()) {
  190. break; // nothing else to add
  191. }
  192. int brk_end = bbcode.find("]", brk_pos + 1);
  193. if (brk_end == -1) {
  194. String text = bbcode.substr(brk_pos, bbcode.length() - brk_pos);
  195. if (code_tag || tag_stack.size() > 0) {
  196. xml_output.append(text.xml_escape());
  197. } else {
  198. Vector<String> lines = text.split("\n");
  199. for (int i = 0; i < lines.size(); i++) {
  200. if (i != 0) {
  201. xml_output.append("<para>");
  202. }
  203. xml_output.append(lines[i].xml_escape());
  204. if (i != lines.size() - 1) {
  205. xml_output.append("</para>\n");
  206. }
  207. }
  208. }
  209. break;
  210. }
  211. String tag = bbcode.substr(brk_pos + 1, brk_end - brk_pos - 1);
  212. if (tag.begins_with("/")) {
  213. bool tag_ok = tag_stack.size() && tag_stack.front()->get() == tag.substr(1, tag.length());
  214. if (!tag_ok) {
  215. xml_output.append("[");
  216. pos = brk_pos + 1;
  217. continue;
  218. }
  219. tag_stack.pop_front();
  220. pos = brk_end + 1;
  221. code_tag = false;
  222. if (tag == "/url") {
  223. xml_output.append("</a>");
  224. } else if (tag == "/code") {
  225. xml_output.append("</c>");
  226. } else if (tag == "/codeblock") {
  227. xml_output.append("</code>");
  228. }
  229. } else if (code_tag) {
  230. xml_output.append("[");
  231. pos = brk_pos + 1;
  232. } else if (tag.begins_with("method ") || tag.begins_with("member ") || tag.begins_with("signal ") || tag.begins_with("enum ") || tag.begins_with("constant ")) {
  233. String link_target = tag.substr(tag.find(" ") + 1, tag.length());
  234. String link_tag = tag.substr(0, tag.find(" "));
  235. Vector<String> link_target_parts = link_target.split(".");
  236. if (link_target_parts.size() <= 0 || link_target_parts.size() > 2) {
  237. ERR_PRINT("Invalid reference format: '" + tag + "'.");
  238. xml_output.append("<c>");
  239. xml_output.append(tag);
  240. xml_output.append("</c>");
  241. pos = brk_end + 1;
  242. continue;
  243. }
  244. const TypeInterface *target_itype;
  245. StringName target_cname;
  246. if (link_target_parts.size() == 2) {
  247. target_itype = _get_type_or_null(TypeReference(link_target_parts[0]));
  248. if (!target_itype) {
  249. target_itype = _get_type_or_null(TypeReference("_" + link_target_parts[0]));
  250. }
  251. target_cname = link_target_parts[1];
  252. } else {
  253. target_itype = p_itype;
  254. target_cname = link_target_parts[0];
  255. }
  256. if (link_tag == "method") {
  257. if (!target_itype || !target_itype->is_object_type) {
  258. if (OS::get_singleton()->is_stdout_verbose()) {
  259. if (target_itype) {
  260. OS::get_singleton()->print("Cannot resolve method reference for non-Godot.Object type in documentation: %s\n", link_target.utf8().get_data());
  261. } else {
  262. OS::get_singleton()->print("Cannot resolve type from method reference in documentation: %s\n", link_target.utf8().get_data());
  263. }
  264. }
  265. // TODO Map what we can
  266. xml_output.append("<c>");
  267. xml_output.append(link_target);
  268. xml_output.append("</c>");
  269. } else {
  270. const MethodInterface *target_imethod = target_itype->find_method_by_name(target_cname);
  271. if (target_imethod) {
  272. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  273. xml_output.append(target_itype->proxy_name);
  274. xml_output.append(".");
  275. xml_output.append(target_imethod->proxy_name);
  276. xml_output.append("\"/>");
  277. }
  278. }
  279. } else if (link_tag == "member") {
  280. if (!target_itype || !target_itype->is_object_type) {
  281. if (OS::get_singleton()->is_stdout_verbose()) {
  282. if (target_itype) {
  283. OS::get_singleton()->print("Cannot resolve member reference for non-Godot.Object type in documentation: %s\n", link_target.utf8().get_data());
  284. } else {
  285. OS::get_singleton()->print("Cannot resolve type from member reference in documentation: %s\n", link_target.utf8().get_data());
  286. }
  287. }
  288. // TODO Map what we can
  289. xml_output.append("<c>");
  290. xml_output.append(link_target);
  291. xml_output.append("</c>");
  292. } else {
  293. const PropertyInterface *target_iprop = target_itype->find_property_by_name(target_cname);
  294. if (target_iprop) {
  295. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  296. xml_output.append(target_itype->proxy_name);
  297. xml_output.append(".");
  298. xml_output.append(target_iprop->proxy_name);
  299. xml_output.append("\"/>");
  300. }
  301. }
  302. } else if (link_tag == "signal") {
  303. // We do not declare signals in any way in C#, so there is nothing to reference
  304. xml_output.append("<c>");
  305. xml_output.append(link_target);
  306. xml_output.append("</c>");
  307. } else if (link_tag == "enum") {
  308. StringName search_cname = !target_itype ? target_cname : StringName(target_itype->name + "." + (String)target_cname);
  309. const Map<StringName, TypeInterface>::Element *enum_match = enum_types.find(search_cname);
  310. if (!enum_match && search_cname != target_cname) {
  311. enum_match = enum_types.find(target_cname);
  312. }
  313. if (enum_match) {
  314. const TypeInterface &target_enum_itype = enum_match->value();
  315. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  316. xml_output.append(target_enum_itype.proxy_name); // Includes nesting class if any
  317. xml_output.append("\"/>");
  318. } else {
  319. ERR_PRINT("Cannot resolve enum reference in documentation: '" + link_target + "'.");
  320. xml_output.append("<c>");
  321. xml_output.append(link_target);
  322. xml_output.append("</c>");
  323. }
  324. } else if (link_tag == "constant") {
  325. if (!target_itype || !target_itype->is_object_type) {
  326. if (OS::get_singleton()->is_stdout_verbose()) {
  327. if (target_itype) {
  328. OS::get_singleton()->print("Cannot resolve constant reference for non-Godot.Object type in documentation: %s\n", link_target.utf8().get_data());
  329. } else {
  330. OS::get_singleton()->print("Cannot resolve type from constant reference in documentation: %s\n", link_target.utf8().get_data());
  331. }
  332. }
  333. // TODO Map what we can
  334. xml_output.append("<c>");
  335. xml_output.append(link_target);
  336. xml_output.append("</c>");
  337. } else if (!target_itype && target_cname == name_cache.type_at_GlobalScope) {
  338. String target_name = (String)target_cname;
  339. // Try to find as a global constant
  340. const ConstantInterface *target_iconst = find_constant_by_name(target_name, global_constants);
  341. if (target_iconst) {
  342. // Found global constant
  343. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "." BINDINGS_GLOBAL_SCOPE_CLASS ".");
  344. xml_output.append(target_iconst->proxy_name);
  345. xml_output.append("\"/>");
  346. } else {
  347. // Try to find as global enum constant
  348. const EnumInterface *target_ienum = nullptr;
  349. for (const EnumInterface &ienum : global_enums) {
  350. target_ienum = &ienum;
  351. target_iconst = find_constant_by_name(target_name, target_ienum->constants);
  352. if (target_iconst) {
  353. break;
  354. }
  355. }
  356. if (target_iconst) {
  357. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  358. xml_output.append(target_ienum->cname);
  359. xml_output.append(".");
  360. xml_output.append(target_iconst->proxy_name);
  361. xml_output.append("\"/>");
  362. } else {
  363. ERR_PRINT("Cannot resolve global constant reference in documentation: '" + link_target + "'.");
  364. xml_output.append("<c>");
  365. xml_output.append(link_target);
  366. xml_output.append("</c>");
  367. }
  368. }
  369. } else {
  370. String target_name = (String)target_cname;
  371. // Try to find the constant in the current class
  372. const ConstantInterface *target_iconst = find_constant_by_name(target_name, target_itype->constants);
  373. if (target_iconst) {
  374. // Found constant in current class
  375. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  376. xml_output.append(target_itype->proxy_name);
  377. xml_output.append(".");
  378. xml_output.append(target_iconst->proxy_name);
  379. xml_output.append("\"/>");
  380. } else {
  381. // Try to find as enum constant in the current class
  382. const EnumInterface *target_ienum = nullptr;
  383. for (const EnumInterface &ienum : target_itype->enums) {
  384. target_ienum = &ienum;
  385. target_iconst = find_constant_by_name(target_name, target_ienum->constants);
  386. if (target_iconst) {
  387. break;
  388. }
  389. }
  390. if (target_iconst) {
  391. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  392. xml_output.append(target_itype->proxy_name);
  393. xml_output.append(".");
  394. xml_output.append(target_ienum->cname);
  395. xml_output.append(".");
  396. xml_output.append(target_iconst->proxy_name);
  397. xml_output.append("\"/>");
  398. } else {
  399. ERR_PRINT("Cannot resolve constant reference in documentation: '" + link_target + "'.");
  400. xml_output.append("<c>");
  401. xml_output.append(link_target);
  402. xml_output.append("</c>");
  403. }
  404. }
  405. }
  406. }
  407. pos = brk_end + 1;
  408. } else if (doc->class_list.has(tag)) {
  409. if (tag == "Array" || tag == "Dictionary") {
  410. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE_COLLECTIONS ".");
  411. xml_output.append(tag);
  412. xml_output.append("\"/>");
  413. } else if (tag == "bool" || tag == "int") {
  414. xml_output.append("<see cref=\"");
  415. xml_output.append(tag);
  416. xml_output.append("\"/>");
  417. } else if (tag == "float") {
  418. xml_output.append("<see cref=\""
  419. #ifdef REAL_T_IS_DOUBLE
  420. "double"
  421. #else
  422. "float"
  423. #endif
  424. "\"/>");
  425. } else if (tag == "Variant") {
  426. // We use System.Object for Variant, so there is no Variant type in C#
  427. xml_output.append("<c>Variant</c>");
  428. } else if (tag == "String") {
  429. xml_output.append("<see cref=\"string\"/>");
  430. } else if (tag == "Nil") {
  431. xml_output.append("<see langword=\"null\"/>");
  432. } else if (tag.begins_with("@")) {
  433. // @GlobalScope, @GDScript, etc
  434. xml_output.append("<c>");
  435. xml_output.append(tag);
  436. xml_output.append("</c>");
  437. } else if (tag == "PackedByteArray") {
  438. xml_output.append("<see cref=\"T:byte[]\"/>");
  439. } else if (tag == "PackedInt32Array") {
  440. xml_output.append("<see cref=\"T:int[]\"/>");
  441. } else if (tag == "PackedInt64Array") {
  442. xml_output.append("<see cref=\"T:long[]\"/>");
  443. } else if (tag == "PackedFloat32Array") {
  444. xml_output.append("<see cref=\"T:float[]\"/>");
  445. } else if (tag == "PackedFloat64Array") {
  446. xml_output.append("<see cref=\"T:double[]\"/>");
  447. } else if (tag == "PackedStringArray") {
  448. xml_output.append("<see cref=\"T:string[]\"/>");
  449. } else if (tag == "PackedVector2Array") {
  450. xml_output.append("<see cref=\"T:" BINDINGS_NAMESPACE ".Vector2[]\"/>");
  451. } else if (tag == "PackedVector3Array") {
  452. xml_output.append("<see cref=\"T:" BINDINGS_NAMESPACE ".Vector3[]\"/>");
  453. } else if (tag == "PackedColorArray") {
  454. xml_output.append("<see cref=\"T:" BINDINGS_NAMESPACE ".Color[]\"/>");
  455. } else {
  456. const TypeInterface *target_itype = _get_type_or_null(TypeReference(tag));
  457. if (!target_itype) {
  458. target_itype = _get_type_or_null(TypeReference("_" + tag));
  459. }
  460. if (target_itype) {
  461. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  462. xml_output.append(target_itype->proxy_name);
  463. xml_output.append("\"/>");
  464. } else {
  465. ERR_PRINT("Cannot resolve type reference in documentation: '" + tag + "'.");
  466. xml_output.append("<c>");
  467. xml_output.append(tag);
  468. xml_output.append("</c>");
  469. }
  470. }
  471. pos = brk_end + 1;
  472. } else if (tag == "b") {
  473. // bold is not supported in xml comments
  474. pos = brk_end + 1;
  475. tag_stack.push_front(tag);
  476. } else if (tag == "i") {
  477. // italics is not supported in xml comments
  478. pos = brk_end + 1;
  479. tag_stack.push_front(tag);
  480. } else if (tag == "code") {
  481. xml_output.append("<c>");
  482. code_tag = true;
  483. pos = brk_end + 1;
  484. tag_stack.push_front(tag);
  485. } else if (tag == "codeblock") {
  486. xml_output.append("<code>");
  487. code_tag = true;
  488. pos = brk_end + 1;
  489. tag_stack.push_front(tag);
  490. } else if (tag == "kbd") {
  491. // keyboard combinations are not supported in xml comments
  492. pos = brk_end + 1;
  493. tag_stack.push_front(tag);
  494. } else if (tag == "center") {
  495. // center alignment is not supported in xml comments
  496. pos = brk_end + 1;
  497. tag_stack.push_front(tag);
  498. } else if (tag == "br") {
  499. xml_output.append("\n"); // FIXME: Should use <para> instead. Luckily this tag isn't used for now.
  500. pos = brk_end + 1;
  501. } else if (tag == "u") {
  502. // underline is not supported in xml comments
  503. pos = brk_end + 1;
  504. tag_stack.push_front(tag);
  505. } else if (tag == "s") {
  506. // strikethrough is not supported in xml comments
  507. pos = brk_end + 1;
  508. tag_stack.push_front(tag);
  509. } else if (tag == "url") {
  510. int end = bbcode.find("[", brk_end);
  511. if (end == -1) {
  512. end = bbcode.length();
  513. }
  514. String url = bbcode.substr(brk_end + 1, end - brk_end - 1);
  515. xml_output.append("<a href=\"");
  516. xml_output.append(url);
  517. xml_output.append("\">");
  518. xml_output.append(url);
  519. pos = brk_end + 1;
  520. tag_stack.push_front(tag);
  521. } else if (tag.begins_with("url=")) {
  522. String url = tag.substr(4, tag.length());
  523. xml_output.append("<a href=\"");
  524. xml_output.append(url);
  525. xml_output.append("\">");
  526. pos = brk_end + 1;
  527. tag_stack.push_front("url");
  528. } else if (tag == "img") {
  529. int end = bbcode.find("[", brk_end);
  530. if (end == -1) {
  531. end = bbcode.length();
  532. }
  533. String image = bbcode.substr(brk_end + 1, end - brk_end - 1);
  534. // Not supported. Just append the bbcode.
  535. xml_output.append("[img]");
  536. xml_output.append(image);
  537. xml_output.append("[/img]");
  538. pos = end;
  539. tag_stack.push_front(tag);
  540. } else if (tag.begins_with("color=")) {
  541. // Not supported.
  542. pos = brk_end + 1;
  543. tag_stack.push_front("color");
  544. } else if (tag.begins_with("font=")) {
  545. // Not supported.
  546. pos = brk_end + 1;
  547. tag_stack.push_front("font");
  548. } else {
  549. xml_output.append("["); // ignore
  550. pos = brk_pos + 1;
  551. }
  552. }
  553. xml_output.append("</para>");
  554. return xml_output.as_string();
  555. }
  556. int BindingsGenerator::_determine_enum_prefix(const EnumInterface &p_ienum) {
  557. CRASH_COND(p_ienum.constants.is_empty());
  558. const ConstantInterface &front_iconstant = p_ienum.constants.front()->get();
  559. Vector<String> front_parts = front_iconstant.name.split("_", /* p_allow_empty: */ true);
  560. int candidate_len = front_parts.size() - 1;
  561. if (candidate_len == 0) {
  562. return 0;
  563. }
  564. for (const ConstantInterface &iconstant : p_ienum.constants) {
  565. Vector<String> parts = iconstant.name.split("_", /* p_allow_empty: */ true);
  566. int i;
  567. for (i = 0; i < candidate_len && i < parts.size(); i++) {
  568. if (front_parts[i] != parts[i]) {
  569. // HARDCODED: Some Flag enums have the prefix 'FLAG_' for everything except 'FLAGS_DEFAULT' (same for 'METHOD_FLAG_' and'METHOD_FLAGS_DEFAULT').
  570. bool hardcoded_exc = (i == candidate_len - 1 && ((front_parts[i] == "FLAGS" && parts[i] == "FLAG") || (front_parts[i] == "FLAG" && parts[i] == "FLAGS")));
  571. if (!hardcoded_exc) {
  572. break;
  573. }
  574. }
  575. }
  576. candidate_len = i;
  577. if (candidate_len == 0) {
  578. return 0;
  579. }
  580. }
  581. return candidate_len;
  582. }
  583. void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumInterface &p_ienum, int p_prefix_length) {
  584. if (p_prefix_length > 0) {
  585. for (ConstantInterface &iconstant : p_ienum.constants) {
  586. int curr_prefix_length = p_prefix_length;
  587. String constant_name = iconstant.name;
  588. Vector<String> parts = constant_name.split("_", /* p_allow_empty: */ true);
  589. if (parts.size() <= curr_prefix_length) {
  590. continue;
  591. }
  592. if (parts[curr_prefix_length][0] >= '0' && parts[curr_prefix_length][0] <= '9') {
  593. // The name of enum constants may begin with a numeric digit when strip from the enum prefix,
  594. // so we make the prefix for this constant one word shorter in those cases.
  595. for (curr_prefix_length = curr_prefix_length - 1; curr_prefix_length > 0; curr_prefix_length--) {
  596. if (parts[curr_prefix_length][0] < '0' || parts[curr_prefix_length][0] > '9') {
  597. break;
  598. }
  599. }
  600. }
  601. constant_name = "";
  602. for (int i = curr_prefix_length; i < parts.size(); i++) {
  603. if (i > curr_prefix_length) {
  604. constant_name += "_";
  605. }
  606. constant_name += parts[i];
  607. }
  608. iconstant.proxy_name = snake_to_pascal_case(constant_name, true);
  609. }
  610. }
  611. }
  612. void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) {
  613. for (const MethodInterface &imethod : p_itype.methods) {
  614. if (imethod.is_virtual) {
  615. continue;
  616. }
  617. const TypeInterface *return_type = _get_type_or_placeholder(imethod.return_type);
  618. String im_sig = "IntPtr " CS_PARAM_METHODBIND ", ";
  619. String im_unique_sig = imethod.return_type.cname.operator String() + ",IntPtr,IntPtr";
  620. im_sig += "IntPtr " CS_PARAM_INSTANCE;
  621. // Get arguments information
  622. int i = 0;
  623. for (const ArgumentInterface &iarg : imethod.arguments) {
  624. const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
  625. im_sig += ", ";
  626. im_sig += arg_type->im_type_in;
  627. im_sig += " arg";
  628. im_sig += itos(i + 1);
  629. im_unique_sig += ",";
  630. im_unique_sig += get_unique_sig(*arg_type);
  631. i++;
  632. }
  633. String im_type_out = return_type->im_type_out;
  634. if (return_type->ret_as_byref_arg) {
  635. // Doesn't affect the unique signature
  636. im_type_out = "void";
  637. im_sig += ", ";
  638. im_sig += return_type->im_type_out;
  639. im_sig += " argRet";
  640. i++;
  641. }
  642. // godot_icall_{argc}_{icallcount}
  643. String icall_method = ICALL_PREFIX;
  644. icall_method += itos(imethod.arguments.size());
  645. icall_method += "_";
  646. icall_method += itos(method_icalls.size());
  647. InternalCall im_icall = InternalCall(p_itype.api_type, icall_method, im_type_out, im_sig, im_unique_sig);
  648. List<InternalCall>::Element *match = method_icalls.find(im_icall);
  649. if (match) {
  650. if (p_itype.api_type != ClassDB::API_EDITOR) {
  651. match->get().editor_only = false;
  652. }
  653. method_icalls_map.insert(&imethod, &match->get());
  654. } else {
  655. List<InternalCall>::Element *added = method_icalls.push_back(im_icall);
  656. method_icalls_map.insert(&imethod, &added->get());
  657. }
  658. }
  659. }
  660. void BindingsGenerator::_generate_array_extensions(StringBuilder &p_output) {
  661. p_output.append("using System;\n\n");
  662. p_output.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  663. // The class where we put the extensions doesn't matter, so just use "GD".
  664. p_output.append(INDENT1 "public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n" INDENT1 "{");
  665. #define ARRAY_IS_EMPTY(m_type) \
  666. p_output.append("\n" INDENT2 "/// <summary>\n"); \
  667. p_output.append(INDENT2 "/// Returns true if this " #m_type " array is empty or doesn't exist.\n"); \
  668. p_output.append(INDENT2 "/// </summary>\n"); \
  669. p_output.append(INDENT2 "/// <param name=\"instance\">The " #m_type " array check.</param>\n"); \
  670. p_output.append(INDENT2 "/// <returns>Whether or not the array is empty.</returns>\n"); \
  671. p_output.append(INDENT2 "public static bool IsEmpty(this " #m_type "[] instance)\n"); \
  672. p_output.append(INDENT2 OPEN_BLOCK); \
  673. p_output.append(INDENT3 "return instance == null || instance.Length == 0;\n"); \
  674. p_output.append(INDENT2 CLOSE_BLOCK);
  675. #define ARRAY_JOIN(m_type) \
  676. p_output.append("\n" INDENT2 "/// <summary>\n"); \
  677. p_output.append(INDENT2 "/// Converts this " #m_type " array to a string delimited by the given string.\n"); \
  678. p_output.append(INDENT2 "/// </summary>\n"); \
  679. p_output.append(INDENT2 "/// <param name=\"instance\">The " #m_type " array to convert.</param>\n"); \
  680. p_output.append(INDENT2 "/// <param name=\"delimiter\">The delimiter to use between items.</param>\n"); \
  681. p_output.append(INDENT2 "/// <returns>A single string with all items.</returns>\n"); \
  682. p_output.append(INDENT2 "public static string Join(this " #m_type "[] instance, string delimiter = \", \")\n"); \
  683. p_output.append(INDENT2 OPEN_BLOCK); \
  684. p_output.append(INDENT3 "return String.Join(delimiter, instance);\n"); \
  685. p_output.append(INDENT2 CLOSE_BLOCK);
  686. #define ARRAY_STRINGIFY(m_type) \
  687. p_output.append("\n" INDENT2 "/// <summary>\n"); \
  688. p_output.append(INDENT2 "/// Converts this " #m_type " array to a string with brackets.\n"); \
  689. p_output.append(INDENT2 "/// </summary>\n"); \
  690. p_output.append(INDENT2 "/// <param name=\"instance\">The " #m_type " array to convert.</param>\n"); \
  691. p_output.append(INDENT2 "/// <returns>A single string with all items.</returns>\n"); \
  692. p_output.append(INDENT2 "public static string Stringify(this " #m_type "[] instance)\n"); \
  693. p_output.append(INDENT2 OPEN_BLOCK); \
  694. p_output.append(INDENT3 "return \"[\" + instance.Join() + \"]\";\n"); \
  695. p_output.append(INDENT2 CLOSE_BLOCK);
  696. #define ARRAY_ALL(m_type) \
  697. ARRAY_IS_EMPTY(m_type) \
  698. ARRAY_JOIN(m_type) \
  699. ARRAY_STRINGIFY(m_type)
  700. ARRAY_ALL(byte);
  701. ARRAY_ALL(int);
  702. ARRAY_ALL(long);
  703. ARRAY_ALL(float);
  704. ARRAY_ALL(double);
  705. ARRAY_ALL(string);
  706. ARRAY_ALL(Color);
  707. ARRAY_ALL(Vector2);
  708. ARRAY_ALL(Vector2i);
  709. ARRAY_ALL(Vector3);
  710. ARRAY_ALL(Vector3i);
  711. #undef ARRAY_ALL
  712. #undef ARRAY_IS_EMPTY
  713. #undef ARRAY_JOIN
  714. #undef ARRAY_STRINGIFY
  715. p_output.append(INDENT1 CLOSE_BLOCK); // End of GD class.
  716. p_output.append(CLOSE_BLOCK); // End of namespace.
  717. }
  718. void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
  719. // Constants (in partial GD class)
  720. p_output.append("\n#pragma warning disable CS1591 // Disable warning: "
  721. "'Missing XML comment for publicly visible type or member'\n");
  722. p_output.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  723. p_output.append(INDENT1 "public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n" INDENT1 "{");
  724. for (const ConstantInterface &iconstant : global_constants) {
  725. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  726. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), nullptr);
  727. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  728. if (summary_lines.size()) {
  729. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  730. for (int i = 0; i < summary_lines.size(); i++) {
  731. p_output.append(INDENT2 "/// ");
  732. p_output.append(summary_lines[i]);
  733. p_output.append("\n");
  734. }
  735. p_output.append(INDENT2 "/// </summary>");
  736. }
  737. }
  738. p_output.append(MEMBER_BEGIN "public const int ");
  739. p_output.append(iconstant.proxy_name);
  740. p_output.append(" = ");
  741. p_output.append(itos(iconstant.value));
  742. p_output.append(";");
  743. }
  744. if (!global_constants.is_empty()) {
  745. p_output.append("\n");
  746. }
  747. p_output.append(INDENT1 CLOSE_BLOCK); // end of GD class
  748. // Enums
  749. for (const EnumInterface &ienum : global_enums) {
  750. CRASH_COND(ienum.constants.is_empty());
  751. String enum_proxy_name = ienum.cname.operator String();
  752. bool enum_in_static_class = false;
  753. if (enum_proxy_name.find(".") > 0) {
  754. enum_in_static_class = true;
  755. String enum_class_name = enum_proxy_name.get_slicec('.', 0);
  756. enum_proxy_name = enum_proxy_name.get_slicec('.', 1);
  757. CRASH_COND(enum_class_name != "Variant"); // Hard-coded...
  758. _log("Declaring global enum '%s' inside static class '%s'\n", enum_proxy_name.utf8().get_data(), enum_class_name.utf8().get_data());
  759. p_output.append("\n" INDENT1 "public static partial class ");
  760. p_output.append(enum_class_name);
  761. p_output.append("\n" INDENT1 OPEN_BLOCK);
  762. }
  763. p_output.append("\n" INDENT1 "public enum ");
  764. p_output.append(enum_proxy_name);
  765. p_output.append("\n" INDENT1 OPEN_BLOCK);
  766. const ConstantInterface &last = ienum.constants.back()->get();
  767. for (const ConstantInterface &iconstant : ienum.constants) {
  768. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  769. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), nullptr);
  770. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  771. if (summary_lines.size()) {
  772. p_output.append(INDENT2 "/// <summary>\n");
  773. for (int i = 0; i < summary_lines.size(); i++) {
  774. p_output.append(INDENT2 "/// ");
  775. p_output.append(summary_lines[i]);
  776. p_output.append("\n");
  777. }
  778. p_output.append(INDENT2 "/// </summary>\n");
  779. }
  780. }
  781. p_output.append(INDENT2);
  782. p_output.append(iconstant.proxy_name);
  783. p_output.append(" = ");
  784. p_output.append(itos(iconstant.value));
  785. p_output.append(&iconstant != &last ? ",\n" : "\n");
  786. }
  787. p_output.append(INDENT1 CLOSE_BLOCK);
  788. if (enum_in_static_class) {
  789. p_output.append(INDENT1 CLOSE_BLOCK);
  790. }
  791. }
  792. p_output.append(CLOSE_BLOCK); // end of namespace
  793. p_output.append("\n#pragma warning restore CS1591\n");
  794. }
  795. Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
  796. ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
  797. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  798. ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
  799. if (!DirAccess::exists(p_proj_dir)) {
  800. Error err = da->make_dir_recursive(p_proj_dir);
  801. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Cannot create directory '" + p_proj_dir + "'.");
  802. }
  803. da->change_dir(p_proj_dir);
  804. da->make_dir("Generated");
  805. da->make_dir("Generated/GodotObjects");
  806. String base_gen_dir = path::join(p_proj_dir, "Generated");
  807. String godot_objects_gen_dir = path::join(base_gen_dir, "GodotObjects");
  808. Vector<String> compile_items;
  809. // Generate source file for global scope constants and enums
  810. {
  811. StringBuilder constants_source;
  812. _generate_global_constants(constants_source);
  813. String output_file = path::join(base_gen_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_constants.cs");
  814. Error save_err = _save_file(output_file, constants_source);
  815. if (save_err != OK) {
  816. return save_err;
  817. }
  818. compile_items.push_back(output_file);
  819. }
  820. // Generate source file for array extensions
  821. {
  822. StringBuilder extensions_source;
  823. _generate_array_extensions(extensions_source);
  824. String output_file = path::join(base_gen_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_extensions.cs");
  825. Error save_err = _save_file(output_file, extensions_source);
  826. if (save_err != OK) {
  827. return save_err;
  828. }
  829. compile_items.push_back(output_file);
  830. }
  831. for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
  832. const TypeInterface &itype = E.get();
  833. if (itype.api_type == ClassDB::API_EDITOR) {
  834. continue;
  835. }
  836. String output_file = path::join(godot_objects_gen_dir, itype.proxy_name + ".cs");
  837. Error err = _generate_cs_type(itype, output_file);
  838. if (err == ERR_SKIP) {
  839. continue;
  840. }
  841. if (err != OK) {
  842. return err;
  843. }
  844. compile_items.push_back(output_file);
  845. }
  846. // Generate sources from compressed files
  847. StringBuilder cs_icalls_content;
  848. cs_icalls_content.append("using System;\n"
  849. "using System.Runtime.CompilerServices;\n"
  850. "\n");
  851. cs_icalls_content.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  852. cs_icalls_content.append(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS "\n" INDENT1 "{");
  853. cs_icalls_content.append(MEMBER_BEGIN "internal static ulong godot_api_hash = ");
  854. cs_icalls_content.append(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + ";\n");
  855. cs_icalls_content.append(MEMBER_BEGIN "internal static uint bindings_version = ");
  856. cs_icalls_content.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n");
  857. cs_icalls_content.append(MEMBER_BEGIN "internal static uint cs_glue_version = ");
  858. cs_icalls_content.append(String::num_uint64(CS_GLUE_VERSION) + ";\n");
  859. #define ADD_INTERNAL_CALL(m_icall) \
  860. if (!m_icall.editor_only) { \
  861. cs_icalls_content.append(MEMBER_BEGIN "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \
  862. cs_icalls_content.append(INDENT2 "internal static extern "); \
  863. cs_icalls_content.append(m_icall.im_type_out + " "); \
  864. cs_icalls_content.append(m_icall.name + "("); \
  865. cs_icalls_content.append(m_icall.im_sig + ");\n"); \
  866. }
  867. for (const InternalCall &internal_call : core_custom_icalls) {
  868. ADD_INTERNAL_CALL(internal_call);
  869. }
  870. for (const InternalCall &internal_call : method_icalls) {
  871. ADD_INTERNAL_CALL(internal_call);
  872. }
  873. #undef ADD_INTERNAL_CALL
  874. cs_icalls_content.append(INDENT1 CLOSE_BLOCK CLOSE_BLOCK);
  875. String internal_methods_file = path::join(base_gen_dir, BINDINGS_CLASS_NATIVECALLS ".cs");
  876. Error err = _save_file(internal_methods_file, cs_icalls_content);
  877. if (err != OK) {
  878. return err;
  879. }
  880. compile_items.push_back(internal_methods_file);
  881. StringBuilder includes_props_content;
  882. includes_props_content.append("<Project>\n"
  883. " <ItemGroup>\n");
  884. for (int i = 0; i < compile_items.size(); i++) {
  885. String include = path::relative_to(compile_items[i], p_proj_dir).replace("/", "\\");
  886. includes_props_content.append(" <Compile Include=\"" + include + "\" />\n");
  887. }
  888. includes_props_content.append(" </ItemGroup>\n"
  889. "</Project>\n");
  890. String includes_props_file = path::join(base_gen_dir, "GeneratedIncludes.props");
  891. err = _save_file(includes_props_file, includes_props_content);
  892. if (err != OK) {
  893. return err;
  894. }
  895. return OK;
  896. }
  897. Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) {
  898. ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
  899. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  900. ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
  901. if (!DirAccess::exists(p_proj_dir)) {
  902. Error err = da->make_dir_recursive(p_proj_dir);
  903. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  904. }
  905. da->change_dir(p_proj_dir);
  906. da->make_dir("Generated");
  907. da->make_dir("Generated/GodotObjects");
  908. String base_gen_dir = path::join(p_proj_dir, "Generated");
  909. String godot_objects_gen_dir = path::join(base_gen_dir, "GodotObjects");
  910. Vector<String> compile_items;
  911. for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
  912. const TypeInterface &itype = E.get();
  913. if (itype.api_type != ClassDB::API_EDITOR) {
  914. continue;
  915. }
  916. String output_file = path::join(godot_objects_gen_dir, itype.proxy_name + ".cs");
  917. Error err = _generate_cs_type(itype, output_file);
  918. if (err == ERR_SKIP) {
  919. continue;
  920. }
  921. if (err != OK) {
  922. return err;
  923. }
  924. compile_items.push_back(output_file);
  925. }
  926. StringBuilder cs_icalls_content;
  927. cs_icalls_content.append("using System;\n"
  928. "using System.Runtime.CompilerServices;\n"
  929. "\n");
  930. cs_icalls_content.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  931. cs_icalls_content.append(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS_EDITOR "\n" INDENT1 OPEN_BLOCK);
  932. cs_icalls_content.append(INDENT2 "internal static ulong godot_api_hash = ");
  933. cs_icalls_content.append(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + ";\n");
  934. cs_icalls_content.append(INDENT2 "internal static uint bindings_version = ");
  935. cs_icalls_content.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n");
  936. cs_icalls_content.append(INDENT2 "internal static uint cs_glue_version = ");
  937. cs_icalls_content.append(String::num_uint64(CS_GLUE_VERSION) + ";\n");
  938. cs_icalls_content.append("\n");
  939. #define ADD_INTERNAL_CALL(m_icall) \
  940. if (m_icall.editor_only) { \
  941. cs_icalls_content.append(INDENT2 "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \
  942. cs_icalls_content.append(INDENT2 "internal static extern "); \
  943. cs_icalls_content.append(m_icall.im_type_out + " "); \
  944. cs_icalls_content.append(m_icall.name + "("); \
  945. cs_icalls_content.append(m_icall.im_sig + ");\n"); \
  946. }
  947. for (const InternalCall &internal_call : editor_custom_icalls) {
  948. ADD_INTERNAL_CALL(internal_call);
  949. }
  950. for (const InternalCall &internal_call : method_icalls) {
  951. ADD_INTERNAL_CALL(internal_call);
  952. }
  953. #undef ADD_INTERNAL_CALL
  954. cs_icalls_content.append(INDENT1 CLOSE_BLOCK CLOSE_BLOCK);
  955. String internal_methods_file = path::join(base_gen_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs");
  956. Error err = _save_file(internal_methods_file, cs_icalls_content);
  957. if (err != OK) {
  958. return err;
  959. }
  960. compile_items.push_back(internal_methods_file);
  961. StringBuilder includes_props_content;
  962. includes_props_content.append("<Project>\n"
  963. " <ItemGroup>\n");
  964. for (int i = 0; i < compile_items.size(); i++) {
  965. String include = path::relative_to(compile_items[i], p_proj_dir).replace("/", "\\");
  966. includes_props_content.append(" <Compile Include=\"" + include + "\" />\n");
  967. }
  968. includes_props_content.append(" </ItemGroup>\n"
  969. "</Project>\n");
  970. String includes_props_file = path::join(base_gen_dir, "GeneratedIncludes.props");
  971. err = _save_file(includes_props_file, includes_props_content);
  972. if (err != OK) {
  973. return err;
  974. }
  975. return OK;
  976. }
  977. Error BindingsGenerator::generate_cs_api(const String &p_output_dir) {
  978. ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
  979. String output_dir = path::abspath(path::realpath(p_output_dir));
  980. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  981. ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
  982. if (!DirAccess::exists(output_dir)) {
  983. Error err = da->make_dir_recursive(output_dir);
  984. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  985. }
  986. Error proj_err;
  987. // Generate GodotSharp source files
  988. String core_proj_dir = output_dir.plus_file(CORE_API_ASSEMBLY_NAME);
  989. proj_err = generate_cs_core_project(core_proj_dir);
  990. if (proj_err != OK) {
  991. ERR_PRINT("Generation of the Core API C# project failed.");
  992. return proj_err;
  993. }
  994. // Generate GodotSharpEditor source files
  995. String editor_proj_dir = output_dir.plus_file(EDITOR_API_ASSEMBLY_NAME);
  996. proj_err = generate_cs_editor_project(editor_proj_dir);
  997. if (proj_err != OK) {
  998. ERR_PRINT("Generation of the Editor API C# project failed.");
  999. return proj_err;
  1000. }
  1001. _log("The Godot API sources were successfully generated\n");
  1002. return OK;
  1003. }
  1004. // FIXME: There are some members that hide other inherited members.
  1005. // - In the case of both members being the same kind, the new one must be declared
  1006. // explicitly as 'new' to avoid the warning (and we must print a message about it).
  1007. // - In the case of both members being of a different kind, then the new one must
  1008. // be renamed to avoid the name collision (and we must print a warning about it).
  1009. // - Csc warning e.g.:
  1010. // ObjectType/LineEdit.cs(140,38): warning CS0108: 'LineEdit.FocusMode' hides inherited member 'Control.FocusMode'. Use the new keyword if hiding was intended.
  1011. Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const String &p_output_file) {
  1012. CRASH_COND(!itype.is_object_type);
  1013. bool is_derived_type = itype.base_name != StringName();
  1014. if (!is_derived_type) {
  1015. // Some Godot.Object assertions
  1016. CRASH_COND(itype.cname != name_cache.type_Object);
  1017. CRASH_COND(!itype.is_instantiable);
  1018. CRASH_COND(itype.api_type != ClassDB::API_CORE);
  1019. CRASH_COND(itype.is_ref_counted);
  1020. CRASH_COND(itype.is_singleton);
  1021. }
  1022. List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls;
  1023. _log("Generating %s.cs...\n", itype.proxy_name.utf8().get_data());
  1024. String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); // Used only for derived types
  1025. StringBuilder output;
  1026. output.append("using System;\n"); // IntPtr
  1027. output.append("using System.Diagnostics;\n"); // DebuggerBrowsable
  1028. output.append("\n"
  1029. "#pragma warning disable CS1591 // Disable warning: "
  1030. "'Missing XML comment for publicly visible type or member'\n"
  1031. "#pragma warning disable CS1573 // Disable warning: "
  1032. "'Parameter has no matching param tag in the XML comment'\n");
  1033. output.append("\nnamespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK);
  1034. const DocData::ClassDoc *class_doc = itype.class_doc;
  1035. if (class_doc && class_doc->description.size()) {
  1036. String xml_summary = bbcode_to_xml(fix_doc_description(class_doc->description), &itype);
  1037. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1038. if (summary_lines.size()) {
  1039. output.append(INDENT1 "/// <summary>\n");
  1040. for (int i = 0; i < summary_lines.size(); i++) {
  1041. output.append(INDENT1 "/// ");
  1042. output.append(summary_lines[i]);
  1043. output.append("\n");
  1044. }
  1045. output.append(INDENT1 "/// </summary>\n");
  1046. }
  1047. }
  1048. output.append(INDENT1 "public ");
  1049. if (itype.is_singleton) {
  1050. output.append("static partial class ");
  1051. } else {
  1052. output.append(itype.is_instantiable ? "partial class " : "abstract partial class ");
  1053. }
  1054. output.append(itype.proxy_name);
  1055. if (itype.is_singleton) {
  1056. output.append("\n");
  1057. } else if (is_derived_type) {
  1058. if (obj_types.has(itype.base_name)) {
  1059. output.append(" : ");
  1060. output.append(obj_types[itype.base_name].proxy_name);
  1061. output.append("\n");
  1062. } else {
  1063. ERR_PRINT("Base type '" + itype.base_name.operator String() + "' does not exist, for class '" + itype.name + "'.");
  1064. return ERR_INVALID_DATA;
  1065. }
  1066. }
  1067. output.append(INDENT1 "{");
  1068. // Add constants
  1069. for (const ConstantInterface &iconstant : itype.constants) {
  1070. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  1071. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
  1072. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1073. if (summary_lines.size()) {
  1074. output.append(MEMBER_BEGIN "/// <summary>\n");
  1075. for (int i = 0; i < summary_lines.size(); i++) {
  1076. output.append(INDENT2 "/// ");
  1077. output.append(summary_lines[i]);
  1078. output.append("\n");
  1079. }
  1080. output.append(INDENT2 "/// </summary>");
  1081. }
  1082. }
  1083. output.append(MEMBER_BEGIN "public const int ");
  1084. output.append(iconstant.proxy_name);
  1085. output.append(" = ");
  1086. output.append(itos(iconstant.value));
  1087. output.append(";");
  1088. }
  1089. if (itype.constants.size()) {
  1090. output.append("\n");
  1091. }
  1092. // Add enums
  1093. for (const EnumInterface &ienum : itype.enums) {
  1094. ERR_FAIL_COND_V(ienum.constants.is_empty(), ERR_BUG);
  1095. output.append(MEMBER_BEGIN "public enum ");
  1096. output.append(ienum.cname.operator String());
  1097. output.append(MEMBER_BEGIN OPEN_BLOCK);
  1098. const ConstantInterface &last = ienum.constants.back()->get();
  1099. for (const ConstantInterface &iconstant : ienum.constants) {
  1100. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  1101. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
  1102. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1103. if (summary_lines.size()) {
  1104. output.append(INDENT3 "/// <summary>\n");
  1105. for (int i = 0; i < summary_lines.size(); i++) {
  1106. output.append(INDENT3 "/// ");
  1107. output.append(summary_lines[i]);
  1108. output.append("\n");
  1109. }
  1110. output.append(INDENT3 "/// </summary>\n");
  1111. }
  1112. }
  1113. output.append(INDENT3);
  1114. output.append(iconstant.proxy_name);
  1115. output.append(" = ");
  1116. output.append(itos(iconstant.value));
  1117. output.append(&iconstant != &last ? ",\n" : "\n");
  1118. }
  1119. output.append(INDENT2 CLOSE_BLOCK);
  1120. }
  1121. // Add properties
  1122. for (const PropertyInterface &iprop : itype.properties) {
  1123. Error prop_err = _generate_cs_property(itype, iprop, output);
  1124. ERR_FAIL_COND_V_MSG(prop_err != OK, prop_err,
  1125. "Failed to generate property '" + iprop.cname.operator String() +
  1126. "' for class '" + itype.name + "'.");
  1127. }
  1128. if (itype.is_singleton) {
  1129. // Add the type name and the singleton pointer as static fields
  1130. output.append(MEMBER_BEGIN "private static Godot.Object singleton;\n");
  1131. output.append(MEMBER_BEGIN "public static Godot.Object Singleton\n" INDENT2 "{\n" INDENT3
  1132. "get\n" INDENT3 "{\n" INDENT4 "if (singleton == null)\n" INDENT5
  1133. "singleton = Engine.GetSingleton(typeof(");
  1134. output.append(itype.proxy_name);
  1135. output.append(").Name);\n" INDENT4 "return singleton;\n" INDENT3 "}\n" INDENT2 "}\n");
  1136. output.append(MEMBER_BEGIN "private static StringName " BINDINGS_NATIVE_NAME_FIELD " = \"");
  1137. output.append(itype.name);
  1138. output.append("\";\n");
  1139. output.append(INDENT2 "internal static IntPtr " BINDINGS_PTR_FIELD " = ");
  1140. output.append(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS);
  1141. output.append("." ICALL_PREFIX);
  1142. output.append(itype.name);
  1143. output.append(SINGLETON_ICALL_SUFFIX "();\n");
  1144. } else if (is_derived_type) {
  1145. // Add member fields
  1146. output.append(MEMBER_BEGIN "private static StringName " BINDINGS_NATIVE_NAME_FIELD " = \"");
  1147. output.append(itype.name);
  1148. output.append("\";\n");
  1149. // Add default constructor
  1150. if (itype.is_instantiable) {
  1151. output.append(MEMBER_BEGIN "public ");
  1152. output.append(itype.proxy_name);
  1153. output.append("() : this(");
  1154. output.append(itype.memory_own ? "true" : "false");
  1155. // The default constructor may also be called by the engine when instancing existing native objects
  1156. // The engine will initialize the pointer field of the managed side before calling the constructor
  1157. // This is why we only allocate a new native object from the constructor if the pointer field is not set
  1158. output.append(")\n" OPEN_BLOCK_L2 "if (" BINDINGS_PTR_FIELD " == IntPtr.Zero)\n" INDENT4 BINDINGS_PTR_FIELD " = ");
  1159. output.append(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS);
  1160. output.append("." + ctor_method);
  1161. output.append("(this);\n" INDENT3 "_InitializeGodotScriptInstanceInternals();\n" CLOSE_BLOCK_L2);
  1162. } else {
  1163. // Hide the constructor
  1164. output.append(MEMBER_BEGIN "internal ");
  1165. output.append(itype.proxy_name);
  1166. output.append("() {}\n");
  1167. }
  1168. // Add.. em.. trick constructor. Sort of.
  1169. output.append(MEMBER_BEGIN "internal ");
  1170. output.append(itype.proxy_name);
  1171. output.append("(bool " CS_FIELD_MEMORYOWN ") : base(" CS_FIELD_MEMORYOWN ") {}\n");
  1172. }
  1173. int method_bind_count = 0;
  1174. for (const MethodInterface &imethod : itype.methods) {
  1175. Error method_err = _generate_cs_method(itype, imethod, method_bind_count, output);
  1176. ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
  1177. "Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'.");
  1178. }
  1179. for (const SignalInterface &isignal : itype.signals_) {
  1180. Error method_err = _generate_cs_signal(itype, isignal, output);
  1181. ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
  1182. "Failed to generate signal '" + isignal.name + "' for class '" + itype.name + "'.");
  1183. }
  1184. if (itype.is_singleton) {
  1185. InternalCall singleton_icall = InternalCall(itype.api_type, ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX, "IntPtr");
  1186. if (!find_icall_by_name(singleton_icall.name, custom_icalls)) {
  1187. custom_icalls.push_back(singleton_icall);
  1188. }
  1189. }
  1190. if (is_derived_type && itype.is_instantiable) {
  1191. InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj");
  1192. if (!find_icall_by_name(ctor_icall.name, custom_icalls)) {
  1193. custom_icalls.push_back(ctor_icall);
  1194. }
  1195. }
  1196. output.append(INDENT1 CLOSE_BLOCK /* class */
  1197. CLOSE_BLOCK /* namespace */);
  1198. output.append("\n"
  1199. "#pragma warning restore CS1591\n"
  1200. "#pragma warning restore CS1573\n");
  1201. return _save_file(p_output_file, output);
  1202. }
  1203. Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInterface &p_itype, const PropertyInterface &p_iprop, StringBuilder &p_output) {
  1204. const MethodInterface *setter = p_itype.find_method_by_name(p_iprop.setter);
  1205. // Search it in base types too
  1206. const TypeInterface *current_type = &p_itype;
  1207. while (!setter && current_type->base_name != StringName()) {
  1208. OrderedHashMap<StringName, TypeInterface>::Element base_match = obj_types.find(current_type->base_name);
  1209. ERR_FAIL_COND_V_MSG(!base_match, ERR_BUG, "Type not found '" + current_type->base_name + "'. Inherited by '" + current_type->name + "'.");
  1210. current_type = &base_match.get();
  1211. setter = current_type->find_method_by_name(p_iprop.setter);
  1212. }
  1213. const MethodInterface *getter = p_itype.find_method_by_name(p_iprop.getter);
  1214. // Search it in base types too
  1215. current_type = &p_itype;
  1216. while (!getter && current_type->base_name != StringName()) {
  1217. OrderedHashMap<StringName, TypeInterface>::Element base_match = obj_types.find(current_type->base_name);
  1218. ERR_FAIL_COND_V_MSG(!base_match, ERR_BUG, "Type not found '" + current_type->base_name + "'. Inherited by '" + current_type->name + "'.");
  1219. current_type = &base_match.get();
  1220. getter = current_type->find_method_by_name(p_iprop.getter);
  1221. }
  1222. ERR_FAIL_COND_V(!setter && !getter, ERR_BUG);
  1223. if (setter) {
  1224. int setter_argc = p_iprop.index != -1 ? 2 : 1;
  1225. ERR_FAIL_COND_V(setter->arguments.size() != setter_argc, ERR_BUG);
  1226. }
  1227. if (getter) {
  1228. int getter_argc = p_iprop.index != -1 ? 1 : 0;
  1229. ERR_FAIL_COND_V(getter->arguments.size() != getter_argc, ERR_BUG);
  1230. }
  1231. if (getter && setter) {
  1232. const ArgumentInterface &setter_first_arg = setter->arguments.back()->get();
  1233. if (getter->return_type.cname != setter_first_arg.type.cname) {
  1234. // Special case for Node::set_name
  1235. bool whitelisted = getter->return_type.cname == name_cache.type_StringName &&
  1236. setter_first_arg.type.cname == name_cache.type_String;
  1237. ERR_FAIL_COND_V_MSG(!whitelisted, ERR_BUG,
  1238. "Return type from getter doesn't match first argument of setter for property: '" +
  1239. p_itype.name + "." + String(p_iprop.cname) + "'.");
  1240. }
  1241. }
  1242. const TypeReference &proptype_name = getter ? getter->return_type : setter->arguments.back()->get().type;
  1243. const TypeInterface *prop_itype = _get_type_or_null(proptype_name);
  1244. ERR_FAIL_NULL_V(prop_itype, ERR_BUG); // Property type not found
  1245. ERR_FAIL_COND_V_MSG(prop_itype->is_singleton, ERR_BUG,
  1246. "Property type is a singleton: '" + p_itype.name + "." + String(p_iprop.cname) + "'.");
  1247. if (p_itype.api_type == ClassDB::API_CORE) {
  1248. ERR_FAIL_COND_V_MSG(prop_itype->api_type == ClassDB::API_EDITOR, ERR_BUG,
  1249. "Property '" + p_itype.name + "." + String(p_iprop.cname) + "' has type '" + prop_itype->name +
  1250. "' from the editor API. Core API cannot have dependencies on the editor API.");
  1251. }
  1252. if (p_iprop.prop_doc && p_iprop.prop_doc->description.size()) {
  1253. String xml_summary = bbcode_to_xml(fix_doc_description(p_iprop.prop_doc->description), &p_itype);
  1254. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1255. if (summary_lines.size()) {
  1256. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  1257. for (int i = 0; i < summary_lines.size(); i++) {
  1258. p_output.append(INDENT2 "/// ");
  1259. p_output.append(summary_lines[i]);
  1260. p_output.append("\n");
  1261. }
  1262. p_output.append(INDENT2 "/// </summary>");
  1263. }
  1264. }
  1265. p_output.append(MEMBER_BEGIN "public ");
  1266. if (p_itype.is_singleton) {
  1267. p_output.append("static ");
  1268. }
  1269. p_output.append(prop_itype->cs_type);
  1270. p_output.append(" ");
  1271. p_output.append(p_iprop.proxy_name);
  1272. p_output.append("\n" INDENT2 OPEN_BLOCK);
  1273. if (getter) {
  1274. p_output.append(INDENT3 "get\n"
  1275. // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
  1276. "#pragma warning disable CS0618 // Disable warning about obsolete method\n"
  1277. OPEN_BLOCK_L3);
  1278. p_output.append("return ");
  1279. p_output.append(getter->proxy_name + "(");
  1280. if (p_iprop.index != -1) {
  1281. const ArgumentInterface &idx_arg = getter->arguments.front()->get();
  1282. if (idx_arg.type.cname != name_cache.type_int) {
  1283. // Assume the index parameter is an enum
  1284. const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type);
  1285. CRASH_COND(idx_arg_type == nullptr);
  1286. p_output.append("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index));
  1287. } else {
  1288. p_output.append(itos(p_iprop.index));
  1289. }
  1290. }
  1291. p_output.append(");\n"
  1292. CLOSE_BLOCK_L3
  1293. // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
  1294. "#pragma warning restore CS0618\n");
  1295. }
  1296. if (setter) {
  1297. p_output.append(INDENT3 "set\n"
  1298. // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
  1299. "#pragma warning disable CS0618 // Disable warning about obsolete method\n"
  1300. OPEN_BLOCK_L3);
  1301. p_output.append(setter->proxy_name + "(");
  1302. if (p_iprop.index != -1) {
  1303. const ArgumentInterface &idx_arg = setter->arguments.front()->get();
  1304. if (idx_arg.type.cname != name_cache.type_int) {
  1305. // Assume the index parameter is an enum
  1306. const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type);
  1307. CRASH_COND(idx_arg_type == nullptr);
  1308. p_output.append("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index) + ", ");
  1309. } else {
  1310. p_output.append(itos(p_iprop.index) + ", ");
  1311. }
  1312. }
  1313. p_output.append("value);\n"
  1314. CLOSE_BLOCK_L3
  1315. // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
  1316. "#pragma warning restore CS0618\n");
  1317. }
  1318. p_output.append(CLOSE_BLOCK_L2);
  1319. return OK;
  1320. }
  1321. Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, int &p_method_bind_count, StringBuilder &p_output) {
  1322. const TypeInterface *return_type = _get_type_or_placeholder(p_imethod.return_type);
  1323. ERR_FAIL_COND_V_MSG(return_type->is_singleton, ERR_BUG,
  1324. "Method return type is a singleton: '" + p_itype.name + "." + p_imethod.name + "'.");
  1325. if (p_itype.api_type == ClassDB::API_CORE) {
  1326. ERR_FAIL_COND_V_MSG(return_type->api_type == ClassDB::API_EDITOR, ERR_BUG,
  1327. "Method '" + p_itype.name + "." + p_imethod.name + "' has return type '" + return_type->name +
  1328. "' from the editor API. Core API cannot have dependencies on the editor API.");
  1329. }
  1330. String method_bind_field = "__method_bind_" + itos(p_method_bind_count);
  1331. String arguments_sig;
  1332. String cs_in_statements;
  1333. String icall_params = method_bind_field + ", ";
  1334. icall_params += sformat(p_itype.cs_in, "this");
  1335. StringBuilder default_args_doc;
  1336. // Retrieve information from the arguments
  1337. const ArgumentInterface &first = p_imethod.arguments.front()->get();
  1338. for (const ArgumentInterface &iarg : p_imethod.arguments) {
  1339. const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
  1340. ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG,
  1341. "Argument type is a singleton: '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "'.");
  1342. if (p_itype.api_type == ClassDB::API_CORE) {
  1343. ERR_FAIL_COND_V_MSG(arg_type->api_type == ClassDB::API_EDITOR, ERR_BUG,
  1344. "Argument '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "' has type '" +
  1345. arg_type->name + "' from the editor API. Core API cannot have dependencies on the editor API.");
  1346. }
  1347. if (iarg.default_argument.size()) {
  1348. CRASH_COND_MSG(!_arg_default_value_is_assignable_to_type(iarg.def_param_value, *arg_type),
  1349. "Invalid default value for parameter '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "'.");
  1350. }
  1351. // Add the current arguments to the signature
  1352. // If the argument has a default value which is not a constant, we will make it Nullable
  1353. {
  1354. if (&iarg != &first) {
  1355. arguments_sig += ", ";
  1356. }
  1357. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  1358. arguments_sig += "Nullable<";
  1359. }
  1360. arguments_sig += arg_type->cs_type;
  1361. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  1362. arguments_sig += "> ";
  1363. } else {
  1364. arguments_sig += " ";
  1365. }
  1366. arguments_sig += iarg.name;
  1367. if (iarg.default_argument.size()) {
  1368. if (iarg.def_param_mode != ArgumentInterface::CONSTANT) {
  1369. arguments_sig += " = null";
  1370. } else {
  1371. arguments_sig += " = " + sformat(iarg.default_argument, arg_type->cs_type);
  1372. }
  1373. }
  1374. }
  1375. icall_params += ", ";
  1376. if (iarg.default_argument.size() && iarg.def_param_mode != ArgumentInterface::CONSTANT) {
  1377. // The default value of an argument must be constant. Otherwise we make it Nullable and do the following:
  1378. // Type arg_in = arg.HasValue ? arg.Value : <non-const default value>;
  1379. String arg_in = iarg.name;
  1380. arg_in += "_in";
  1381. cs_in_statements += arg_type->cs_type;
  1382. cs_in_statements += " ";
  1383. cs_in_statements += arg_in;
  1384. cs_in_statements += " = ";
  1385. cs_in_statements += iarg.name;
  1386. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  1387. cs_in_statements += ".HasValue ? ";
  1388. } else {
  1389. cs_in_statements += " != null ? ";
  1390. }
  1391. cs_in_statements += iarg.name;
  1392. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  1393. cs_in_statements += ".Value : ";
  1394. } else {
  1395. cs_in_statements += " : ";
  1396. }
  1397. String cs_type = arg_type->cs_type;
  1398. if (cs_type.ends_with("[]")) {
  1399. cs_type = cs_type.substr(0, cs_type.length() - 2);
  1400. }
  1401. String def_arg = sformat(iarg.default_argument, cs_type);
  1402. cs_in_statements += def_arg;
  1403. cs_in_statements += ";\n" INDENT3;
  1404. icall_params += arg_type->cs_in.is_empty() ? arg_in : sformat(arg_type->cs_in, arg_in);
  1405. // Apparently the name attribute must not include the @
  1406. String param_tag_name = iarg.name.begins_with("@") ? iarg.name.substr(1, iarg.name.length()) : iarg.name;
  1407. // Escape < and > in the attribute default value
  1408. String param_def_arg = def_arg.replacen("<", "&lt;").replacen(">", "&gt;");
  1409. default_args_doc.append(MEMBER_BEGIN "/// <param name=\"" + param_tag_name + "\">If the parameter is null, then the default value is " + param_def_arg + "</param>");
  1410. } else {
  1411. icall_params += arg_type->cs_in.is_empty() ? iarg.name : sformat(arg_type->cs_in, iarg.name);
  1412. }
  1413. }
  1414. // Generate method
  1415. {
  1416. if (!p_imethod.is_virtual && !p_imethod.requires_object_call) {
  1417. p_output.append(MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]" MEMBER_BEGIN "private static readonly IntPtr ");
  1418. p_output.append(method_bind_field);
  1419. p_output.append(" = Object." ICALL_GET_METHODBIND "(" BINDINGS_NATIVE_NAME_FIELD ", \"");
  1420. p_output.append(p_imethod.name);
  1421. p_output.append("\");\n");
  1422. }
  1423. if (p_imethod.method_doc && p_imethod.method_doc->description.size()) {
  1424. String xml_summary = bbcode_to_xml(fix_doc_description(p_imethod.method_doc->description), &p_itype);
  1425. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1426. if (summary_lines.size()) {
  1427. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  1428. for (int i = 0; i < summary_lines.size(); i++) {
  1429. p_output.append(INDENT2 "/// ");
  1430. p_output.append(summary_lines[i]);
  1431. p_output.append("\n");
  1432. }
  1433. p_output.append(INDENT2 "/// </summary>");
  1434. }
  1435. }
  1436. if (default_args_doc.get_string_length()) {
  1437. p_output.append(default_args_doc.as_string());
  1438. }
  1439. if (!p_imethod.is_internal) {
  1440. // TODO: This alone adds ~0.2 MB of bloat to the core API assembly. It would be
  1441. // better to generate a table in the C++ glue instead. That way the strings wouldn't
  1442. // add that much extra bloat as they're already used in engine code. Also, it would
  1443. // probably be much faster than looking up the attributes when fetching methods.
  1444. p_output.append(MEMBER_BEGIN "[GodotMethod(\"");
  1445. p_output.append(p_imethod.name);
  1446. p_output.append("\")]");
  1447. }
  1448. if (p_imethod.is_deprecated) {
  1449. if (p_imethod.deprecation_message.is_empty()) {
  1450. WARN_PRINT("An empty deprecation message is discouraged. Method: '" + p_imethod.proxy_name + "'.");
  1451. }
  1452. p_output.append(MEMBER_BEGIN "[Obsolete(\"");
  1453. p_output.append(p_imethod.deprecation_message);
  1454. p_output.append("\")]");
  1455. }
  1456. p_output.append(MEMBER_BEGIN);
  1457. p_output.append(p_imethod.is_internal ? "internal " : "public ");
  1458. if (p_itype.is_singleton) {
  1459. p_output.append("static ");
  1460. } else if (p_imethod.is_virtual) {
  1461. p_output.append("virtual ");
  1462. }
  1463. p_output.append(return_type->cs_type + " ");
  1464. p_output.append(p_imethod.proxy_name + "(");
  1465. p_output.append(arguments_sig + ")\n" OPEN_BLOCK_L2);
  1466. if (p_imethod.is_virtual) {
  1467. // Godot virtual method must be overridden, therefore we return a default value by default.
  1468. if (return_type->cname == name_cache.type_void) {
  1469. p_output.append("return;\n" CLOSE_BLOCK_L2);
  1470. } else {
  1471. p_output.append("return default(");
  1472. p_output.append(return_type->cs_type);
  1473. p_output.append(");\n" CLOSE_BLOCK_L2);
  1474. }
  1475. return OK; // Won't increment method bind count
  1476. }
  1477. if (p_imethod.requires_object_call) {
  1478. // Fallback to Godot's object.Call(string, params)
  1479. p_output.append(CS_METHOD_CALL "(\"");
  1480. p_output.append(p_imethod.name);
  1481. p_output.append("\"");
  1482. for (const ArgumentInterface &iarg : p_imethod.arguments) {
  1483. p_output.append(", ");
  1484. p_output.append(iarg.name);
  1485. }
  1486. p_output.append(");\n" CLOSE_BLOCK_L2);
  1487. return OK; // Won't increment method bind count
  1488. }
  1489. const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&p_imethod);
  1490. ERR_FAIL_NULL_V(match, ERR_BUG);
  1491. const InternalCall *im_icall = match->value();
  1492. String im_call = im_icall->editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS;
  1493. im_call += ".";
  1494. im_call += im_icall->name;
  1495. if (p_imethod.arguments.size()) {
  1496. p_output.append(cs_in_statements);
  1497. }
  1498. if (return_type->cname == name_cache.type_void) {
  1499. p_output.append(im_call + "(" + icall_params + ");\n");
  1500. } else if (return_type->cs_out.is_empty()) {
  1501. p_output.append("return " + im_call + "(" + icall_params + ");\n");
  1502. } else {
  1503. p_output.append(sformat(return_type->cs_out, im_call, icall_params, return_type->cs_type, return_type->im_type_out));
  1504. p_output.append("\n");
  1505. }
  1506. p_output.append(CLOSE_BLOCK_L2);
  1507. }
  1508. p_method_bind_count++;
  1509. return OK;
  1510. }
  1511. Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::SignalInterface &p_isignal, StringBuilder &p_output) {
  1512. String arguments_sig;
  1513. // Retrieve information from the arguments
  1514. const ArgumentInterface &first = p_isignal.arguments.front()->get();
  1515. for (const ArgumentInterface &iarg : p_isignal.arguments) {
  1516. const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
  1517. ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG,
  1518. "Argument type is a singleton: '" + iarg.name + "' of signal '" + p_itype.name + "." + p_isignal.name + "'.");
  1519. if (p_itype.api_type == ClassDB::API_CORE) {
  1520. ERR_FAIL_COND_V_MSG(arg_type->api_type == ClassDB::API_EDITOR, ERR_BUG,
  1521. "Argument '" + iarg.name + "' of signal '" + p_itype.name + "." + p_isignal.name + "' has type '" +
  1522. arg_type->name + "' from the editor API. Core API cannot have dependencies on the editor API.");
  1523. }
  1524. // Add the current arguments to the signature
  1525. if (&iarg != &first) {
  1526. arguments_sig += ", ";
  1527. }
  1528. arguments_sig += arg_type->cs_type;
  1529. arguments_sig += " ";
  1530. arguments_sig += iarg.name;
  1531. }
  1532. // Generate signal
  1533. {
  1534. if (p_isignal.method_doc && p_isignal.method_doc->description.size()) {
  1535. String xml_summary = bbcode_to_xml(fix_doc_description(p_isignal.method_doc->description), &p_itype);
  1536. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1537. if (summary_lines.size()) {
  1538. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  1539. for (int i = 0; i < summary_lines.size(); i++) {
  1540. p_output.append(INDENT2 "/// ");
  1541. p_output.append(summary_lines[i]);
  1542. p_output.append("\n");
  1543. }
  1544. p_output.append(INDENT2 "/// </summary>");
  1545. }
  1546. }
  1547. if (p_isignal.is_deprecated) {
  1548. if (p_isignal.deprecation_message.is_empty()) {
  1549. WARN_PRINT("An empty deprecation message is discouraged. Signal: '" + p_isignal.proxy_name + "'.");
  1550. }
  1551. p_output.append(MEMBER_BEGIN "[Obsolete(\"");
  1552. p_output.append(p_isignal.deprecation_message);
  1553. p_output.append("\")]");
  1554. }
  1555. String delegate_name = p_isignal.proxy_name;
  1556. delegate_name += "Handler"; // Delegate name is [SignalName]Handler
  1557. // Generate delegate
  1558. p_output.append(MEMBER_BEGIN "public delegate void ");
  1559. p_output.append(delegate_name);
  1560. p_output.append("(");
  1561. p_output.append(arguments_sig);
  1562. p_output.append(");\n");
  1563. // TODO:
  1564. // Could we assume the StringName instance of signal name will never be freed (it's stored in ClassDB) before the managed world is unloaded?
  1565. // If so, we could store the pointer we get from `data_unique_pointer()` instead of allocating StringName here.
  1566. // Cached signal name (StringName)
  1567. p_output.append(MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]" MEMBER_BEGIN "private static StringName __signal_name_");
  1568. p_output.append(p_isignal.name);
  1569. p_output.append(" = \"");
  1570. p_output.append(p_isignal.name);
  1571. p_output.append("\";\n");
  1572. // Generate event
  1573. p_output.append(MEMBER_BEGIN "[Signal]" MEMBER_BEGIN "public ");
  1574. if (p_itype.is_singleton) {
  1575. p_output.append("static ");
  1576. }
  1577. p_output.append("event ");
  1578. p_output.append(delegate_name);
  1579. p_output.append(" ");
  1580. p_output.append(p_isignal.proxy_name);
  1581. p_output.append("\n" OPEN_BLOCK_L2);
  1582. if (p_itype.is_singleton) {
  1583. p_output.append("add => Singleton.Connect(__signal_name_");
  1584. } else {
  1585. p_output.append("add => Connect(__signal_name_");
  1586. }
  1587. p_output.append(p_isignal.name);
  1588. p_output.append(", new Callable(value));\n");
  1589. if (p_itype.is_singleton) {
  1590. p_output.append(INDENT3 "remove => Singleton.Disconnect(__signal_name_");
  1591. } else {
  1592. p_output.append(INDENT3 "remove => Disconnect(__signal_name_");
  1593. }
  1594. p_output.append(p_isignal.name);
  1595. p_output.append(", new Callable(value));\n");
  1596. p_output.append(CLOSE_BLOCK_L2);
  1597. }
  1598. return OK;
  1599. }
  1600. Error BindingsGenerator::generate_glue(const String &p_output_dir) {
  1601. ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
  1602. bool dir_exists = DirAccess::exists(p_output_dir);
  1603. ERR_FAIL_COND_V_MSG(!dir_exists, ERR_FILE_BAD_PATH, "The output directory does not exist.");
  1604. StringBuilder output;
  1605. output.append("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
  1606. output.append("#include \"" GLUE_HEADER_FILE "\"\n");
  1607. output.append("\n#ifdef MONO_GLUE_ENABLED\n");
  1608. generated_icall_funcs.clear();
  1609. for (OrderedHashMap<StringName, TypeInterface>::Element type_elem = obj_types.front(); type_elem; type_elem = type_elem.next()) {
  1610. const TypeInterface &itype = type_elem.get();
  1611. bool is_derived_type = itype.base_name != StringName();
  1612. if (!is_derived_type) {
  1613. // Some Object assertions
  1614. CRASH_COND(itype.cname != name_cache.type_Object);
  1615. CRASH_COND(!itype.is_instantiable);
  1616. CRASH_COND(itype.api_type != ClassDB::API_CORE);
  1617. CRASH_COND(itype.is_singleton);
  1618. }
  1619. List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls;
  1620. OS::get_singleton()->print("Generating %s...\n", itype.name.utf8().get_data());
  1621. String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); // Used only for derived types
  1622. for (const MethodInterface &imethod : itype.methods) {
  1623. Error method_err = _generate_glue_method(itype, imethod, output);
  1624. ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
  1625. "Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'.");
  1626. }
  1627. if (itype.is_singleton) {
  1628. String singleton_icall_name = ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX;
  1629. InternalCall singleton_icall = InternalCall(itype.api_type, singleton_icall_name, "IntPtr");
  1630. if (!find_icall_by_name(singleton_icall.name, custom_icalls)) {
  1631. custom_icalls.push_back(singleton_icall);
  1632. }
  1633. output.append("Object* ");
  1634. output.append(singleton_icall_name);
  1635. output.append("() " OPEN_BLOCK "\treturn Engine::get_singleton()->get_singleton_object(\"");
  1636. output.append(itype.proxy_name);
  1637. output.append("\");\n" CLOSE_BLOCK "\n");
  1638. }
  1639. if (is_derived_type && itype.is_instantiable) {
  1640. InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj");
  1641. if (!find_icall_by_name(ctor_icall.name, custom_icalls)) {
  1642. custom_icalls.push_back(ctor_icall);
  1643. }
  1644. output.append("Object* ");
  1645. output.append(ctor_method);
  1646. output.append("(MonoObject* obj) " OPEN_BLOCK
  1647. "\t" C_MACRO_OBJECT_CONSTRUCT "(instance, \"");
  1648. output.append(itype.name);
  1649. output.append("\");\n"
  1650. "\t" C_METHOD_TIE_MANAGED_TO_UNMANAGED "(obj, instance);\n"
  1651. "\treturn instance;\n" CLOSE_BLOCK "\n");
  1652. }
  1653. }
  1654. output.append("namespace GodotSharpBindings\n" OPEN_BLOCK "\n");
  1655. output.append("uint64_t get_core_api_hash() { return ");
  1656. output.append(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + "U; }\n");
  1657. output.append("#ifdef TOOLS_ENABLED\n"
  1658. "uint64_t get_editor_api_hash() { return ");
  1659. output.append(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + "U; }\n");
  1660. output.append("#endif // TOOLS_ENABLED\n");
  1661. output.append("uint32_t get_bindings_version() { return ");
  1662. output.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + "; }\n");
  1663. output.append("uint32_t get_cs_glue_version() { return ");
  1664. output.append(String::num_uint64(CS_GLUE_VERSION) + "; }\n");
  1665. output.append("\nvoid register_generated_icalls() " OPEN_BLOCK);
  1666. output.append("\tgodot_register_glue_header_icalls();\n");
  1667. #define ADD_INTERNAL_CALL_REGISTRATION(m_icall) \
  1668. { \
  1669. output.append("\tGDMonoUtils::add_internal_call("); \
  1670. output.append("\"" BINDINGS_NAMESPACE "."); \
  1671. output.append(m_icall.editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); \
  1672. output.append("::"); \
  1673. output.append(m_icall.name); \
  1674. output.append("\", "); \
  1675. output.append(m_icall.name); \
  1676. output.append(");\n"); \
  1677. }
  1678. bool tools_sequence = false;
  1679. for (const InternalCall &internal_call : core_custom_icalls) {
  1680. if (tools_sequence) {
  1681. if (!internal_call.editor_only) {
  1682. tools_sequence = false;
  1683. output.append("#endif\n");
  1684. }
  1685. } else {
  1686. if (internal_call.editor_only) {
  1687. output.append("#ifdef TOOLS_ENABLED\n");
  1688. tools_sequence = true;
  1689. }
  1690. }
  1691. ADD_INTERNAL_CALL_REGISTRATION(internal_call);
  1692. }
  1693. if (tools_sequence) {
  1694. tools_sequence = false;
  1695. output.append("#endif\n");
  1696. }
  1697. output.append("#ifdef TOOLS_ENABLED\n");
  1698. for (const InternalCall &internal_call : editor_custom_icalls)
  1699. ADD_INTERNAL_CALL_REGISTRATION(internal_call);
  1700. output.append("#endif // TOOLS_ENABLED\n");
  1701. for (const InternalCall &internal_call : method_icalls) {
  1702. if (tools_sequence) {
  1703. if (!internal_call.editor_only) {
  1704. tools_sequence = false;
  1705. output.append("#endif\n");
  1706. }
  1707. } else {
  1708. if (internal_call.editor_only) {
  1709. output.append("#ifdef TOOLS_ENABLED\n");
  1710. tools_sequence = true;
  1711. }
  1712. }
  1713. ADD_INTERNAL_CALL_REGISTRATION(internal_call);
  1714. }
  1715. if (tools_sequence) {
  1716. tools_sequence = false;
  1717. output.append("#endif\n");
  1718. }
  1719. #undef ADD_INTERNAL_CALL_REGISTRATION
  1720. output.append(CLOSE_BLOCK "\n} // namespace GodotSharpBindings\n");
  1721. output.append("\n#endif // MONO_GLUE_ENABLED\n");
  1722. Error save_err = _save_file(path::join(p_output_dir, "mono_glue.gen.cpp"), output);
  1723. if (save_err != OK) {
  1724. return save_err;
  1725. }
  1726. OS::get_singleton()->print("Mono glue generated successfully\n");
  1727. return OK;
  1728. }
  1729. uint32_t BindingsGenerator::get_version() {
  1730. return BINDINGS_GENERATOR_VERSION;
  1731. }
  1732. Error BindingsGenerator::_save_file(const String &p_path, const StringBuilder &p_content) {
  1733. FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE);
  1734. ERR_FAIL_COND_V_MSG(!file, ERR_FILE_CANT_WRITE, "Cannot open file: '" + p_path + "'.");
  1735. file->store_string(p_content.as_string());
  1736. file->close();
  1737. return OK;
  1738. }
  1739. Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, StringBuilder &p_output) {
  1740. if (p_imethod.is_virtual) {
  1741. return OK; // Ignore
  1742. }
  1743. bool ret_void = p_imethod.return_type.cname == name_cache.type_void;
  1744. const TypeInterface *return_type = _get_type_or_placeholder(p_imethod.return_type);
  1745. String argc_str = itos(p_imethod.arguments.size());
  1746. String c_func_sig = "MethodBind* " CS_PARAM_METHODBIND ", " + p_itype.c_type_in + " " CS_PARAM_INSTANCE;
  1747. String c_in_statements;
  1748. String c_args_var_content;
  1749. // Get arguments information
  1750. int i = 0;
  1751. for (const ArgumentInterface &iarg : p_imethod.arguments) {
  1752. const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
  1753. String c_param_name = "arg" + itos(i + 1);
  1754. if (p_imethod.is_vararg) {
  1755. if (i < p_imethod.arguments.size() - 1) {
  1756. c_in_statements += sformat(arg_type->c_in.size() ? arg_type->c_in : TypeInterface::DEFAULT_VARARG_C_IN, "Variant", c_param_name);
  1757. c_in_statements += "\t" C_LOCAL_PTRCALL_ARGS ".set(";
  1758. c_in_statements += itos(i);
  1759. c_in_statements += sformat(", &%s_in);\n", c_param_name);
  1760. }
  1761. } else {
  1762. if (i > 0) {
  1763. c_args_var_content += ", ";
  1764. }
  1765. if (arg_type->c_in.size()) {
  1766. c_in_statements += sformat(arg_type->c_in, arg_type->c_type, c_param_name);
  1767. }
  1768. c_args_var_content += sformat(arg_type->c_arg_in, c_param_name);
  1769. }
  1770. c_func_sig += ", ";
  1771. c_func_sig += arg_type->c_type_in;
  1772. c_func_sig += " ";
  1773. c_func_sig += c_param_name;
  1774. i++;
  1775. }
  1776. if (return_type->ret_as_byref_arg) {
  1777. c_func_sig += ", ";
  1778. c_func_sig += return_type->c_type_in;
  1779. c_func_sig += " ";
  1780. c_func_sig += "arg_ret";
  1781. i++;
  1782. }
  1783. const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&p_imethod);
  1784. ERR_FAIL_NULL_V(match, ERR_BUG);
  1785. const InternalCall *im_icall = match->value();
  1786. String icall_method = im_icall->name;
  1787. if (!generated_icall_funcs.find(im_icall)) {
  1788. generated_icall_funcs.push_back(im_icall);
  1789. if (im_icall->editor_only) {
  1790. p_output.append("#ifdef TOOLS_ENABLED\n");
  1791. }
  1792. // Generate icall function
  1793. p_output.append((ret_void || return_type->ret_as_byref_arg) ? "void " : return_type->c_type_out + " ");
  1794. p_output.append(icall_method);
  1795. p_output.append("(");
  1796. p_output.append(c_func_sig);
  1797. p_output.append(") " OPEN_BLOCK);
  1798. if (!ret_void) {
  1799. String ptrcall_return_type;
  1800. String initialization;
  1801. if (p_imethod.is_vararg && return_type->cname != name_cache.type_Variant) {
  1802. // VarArg methods always return Variant, but there are some cases in which MethodInfo provides
  1803. // a specific return type. We trust this information is valid. We need a temporary local to keep
  1804. // the Variant alive until the method returns. Otherwise, if the returned Variant holds a RefPtr,
  1805. // it could be deleted too early. This is the case with GDScript.new() which returns OBJECT.
  1806. // Alternatively, we could just return Variant, but that would result in a worse API.
  1807. p_output.append("\tVariant " C_LOCAL_VARARG_RET ";\n");
  1808. }
  1809. if (return_type->is_object_type) {
  1810. ptrcall_return_type = return_type->is_ref_counted ? "Ref<RefCounted>" : return_type->c_type;
  1811. initialization = return_type->is_ref_counted ? "" : " = nullptr";
  1812. } else {
  1813. ptrcall_return_type = return_type->c_type;
  1814. }
  1815. p_output.append("\t" + ptrcall_return_type);
  1816. p_output.append(" " C_LOCAL_RET);
  1817. p_output.append(initialization + ";\n");
  1818. String fail_ret = return_type->c_type_out.ends_with("*") && !return_type->ret_as_byref_arg ? "nullptr" : return_type->c_type_out + "()";
  1819. if (return_type->ret_as_byref_arg) {
  1820. p_output.append("\tif (" CS_PARAM_INSTANCE " == nullptr) { *arg_ret = ");
  1821. p_output.append(fail_ret);
  1822. p_output.append("; ERR_FAIL_MSG(\"Parameter ' " CS_PARAM_INSTANCE " ' is null.\"); }\n");
  1823. } else {
  1824. p_output.append("\tERR_FAIL_NULL_V(" CS_PARAM_INSTANCE ", ");
  1825. p_output.append(fail_ret);
  1826. p_output.append(");\n");
  1827. }
  1828. } else {
  1829. p_output.append("\tERR_FAIL_NULL(" CS_PARAM_INSTANCE ");\n");
  1830. }
  1831. if (p_imethod.arguments.size()) {
  1832. if (p_imethod.is_vararg) {
  1833. String vararg_arg = "arg" + argc_str;
  1834. String real_argc_str = itos(p_imethod.arguments.size() - 1); // Arguments count without vararg
  1835. p_output.append("\tint vararg_length = mono_array_length(");
  1836. p_output.append(vararg_arg);
  1837. p_output.append(");\n\tint total_length = ");
  1838. p_output.append(real_argc_str);
  1839. p_output.append(" + vararg_length;\n"
  1840. "\tArgumentsVector<Variant> varargs(vararg_length);\n"
  1841. "\tArgumentsVector<const Variant *> " C_LOCAL_PTRCALL_ARGS "(total_length);\n");
  1842. p_output.append(c_in_statements);
  1843. p_output.append("\tfor (int i = 0; i < vararg_length; i++) " OPEN_BLOCK
  1844. "\t\tMonoObject* elem = mono_array_get(");
  1845. p_output.append(vararg_arg);
  1846. p_output.append(", MonoObject*, i);\n"
  1847. "\t\tvarargs.set(i, GDMonoMarshal::mono_object_to_variant(elem));\n"
  1848. "\t\t" C_LOCAL_PTRCALL_ARGS ".set(");
  1849. p_output.append(real_argc_str);
  1850. p_output.append(" + i, &varargs.get(i));\n\t" CLOSE_BLOCK);
  1851. } else {
  1852. p_output.append(c_in_statements);
  1853. p_output.append("\tconst void* " C_LOCAL_PTRCALL_ARGS "[");
  1854. p_output.append(argc_str + "] = { ");
  1855. p_output.append(c_args_var_content + " };\n");
  1856. }
  1857. }
  1858. if (p_imethod.is_vararg) {
  1859. p_output.append("\tCallable::CallError vcall_error;\n\t");
  1860. if (!ret_void) {
  1861. // See the comment on the C_LOCAL_VARARG_RET declaration
  1862. if (return_type->cname != name_cache.type_Variant) {
  1863. p_output.append(C_LOCAL_VARARG_RET " = ");
  1864. } else {
  1865. p_output.append(C_LOCAL_RET " = ");
  1866. }
  1867. }
  1868. p_output.append(CS_PARAM_METHODBIND "->call(" CS_PARAM_INSTANCE ", ");
  1869. p_output.append(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ".ptr()" : "nullptr");
  1870. p_output.append(", total_length, vcall_error);\n");
  1871. if (!ret_void) {
  1872. // See the comment on the C_LOCAL_VARARG_RET declaration
  1873. if (return_type->cname != name_cache.type_Variant) {
  1874. p_output.append("\t" C_LOCAL_RET " = " C_LOCAL_VARARG_RET ";\n");
  1875. }
  1876. }
  1877. } else {
  1878. p_output.append("\t" CS_PARAM_METHODBIND "->ptrcall(" CS_PARAM_INSTANCE ", ");
  1879. p_output.append(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ", " : "nullptr, ");
  1880. p_output.append(!ret_void ? "&" C_LOCAL_RET ");\n" : "nullptr);\n");
  1881. }
  1882. if (!ret_void) {
  1883. if (return_type->c_out.is_empty()) {
  1884. p_output.append("\treturn " C_LOCAL_RET ";\n");
  1885. } else if (return_type->ret_as_byref_arg) {
  1886. p_output.append(sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET, return_type->name, "arg_ret"));
  1887. } else {
  1888. p_output.append(sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET, return_type->name));
  1889. }
  1890. }
  1891. p_output.append(CLOSE_BLOCK "\n");
  1892. if (im_icall->editor_only) {
  1893. p_output.append("#endif // TOOLS_ENABLED\n");
  1894. }
  1895. }
  1896. return OK;
  1897. }
  1898. const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_null(const TypeReference &p_typeref) {
  1899. const Map<StringName, TypeInterface>::Element *builtin_type_match = builtin_types.find(p_typeref.cname);
  1900. if (builtin_type_match) {
  1901. return &builtin_type_match->get();
  1902. }
  1903. const OrderedHashMap<StringName, TypeInterface>::Element obj_type_match = obj_types.find(p_typeref.cname);
  1904. if (obj_type_match) {
  1905. return &obj_type_match.get();
  1906. }
  1907. if (p_typeref.is_enum) {
  1908. const Map<StringName, TypeInterface>::Element *enum_match = enum_types.find(p_typeref.cname);
  1909. if (enum_match) {
  1910. return &enum_match->get();
  1911. }
  1912. // Enum not found. Most likely because none of its constants were bound, so it's empty. That's fine. Use int instead.
  1913. const Map<StringName, TypeInterface>::Element *int_match = builtin_types.find(name_cache.type_int);
  1914. ERR_FAIL_NULL_V(int_match, nullptr);
  1915. return &int_match->get();
  1916. }
  1917. return nullptr;
  1918. }
  1919. const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_placeholder(const TypeReference &p_typeref) {
  1920. const TypeInterface *found = _get_type_or_null(p_typeref);
  1921. if (found) {
  1922. return found;
  1923. }
  1924. ERR_PRINT(String() + "Type not found. Creating placeholder: '" + p_typeref.cname.operator String() + "'.");
  1925. const Map<StringName, TypeInterface>::Element *match = placeholder_types.find(p_typeref.cname);
  1926. if (match) {
  1927. return &match->get();
  1928. }
  1929. TypeInterface placeholder;
  1930. TypeInterface::create_placeholder_type(placeholder, p_typeref.cname);
  1931. return &placeholder_types.insert(placeholder.cname, placeholder)->get();
  1932. }
  1933. StringName BindingsGenerator::_get_int_type_name_from_meta(GodotTypeInfo::Metadata p_meta) {
  1934. switch (p_meta) {
  1935. case GodotTypeInfo::METADATA_INT_IS_INT8:
  1936. return "sbyte";
  1937. break;
  1938. case GodotTypeInfo::METADATA_INT_IS_INT16:
  1939. return "short";
  1940. break;
  1941. case GodotTypeInfo::METADATA_INT_IS_INT32:
  1942. return "int";
  1943. break;
  1944. case GodotTypeInfo::METADATA_INT_IS_INT64:
  1945. return "long";
  1946. break;
  1947. case GodotTypeInfo::METADATA_INT_IS_UINT8:
  1948. return "byte";
  1949. break;
  1950. case GodotTypeInfo::METADATA_INT_IS_UINT16:
  1951. return "ushort";
  1952. break;
  1953. case GodotTypeInfo::METADATA_INT_IS_UINT32:
  1954. return "uint";
  1955. break;
  1956. case GodotTypeInfo::METADATA_INT_IS_UINT64:
  1957. return "ulong";
  1958. break;
  1959. default:
  1960. // Assume INT32
  1961. return "int";
  1962. }
  1963. }
  1964. StringName BindingsGenerator::_get_float_type_name_from_meta(GodotTypeInfo::Metadata p_meta) {
  1965. switch (p_meta) {
  1966. case GodotTypeInfo::METADATA_REAL_IS_FLOAT:
  1967. return "float";
  1968. break;
  1969. case GodotTypeInfo::METADATA_REAL_IS_DOUBLE:
  1970. return "double";
  1971. break;
  1972. default:
  1973. // Assume real_t (float or double depending of REAL_T_IS_DOUBLE)
  1974. #ifdef REAL_T_IS_DOUBLE
  1975. return "double";
  1976. #else
  1977. return "float";
  1978. #endif
  1979. }
  1980. }
  1981. bool BindingsGenerator::_arg_default_value_is_assignable_to_type(const Variant &p_val, const TypeInterface &p_arg_type) {
  1982. if (p_arg_type.name == name_cache.type_Variant) {
  1983. // Variant can take anything
  1984. return true;
  1985. }
  1986. switch (p_val.get_type()) {
  1987. case Variant::NIL:
  1988. return p_arg_type.is_object_type ||
  1989. name_cache.is_nullable_type(p_arg_type.name);
  1990. case Variant::BOOL:
  1991. return p_arg_type.name == name_cache.type_bool;
  1992. case Variant::INT:
  1993. return p_arg_type.name == name_cache.type_sbyte ||
  1994. p_arg_type.name == name_cache.type_short ||
  1995. p_arg_type.name == name_cache.type_int ||
  1996. p_arg_type.name == name_cache.type_byte ||
  1997. p_arg_type.name == name_cache.type_ushort ||
  1998. p_arg_type.name == name_cache.type_uint ||
  1999. p_arg_type.name == name_cache.type_long ||
  2000. p_arg_type.name == name_cache.type_ulong ||
  2001. p_arg_type.name == name_cache.type_float ||
  2002. p_arg_type.name == name_cache.type_double ||
  2003. p_arg_type.is_enum;
  2004. case Variant::FLOAT:
  2005. return p_arg_type.name == name_cache.type_float ||
  2006. p_arg_type.name == name_cache.type_double;
  2007. case Variant::STRING:
  2008. case Variant::STRING_NAME:
  2009. return p_arg_type.name == name_cache.type_String ||
  2010. p_arg_type.name == name_cache.type_StringName ||
  2011. p_arg_type.name == name_cache.type_NodePath;
  2012. case Variant::NODE_PATH:
  2013. return p_arg_type.name == name_cache.type_NodePath;
  2014. case Variant::TRANSFORM2D:
  2015. case Variant::TRANSFORM3D:
  2016. case Variant::BASIS:
  2017. case Variant::QUATERNION:
  2018. case Variant::PLANE:
  2019. case Variant::AABB:
  2020. case Variant::COLOR:
  2021. case Variant::VECTOR2:
  2022. case Variant::RECT2:
  2023. case Variant::VECTOR3:
  2024. case Variant::RID:
  2025. case Variant::ARRAY:
  2026. case Variant::DICTIONARY:
  2027. case Variant::PACKED_BYTE_ARRAY:
  2028. case Variant::PACKED_INT32_ARRAY:
  2029. case Variant::PACKED_INT64_ARRAY:
  2030. case Variant::PACKED_FLOAT32_ARRAY:
  2031. case Variant::PACKED_FLOAT64_ARRAY:
  2032. case Variant::PACKED_STRING_ARRAY:
  2033. case Variant::PACKED_VECTOR2_ARRAY:
  2034. case Variant::PACKED_VECTOR3_ARRAY:
  2035. case Variant::PACKED_COLOR_ARRAY:
  2036. case Variant::CALLABLE:
  2037. case Variant::SIGNAL:
  2038. return p_arg_type.name == Variant::get_type_name(p_val.get_type());
  2039. case Variant::OBJECT:
  2040. return p_arg_type.is_object_type;
  2041. case Variant::VECTOR2I:
  2042. return p_arg_type.name == name_cache.type_Vector2 ||
  2043. p_arg_type.name == Variant::get_type_name(p_val.get_type());
  2044. case Variant::RECT2I:
  2045. return p_arg_type.name == name_cache.type_Rect2 ||
  2046. p_arg_type.name == Variant::get_type_name(p_val.get_type());
  2047. case Variant::VECTOR3I:
  2048. return p_arg_type.name == name_cache.type_Vector3 ||
  2049. p_arg_type.name == Variant::get_type_name(p_val.get_type());
  2050. default:
  2051. CRASH_NOW_MSG("Unexpected Variant type: " + itos(p_val.get_type()));
  2052. break;
  2053. }
  2054. return false;
  2055. }
  2056. bool BindingsGenerator::_populate_object_type_interfaces() {
  2057. obj_types.clear();
  2058. List<StringName> class_list;
  2059. ClassDB::get_class_list(&class_list);
  2060. class_list.sort_custom<StringName::AlphCompare>();
  2061. while (class_list.size()) {
  2062. StringName type_cname = class_list.front()->get();
  2063. ClassDB::APIType api_type = ClassDB::get_api_type(type_cname);
  2064. if (api_type == ClassDB::API_NONE) {
  2065. class_list.pop_front();
  2066. continue;
  2067. }
  2068. if (!ClassDB::is_class_exposed(type_cname)) {
  2069. _log("Ignoring type '%s' because it's not exposed\n", String(type_cname).utf8().get_data());
  2070. class_list.pop_front();
  2071. continue;
  2072. }
  2073. if (!ClassDB::is_class_enabled(type_cname)) {
  2074. _log("Ignoring type '%s' because it's not enabled\n", String(type_cname).utf8().get_data());
  2075. class_list.pop_front();
  2076. continue;
  2077. }
  2078. ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(type_cname);
  2079. TypeInterface itype = TypeInterface::create_object_type(type_cname, api_type);
  2080. itype.base_name = ClassDB::get_parent_class(type_cname);
  2081. itype.is_singleton = Engine::get_singleton()->has_singleton(itype.proxy_name);
  2082. itype.is_instantiable = class_info->creation_func && !itype.is_singleton;
  2083. itype.is_ref_counted = ClassDB::is_parent_class(type_cname, name_cache.type_RefCounted);
  2084. itype.memory_own = itype.is_ref_counted;
  2085. itype.c_out = "\treturn ";
  2086. itype.c_out += C_METHOD_UNMANAGED_GET_MANAGED;
  2087. itype.c_out += itype.is_ref_counted ? "(%1.ptr());\n" : "(%1);\n";
  2088. itype.cs_in = itype.is_singleton ? BINDINGS_PTR_FIELD : "Object." CS_SMETHOD_GETINSTANCE "(%0)";
  2089. itype.c_type = "Object*";
  2090. itype.c_type_in = itype.c_type;
  2091. itype.c_type_out = "MonoObject*";
  2092. itype.cs_type = itype.proxy_name;
  2093. itype.im_type_in = "IntPtr";
  2094. itype.im_type_out = itype.proxy_name;
  2095. // Populate properties
  2096. List<PropertyInfo> property_list;
  2097. ClassDB::get_property_list(type_cname, &property_list, true);
  2098. Map<StringName, StringName> accessor_methods;
  2099. for (const PropertyInfo &property : property_list) {
  2100. if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY || (property.type == Variant::NIL && property.usage & PROPERTY_USAGE_ARRAY)) {
  2101. continue;
  2102. }
  2103. if (property.name.find("/") >= 0) {
  2104. // Ignore properties with '/' (slash) in the name. These are only meant for use in the inspector.
  2105. continue;
  2106. }
  2107. PropertyInterface iprop;
  2108. iprop.cname = property.name;
  2109. iprop.setter = ClassDB::get_property_setter(type_cname, iprop.cname);
  2110. iprop.getter = ClassDB::get_property_getter(type_cname, iprop.cname);
  2111. if (iprop.setter != StringName()) {
  2112. accessor_methods[iprop.setter] = iprop.cname;
  2113. }
  2114. if (iprop.getter != StringName()) {
  2115. accessor_methods[iprop.getter] = iprop.cname;
  2116. }
  2117. bool valid = false;
  2118. iprop.index = ClassDB::get_property_index(type_cname, iprop.cname, &valid);
  2119. ERR_FAIL_COND_V_MSG(!valid, false, "Invalid property: '" + itype.name + "." + String(iprop.cname) + "'.");
  2120. iprop.proxy_name = escape_csharp_keyword(snake_to_pascal_case(iprop.cname));
  2121. // Prevent the property and its enclosing type from sharing the same name
  2122. if (iprop.proxy_name == itype.proxy_name) {
  2123. _log("Name of property '%s' is ambiguous with the name of its enclosing class '%s'. Renaming property to '%s_'\n",
  2124. iprop.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), iprop.proxy_name.utf8().get_data());
  2125. iprop.proxy_name += "_";
  2126. }
  2127. iprop.prop_doc = nullptr;
  2128. for (int i = 0; i < itype.class_doc->properties.size(); i++) {
  2129. const DocData::PropertyDoc &prop_doc = itype.class_doc->properties[i];
  2130. if (prop_doc.name == iprop.cname) {
  2131. iprop.prop_doc = &prop_doc;
  2132. break;
  2133. }
  2134. }
  2135. itype.properties.push_back(iprop);
  2136. }
  2137. // Populate methods
  2138. List<MethodInfo> virtual_method_list;
  2139. ClassDB::get_virtual_methods(type_cname, &virtual_method_list, true);
  2140. List<MethodInfo> method_list;
  2141. ClassDB::get_method_list(type_cname, &method_list, true);
  2142. method_list.sort();
  2143. for (const MethodInfo &method_info : method_list) {
  2144. int argc = method_info.arguments.size();
  2145. if (method_info.name.is_empty()) {
  2146. continue;
  2147. }
  2148. String cname = method_info.name;
  2149. if (blacklisted_methods.find(itype.cname) && blacklisted_methods[itype.cname].find(cname)) {
  2150. continue;
  2151. }
  2152. MethodInterface imethod;
  2153. imethod.name = method_info.name;
  2154. imethod.cname = cname;
  2155. if (method_info.flags & METHOD_FLAG_VIRTUAL) {
  2156. imethod.is_virtual = true;
  2157. }
  2158. PropertyInfo return_info = method_info.return_val;
  2159. MethodBind *m = imethod.is_virtual ? nullptr : ClassDB::get_method(type_cname, method_info.name);
  2160. imethod.is_vararg = m && m->is_vararg();
  2161. if (!m && !imethod.is_virtual) {
  2162. ERR_FAIL_COND_V_MSG(!virtual_method_list.find(method_info), false,
  2163. "Missing MethodBind for non-virtual method: '" + itype.name + "." + imethod.name + "'.");
  2164. // A virtual method without the virtual flag. This is a special case.
  2165. // There is no method bind, so let's fallback to Godot's object.Call(string, params)
  2166. imethod.requires_object_call = true;
  2167. // The method Object.free is registered as a virtual method, but without the virtual flag.
  2168. // This is because this method is not supposed to be overridden, but called.
  2169. // We assume the return type is void.
  2170. imethod.return_type.cname = name_cache.type_void;
  2171. // Actually, more methods like this may be added in the future, which could return
  2172. // something different. Let's put this check to notify us if that ever happens.
  2173. if (itype.cname != name_cache.type_Object || imethod.name != "free") {
  2174. WARN_PRINT("Notification: New unexpected virtual non-overridable method found."
  2175. " We only expected Object.free, but found '" +
  2176. itype.name + "." + imethod.name + "'.");
  2177. }
  2178. } else if (return_info.type == Variant::INT && return_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
  2179. imethod.return_type.cname = return_info.class_name;
  2180. imethod.return_type.is_enum = true;
  2181. } else if (return_info.class_name != StringName()) {
  2182. imethod.return_type.cname = return_info.class_name;
  2183. bool bad_reference_hint = !imethod.is_virtual && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE &&
  2184. ClassDB::is_parent_class(return_info.class_name, name_cache.type_RefCounted);
  2185. ERR_FAIL_COND_V_MSG(bad_reference_hint, false,
  2186. String() + "Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'." +
  2187. " Are you returning a reference type by pointer? Method: '" + itype.name + "." + imethod.name + "'.");
  2188. } else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  2189. imethod.return_type.cname = return_info.hint_string;
  2190. } else if (return_info.type == Variant::NIL && return_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
  2191. imethod.return_type.cname = name_cache.type_Variant;
  2192. } else if (return_info.type == Variant::NIL) {
  2193. imethod.return_type.cname = name_cache.type_void;
  2194. } else {
  2195. if (return_info.type == Variant::INT) {
  2196. imethod.return_type.cname = _get_int_type_name_from_meta(m ? m->get_argument_meta(-1) : GodotTypeInfo::METADATA_NONE);
  2197. } else if (return_info.type == Variant::FLOAT) {
  2198. imethod.return_type.cname = _get_float_type_name_from_meta(m ? m->get_argument_meta(-1) : GodotTypeInfo::METADATA_NONE);
  2199. } else {
  2200. imethod.return_type.cname = Variant::get_type_name(return_info.type);
  2201. }
  2202. }
  2203. for (int i = 0; i < argc; i++) {
  2204. PropertyInfo arginfo = method_info.arguments[i];
  2205. String orig_arg_name = arginfo.name;
  2206. ArgumentInterface iarg;
  2207. iarg.name = orig_arg_name;
  2208. if (arginfo.type == Variant::INT && arginfo.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
  2209. iarg.type.cname = arginfo.class_name;
  2210. iarg.type.is_enum = true;
  2211. } else if (arginfo.class_name != StringName()) {
  2212. iarg.type.cname = arginfo.class_name;
  2213. } else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  2214. iarg.type.cname = arginfo.hint_string;
  2215. } else if (arginfo.type == Variant::NIL) {
  2216. iarg.type.cname = name_cache.type_Variant;
  2217. } else {
  2218. if (arginfo.type == Variant::INT) {
  2219. iarg.type.cname = _get_int_type_name_from_meta(m ? m->get_argument_meta(i) : GodotTypeInfo::METADATA_NONE);
  2220. } else if (arginfo.type == Variant::FLOAT) {
  2221. iarg.type.cname = _get_float_type_name_from_meta(m ? m->get_argument_meta(i) : GodotTypeInfo::METADATA_NONE);
  2222. } else {
  2223. iarg.type.cname = Variant::get_type_name(arginfo.type);
  2224. }
  2225. }
  2226. iarg.name = escape_csharp_keyword(snake_to_camel_case(iarg.name));
  2227. if (m && m->has_default_argument(i)) {
  2228. bool defval_ok = _arg_default_value_from_variant(m->get_default_argument(i), iarg);
  2229. ERR_FAIL_COND_V_MSG(!defval_ok, false,
  2230. "Cannot determine default value for argument '" + orig_arg_name + "' of method '" + itype.name + "." + imethod.name + "'.");
  2231. }
  2232. imethod.add_argument(iarg);
  2233. }
  2234. if (imethod.is_vararg) {
  2235. ArgumentInterface ivararg;
  2236. ivararg.type.cname = name_cache.type_VarArg;
  2237. ivararg.name = "@args";
  2238. imethod.add_argument(ivararg);
  2239. }
  2240. imethod.proxy_name = escape_csharp_keyword(snake_to_pascal_case(imethod.name));
  2241. // Prevent the method and its enclosing type from sharing the same name
  2242. if (imethod.proxy_name == itype.proxy_name) {
  2243. _log("Name of method '%s' is ambiguous with the name of its enclosing class '%s'. Renaming method to '%s_'\n",
  2244. imethod.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), imethod.proxy_name.utf8().get_data());
  2245. imethod.proxy_name += "_";
  2246. }
  2247. Map<StringName, StringName>::Element *accessor = accessor_methods.find(imethod.cname);
  2248. if (accessor) {
  2249. const PropertyInterface *accessor_property = itype.find_property_by_name(accessor->value());
  2250. // We only deprecate an accessor method if it's in the same class as the property. It's easier this way, but also
  2251. // we don't know if an accessor method in a different class could have other purposes, so better leave those untouched.
  2252. imethod.is_deprecated = true;
  2253. imethod.deprecation_message = imethod.proxy_name + " is deprecated. Use the " + accessor_property->proxy_name + " property instead.";
  2254. }
  2255. if (itype.class_doc) {
  2256. for (int i = 0; i < itype.class_doc->methods.size(); i++) {
  2257. if (itype.class_doc->methods[i].name == imethod.name) {
  2258. imethod.method_doc = &itype.class_doc->methods[i];
  2259. break;
  2260. }
  2261. }
  2262. }
  2263. ERR_FAIL_COND_V_MSG(itype.find_property_by_name(imethod.cname), false,
  2264. "Method name conflicts with property: '" + itype.name + "." + imethod.name + "'.");
  2265. // Classes starting with an underscore are ignored unless they're used as a property setter or getter
  2266. if (!imethod.is_virtual && imethod.name[0] == '_') {
  2267. for (const PropertyInterface &iprop : itype.properties) {
  2268. if (iprop.setter == imethod.name || iprop.getter == imethod.name) {
  2269. imethod.is_internal = true;
  2270. itype.methods.push_back(imethod);
  2271. break;
  2272. }
  2273. }
  2274. } else {
  2275. itype.methods.push_back(imethod);
  2276. }
  2277. }
  2278. // Populate signals
  2279. const HashMap<StringName, MethodInfo> &signal_map = class_info->signal_map;
  2280. const StringName *k = nullptr;
  2281. while ((k = signal_map.next(k))) {
  2282. SignalInterface isignal;
  2283. const MethodInfo &method_info = signal_map.get(*k);
  2284. isignal.name = method_info.name;
  2285. isignal.cname = method_info.name;
  2286. int argc = method_info.arguments.size();
  2287. for (int i = 0; i < argc; i++) {
  2288. PropertyInfo arginfo = method_info.arguments[i];
  2289. String orig_arg_name = arginfo.name;
  2290. ArgumentInterface iarg;
  2291. iarg.name = orig_arg_name;
  2292. if (arginfo.type == Variant::INT && arginfo.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
  2293. iarg.type.cname = arginfo.class_name;
  2294. iarg.type.is_enum = true;
  2295. } else if (arginfo.class_name != StringName()) {
  2296. iarg.type.cname = arginfo.class_name;
  2297. } else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  2298. iarg.type.cname = arginfo.hint_string;
  2299. } else if (arginfo.type == Variant::NIL) {
  2300. iarg.type.cname = name_cache.type_Variant;
  2301. } else {
  2302. if (arginfo.type == Variant::INT) {
  2303. iarg.type.cname = _get_int_type_name_from_meta(GodotTypeInfo::METADATA_NONE);
  2304. } else if (arginfo.type == Variant::FLOAT) {
  2305. iarg.type.cname = _get_float_type_name_from_meta(GodotTypeInfo::METADATA_NONE);
  2306. } else {
  2307. iarg.type.cname = Variant::get_type_name(arginfo.type);
  2308. }
  2309. }
  2310. iarg.name = escape_csharp_keyword(snake_to_camel_case(iarg.name));
  2311. isignal.add_argument(iarg);
  2312. }
  2313. isignal.proxy_name = escape_csharp_keyword(snake_to_pascal_case(isignal.name));
  2314. // Prevent the signal and its enclosing type from sharing the same name
  2315. if (isignal.proxy_name == itype.proxy_name) {
  2316. _log("Name of signal '%s' is ambiguous with the name of its enclosing class '%s'. Renaming signal to '%s_'\n",
  2317. isignal.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), isignal.proxy_name.utf8().get_data());
  2318. isignal.proxy_name += "_";
  2319. }
  2320. if (itype.find_property_by_proxy_name(isignal.proxy_name) || itype.find_method_by_proxy_name(isignal.proxy_name)) {
  2321. // ClassDB allows signal names that conflict with method or property names.
  2322. // While registering a signal with a conflicting name is considered wrong,
  2323. // it may still happen and it may take some time until someone fixes the name.
  2324. // We can't allow the bindings to be in a broken state while we wait for a fix;
  2325. // that's why we must handle this possibility by renaming the signal.
  2326. isignal.proxy_name += "Signal";
  2327. }
  2328. if (itype.class_doc) {
  2329. for (int i = 0; i < itype.class_doc->signals.size(); i++) {
  2330. const DocData::MethodDoc &signal_doc = itype.class_doc->signals[i];
  2331. if (signal_doc.name == isignal.name) {
  2332. isignal.method_doc = &signal_doc;
  2333. break;
  2334. }
  2335. }
  2336. }
  2337. itype.signals_.push_back(isignal);
  2338. }
  2339. // Populate enums and constants
  2340. List<String> constants;
  2341. ClassDB::get_integer_constant_list(type_cname, &constants, true);
  2342. const HashMap<StringName, List<StringName>> &enum_map = class_info->enum_map;
  2343. k = nullptr;
  2344. while ((k = enum_map.next(k))) {
  2345. StringName enum_proxy_cname = *k;
  2346. String enum_proxy_name = enum_proxy_cname.operator String();
  2347. if (itype.find_property_by_proxy_name(enum_proxy_cname)) {
  2348. // We have several conflicts between enums and PascalCase properties,
  2349. // so we append 'Enum' to the enum name in those cases.
  2350. enum_proxy_name += "Enum";
  2351. enum_proxy_cname = StringName(enum_proxy_name);
  2352. }
  2353. EnumInterface ienum(enum_proxy_cname);
  2354. const List<StringName> &enum_constants = enum_map.get(*k);
  2355. for (const StringName &constant_cname : enum_constants) {
  2356. String constant_name = constant_cname.operator String();
  2357. int *value = class_info->constant_map.getptr(constant_cname);
  2358. ERR_FAIL_NULL_V(value, false);
  2359. constants.erase(constant_name);
  2360. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value);
  2361. iconstant.const_doc = nullptr;
  2362. for (int i = 0; i < itype.class_doc->constants.size(); i++) {
  2363. const DocData::ConstantDoc &const_doc = itype.class_doc->constants[i];
  2364. if (const_doc.name == iconstant.name) {
  2365. iconstant.const_doc = &const_doc;
  2366. break;
  2367. }
  2368. }
  2369. ienum.constants.push_back(iconstant);
  2370. }
  2371. int prefix_length = _determine_enum_prefix(ienum);
  2372. _apply_prefix_to_enum_constants(ienum, prefix_length);
  2373. itype.enums.push_back(ienum);
  2374. TypeInterface enum_itype;
  2375. enum_itype.is_enum = true;
  2376. enum_itype.name = itype.name + "." + String(*k);
  2377. enum_itype.cname = StringName(enum_itype.name);
  2378. enum_itype.proxy_name = itype.proxy_name + "." + enum_proxy_name;
  2379. TypeInterface::postsetup_enum_type(enum_itype);
  2380. enum_types.insert(enum_itype.cname, enum_itype);
  2381. }
  2382. for (const String &constant_name : constants) {
  2383. int *value = class_info->constant_map.getptr(StringName(constant_name));
  2384. ERR_FAIL_NULL_V(value, false);
  2385. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value);
  2386. iconstant.const_doc = nullptr;
  2387. for (int i = 0; i < itype.class_doc->constants.size(); i++) {
  2388. const DocData::ConstantDoc &const_doc = itype.class_doc->constants[i];
  2389. if (const_doc.name == iconstant.name) {
  2390. iconstant.const_doc = &const_doc;
  2391. break;
  2392. }
  2393. }
  2394. itype.constants.push_back(iconstant);
  2395. }
  2396. obj_types.insert(itype.cname, itype);
  2397. class_list.pop_front();
  2398. }
  2399. return true;
  2400. }
  2401. bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, ArgumentInterface &r_iarg) {
  2402. r_iarg.def_param_value = p_val;
  2403. r_iarg.default_argument = p_val.operator String();
  2404. switch (p_val.get_type()) {
  2405. case Variant::NIL:
  2406. // Either Object type or Variant
  2407. r_iarg.default_argument = "null";
  2408. break;
  2409. // Atomic types
  2410. case Variant::BOOL:
  2411. r_iarg.default_argument = bool(p_val) ? "true" : "false";
  2412. break;
  2413. case Variant::INT:
  2414. if (r_iarg.type.cname != name_cache.type_int) {
  2415. r_iarg.default_argument = "(%s)" + r_iarg.default_argument;
  2416. }
  2417. break;
  2418. case Variant::FLOAT:
  2419. if (r_iarg.type.cname == name_cache.type_float) {
  2420. r_iarg.default_argument += "f";
  2421. }
  2422. break;
  2423. case Variant::STRING:
  2424. case Variant::STRING_NAME:
  2425. case Variant::NODE_PATH:
  2426. if (r_iarg.type.cname == name_cache.type_StringName || r_iarg.type.cname == name_cache.type_NodePath) {
  2427. r_iarg.default_argument = "(%s)\"" + r_iarg.default_argument + "\"";
  2428. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  2429. } else {
  2430. CRASH_COND(r_iarg.type.cname != name_cache.type_String);
  2431. r_iarg.default_argument = "\"" + r_iarg.default_argument + "\"";
  2432. }
  2433. break;
  2434. case Variant::PLANE: {
  2435. Plane plane = p_val.operator Plane();
  2436. r_iarg.default_argument = "new Plane(new Vector3" + plane.normal.operator String() + ", " + rtos(plane.d) + ")";
  2437. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2438. } break;
  2439. case Variant::AABB: {
  2440. AABB aabb = p_val.operator ::AABB();
  2441. r_iarg.default_argument = "new AABB(new Vector3" + aabb.position.operator String() + ", new Vector3" + aabb.size.operator String() + ")";
  2442. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2443. } break;
  2444. case Variant::RECT2: {
  2445. Rect2 rect = p_val.operator Rect2();
  2446. r_iarg.default_argument = "new Rect2(new Vector2" + rect.position.operator String() + ", new Vector2" + rect.size.operator String() + ")";
  2447. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2448. } break;
  2449. case Variant::RECT2I: {
  2450. Rect2i rect = p_val.operator Rect2i();
  2451. r_iarg.default_argument = "new Rect2i(new Vector2i" + rect.position.operator String() + ", new Vector2i" + rect.size.operator String() + ")";
  2452. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2453. } break;
  2454. case Variant::COLOR:
  2455. case Variant::VECTOR2:
  2456. case Variant::VECTOR2I:
  2457. case Variant::VECTOR3:
  2458. case Variant::VECTOR3I:
  2459. r_iarg.default_argument = "new %s" + r_iarg.default_argument;
  2460. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2461. break;
  2462. case Variant::OBJECT:
  2463. ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
  2464. "Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
  2465. r_iarg.default_argument = "null";
  2466. break;
  2467. case Variant::DICTIONARY:
  2468. r_iarg.default_argument = "new %s()";
  2469. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  2470. break;
  2471. case Variant::RID:
  2472. ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_RID, false,
  2473. "Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_RID) + "'.");
  2474. ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
  2475. "Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
  2476. r_iarg.default_argument = "null";
  2477. break;
  2478. case Variant::ARRAY:
  2479. r_iarg.default_argument = "new %s { }";
  2480. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  2481. break;
  2482. case Variant::PACKED_BYTE_ARRAY:
  2483. case Variant::PACKED_INT32_ARRAY:
  2484. case Variant::PACKED_INT64_ARRAY:
  2485. case Variant::PACKED_FLOAT32_ARRAY:
  2486. case Variant::PACKED_FLOAT64_ARRAY:
  2487. case Variant::PACKED_STRING_ARRAY:
  2488. case Variant::PACKED_VECTOR2_ARRAY:
  2489. case Variant::PACKED_VECTOR3_ARRAY:
  2490. case Variant::PACKED_COLOR_ARRAY:
  2491. r_iarg.default_argument = "Array.Empty<%s>()";
  2492. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  2493. break;
  2494. case Variant::TRANSFORM2D: {
  2495. Transform2D transform = p_val.operator Transform2D();
  2496. if (transform == Transform2D()) {
  2497. r_iarg.default_argument = "Transform2D.Identity";
  2498. } else {
  2499. r_iarg.default_argument = "new Transform2D(new Vector2" + transform.elements[0].operator String() + ", new Vector2" + transform.elements[1].operator String() + ", new Vector2" + transform.elements[2].operator String() + ")";
  2500. }
  2501. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2502. } break;
  2503. case Variant::TRANSFORM3D: {
  2504. Transform3D transform = p_val.operator Transform3D();
  2505. if (transform == Transform3D()) {
  2506. r_iarg.default_argument = "Transform3D.Identity";
  2507. } else {
  2508. Basis basis = transform.basis;
  2509. r_iarg.default_argument = "new Transform3D(new Vector3" + basis.get_column(0).operator String() + ", new Vector3" + basis.get_column(1).operator String() + ", new Vector3" + basis.get_column(2).operator String() + ", new Vector3" + transform.origin.operator String() + ")";
  2510. }
  2511. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2512. } break;
  2513. case Variant::BASIS: {
  2514. Basis basis = p_val.operator Basis();
  2515. if (basis == Basis()) {
  2516. r_iarg.default_argument = "Basis.Identity";
  2517. } else {
  2518. r_iarg.default_argument = "new Basis(new Vector3" + basis.get_column(0).operator String() + ", new Vector3" + basis.get_column(1).operator String() + ", new Vector3" + basis.get_column(2).operator String() + ")";
  2519. }
  2520. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2521. } break;
  2522. case Variant::QUATERNION: {
  2523. Quaternion quaternion = p_val.operator Quaternion();
  2524. if (quaternion == Quaternion()) {
  2525. r_iarg.default_argument = "Quaternion.Identity";
  2526. } else {
  2527. r_iarg.default_argument = "new Quaternion" + quaternion.operator String();
  2528. }
  2529. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  2530. } break;
  2531. case Variant::CALLABLE:
  2532. ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_Callable, false,
  2533. "Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_Callable) + "'.");
  2534. ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
  2535. "Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
  2536. r_iarg.default_argument = "default";
  2537. break;
  2538. case Variant::SIGNAL:
  2539. ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_Signal, false,
  2540. "Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_Signal) + "'.");
  2541. ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
  2542. "Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
  2543. r_iarg.default_argument = "default";
  2544. break;
  2545. default:
  2546. CRASH_NOW_MSG("Unexpected Variant type: " + itos(p_val.get_type()));
  2547. break;
  2548. }
  2549. if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "null") {
  2550. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  2551. }
  2552. return true;
  2553. }
  2554. void BindingsGenerator::_populate_builtin_type_interfaces() {
  2555. builtin_types.clear();
  2556. TypeInterface itype;
  2557. #define INSERT_STRUCT_TYPE(m_type) \
  2558. { \
  2559. itype = TypeInterface::create_value_type(String(#m_type)); \
  2560. itype.c_in = "\t%0 %1_in = MARSHALLED_IN(" #m_type ", %1);\n"; \
  2561. itype.c_out = "\t*%3 = MARSHALLED_OUT(" #m_type ", %1);\n"; \
  2562. itype.c_arg_in = "&%s_in"; \
  2563. itype.c_type_in = "GDMonoMarshal::M_" #m_type "*"; \
  2564. itype.c_type_out = "GDMonoMarshal::M_" #m_type; \
  2565. itype.cs_in = "ref %s"; \
  2566. /* in cs_out, im_type_out (%3) includes the 'out ' part */ \
  2567. itype.cs_out = "%0(%1, %3 argRet); return argRet;"; \
  2568. itype.im_type_out = "out " + itype.cs_type; \
  2569. itype.ret_as_byref_arg = true; \
  2570. builtin_types.insert(itype.cname, itype); \
  2571. }
  2572. INSERT_STRUCT_TYPE(Vector2)
  2573. INSERT_STRUCT_TYPE(Vector2i)
  2574. INSERT_STRUCT_TYPE(Rect2)
  2575. INSERT_STRUCT_TYPE(Rect2i)
  2576. INSERT_STRUCT_TYPE(Transform2D)
  2577. INSERT_STRUCT_TYPE(Vector3)
  2578. INSERT_STRUCT_TYPE(Vector3i)
  2579. INSERT_STRUCT_TYPE(Basis)
  2580. INSERT_STRUCT_TYPE(Quaternion)
  2581. INSERT_STRUCT_TYPE(Transform3D)
  2582. INSERT_STRUCT_TYPE(AABB)
  2583. INSERT_STRUCT_TYPE(Color)
  2584. INSERT_STRUCT_TYPE(Plane)
  2585. #undef INSERT_STRUCT_TYPE
  2586. // bool
  2587. itype = TypeInterface::create_value_type(String("bool"));
  2588. {
  2589. // MonoBoolean <---> bool
  2590. itype.c_in = "\t%0 %1_in = (%0)%1;\n";
  2591. itype.c_out = "\treturn (%0)%1;\n";
  2592. itype.c_type = "bool";
  2593. itype.c_type_in = "MonoBoolean";
  2594. itype.c_type_out = itype.c_type_in;
  2595. itype.c_arg_in = "&%s_in";
  2596. }
  2597. itype.im_type_in = itype.name;
  2598. itype.im_type_out = itype.name;
  2599. builtin_types.insert(itype.cname, itype);
  2600. // Integer types
  2601. {
  2602. // C interface for 'uint32_t' is the same as that of enums. Remember to apply
  2603. // any of the changes done here to 'TypeInterface::postsetup_enum_type' as well.
  2604. #define INSERT_INT_TYPE(m_name, m_c_type_in_out, m_c_type) \
  2605. { \
  2606. itype = TypeInterface::create_value_type(String(m_name)); \
  2607. { \
  2608. itype.c_in = "\t%0 %1_in = (%0)%1;\n"; \
  2609. itype.c_out = "\treturn (%0)%1;\n"; \
  2610. itype.c_type = #m_c_type; \
  2611. itype.c_arg_in = "&%s_in"; \
  2612. } \
  2613. itype.c_type_in = #m_c_type_in_out; \
  2614. itype.c_type_out = itype.c_type_in; \
  2615. itype.im_type_in = itype.name; \
  2616. itype.im_type_out = itype.name; \
  2617. builtin_types.insert(itype.cname, itype); \
  2618. }
  2619. // The expected type for all integers in ptrcall is 'int64_t', so that's what we use for 'c_type'
  2620. INSERT_INT_TYPE("sbyte", int8_t, int64_t);
  2621. INSERT_INT_TYPE("short", int16_t, int64_t);
  2622. INSERT_INT_TYPE("int", int32_t, int64_t);
  2623. INSERT_INT_TYPE("long", int64_t, int64_t);
  2624. INSERT_INT_TYPE("byte", uint8_t, int64_t);
  2625. INSERT_INT_TYPE("ushort", uint16_t, int64_t);
  2626. INSERT_INT_TYPE("uint", uint32_t, int64_t);
  2627. INSERT_INT_TYPE("ulong", uint64_t, int64_t);
  2628. }
  2629. // Floating point types
  2630. {
  2631. // float
  2632. itype = TypeInterface();
  2633. itype.name = "float";
  2634. itype.cname = itype.name;
  2635. itype.proxy_name = "float";
  2636. {
  2637. // The expected type for 'float' in ptrcall is 'double'
  2638. itype.c_in = "\t%0 %1_in = (%0)%1;\n";
  2639. itype.c_out = "\treturn (%0)%1;\n";
  2640. itype.c_type = "double";
  2641. itype.c_type_in = "float";
  2642. itype.c_type_out = "float";
  2643. itype.c_arg_in = "&%s_in";
  2644. }
  2645. itype.cs_type = itype.proxy_name;
  2646. itype.im_type_in = itype.proxy_name;
  2647. itype.im_type_out = itype.proxy_name;
  2648. builtin_types.insert(itype.cname, itype);
  2649. // double
  2650. itype = TypeInterface();
  2651. itype.name = "double";
  2652. itype.cname = itype.name;
  2653. itype.proxy_name = "double";
  2654. {
  2655. itype.c_type = "double";
  2656. itype.c_type_in = "double";
  2657. itype.c_type_out = "double";
  2658. itype.c_arg_in = "&%s";
  2659. }
  2660. itype.cs_type = itype.proxy_name;
  2661. itype.im_type_in = itype.proxy_name;
  2662. itype.im_type_out = itype.proxy_name;
  2663. builtin_types.insert(itype.cname, itype);
  2664. }
  2665. // String
  2666. itype = TypeInterface();
  2667. itype.name = "String";
  2668. itype.cname = itype.name;
  2669. itype.proxy_name = "string";
  2670. itype.c_in = "\t%0 %1_in = " C_METHOD_MONOSTR_TO_GODOT "(%1);\n";
  2671. itype.c_out = "\treturn " C_METHOD_MONOSTR_FROM_GODOT "(%1);\n";
  2672. itype.c_arg_in = "&%s_in";
  2673. itype.c_type = itype.name;
  2674. itype.c_type_in = "MonoString*";
  2675. itype.c_type_out = "MonoString*";
  2676. itype.cs_type = itype.proxy_name;
  2677. itype.im_type_in = itype.proxy_name;
  2678. itype.im_type_out = itype.proxy_name;
  2679. builtin_types.insert(itype.cname, itype);
  2680. // StringName
  2681. itype = TypeInterface();
  2682. itype.name = "StringName";
  2683. itype.cname = itype.name;
  2684. itype.proxy_name = "StringName";
  2685. itype.c_in = "\t%0 %1_in = %1 ? *%1 : StringName();\n";
  2686. itype.c_out = "\treturn memnew(StringName(%1));\n";
  2687. itype.c_arg_in = "&%s_in";
  2688. itype.c_type = itype.name;
  2689. itype.c_type_in = itype.c_type + "*";
  2690. itype.c_type_out = itype.c_type + "*";
  2691. itype.cs_type = itype.proxy_name;
  2692. itype.cs_in = "StringName." CS_SMETHOD_GETINSTANCE "(%0)";
  2693. itype.cs_out = "return new %2(%0(%1));";
  2694. itype.im_type_in = "IntPtr";
  2695. itype.im_type_out = "IntPtr";
  2696. builtin_types.insert(itype.cname, itype);
  2697. // NodePath
  2698. itype = TypeInterface();
  2699. itype.name = "NodePath";
  2700. itype.cname = itype.name;
  2701. itype.proxy_name = "NodePath";
  2702. itype.c_out = "\treturn memnew(NodePath(%1));\n";
  2703. itype.c_type = itype.name;
  2704. itype.c_type_in = itype.c_type + "*";
  2705. itype.c_type_out = itype.c_type + "*";
  2706. itype.cs_type = itype.proxy_name;
  2707. itype.cs_in = "NodePath." CS_SMETHOD_GETINSTANCE "(%0)";
  2708. itype.cs_out = "return new %2(%0(%1));";
  2709. itype.im_type_in = "IntPtr";
  2710. itype.im_type_out = "IntPtr";
  2711. builtin_types.insert(itype.cname, itype);
  2712. // RID
  2713. itype = TypeInterface();
  2714. itype.name = "RID";
  2715. itype.cname = itype.name;
  2716. itype.proxy_name = "RID";
  2717. itype.c_out = "\treturn memnew(RID(%1));\n";
  2718. itype.c_type = itype.name;
  2719. itype.c_type_in = itype.c_type + "*";
  2720. itype.c_type_out = itype.c_type + "*";
  2721. itype.cs_type = itype.proxy_name;
  2722. itype.cs_in = "RID." CS_SMETHOD_GETINSTANCE "(%0)";
  2723. itype.cs_out = "return new %2(%0(%1));";
  2724. itype.im_type_in = "IntPtr";
  2725. itype.im_type_out = "IntPtr";
  2726. builtin_types.insert(itype.cname, itype);
  2727. // Variant
  2728. itype = TypeInterface();
  2729. itype.name = "Variant";
  2730. itype.cname = itype.name;
  2731. itype.proxy_name = "object";
  2732. itype.c_in = "\t%0 %1_in = " C_METHOD_MANAGED_TO_VARIANT "(%1);\n";
  2733. itype.c_out = "\treturn " C_METHOD_MANAGED_FROM_VARIANT "(%1);\n";
  2734. itype.c_arg_in = "&%s_in";
  2735. itype.c_type = itype.name;
  2736. itype.c_type_in = "MonoObject*";
  2737. itype.c_type_out = "MonoObject*";
  2738. itype.cs_type = itype.proxy_name;
  2739. itype.im_type_in = "object";
  2740. itype.im_type_out = itype.proxy_name;
  2741. builtin_types.insert(itype.cname, itype);
  2742. // Callable
  2743. itype = TypeInterface::create_value_type(String("Callable"));
  2744. itype.c_in = "\t%0 %1_in = " C_METHOD_MANAGED_TO_CALLABLE "(*%1);\n";
  2745. itype.c_out = "\t*%3 = " C_METHOD_MANAGED_FROM_CALLABLE "(%1);\n";
  2746. itype.c_arg_in = "&%s_in";
  2747. itype.c_type_in = "GDMonoMarshal::M_Callable*";
  2748. itype.c_type_out = "GDMonoMarshal::M_Callable";
  2749. itype.cs_in = "ref %s";
  2750. /* in cs_out, im_type_out (%3) includes the 'out ' part */
  2751. itype.cs_out = "%0(%1, %3 argRet); return argRet;";
  2752. itype.im_type_out = "out " + itype.cs_type;
  2753. itype.ret_as_byref_arg = true;
  2754. builtin_types.insert(itype.cname, itype);
  2755. // Signal
  2756. itype = TypeInterface();
  2757. itype.name = "Signal";
  2758. itype.cname = itype.name;
  2759. itype.proxy_name = "SignalInfo";
  2760. itype.c_in = "\t%0 %1_in = " C_METHOD_MANAGED_TO_SIGNAL "(*%1);\n";
  2761. itype.c_out = "\t*%3 = " C_METHOD_MANAGED_FROM_SIGNAL "(%1);\n";
  2762. itype.c_arg_in = "&%s_in";
  2763. itype.c_type = itype.name;
  2764. itype.c_type_in = "GDMonoMarshal::M_SignalInfo*";
  2765. itype.c_type_out = "GDMonoMarshal::M_SignalInfo";
  2766. itype.cs_in = "ref %s";
  2767. /* in cs_out, im_type_out (%3) includes the 'out ' part */
  2768. itype.cs_out = "%0(%1, %3 argRet); return argRet;";
  2769. itype.cs_type = itype.proxy_name;
  2770. itype.im_type_in = "ref " + itype.cs_type;
  2771. itype.im_type_out = "out " + itype.cs_type;
  2772. itype.ret_as_byref_arg = true;
  2773. builtin_types.insert(itype.cname, itype);
  2774. // VarArg (fictitious type to represent variable arguments)
  2775. itype = TypeInterface();
  2776. itype.name = "VarArg";
  2777. itype.cname = itype.name;
  2778. itype.proxy_name = "object[]";
  2779. itype.c_in = "\t%0 %1_in = " C_METHOD_MONOARRAY_TO(Array) "(%1);\n";
  2780. itype.c_arg_in = "&%s_in";
  2781. itype.c_type = "Array";
  2782. itype.c_type_in = "MonoArray*";
  2783. itype.cs_type = "params object[]";
  2784. itype.im_type_in = "object[]";
  2785. builtin_types.insert(itype.cname, itype);
  2786. #define INSERT_ARRAY_FULL(m_name, m_type, m_proxy_t) \
  2787. { \
  2788. itype = TypeInterface(); \
  2789. itype.name = #m_name; \
  2790. itype.cname = itype.name; \
  2791. itype.proxy_name = #m_proxy_t "[]"; \
  2792. itype.c_in = "\t%0 %1_in = " C_METHOD_MONOARRAY_TO(m_type) "(%1);\n"; \
  2793. itype.c_out = "\treturn " C_METHOD_MONOARRAY_FROM(m_type) "(%1);\n"; \
  2794. itype.c_arg_in = "&%s_in"; \
  2795. itype.c_type = #m_type; \
  2796. itype.c_type_in = "MonoArray*"; \
  2797. itype.c_type_out = "MonoArray*"; \
  2798. itype.cs_type = itype.proxy_name; \
  2799. itype.im_type_in = itype.proxy_name; \
  2800. itype.im_type_out = itype.proxy_name; \
  2801. builtin_types.insert(itype.name, itype); \
  2802. }
  2803. #define INSERT_ARRAY(m_type, m_proxy_t) INSERT_ARRAY_FULL(m_type, m_type, m_proxy_t)
  2804. INSERT_ARRAY(PackedInt32Array, int);
  2805. INSERT_ARRAY(PackedInt64Array, long);
  2806. INSERT_ARRAY_FULL(PackedByteArray, PackedByteArray, byte);
  2807. INSERT_ARRAY(PackedFloat32Array, float);
  2808. INSERT_ARRAY(PackedFloat64Array, double);
  2809. INSERT_ARRAY(PackedStringArray, string);
  2810. INSERT_ARRAY(PackedColorArray, Color);
  2811. INSERT_ARRAY(PackedVector2Array, Vector2);
  2812. INSERT_ARRAY(PackedVector3Array, Vector3);
  2813. #undef INSERT_ARRAY
  2814. // Array
  2815. itype = TypeInterface();
  2816. itype.name = "Array";
  2817. itype.cname = itype.name;
  2818. itype.proxy_name = itype.name;
  2819. itype.c_out = "\treturn memnew(Array(%1));\n";
  2820. itype.c_type = itype.name;
  2821. itype.c_type_in = itype.c_type + "*";
  2822. itype.c_type_out = itype.c_type + "*";
  2823. itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
  2824. itype.cs_in = "%0." CS_SMETHOD_GETINSTANCE "()";
  2825. itype.cs_out = "return new " + itype.cs_type + "(%0(%1));";
  2826. itype.im_type_in = "IntPtr";
  2827. itype.im_type_out = "IntPtr";
  2828. builtin_types.insert(itype.cname, itype);
  2829. // Dictionary
  2830. itype = TypeInterface();
  2831. itype.name = "Dictionary";
  2832. itype.cname = itype.name;
  2833. itype.proxy_name = itype.name;
  2834. itype.c_out = "\treturn memnew(Dictionary(%1));\n";
  2835. itype.c_type = itype.name;
  2836. itype.c_type_in = itype.c_type + "*";
  2837. itype.c_type_out = itype.c_type + "*";
  2838. itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
  2839. itype.cs_in = "%0." CS_SMETHOD_GETINSTANCE "()";
  2840. itype.cs_out = "return new " + itype.cs_type + "(%0(%1));";
  2841. itype.im_type_in = "IntPtr";
  2842. itype.im_type_out = "IntPtr";
  2843. builtin_types.insert(itype.cname, itype);
  2844. // void (fictitious type to represent the return type of methods that do not return anything)
  2845. itype = TypeInterface();
  2846. itype.name = "void";
  2847. itype.cname = itype.name;
  2848. itype.proxy_name = itype.name;
  2849. itype.c_type = itype.name;
  2850. itype.c_type_in = itype.c_type;
  2851. itype.c_type_out = itype.c_type;
  2852. itype.cs_type = itype.proxy_name;
  2853. itype.im_type_in = itype.proxy_name;
  2854. itype.im_type_out = itype.proxy_name;
  2855. builtin_types.insert(itype.cname, itype);
  2856. }
  2857. void BindingsGenerator::_populate_global_constants() {
  2858. int global_constants_count = CoreConstants::get_global_constant_count();
  2859. if (global_constants_count > 0) {
  2860. Map<String, DocData::ClassDoc>::Element *match = EditorHelp::get_doc_data()->class_list.find("@GlobalScope");
  2861. CRASH_COND_MSG(!match, "Could not find '@GlobalScope' in DocData.");
  2862. const DocData::ClassDoc &global_scope_doc = match->value();
  2863. for (int i = 0; i < global_constants_count; i++) {
  2864. String constant_name = CoreConstants::get_global_constant_name(i);
  2865. const DocData::ConstantDoc *const_doc = nullptr;
  2866. for (int j = 0; j < global_scope_doc.constants.size(); j++) {
  2867. const DocData::ConstantDoc &curr_const_doc = global_scope_doc.constants[j];
  2868. if (curr_const_doc.name == constant_name) {
  2869. const_doc = &curr_const_doc;
  2870. break;
  2871. }
  2872. }
  2873. int constant_value = CoreConstants::get_global_constant_value(i);
  2874. StringName enum_name = CoreConstants::get_global_constant_enum(i);
  2875. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), constant_value);
  2876. iconstant.const_doc = const_doc;
  2877. if (enum_name != StringName()) {
  2878. EnumInterface ienum(enum_name);
  2879. List<EnumInterface>::Element *enum_match = global_enums.find(ienum);
  2880. if (enum_match) {
  2881. enum_match->get().constants.push_back(iconstant);
  2882. } else {
  2883. ienum.constants.push_back(iconstant);
  2884. global_enums.push_back(ienum);
  2885. }
  2886. } else {
  2887. global_constants.push_back(iconstant);
  2888. }
  2889. }
  2890. for (EnumInterface &ienum : global_enums) {
  2891. TypeInterface enum_itype;
  2892. enum_itype.is_enum = true;
  2893. enum_itype.name = ienum.cname.operator String();
  2894. enum_itype.cname = ienum.cname;
  2895. enum_itype.proxy_name = enum_itype.name;
  2896. TypeInterface::postsetup_enum_type(enum_itype);
  2897. enum_types.insert(enum_itype.cname, enum_itype);
  2898. int prefix_length = _determine_enum_prefix(ienum);
  2899. // HARDCODED: The Error enum have the prefix 'ERR_' for everything except 'OK' and 'FAILED'.
  2900. if (ienum.cname == name_cache.enum_Error) {
  2901. if (prefix_length > 0) { // Just in case it ever changes
  2902. ERR_PRINT("Prefix for enum '" _STR(Error) "' is not empty.");
  2903. }
  2904. prefix_length = 1; // 'ERR_'
  2905. }
  2906. _apply_prefix_to_enum_constants(ienum, prefix_length);
  2907. }
  2908. }
  2909. // HARDCODED
  2910. List<StringName> hardcoded_enums;
  2911. hardcoded_enums.push_back("Vector2.Axis");
  2912. hardcoded_enums.push_back("Vector2i.Axis");
  2913. hardcoded_enums.push_back("Vector3.Axis");
  2914. hardcoded_enums.push_back("Vector3i.Axis");
  2915. for (const StringName &enum_cname : hardcoded_enums) {
  2916. // These enums are not generated and must be written manually (e.g.: Vector3.Axis)
  2917. // Here, we assume core types do not begin with underscore
  2918. TypeInterface enum_itype;
  2919. enum_itype.is_enum = true;
  2920. enum_itype.name = enum_cname.operator String();
  2921. enum_itype.cname = enum_cname;
  2922. enum_itype.proxy_name = enum_itype.name;
  2923. TypeInterface::postsetup_enum_type(enum_itype);
  2924. enum_types.insert(enum_itype.cname, enum_itype);
  2925. }
  2926. }
  2927. void BindingsGenerator::_initialize_blacklisted_methods() {
  2928. blacklisted_methods["Object"].push_back("to_string"); // there is already ToString
  2929. blacklisted_methods["Object"].push_back("_to_string"); // override ToString instead
  2930. blacklisted_methods["Object"].push_back("_init"); // never called in C# (TODO: implement it)
  2931. }
  2932. void BindingsGenerator::_log(const char *p_format, ...) {
  2933. if (log_print_enabled) {
  2934. va_list list;
  2935. va_start(list, p_format);
  2936. OS::get_singleton()->print("%s", str_format(p_format, list).utf8().get_data());
  2937. va_end(list);
  2938. }
  2939. }
  2940. void BindingsGenerator::_initialize() {
  2941. initialized = false;
  2942. EditorHelp::generate_doc();
  2943. enum_types.clear();
  2944. _initialize_blacklisted_methods();
  2945. bool obj_type_ok = _populate_object_type_interfaces();
  2946. ERR_FAIL_COND_MSG(!obj_type_ok, "Failed to generate object type interfaces");
  2947. _populate_builtin_type_interfaces();
  2948. _populate_global_constants();
  2949. // Generate internal calls (after populating type interfaces and global constants)
  2950. core_custom_icalls.clear();
  2951. editor_custom_icalls.clear();
  2952. for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
  2953. _generate_method_icalls(E.get());
  2954. }
  2955. initialized = true;
  2956. }
  2957. static String generate_all_glue_option = "--generate-mono-glue";
  2958. static String generate_cs_glue_option = "--generate-mono-cs-glue";
  2959. static String generate_cpp_glue_option = "--generate-mono-cpp-glue";
  2960. static void handle_cmdline_options(String glue_dir_path, String cs_dir_path, String cpp_dir_path) {
  2961. BindingsGenerator bindings_generator;
  2962. bindings_generator.set_log_print_enabled(true);
  2963. if (!bindings_generator.is_initialized()) {
  2964. ERR_PRINT("Failed to initialize the bindings generator");
  2965. return;
  2966. }
  2967. if (glue_dir_path.length()) {
  2968. if (bindings_generator.generate_glue(glue_dir_path) != OK) {
  2969. ERR_PRINT(generate_all_glue_option + ": Failed to generate the C++ glue.");
  2970. }
  2971. if (bindings_generator.generate_cs_api(glue_dir_path.plus_file(API_SOLUTION_NAME)) != OK) {
  2972. ERR_PRINT(generate_all_glue_option + ": Failed to generate the C# API.");
  2973. }
  2974. }
  2975. if (cs_dir_path.length()) {
  2976. if (bindings_generator.generate_cs_api(cs_dir_path) != OK) {
  2977. ERR_PRINT(generate_cs_glue_option + ": Failed to generate the C# API.");
  2978. }
  2979. }
  2980. if (cpp_dir_path.length()) {
  2981. if (bindings_generator.generate_glue(cpp_dir_path) != OK) {
  2982. ERR_PRINT(generate_cpp_glue_option + ": Failed to generate the C++ glue.");
  2983. }
  2984. }
  2985. }
  2986. void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) {
  2987. const int NUM_OPTIONS = 2;
  2988. String glue_dir_path;
  2989. String cs_dir_path;
  2990. String cpp_dir_path;
  2991. int options_left = NUM_OPTIONS;
  2992. bool exit_godot = false;
  2993. const List<String>::Element *elem = p_cmdline_args.front();
  2994. while (elem && options_left) {
  2995. if (elem->get() == generate_all_glue_option) {
  2996. const List<String>::Element *path_elem = elem->next();
  2997. if (path_elem) {
  2998. glue_dir_path = path_elem->get();
  2999. elem = elem->next();
  3000. } else {
  3001. ERR_PRINT(generate_all_glue_option + ": No output directory specified (expected path to '{GODOT_ROOT}/modules/mono/glue').");
  3002. exit_godot = true;
  3003. }
  3004. --options_left;
  3005. } else if (elem->get() == generate_cs_glue_option) {
  3006. const List<String>::Element *path_elem = elem->next();
  3007. if (path_elem) {
  3008. cs_dir_path = path_elem->get();
  3009. elem = elem->next();
  3010. } else {
  3011. ERR_PRINT(generate_cs_glue_option + ": No output directory specified.");
  3012. exit_godot = true;
  3013. }
  3014. --options_left;
  3015. } else if (elem->get() == generate_cpp_glue_option) {
  3016. const List<String>::Element *path_elem = elem->next();
  3017. if (path_elem) {
  3018. cpp_dir_path = path_elem->get();
  3019. elem = elem->next();
  3020. } else {
  3021. ERR_PRINT(generate_cpp_glue_option + ": No output directory specified.");
  3022. exit_godot = true;
  3023. }
  3024. --options_left;
  3025. }
  3026. elem = elem->next();
  3027. }
  3028. if (glue_dir_path.length() || cs_dir_path.length() || cpp_dir_path.length()) {
  3029. handle_cmdline_options(glue_dir_path, cs_dir_path, cpp_dir_path);
  3030. exit_godot = true;
  3031. }
  3032. if (exit_godot) {
  3033. // Exit once done
  3034. Main::cleanup(true);
  3035. ::exit(0);
  3036. }
  3037. }
  3038. #endif