bindings_generator.cpp 140 KB

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