bindings_generator.cpp 114 KB

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