bindings_generator.cpp 138 KB

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