bindings_generator.cpp 143 KB

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