bindings_generator.cpp 130 KB

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