bindings_generator.cpp 193 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293
  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 "../godotsharp_defs.h"
  33. #include "../utils/naming_utils.h"
  34. #include "../utils/path_utils.h"
  35. #include "../utils/string_utils.h"
  36. #include "core/config/engine.h"
  37. #include "core/core_constants.h"
  38. #include "core/io/compression.h"
  39. #include "core/io/dir_access.h"
  40. #include "core/io/file_access.h"
  41. #include "core/os/os.h"
  42. #include "main/main.h"
  43. StringBuilder &operator<<(StringBuilder &r_sb, const String &p_string) {
  44. r_sb.append(p_string);
  45. return r_sb;
  46. }
  47. StringBuilder &operator<<(StringBuilder &r_sb, const char *p_cstring) {
  48. r_sb.append(p_cstring);
  49. return r_sb;
  50. }
  51. #define CS_INDENT " " // 4 whitespaces
  52. #define INDENT1 CS_INDENT
  53. #define INDENT2 INDENT1 INDENT1
  54. #define INDENT3 INDENT2 INDENT1
  55. #define INDENT4 INDENT3 INDENT1
  56. #define MEMBER_BEGIN "\n" INDENT1
  57. #define OPEN_BLOCK "{\n"
  58. #define CLOSE_BLOCK "}\n"
  59. #define OPEN_BLOCK_L1 INDENT1 OPEN_BLOCK
  60. #define OPEN_BLOCK_L2 INDENT2 OPEN_BLOCK
  61. #define OPEN_BLOCK_L3 INDENT3 OPEN_BLOCK
  62. #define CLOSE_BLOCK_L1 INDENT1 CLOSE_BLOCK
  63. #define CLOSE_BLOCK_L2 INDENT2 CLOSE_BLOCK
  64. #define CLOSE_BLOCK_L3 INDENT3 CLOSE_BLOCK
  65. #define BINDINGS_GLOBAL_SCOPE_CLASS "GD"
  66. #define BINDINGS_NATIVE_NAME_FIELD "NativeName"
  67. #define BINDINGS_CLASS_CONSTRUCTOR "Constructors"
  68. #define BINDINGS_CLASS_CONSTRUCTOR_EDITOR "EditorConstructors"
  69. #define BINDINGS_CLASS_CONSTRUCTOR_DICTIONARY "BuiltInMethodConstructors"
  70. #define CS_PARAM_MEMORYOWN "memoryOwn"
  71. #define CS_PARAM_METHODBIND "method"
  72. #define CS_PARAM_INSTANCE "ptr"
  73. #define CS_STATIC_METHOD_GETINSTANCE "GetPtr"
  74. #define CS_METHOD_CALL "Call"
  75. #define CS_PROPERTY_SINGLETON "Singleton"
  76. #define CS_SINGLETON_INSTANCE_SUFFIX "Instance"
  77. #define CS_METHOD_INVOKE_GODOT_CLASS_METHOD "InvokeGodotClassMethod"
  78. #define CS_METHOD_HAS_GODOT_CLASS_METHOD "HasGodotClassMethod"
  79. #define CS_METHOD_HAS_GODOT_CLASS_SIGNAL "HasGodotClassSignal"
  80. #define CS_STATIC_FIELD_NATIVE_CTOR "NativeCtor"
  81. #define CS_STATIC_FIELD_METHOD_BIND_PREFIX "MethodBind"
  82. #define CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX "MethodProxyName_"
  83. #define CS_STATIC_FIELD_SIGNAL_PROXY_NAME_PREFIX "SignalProxyName_"
  84. #define ICALL_PREFIX "godot_icall_"
  85. #define ICALL_CLASSDB_GET_METHOD "ClassDB_get_method"
  86. #define ICALL_CLASSDB_GET_METHOD_WITH_COMPATIBILITY "ClassDB_get_method_with_compatibility"
  87. #define ICALL_CLASSDB_GET_CONSTRUCTOR "ClassDB_get_constructor"
  88. #define C_LOCAL_RET "ret"
  89. #define C_LOCAL_VARARG_RET "vararg_ret"
  90. #define C_LOCAL_PTRCALL_ARGS "call_args"
  91. #define C_CLASS_NATIVE_FUNCS "NativeFuncs"
  92. #define C_NS_MONOUTILS "InteropUtils"
  93. #define C_METHOD_UNMANAGED_GET_MANAGED C_NS_MONOUTILS ".UnmanagedGetManaged"
  94. #define C_METHOD_ENGINE_GET_SINGLETON C_NS_MONOUTILS ".EngineGetSingleton"
  95. #define C_NS_MONOMARSHAL "Marshaling"
  96. #define C_METHOD_MONOSTR_TO_GODOT C_NS_MONOMARSHAL ".ConvertStringToNative"
  97. #define C_METHOD_MONOSTR_FROM_GODOT C_NS_MONOMARSHAL ".ConvertStringToManaged"
  98. #define C_METHOD_MONOARRAY_TO(m_type) C_NS_MONOMARSHAL ".ConvertSystemArrayToNative" #m_type
  99. #define C_METHOD_MONOARRAY_FROM(m_type) C_NS_MONOMARSHAL ".ConvertNative" #m_type "ToSystemArray"
  100. #define C_METHOD_MANAGED_TO_CALLABLE C_NS_MONOMARSHAL ".ConvertCallableToNative"
  101. #define C_METHOD_MANAGED_FROM_CALLABLE C_NS_MONOMARSHAL ".ConvertCallableToManaged"
  102. #define C_METHOD_MANAGED_TO_SIGNAL C_NS_MONOMARSHAL ".ConvertSignalToNative"
  103. #define C_METHOD_MANAGED_FROM_SIGNAL C_NS_MONOMARSHAL ".ConvertSignalToManaged"
  104. // Types that will be ignored by the generator and won't be available in C#.
  105. // This must be kept in sync with `ignored_types` in csharp_script.cpp
  106. const Vector<String> ignored_types = {};
  107. // Special [code] keywords to wrap with <see langword="code"/> instead of <c>code</c>.
  108. // Don't check against all C# reserved words, as many cases are GDScript-specific.
  109. const Vector<String> langword_check = { "true", "false", "null" };
  110. // The following properties currently need to be defined with `new` to avoid warnings. We treat
  111. // them as a special case instead of silencing the warnings altogether, to be warned if more
  112. // shadowing appears.
  113. const Vector<String> prop_allowed_inherited_member_hiding = {
  114. "ArrayMesh.BlendShapeMode",
  115. "Button.TextDirection",
  116. "Label.TextDirection",
  117. "LineEdit.TextDirection",
  118. "LinkButton.TextDirection",
  119. "MenuBar.TextDirection",
  120. "RichTextLabel.TextDirection",
  121. "TextEdit.TextDirection",
  122. "VisualShaderNodeReroute.PortType",
  123. // The following instances are uniquely egregious violations, hiding `GetType()` from `object`.
  124. // Included for the sake of CI, with the understanding that they *deserve* warnings.
  125. "GltfAccessor.GetType",
  126. "GltfAccessor.MethodName.GetType",
  127. };
  128. void BindingsGenerator::TypeInterface::postsetup_enum_type(BindingsGenerator::TypeInterface &r_enum_itype) {
  129. // C interface for enums is the same as that of 'uint32_t'. Remember to apply
  130. // any of the changes done here to the 'uint32_t' type interface as well.
  131. r_enum_itype.cs_type = r_enum_itype.proxy_name;
  132. r_enum_itype.cs_in_expr = "(int)%0";
  133. r_enum_itype.cs_out = "%5return (%2)%0(%1);";
  134. {
  135. // The expected types for parameters and return value in ptrcall are 'int64_t' or 'uint64_t'.
  136. r_enum_itype.c_in = "%5%0 %1_in = %1;\n";
  137. r_enum_itype.c_out = "%5return (%0)(%1);\n";
  138. r_enum_itype.c_type = "long";
  139. r_enum_itype.c_arg_in = "&%s_in";
  140. }
  141. r_enum_itype.c_type_in = "int";
  142. r_enum_itype.c_type_out = r_enum_itype.c_type_in;
  143. r_enum_itype.class_doc = &EditorHelp::get_doc_data()->class_list[r_enum_itype.proxy_name];
  144. }
  145. static String fix_doc_description(const String &p_bbcode) {
  146. // This seems to be the correct way to do this. It's the same EditorHelp does.
  147. return p_bbcode.dedent()
  148. .replace("\t", "")
  149. .replace("\r", "")
  150. .strip_edges();
  151. }
  152. String BindingsGenerator::bbcode_to_text(const String &p_bbcode, const TypeInterface *p_itype) {
  153. // Based on the version in EditorHelp.
  154. if (p_bbcode.is_empty()) {
  155. return String();
  156. }
  157. DocTools *doc = EditorHelp::get_doc_data();
  158. String bbcode = p_bbcode;
  159. StringBuilder output;
  160. List<String> tag_stack;
  161. bool code_tag = false;
  162. int pos = 0;
  163. while (pos < bbcode.length()) {
  164. int brk_pos = bbcode.find_char('[', pos);
  165. if (brk_pos < 0) {
  166. brk_pos = bbcode.length();
  167. }
  168. if (brk_pos > pos) {
  169. String text = bbcode.substr(pos, brk_pos - pos);
  170. if (code_tag || tag_stack.size() > 0) {
  171. output.append("'" + text + "'");
  172. } else {
  173. output.append(text);
  174. }
  175. }
  176. if (brk_pos == bbcode.length()) {
  177. // Nothing else to add.
  178. break;
  179. }
  180. int brk_end = bbcode.find_char(']', brk_pos + 1);
  181. if (brk_end == -1) {
  182. String text = bbcode.substr(brk_pos);
  183. if (code_tag || tag_stack.size() > 0) {
  184. output.append("'" + text + "'");
  185. }
  186. break;
  187. }
  188. String tag = bbcode.substr(brk_pos + 1, brk_end - brk_pos - 1);
  189. if (tag.begins_with("/")) {
  190. bool tag_ok = tag_stack.size() && tag_stack.front()->get() == tag.substr(1);
  191. if (!tag_ok) {
  192. output.append("]");
  193. pos = brk_pos + 1;
  194. continue;
  195. }
  196. tag_stack.pop_front();
  197. pos = brk_end + 1;
  198. code_tag = false;
  199. } else if (code_tag) {
  200. output.append("[");
  201. pos = brk_pos + 1;
  202. } else if (tag.begins_with("method ") || tag.begins_with("constructor ") || tag.begins_with("operator ") || tag.begins_with("member ") || tag.begins_with("signal ") || tag.begins_with("enum ") || tag.begins_with("constant ") || tag.begins_with("theme_item ") || tag.begins_with("param ")) {
  203. const int tag_end = tag.find_char(' ');
  204. const String link_tag = tag.substr(0, tag_end);
  205. const String link_target = tag.substr(tag_end + 1).lstrip(" ");
  206. const Vector<String> link_target_parts = link_target.split(".");
  207. if (link_target_parts.size() <= 0 || link_target_parts.size() > 2) {
  208. ERR_PRINT("Invalid reference format: '" + tag + "'.");
  209. output.append(tag);
  210. pos = brk_end + 1;
  211. continue;
  212. }
  213. const TypeInterface *target_itype;
  214. StringName target_cname;
  215. if (link_target_parts.size() == 2) {
  216. target_itype = _get_type_or_null(TypeReference(link_target_parts[0]));
  217. if (!target_itype) {
  218. target_itype = _get_type_or_null(TypeReference("_" + link_target_parts[0]));
  219. }
  220. target_cname = link_target_parts[1];
  221. } else {
  222. target_itype = p_itype;
  223. target_cname = link_target_parts[0];
  224. }
  225. if (link_tag == "method") {
  226. _append_text_method(output, target_itype, target_cname, link_target, link_target_parts);
  227. } else if (link_tag == "constructor") {
  228. // TODO: Support constructors?
  229. _append_text_undeclared(output, link_target);
  230. } else if (link_tag == "operator") {
  231. // TODO: Support operators?
  232. _append_text_undeclared(output, link_target);
  233. } else if (link_tag == "member") {
  234. _append_text_member(output, target_itype, target_cname, link_target, link_target_parts);
  235. } else if (link_tag == "signal") {
  236. _append_text_signal(output, target_itype, target_cname, link_target, link_target_parts);
  237. } else if (link_tag == "enum") {
  238. _append_text_enum(output, target_itype, target_cname, link_target, link_target_parts);
  239. } else if (link_tag == "constant") {
  240. _append_text_constant(output, target_itype, target_cname, link_target, link_target_parts);
  241. } else if (link_tag == "param") {
  242. _append_text_param(output, link_target);
  243. } else if (link_tag == "theme_item") {
  244. // We do not declare theme_items in any way in C#, so there is nothing to reference.
  245. _append_text_undeclared(output, link_target);
  246. }
  247. pos = brk_end + 1;
  248. } else if (doc->class_list.has(tag)) {
  249. if (tag == "Array" || tag == "Dictionary") {
  250. output.append("'" BINDINGS_NAMESPACE_COLLECTIONS ".");
  251. output.append(tag);
  252. output.append("'");
  253. } else if (tag == "bool" || tag == "int") {
  254. output.append(tag);
  255. } else if (tag == "float") {
  256. output.append(
  257. #ifdef REAL_T_IS_DOUBLE
  258. "double"
  259. #else
  260. "float"
  261. #endif
  262. );
  263. } else if (tag == "Variant") {
  264. output.append("'Godot.Variant'");
  265. } else if (tag == "String") {
  266. output.append("string");
  267. } else if (tag == "Nil") {
  268. output.append("null");
  269. } else if (tag.begins_with("@")) {
  270. // @GlobalScope, @GDScript, etc.
  271. output.append("'" + tag + "'");
  272. } else if (tag == "PackedByteArray") {
  273. output.append("byte[]");
  274. } else if (tag == "PackedInt32Array") {
  275. output.append("int[]");
  276. } else if (tag == "PackedInt64Array") {
  277. output.append("long[]");
  278. } else if (tag == "PackedFloat32Array") {
  279. output.append("float[]");
  280. } else if (tag == "PackedFloat64Array") {
  281. output.append("double[]");
  282. } else if (tag == "PackedStringArray") {
  283. output.append("string[]");
  284. } else if (tag == "PackedVector2Array") {
  285. output.append("'" BINDINGS_NAMESPACE ".Vector2[]'");
  286. } else if (tag == "PackedVector3Array") {
  287. output.append("'" BINDINGS_NAMESPACE ".Vector3[]'");
  288. } else if (tag == "PackedColorArray") {
  289. output.append("'" BINDINGS_NAMESPACE ".Color[]'");
  290. } else if (tag == "PackedVector4Array") {
  291. output.append("'" BINDINGS_NAMESPACE ".Vector4[]'");
  292. } else {
  293. const TypeInterface *target_itype = _get_type_or_null(TypeReference(tag));
  294. if (!target_itype) {
  295. target_itype = _get_type_or_null(TypeReference("_" + tag));
  296. }
  297. if (target_itype) {
  298. output.append("'" + target_itype->proxy_name + "'");
  299. } else {
  300. ERR_PRINT("Cannot resolve type reference in documentation: '" + tag + "'.");
  301. output.append("'" + tag + "'");
  302. }
  303. }
  304. pos = brk_end + 1;
  305. } else if (tag == "b") {
  306. // Bold is not supported.
  307. pos = brk_end + 1;
  308. tag_stack.push_front(tag);
  309. } else if (tag == "i") {
  310. // Italic is not supported.
  311. pos = brk_end + 1;
  312. tag_stack.push_front(tag);
  313. } else if (tag == "code" || tag.begins_with("code ")) {
  314. code_tag = true;
  315. pos = brk_end + 1;
  316. tag_stack.push_front("code");
  317. } else if (tag == "kbd") {
  318. // Keyboard combinations are not supported.
  319. pos = brk_end + 1;
  320. tag_stack.push_front(tag);
  321. } else if (tag == "center") {
  322. // Center alignment is not supported.
  323. pos = brk_end + 1;
  324. tag_stack.push_front(tag);
  325. } else if (tag == "br") {
  326. // Break is not supported.
  327. pos = brk_end + 1;
  328. tag_stack.push_front(tag);
  329. } else if (tag == "u") {
  330. // Underline is not supported.
  331. pos = brk_end + 1;
  332. tag_stack.push_front(tag);
  333. } else if (tag == "s") {
  334. // Strikethrough is not supported.
  335. pos = brk_end + 1;
  336. tag_stack.push_front(tag);
  337. } else if (tag == "url") {
  338. int end = bbcode.find_char('[', brk_end);
  339. if (end == -1) {
  340. end = bbcode.length();
  341. }
  342. String url = bbcode.substr(brk_end + 1, end - brk_end - 1);
  343. // Not supported. Just append the url.
  344. output.append(url);
  345. pos = brk_end + 1;
  346. tag_stack.push_front(tag);
  347. } else if (tag.begins_with("url=")) {
  348. String url = tag.substr(4);
  349. // Not supported. Just append the url.
  350. output.append(url);
  351. pos = brk_end + 1;
  352. tag_stack.push_front("url");
  353. } else if (tag == "img") {
  354. int end = bbcode.find_char('[', brk_end);
  355. if (end == -1) {
  356. end = bbcode.length();
  357. }
  358. String image = bbcode.substr(brk_end + 1, end - brk_end - 1);
  359. // Not supported. Just append the bbcode.
  360. output.append("[img]");
  361. output.append(image);
  362. output.append("[/img]");
  363. pos = end;
  364. tag_stack.push_front(tag);
  365. } else if (tag.begins_with("color=")) {
  366. // Not supported.
  367. pos = brk_end + 1;
  368. tag_stack.push_front("color");
  369. } else if (tag.begins_with("font=")) {
  370. // Not supported.
  371. pos = brk_end + 1;
  372. tag_stack.push_front("font");
  373. } else {
  374. // Ignore unrecognized tag.
  375. output.append("[");
  376. pos = brk_pos + 1;
  377. }
  378. }
  379. return output.as_string();
  380. }
  381. String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterface *p_itype, bool p_is_signal) {
  382. // Based on the version in EditorHelp.
  383. if (p_bbcode.is_empty()) {
  384. return String();
  385. }
  386. DocTools *doc = EditorHelp::get_doc_data();
  387. String bbcode = p_bbcode;
  388. StringBuilder xml_output;
  389. xml_output.append("<para>");
  390. List<String> tag_stack;
  391. bool code_tag = false;
  392. bool line_del = false;
  393. int pos = 0;
  394. while (pos < bbcode.length()) {
  395. int brk_pos = bbcode.find_char('[', pos);
  396. if (brk_pos < 0) {
  397. brk_pos = bbcode.length();
  398. }
  399. if (brk_pos > pos) {
  400. if (!line_del) {
  401. String text = bbcode.substr(pos, brk_pos - pos);
  402. if (code_tag || tag_stack.size() > 0) {
  403. xml_output.append(text.xml_escape());
  404. } else {
  405. Vector<String> lines = text.split("\n");
  406. for (int i = 0; i < lines.size(); i++) {
  407. if (i != 0) {
  408. xml_output.append("<para>");
  409. }
  410. xml_output.append(lines[i].xml_escape());
  411. if (i != lines.size() - 1) {
  412. xml_output.append("</para>\n");
  413. }
  414. }
  415. }
  416. }
  417. }
  418. if (brk_pos == bbcode.length()) {
  419. // Nothing else to add.
  420. break;
  421. }
  422. int brk_end = bbcode.find_char(']', brk_pos + 1);
  423. if (brk_end == -1) {
  424. if (!line_del) {
  425. String text = bbcode.substr(brk_pos);
  426. if (code_tag || tag_stack.size() > 0) {
  427. xml_output.append(text.xml_escape());
  428. } else {
  429. Vector<String> lines = text.split("\n");
  430. for (int i = 0; i < lines.size(); i++) {
  431. if (i != 0) {
  432. xml_output.append("<para>");
  433. }
  434. xml_output.append(lines[i].xml_escape());
  435. if (i != lines.size() - 1) {
  436. xml_output.append("</para>\n");
  437. }
  438. }
  439. }
  440. }
  441. break;
  442. }
  443. String tag = bbcode.substr(brk_pos + 1, brk_end - brk_pos - 1);
  444. if (tag.begins_with("/")) {
  445. bool tag_ok = tag_stack.size() && tag_stack.front()->get() == tag.substr(1);
  446. if (!tag_ok) {
  447. if (!line_del) {
  448. xml_output.append("[");
  449. }
  450. pos = brk_pos + 1;
  451. continue;
  452. }
  453. tag_stack.pop_front();
  454. pos = brk_end + 1;
  455. code_tag = false;
  456. if (tag == "/url") {
  457. xml_output.append("</a>");
  458. } else if (tag == "/code") {
  459. xml_output.append("</c>");
  460. } else if (tag == "/codeblock") {
  461. xml_output.append("</code>");
  462. } else if (tag == "/b") {
  463. xml_output.append("</b>");
  464. } else if (tag == "/i") {
  465. xml_output.append("</i>");
  466. } else if (tag == "/csharp") {
  467. xml_output.append("</code>");
  468. line_del = true;
  469. } else if (tag == "/codeblocks") {
  470. line_del = false;
  471. }
  472. } else if (code_tag) {
  473. xml_output.append("[");
  474. pos = brk_pos + 1;
  475. } else if (tag.begins_with("method ") || tag.begins_with("constructor ") || tag.begins_with("operator ") || tag.begins_with("member ") || tag.begins_with("signal ") || tag.begins_with("enum ") || tag.begins_with("constant ") || tag.begins_with("theme_item ") || tag.begins_with("param ")) {
  476. const int tag_end = tag.find_char(' ');
  477. const String link_tag = tag.substr(0, tag_end);
  478. const String link_target = tag.substr(tag_end + 1).lstrip(" ");
  479. const Vector<String> link_target_parts = link_target.split(".");
  480. if (link_target_parts.size() <= 0 || link_target_parts.size() > 2) {
  481. ERR_PRINT("Invalid reference format: '" + tag + "'.");
  482. xml_output.append("<c>");
  483. xml_output.append(tag);
  484. xml_output.append("</c>");
  485. pos = brk_end + 1;
  486. continue;
  487. }
  488. const TypeInterface *target_itype;
  489. StringName target_cname;
  490. if (link_target_parts.size() == 2) {
  491. target_itype = _get_type_or_null(TypeReference(link_target_parts[0]));
  492. if (!target_itype) {
  493. target_itype = _get_type_or_null(TypeReference("_" + link_target_parts[0]));
  494. }
  495. target_cname = link_target_parts[1];
  496. } else {
  497. target_itype = p_itype;
  498. target_cname = link_target_parts[0];
  499. }
  500. if (link_tag == "method") {
  501. _append_xml_method(xml_output, target_itype, target_cname, link_target, link_target_parts, p_itype);
  502. } else if (link_tag == "constructor") {
  503. // TODO: Support constructors?
  504. _append_xml_undeclared(xml_output, link_target);
  505. } else if (link_tag == "operator") {
  506. // TODO: Support operators?
  507. _append_xml_undeclared(xml_output, link_target);
  508. } else if (link_tag == "member") {
  509. _append_xml_member(xml_output, target_itype, target_cname, link_target, link_target_parts, p_itype);
  510. } else if (link_tag == "signal") {
  511. _append_xml_signal(xml_output, target_itype, target_cname, link_target, link_target_parts, p_itype);
  512. } else if (link_tag == "enum") {
  513. _append_xml_enum(xml_output, target_itype, target_cname, link_target, link_target_parts, p_itype);
  514. } else if (link_tag == "constant") {
  515. _append_xml_constant(xml_output, target_itype, target_cname, link_target, link_target_parts);
  516. } else if (link_tag == "param") {
  517. _append_xml_param(xml_output, link_target, p_is_signal);
  518. } else if (link_tag == "theme_item") {
  519. // We do not declare theme_items in any way in C#, so there is nothing to reference.
  520. _append_xml_undeclared(xml_output, link_target);
  521. }
  522. pos = brk_end + 1;
  523. } else if (doc->class_list.has(tag)) {
  524. if (tag == "Array" || tag == "Dictionary") {
  525. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE_COLLECTIONS ".");
  526. xml_output.append(tag);
  527. xml_output.append("\"/>");
  528. } else if (tag == "bool" || tag == "int") {
  529. xml_output.append("<see cref=\"");
  530. xml_output.append(tag);
  531. xml_output.append("\"/>");
  532. } else if (tag == "float") {
  533. xml_output.append("<see cref=\""
  534. #ifdef REAL_T_IS_DOUBLE
  535. "double"
  536. #else
  537. "float"
  538. #endif
  539. "\"/>");
  540. } else if (tag == "Variant") {
  541. xml_output.append("<see cref=\"Godot.Variant\"/>");
  542. } else if (tag == "String") {
  543. xml_output.append("<see cref=\"string\"/>");
  544. } else if (tag == "Nil") {
  545. xml_output.append("<see langword=\"null\"/>");
  546. } else if (tag.begins_with("@")) {
  547. // @GlobalScope, @GDScript, etc.
  548. xml_output.append("<c>");
  549. xml_output.append(tag);
  550. xml_output.append("</c>");
  551. } else if (tag == "PackedByteArray") {
  552. xml_output.append("<see cref=\"byte\"/>[]");
  553. } else if (tag == "PackedInt32Array") {
  554. xml_output.append("<see cref=\"int\"/>[]");
  555. } else if (tag == "PackedInt64Array") {
  556. xml_output.append("<see cref=\"long\"/>[]");
  557. } else if (tag == "PackedFloat32Array") {
  558. xml_output.append("<see cref=\"float\"/>[]");
  559. } else if (tag == "PackedFloat64Array") {
  560. xml_output.append("<see cref=\"double\"/>[]");
  561. } else if (tag == "PackedStringArray") {
  562. xml_output.append("<see cref=\"string\"/>[]");
  563. } else if (tag == "PackedVector2Array") {
  564. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Vector2\"/>[]");
  565. } else if (tag == "PackedVector3Array") {
  566. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Vector3\"/>[]");
  567. } else if (tag == "PackedColorArray") {
  568. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Color\"/>[]");
  569. } else if (tag == "PackedVector4Array") {
  570. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Vector4\"/>[]");
  571. } else {
  572. const TypeInterface *target_itype = _get_type_or_null(TypeReference(tag));
  573. if (!target_itype) {
  574. target_itype = _get_type_or_null(TypeReference("_" + tag));
  575. }
  576. if (target_itype) {
  577. if (!_validate_api_type(target_itype, p_itype)) {
  578. _append_xml_undeclared(xml_output, target_itype->proxy_name);
  579. } else {
  580. xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  581. xml_output.append(target_itype->proxy_name);
  582. xml_output.append("\"/>");
  583. }
  584. } else {
  585. ERR_PRINT("Cannot resolve type reference in documentation: '" + tag + "'.");
  586. xml_output.append("<c>");
  587. xml_output.append(tag);
  588. xml_output.append("</c>");
  589. }
  590. }
  591. pos = brk_end + 1;
  592. } else if (tag == "b") {
  593. xml_output.append("<b>");
  594. pos = brk_end + 1;
  595. tag_stack.push_front(tag);
  596. } else if (tag == "i") {
  597. xml_output.append("<i>");
  598. pos = brk_end + 1;
  599. tag_stack.push_front(tag);
  600. } else if (tag == "code" || tag.begins_with("code ")) {
  601. int end = bbcode.find_char('[', brk_end);
  602. if (end == -1) {
  603. end = bbcode.length();
  604. }
  605. String code = bbcode.substr(brk_end + 1, end - brk_end - 1);
  606. if (langword_check.has(code)) {
  607. xml_output.append("<see langword=\"");
  608. xml_output.append(code);
  609. xml_output.append("\"/>");
  610. pos = brk_end + code.length() + 8;
  611. } else {
  612. xml_output.append("<c>");
  613. code_tag = true;
  614. pos = brk_end + 1;
  615. tag_stack.push_front("code");
  616. }
  617. } else if (tag == "codeblock" || tag.begins_with("codeblock ")) {
  618. xml_output.append("<code>");
  619. code_tag = true;
  620. pos = brk_end + 1;
  621. tag_stack.push_front("codeblock");
  622. } else if (tag == "codeblocks") {
  623. line_del = true;
  624. pos = brk_end + 1;
  625. tag_stack.push_front(tag);
  626. } else if (tag == "csharp" || tag.begins_with("csharp ")) {
  627. xml_output.append("<code>");
  628. line_del = false;
  629. code_tag = true;
  630. pos = brk_end + 1;
  631. tag_stack.push_front("csharp");
  632. } else if (tag == "kbd") {
  633. // Keyboard combinations are not supported in xml comments.
  634. pos = brk_end + 1;
  635. tag_stack.push_front(tag);
  636. } else if (tag == "center") {
  637. // Center alignment is not supported in xml comments.
  638. pos = brk_end + 1;
  639. tag_stack.push_front(tag);
  640. } else if (tag == "br") {
  641. xml_output.append("\n"); // FIXME: Should use <para> instead. Luckily this tag isn't used for now.
  642. pos = brk_end + 1;
  643. } else if (tag == "u") {
  644. // Underline is not supported in Rider xml comments.
  645. pos = brk_end + 1;
  646. tag_stack.push_front(tag);
  647. } else if (tag == "s") {
  648. // Strikethrough is not supported in xml comments.
  649. pos = brk_end + 1;
  650. tag_stack.push_front(tag);
  651. } else if (tag == "url") {
  652. int end = bbcode.find_char('[', brk_end);
  653. if (end == -1) {
  654. end = bbcode.length();
  655. }
  656. String url = bbcode.substr(brk_end + 1, end - brk_end - 1);
  657. xml_output.append("<a href=\"");
  658. xml_output.append(url);
  659. xml_output.append("\">");
  660. xml_output.append(url);
  661. pos = brk_end + 1;
  662. tag_stack.push_front(tag);
  663. } else if (tag.begins_with("url=")) {
  664. String url = tag.substr(4);
  665. xml_output.append("<a href=\"");
  666. xml_output.append(url);
  667. xml_output.append("\">");
  668. pos = brk_end + 1;
  669. tag_stack.push_front("url");
  670. } else if (tag == "img") {
  671. int end = bbcode.find_char('[', brk_end);
  672. if (end == -1) {
  673. end = bbcode.length();
  674. }
  675. String image = bbcode.substr(brk_end + 1, end - brk_end - 1);
  676. // Not supported. Just append the bbcode.
  677. xml_output.append("[img]");
  678. xml_output.append(image);
  679. xml_output.append("[/img]");
  680. pos = end;
  681. tag_stack.push_front(tag);
  682. } else if (tag.begins_with("color=")) {
  683. // Not supported.
  684. pos = brk_end + 1;
  685. tag_stack.push_front("color");
  686. } else if (tag.begins_with("font=")) {
  687. // Not supported.
  688. pos = brk_end + 1;
  689. tag_stack.push_front("font");
  690. } else {
  691. if (!line_del) {
  692. // Ignore unrecognized tag.
  693. xml_output.append("[");
  694. }
  695. pos = brk_pos + 1;
  696. }
  697. }
  698. xml_output.append("</para>");
  699. return xml_output.as_string();
  700. }
  701. void BindingsGenerator::_append_text_method(StringBuilder &p_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) {
  702. if (p_link_target_parts[0] == name_cache.type_at_GlobalScope) {
  703. if (OS::get_singleton()->is_stdout_verbose()) {
  704. OS::get_singleton()->print("Cannot resolve @GlobalScope method reference in documentation: %s\n", p_link_target.utf8().get_data());
  705. }
  706. // TODO Map what we can
  707. _append_text_undeclared(p_output, p_link_target);
  708. } else if (!p_target_itype || !p_target_itype->is_object_type) {
  709. if (OS::get_singleton()->is_stdout_verbose()) {
  710. if (p_target_itype) {
  711. OS::get_singleton()->print("Cannot resolve method reference for non-GodotObject type in documentation: %s\n", p_link_target.utf8().get_data());
  712. } else {
  713. OS::get_singleton()->print("Cannot resolve type from method reference in documentation: %s\n", p_link_target.utf8().get_data());
  714. }
  715. }
  716. // TODO Map what we can
  717. _append_text_undeclared(p_output, p_link_target);
  718. } else {
  719. if (p_target_cname == "_init") {
  720. // The _init method is not declared in C#, reference the constructor instead
  721. p_output.append("'new " BINDINGS_NAMESPACE ".");
  722. p_output.append(p_target_itype->proxy_name);
  723. p_output.append("()'");
  724. } else {
  725. const MethodInterface *target_imethod = p_target_itype->find_method_by_name(p_target_cname);
  726. if (target_imethod) {
  727. p_output.append("'" BINDINGS_NAMESPACE ".");
  728. p_output.append(p_target_itype->proxy_name);
  729. p_output.append(".");
  730. p_output.append(target_imethod->proxy_name);
  731. p_output.append("(");
  732. bool first_key = true;
  733. for (const ArgumentInterface &iarg : target_imethod->arguments) {
  734. const TypeInterface *arg_type = _get_type_or_null(iarg.type);
  735. if (first_key) {
  736. first_key = false;
  737. } else {
  738. p_output.append(", ");
  739. }
  740. if (!arg_type) {
  741. ERR_PRINT("Cannot resolve argument type in documentation: '" + p_link_target + "'.");
  742. p_output.append(iarg.type.cname);
  743. continue;
  744. }
  745. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  746. p_output.append("Nullable<");
  747. }
  748. String arg_cs_type = arg_type->cs_type + _get_generic_type_parameters(*arg_type, iarg.type.generic_type_parameters);
  749. p_output.append(arg_cs_type.replacen("params ", ""));
  750. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  751. p_output.append(">");
  752. }
  753. }
  754. p_output.append(")'");
  755. } else {
  756. if (!p_target_itype->is_intentionally_ignored(p_link_target)) {
  757. ERR_PRINT("Cannot resolve method reference in documentation: '" + p_link_target + "'.");
  758. }
  759. _append_text_undeclared(p_output, p_link_target);
  760. }
  761. }
  762. }
  763. }
  764. void BindingsGenerator::_append_text_member(StringBuilder &p_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) {
  765. if (p_link_target.contains_char('/')) {
  766. // Properties with '/' (slash) in the name are not declared in C#, so there is nothing to reference.
  767. _append_text_undeclared(p_output, p_link_target);
  768. } else if (!p_target_itype || !p_target_itype->is_object_type) {
  769. if (OS::get_singleton()->is_stdout_verbose()) {
  770. if (p_target_itype) {
  771. OS::get_singleton()->print("Cannot resolve member reference for non-GodotObject type in documentation: %s\n", p_link_target.utf8().get_data());
  772. } else {
  773. OS::get_singleton()->print("Cannot resolve type from member reference in documentation: %s\n", p_link_target.utf8().get_data());
  774. }
  775. }
  776. // TODO Map what we can
  777. _append_text_undeclared(p_output, p_link_target);
  778. } else {
  779. const TypeInterface *current_itype = p_target_itype;
  780. const PropertyInterface *target_iprop = nullptr;
  781. while (target_iprop == nullptr && current_itype != nullptr) {
  782. target_iprop = current_itype->find_property_by_name(p_target_cname);
  783. if (target_iprop == nullptr) {
  784. current_itype = _get_type_or_null(TypeReference(current_itype->base_name));
  785. }
  786. }
  787. if (target_iprop) {
  788. p_output.append("'" BINDINGS_NAMESPACE ".");
  789. p_output.append(current_itype->proxy_name);
  790. p_output.append(".");
  791. p_output.append(target_iprop->proxy_name);
  792. p_output.append("'");
  793. } else {
  794. if (!p_target_itype->is_intentionally_ignored(p_link_target)) {
  795. ERR_PRINT("Cannot resolve member reference in documentation: '" + p_link_target + "'.");
  796. }
  797. _append_text_undeclared(p_output, p_link_target);
  798. }
  799. }
  800. }
  801. void BindingsGenerator::_append_text_signal(StringBuilder &p_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) {
  802. if (!p_target_itype || !p_target_itype->is_object_type) {
  803. if (OS::get_singleton()->is_stdout_verbose()) {
  804. if (p_target_itype) {
  805. OS::get_singleton()->print("Cannot resolve signal reference for non-GodotObject type in documentation: %s\n", p_link_target.utf8().get_data());
  806. } else {
  807. OS::get_singleton()->print("Cannot resolve type from signal reference in documentation: %s\n", p_link_target.utf8().get_data());
  808. }
  809. }
  810. // TODO Map what we can
  811. _append_text_undeclared(p_output, p_link_target);
  812. } else {
  813. const SignalInterface *target_isignal = p_target_itype->find_signal_by_name(p_target_cname);
  814. if (target_isignal) {
  815. p_output.append("'" BINDINGS_NAMESPACE ".");
  816. p_output.append(p_target_itype->proxy_name);
  817. p_output.append(".");
  818. p_output.append(target_isignal->proxy_name);
  819. p_output.append("'");
  820. } else {
  821. if (!p_target_itype->is_intentionally_ignored(p_link_target)) {
  822. ERR_PRINT("Cannot resolve signal reference in documentation: '" + p_link_target + "'.");
  823. }
  824. _append_text_undeclared(p_output, p_link_target);
  825. }
  826. }
  827. }
  828. void BindingsGenerator::_append_text_enum(StringBuilder &p_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) {
  829. const StringName search_cname = !p_target_itype ? p_target_cname : StringName(p_target_itype->name + "." + (String)p_target_cname);
  830. HashMap<StringName, TypeInterface>::ConstIterator enum_match = enum_types.find(search_cname);
  831. if (!enum_match && search_cname != p_target_cname) {
  832. enum_match = enum_types.find(p_target_cname);
  833. }
  834. if (enum_match) {
  835. const TypeInterface &target_enum_itype = enum_match->value;
  836. p_output.append("'" BINDINGS_NAMESPACE ".");
  837. p_output.append(target_enum_itype.proxy_name); // Includes nesting class if any
  838. p_output.append("'");
  839. } else {
  840. if (!p_target_itype->is_intentionally_ignored(p_link_target)) {
  841. ERR_PRINT("Cannot resolve enum reference in documentation: '" + p_link_target + "'.");
  842. }
  843. _append_text_undeclared(p_output, p_link_target);
  844. }
  845. }
  846. void BindingsGenerator::_append_text_constant(StringBuilder &p_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) {
  847. if (p_link_target_parts[0] == name_cache.type_at_GlobalScope) {
  848. _append_text_constant_in_global_scope(p_output, p_target_cname, p_link_target);
  849. } else if (!p_target_itype || !p_target_itype->is_object_type) {
  850. // Search in @GlobalScope as a last resort if no class was specified
  851. if (p_link_target_parts.size() == 1) {
  852. _append_text_constant_in_global_scope(p_output, p_target_cname, p_link_target);
  853. return;
  854. }
  855. if (OS::get_singleton()->is_stdout_verbose()) {
  856. if (p_target_itype) {
  857. OS::get_singleton()->print("Cannot resolve constant reference for non-GodotObject type in documentation: %s\n", p_link_target.utf8().get_data());
  858. } else {
  859. OS::get_singleton()->print("Cannot resolve type from constant reference in documentation: %s\n", p_link_target.utf8().get_data());
  860. }
  861. }
  862. // TODO Map what we can
  863. _append_text_undeclared(p_output, p_link_target);
  864. } else {
  865. // Try to find the constant in the current class
  866. if (p_target_itype->is_singleton_instance) {
  867. // Constants and enums are declared in the static singleton class.
  868. p_target_itype = &obj_types[p_target_itype->cname];
  869. }
  870. const ConstantInterface *target_iconst = find_constant_by_name(p_target_cname, p_target_itype->constants);
  871. if (target_iconst) {
  872. // Found constant in current class
  873. p_output.append("'" BINDINGS_NAMESPACE ".");
  874. p_output.append(p_target_itype->proxy_name);
  875. p_output.append(".");
  876. p_output.append(target_iconst->proxy_name);
  877. p_output.append("'");
  878. } else {
  879. // Try to find as enum constant in the current class
  880. const EnumInterface *target_ienum = nullptr;
  881. for (const EnumInterface &ienum : p_target_itype->enums) {
  882. target_ienum = &ienum;
  883. target_iconst = find_constant_by_name(p_target_cname, target_ienum->constants);
  884. if (target_iconst) {
  885. break;
  886. }
  887. }
  888. if (target_iconst) {
  889. p_output.append("'" BINDINGS_NAMESPACE ".");
  890. p_output.append(p_target_itype->proxy_name);
  891. p_output.append(".");
  892. p_output.append(target_ienum->proxy_name);
  893. p_output.append(".");
  894. p_output.append(target_iconst->proxy_name);
  895. p_output.append("'");
  896. } else if (p_link_target_parts.size() == 1) {
  897. // Also search in @GlobalScope as a last resort if no class was specified
  898. _append_text_constant_in_global_scope(p_output, p_target_cname, p_link_target);
  899. } else {
  900. if (!p_target_itype->is_intentionally_ignored(p_link_target)) {
  901. ERR_PRINT("Cannot resolve constant reference in documentation: '" + p_link_target + "'.");
  902. }
  903. _append_xml_undeclared(p_output, p_link_target);
  904. }
  905. }
  906. }
  907. }
  908. void BindingsGenerator::_append_text_constant_in_global_scope(StringBuilder &p_output, const String &p_target_cname, const String &p_link_target) {
  909. // Try to find as a global constant
  910. const ConstantInterface *target_iconst = find_constant_by_name(p_target_cname, global_constants);
  911. if (target_iconst) {
  912. // Found global constant
  913. p_output.append("'" BINDINGS_NAMESPACE "." BINDINGS_GLOBAL_SCOPE_CLASS ".");
  914. p_output.append(target_iconst->proxy_name);
  915. p_output.append("'");
  916. } else {
  917. // Try to find as global enum constant
  918. const EnumInterface *target_ienum = nullptr;
  919. for (const EnumInterface &ienum : global_enums) {
  920. target_ienum = &ienum;
  921. target_iconst = find_constant_by_name(p_target_cname, target_ienum->constants);
  922. if (target_iconst) {
  923. break;
  924. }
  925. }
  926. if (target_iconst) {
  927. p_output.append("'" BINDINGS_NAMESPACE ".");
  928. p_output.append(target_ienum->proxy_name);
  929. p_output.append(".");
  930. p_output.append(target_iconst->proxy_name);
  931. p_output.append("'");
  932. } else {
  933. ERR_PRINT("Cannot resolve global constant reference in documentation: '" + p_link_target + "'.");
  934. _append_text_undeclared(p_output, p_link_target);
  935. }
  936. }
  937. }
  938. void BindingsGenerator::_append_text_param(StringBuilder &p_output, const String &p_link_target) {
  939. const String link_target = snake_to_camel_case(p_link_target);
  940. p_output.append("'" + link_target + "'");
  941. }
  942. void BindingsGenerator::_append_text_undeclared(StringBuilder &p_output, const String &p_link_target) {
  943. p_output.append("'" + p_link_target + "'");
  944. }
  945. 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, const TypeInterface *p_source_itype) {
  946. if (p_link_target_parts[0] == name_cache.type_at_GlobalScope) {
  947. if (OS::get_singleton()->is_stdout_verbose()) {
  948. OS::get_singleton()->print("Cannot resolve @GlobalScope method reference in documentation: %s\n", p_link_target.utf8().get_data());
  949. }
  950. // TODO Map what we can
  951. _append_xml_undeclared(p_xml_output, p_link_target);
  952. } else if (!p_target_itype || !p_target_itype->is_object_type) {
  953. if (OS::get_singleton()->is_stdout_verbose()) {
  954. if (p_target_itype) {
  955. OS::get_singleton()->print("Cannot resolve method reference for non-GodotObject type in documentation: %s\n", p_link_target.utf8().get_data());
  956. } else {
  957. OS::get_singleton()->print("Cannot resolve type from method reference in documentation: %s\n", p_link_target.utf8().get_data());
  958. }
  959. }
  960. // TODO Map what we can
  961. _append_xml_undeclared(p_xml_output, p_link_target);
  962. } else {
  963. if (p_target_cname == "_init") {
  964. // The _init method is not declared in C#, reference the constructor instead
  965. p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  966. p_xml_output.append(p_target_itype->proxy_name);
  967. p_xml_output.append(".");
  968. p_xml_output.append(p_target_itype->proxy_name);
  969. p_xml_output.append("()\"/>");
  970. } else {
  971. const MethodInterface *target_imethod = p_target_itype->find_method_by_name(p_target_cname);
  972. if (target_imethod) {
  973. const String method_name = p_target_itype->proxy_name + "." + target_imethod->proxy_name;
  974. if (!_validate_api_type(p_target_itype, p_source_itype)) {
  975. _append_xml_undeclared(p_xml_output, method_name);
  976. } else {
  977. p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  978. p_xml_output.append(method_name);
  979. p_xml_output.append("(");
  980. bool first_key = true;
  981. for (const ArgumentInterface &iarg : target_imethod->arguments) {
  982. const TypeInterface *arg_type = _get_type_or_null(iarg.type);
  983. if (first_key) {
  984. first_key = false;
  985. } else {
  986. p_xml_output.append(", ");
  987. }
  988. if (!arg_type) {
  989. ERR_PRINT("Cannot resolve argument type in documentation: '" + p_link_target + "'.");
  990. p_xml_output.append(iarg.type.cname);
  991. continue;
  992. }
  993. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  994. p_xml_output.append("Nullable{");
  995. }
  996. String arg_cs_type = arg_type->cs_type + _get_generic_type_parameters(*arg_type, iarg.type.generic_type_parameters);
  997. p_xml_output.append(arg_cs_type.replacen("<", "{").replacen(">", "}").replacen("params ", ""));
  998. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  999. p_xml_output.append("}");
  1000. }
  1001. }
  1002. p_xml_output.append(")\"/>");
  1003. }
  1004. } else {
  1005. if (!p_target_itype->is_intentionally_ignored(p_link_target)) {
  1006. ERR_PRINT("Cannot resolve method reference in documentation: '" + p_link_target + "'.");
  1007. }
  1008. _append_xml_undeclared(p_xml_output, p_link_target);
  1009. }
  1010. }
  1011. }
  1012. }
  1013. 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, const TypeInterface *p_source_itype) {
  1014. if (p_link_target.contains_char('/')) {
  1015. // Properties with '/' (slash) in the name are not declared in C#, so there is nothing to reference.
  1016. _append_xml_undeclared(p_xml_output, p_link_target);
  1017. } else if (!p_target_itype || !p_target_itype->is_object_type) {
  1018. if (OS::get_singleton()->is_stdout_verbose()) {
  1019. if (p_target_itype) {
  1020. OS::get_singleton()->print("Cannot resolve member reference for non-GodotObject type in documentation: %s\n", p_link_target.utf8().get_data());
  1021. } else {
  1022. OS::get_singleton()->print("Cannot resolve type from member reference in documentation: %s\n", p_link_target.utf8().get_data());
  1023. }
  1024. }
  1025. // TODO Map what we can
  1026. _append_xml_undeclared(p_xml_output, p_link_target);
  1027. } else {
  1028. const TypeInterface *current_itype = p_target_itype;
  1029. const PropertyInterface *target_iprop = nullptr;
  1030. while (target_iprop == nullptr && current_itype != nullptr) {
  1031. target_iprop = current_itype->find_property_by_name(p_target_cname);
  1032. if (target_iprop == nullptr) {
  1033. current_itype = _get_type_or_null(TypeReference(current_itype->base_name));
  1034. }
  1035. }
  1036. if (target_iprop) {
  1037. const String member_name = current_itype->proxy_name + "." + target_iprop->proxy_name;
  1038. if (!_validate_api_type(p_target_itype, p_source_itype)) {
  1039. _append_xml_undeclared(p_xml_output, member_name);
  1040. } else {
  1041. p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  1042. p_xml_output.append(member_name);
  1043. p_xml_output.append("\"/>");
  1044. }
  1045. } else {
  1046. if (!p_target_itype->is_intentionally_ignored(p_link_target)) {
  1047. ERR_PRINT("Cannot resolve member reference in documentation: '" + p_link_target + "'.");
  1048. }
  1049. _append_xml_undeclared(p_xml_output, p_link_target);
  1050. }
  1051. }
  1052. }
  1053. void BindingsGenerator::_append_xml_signal(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts, const TypeInterface *p_source_itype) {
  1054. if (!p_target_itype || !p_target_itype->is_object_type) {
  1055. if (OS::get_singleton()->is_stdout_verbose()) {
  1056. if (p_target_itype) {
  1057. OS::get_singleton()->print("Cannot resolve signal reference for non-GodotObject type in documentation: %s\n", p_link_target.utf8().get_data());
  1058. } else {
  1059. OS::get_singleton()->print("Cannot resolve type from signal reference in documentation: %s\n", p_link_target.utf8().get_data());
  1060. }
  1061. }
  1062. // TODO Map what we can
  1063. _append_xml_undeclared(p_xml_output, p_link_target);
  1064. } else {
  1065. const SignalInterface *target_isignal = p_target_itype->find_signal_by_name(p_target_cname);
  1066. if (target_isignal) {
  1067. const String signal_name = p_target_itype->proxy_name + "." + target_isignal->proxy_name;
  1068. if (!_validate_api_type(p_target_itype, p_source_itype)) {
  1069. _append_xml_undeclared(p_xml_output, signal_name);
  1070. } else {
  1071. p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  1072. p_xml_output.append(signal_name);
  1073. p_xml_output.append("\"/>");
  1074. }
  1075. } else {
  1076. if (!p_target_itype->is_intentionally_ignored(p_link_target)) {
  1077. ERR_PRINT("Cannot resolve signal reference in documentation: '" + p_link_target + "'.");
  1078. }
  1079. _append_xml_undeclared(p_xml_output, p_link_target);
  1080. }
  1081. }
  1082. }
  1083. 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, const TypeInterface *p_source_itype) {
  1084. const StringName search_cname = !p_target_itype ? p_target_cname : StringName(p_target_itype->name + "." + (String)p_target_cname);
  1085. HashMap<StringName, TypeInterface>::ConstIterator enum_match = enum_types.find(search_cname);
  1086. if (!enum_match && search_cname != p_target_cname) {
  1087. enum_match = enum_types.find(p_target_cname);
  1088. }
  1089. if (enum_match) {
  1090. const TypeInterface &target_enum_itype = enum_match->value;
  1091. if (!_validate_api_type(p_target_itype, p_source_itype)) {
  1092. _append_xml_undeclared(p_xml_output, target_enum_itype.proxy_name);
  1093. } else {
  1094. p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  1095. p_xml_output.append(target_enum_itype.proxy_name); // Includes nesting class if any
  1096. p_xml_output.append("\"/>");
  1097. }
  1098. } else {
  1099. if (!p_target_itype->is_intentionally_ignored(p_link_target)) {
  1100. ERR_PRINT("Cannot resolve enum reference in documentation: '" + p_link_target + "'.");
  1101. }
  1102. _append_xml_undeclared(p_xml_output, p_link_target);
  1103. }
  1104. }
  1105. 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) {
  1106. if (p_link_target_parts[0] == name_cache.type_at_GlobalScope) {
  1107. _append_xml_constant_in_global_scope(p_xml_output, p_target_cname, p_link_target);
  1108. } else if (!p_target_itype || !p_target_itype->is_object_type) {
  1109. // Search in @GlobalScope as a last resort if no class was specified
  1110. if (p_link_target_parts.size() == 1) {
  1111. _append_xml_constant_in_global_scope(p_xml_output, p_target_cname, p_link_target);
  1112. return;
  1113. }
  1114. if (OS::get_singleton()->is_stdout_verbose()) {
  1115. if (p_target_itype) {
  1116. OS::get_singleton()->print("Cannot resolve constant reference for non-GodotObject type in documentation: %s\n", p_link_target.utf8().get_data());
  1117. } else {
  1118. OS::get_singleton()->print("Cannot resolve type from constant reference in documentation: %s\n", p_link_target.utf8().get_data());
  1119. }
  1120. }
  1121. // TODO Map what we can
  1122. _append_xml_undeclared(p_xml_output, p_link_target);
  1123. } else {
  1124. // Try to find the constant in the current class
  1125. if (p_target_itype->is_singleton_instance) {
  1126. // Constants and enums are declared in the static singleton class.
  1127. p_target_itype = &obj_types[p_target_itype->cname];
  1128. }
  1129. const ConstantInterface *target_iconst = find_constant_by_name(p_target_cname, p_target_itype->constants);
  1130. if (target_iconst) {
  1131. // Found constant in current class
  1132. p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  1133. p_xml_output.append(p_target_itype->proxy_name);
  1134. p_xml_output.append(".");
  1135. p_xml_output.append(target_iconst->proxy_name);
  1136. p_xml_output.append("\"/>");
  1137. } else {
  1138. // Try to find as enum constant in the current class
  1139. const EnumInterface *target_ienum = nullptr;
  1140. for (const EnumInterface &ienum : p_target_itype->enums) {
  1141. target_ienum = &ienum;
  1142. target_iconst = find_constant_by_name(p_target_cname, target_ienum->constants);
  1143. if (target_iconst) {
  1144. break;
  1145. }
  1146. }
  1147. if (target_iconst) {
  1148. p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  1149. p_xml_output.append(p_target_itype->proxy_name);
  1150. p_xml_output.append(".");
  1151. p_xml_output.append(target_ienum->proxy_name);
  1152. p_xml_output.append(".");
  1153. p_xml_output.append(target_iconst->proxy_name);
  1154. p_xml_output.append("\"/>");
  1155. } else if (p_link_target_parts.size() == 1) {
  1156. // Also search in @GlobalScope as a last resort if no class was specified
  1157. _append_xml_constant_in_global_scope(p_xml_output, p_target_cname, p_link_target);
  1158. } else {
  1159. if (!p_target_itype->is_intentionally_ignored(p_link_target)) {
  1160. ERR_PRINT("Cannot resolve constant reference in documentation: '" + p_link_target + "'.");
  1161. }
  1162. _append_xml_undeclared(p_xml_output, p_link_target);
  1163. }
  1164. }
  1165. }
  1166. }
  1167. void BindingsGenerator::_append_xml_constant_in_global_scope(StringBuilder &p_xml_output, const String &p_target_cname, const String &p_link_target) {
  1168. // Try to find as a global constant
  1169. const ConstantInterface *target_iconst = find_constant_by_name(p_target_cname, global_constants);
  1170. if (target_iconst) {
  1171. // Found global constant
  1172. p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "." BINDINGS_GLOBAL_SCOPE_CLASS ".");
  1173. p_xml_output.append(target_iconst->proxy_name);
  1174. p_xml_output.append("\"/>");
  1175. } else {
  1176. // Try to find as global enum constant
  1177. const EnumInterface *target_ienum = nullptr;
  1178. for (const EnumInterface &ienum : global_enums) {
  1179. target_ienum = &ienum;
  1180. target_iconst = find_constant_by_name(p_target_cname, target_ienum->constants);
  1181. if (target_iconst) {
  1182. break;
  1183. }
  1184. }
  1185. if (target_iconst) {
  1186. p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
  1187. p_xml_output.append(target_ienum->proxy_name);
  1188. p_xml_output.append(".");
  1189. p_xml_output.append(target_iconst->proxy_name);
  1190. p_xml_output.append("\"/>");
  1191. } else {
  1192. ERR_PRINT("Cannot resolve global constant reference in documentation: '" + p_link_target + "'.");
  1193. _append_xml_undeclared(p_xml_output, p_link_target);
  1194. }
  1195. }
  1196. }
  1197. void BindingsGenerator::_append_xml_param(StringBuilder &p_xml_output, const String &p_link_target, bool p_is_signal) {
  1198. const String link_target = snake_to_camel_case(p_link_target);
  1199. if (!p_is_signal) {
  1200. p_xml_output.append("<paramref name=\"");
  1201. p_xml_output.append(link_target);
  1202. p_xml_output.append("\"/>");
  1203. } else {
  1204. // Documentation in C# is added to an event, not the delegate itself;
  1205. // as such, we treat these parameters as codeblocks instead.
  1206. // See: https://github.com/godotengine/godot/pull/65529
  1207. _append_xml_undeclared(p_xml_output, link_target);
  1208. }
  1209. }
  1210. void BindingsGenerator::_append_xml_undeclared(StringBuilder &p_xml_output, const String &p_link_target) {
  1211. p_xml_output.append("<c>");
  1212. p_xml_output.append(p_link_target);
  1213. p_xml_output.append("</c>");
  1214. }
  1215. bool BindingsGenerator::_validate_api_type(const TypeInterface *p_target_itype, const TypeInterface *p_source_itype) {
  1216. static constexpr const char *api_types[5] = {
  1217. "Core",
  1218. "Editor",
  1219. "Extension",
  1220. "Editor Extension",
  1221. "None",
  1222. };
  1223. const ClassDB::APIType target_api = p_target_itype ? p_target_itype->api_type : ClassDB::API_NONE;
  1224. ERR_FAIL_INDEX_V((int)target_api, 5, false);
  1225. const ClassDB::APIType source_api = p_source_itype ? p_source_itype->api_type : ClassDB::API_NONE;
  1226. ERR_FAIL_INDEX_V((int)source_api, 5, false);
  1227. bool validate = false;
  1228. switch (target_api) {
  1229. case ClassDB::API_NONE:
  1230. case ClassDB::API_CORE:
  1231. default:
  1232. validate = true;
  1233. break;
  1234. case ClassDB::API_EDITOR:
  1235. validate = source_api == ClassDB::API_EDITOR || source_api == ClassDB::API_EDITOR_EXTENSION;
  1236. break;
  1237. case ClassDB::API_EXTENSION:
  1238. validate = source_api == ClassDB::API_EXTENSION || source_api == ClassDB::API_EDITOR_EXTENSION;
  1239. break;
  1240. case ClassDB::API_EDITOR_EXTENSION:
  1241. validate = source_api == ClassDB::API_EDITOR_EXTENSION;
  1242. break;
  1243. }
  1244. if (!validate) {
  1245. const String target_name = p_target_itype ? p_target_itype->proxy_name : "@GlobalScope";
  1246. const String source_name = p_source_itype ? p_source_itype->proxy_name : "@GlobalScope";
  1247. WARN_PRINT(vformat("Type '%s' has API level '%s'; it cannot be referenced by type '%s' with API level '%s'.",
  1248. target_name, api_types[target_api], source_name, api_types[source_api]));
  1249. }
  1250. return validate;
  1251. }
  1252. int BindingsGenerator::_determine_enum_prefix(const EnumInterface &p_ienum) {
  1253. CRASH_COND(p_ienum.constants.is_empty());
  1254. const ConstantInterface &front_iconstant = p_ienum.constants.front()->get();
  1255. Vector<String> front_parts = front_iconstant.name.split("_", /* p_allow_empty: */ true);
  1256. int candidate_len = front_parts.size() - 1;
  1257. if (candidate_len == 0) {
  1258. return 0;
  1259. }
  1260. for (const ConstantInterface &iconstant : p_ienum.constants) {
  1261. Vector<String> parts = iconstant.name.split("_", /* p_allow_empty: */ true);
  1262. int i;
  1263. for (i = 0; i < candidate_len && i < parts.size(); i++) {
  1264. if (front_parts[i] != parts[i]) {
  1265. // HARDCODED: Some Flag enums have the prefix 'FLAG_' for everything except 'FLAGS_DEFAULT' (same for 'METHOD_FLAG_' and'METHOD_FLAGS_DEFAULT').
  1266. bool hardcoded_exc = (i == candidate_len - 1 && ((front_parts[i] == "FLAGS" && parts[i] == "FLAG") || (front_parts[i] == "FLAG" && parts[i] == "FLAGS")));
  1267. if (!hardcoded_exc) {
  1268. break;
  1269. }
  1270. }
  1271. }
  1272. candidate_len = i;
  1273. if (candidate_len == 0) {
  1274. return 0;
  1275. }
  1276. }
  1277. return candidate_len;
  1278. }
  1279. void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumInterface &p_ienum, int p_prefix_length) {
  1280. if (p_prefix_length > 0) {
  1281. for (ConstantInterface &iconstant : p_ienum.constants) {
  1282. int curr_prefix_length = p_prefix_length;
  1283. String constant_name = iconstant.name;
  1284. Vector<String> parts = constant_name.split("_", /* p_allow_empty: */ true);
  1285. if (parts.size() <= curr_prefix_length) {
  1286. continue;
  1287. }
  1288. if (is_digit(parts[curr_prefix_length][0])) {
  1289. // The name of enum constants may begin with a numeric digit when strip from the enum prefix,
  1290. // so we make the prefix for this constant one word shorter in those cases.
  1291. for (curr_prefix_length = curr_prefix_length - 1; curr_prefix_length > 0; curr_prefix_length--) {
  1292. if (!is_digit(parts[curr_prefix_length][0])) {
  1293. break;
  1294. }
  1295. }
  1296. }
  1297. constant_name = "";
  1298. for (int i = curr_prefix_length; i < parts.size(); i++) {
  1299. if (i > curr_prefix_length) {
  1300. constant_name += "_";
  1301. }
  1302. constant_name += parts[i];
  1303. }
  1304. iconstant.proxy_name = snake_to_pascal_case(constant_name, true);
  1305. }
  1306. }
  1307. }
  1308. Error BindingsGenerator::_populate_method_icalls_table(const TypeInterface &p_itype) {
  1309. for (const MethodInterface &imethod : p_itype.methods) {
  1310. if (imethod.is_virtual) {
  1311. continue;
  1312. }
  1313. const TypeInterface *return_type = _get_type_or_null(imethod.return_type);
  1314. ERR_FAIL_NULL_V_MSG(return_type, ERR_BUG, "Return type '" + imethod.return_type.cname + "' was not found.");
  1315. String im_unique_sig = get_ret_unique_sig(return_type) + ",CallMethodBind";
  1316. if (!imethod.is_static) {
  1317. im_unique_sig += ",CallInstance";
  1318. }
  1319. // Get arguments information
  1320. for (const ArgumentInterface &iarg : imethod.arguments) {
  1321. const TypeInterface *arg_type = _get_type_or_null(iarg.type);
  1322. ERR_FAIL_NULL_V_MSG(arg_type, ERR_BUG, "Argument type '" + iarg.type.cname + "' was not found.");
  1323. im_unique_sig += ",";
  1324. im_unique_sig += get_arg_unique_sig(*arg_type);
  1325. }
  1326. // godot_icall_{argc}_{icallcount}
  1327. String icall_method = ICALL_PREFIX;
  1328. icall_method += itos(imethod.arguments.size());
  1329. icall_method += "_";
  1330. icall_method += itos(method_icalls.size());
  1331. InternalCall im_icall = InternalCall(p_itype.api_type, icall_method, im_unique_sig);
  1332. im_icall.is_vararg = imethod.is_vararg;
  1333. im_icall.is_static = imethod.is_static;
  1334. im_icall.return_type = imethod.return_type;
  1335. for (const List<ArgumentInterface>::Element *F = imethod.arguments.front(); F; F = F->next()) {
  1336. im_icall.argument_types.push_back(F->get().type);
  1337. }
  1338. List<InternalCall>::Element *match = method_icalls.find(im_icall);
  1339. if (match) {
  1340. if (p_itype.api_type != ClassDB::API_EDITOR) {
  1341. match->get().editor_only = false;
  1342. }
  1343. method_icalls_map.insert(&imethod, &match->get());
  1344. } else {
  1345. List<InternalCall>::Element *added = method_icalls.push_back(im_icall);
  1346. method_icalls_map.insert(&imethod, &added->get());
  1347. }
  1348. }
  1349. return OK;
  1350. }
  1351. void BindingsGenerator::_generate_array_extensions(StringBuilder &p_output) {
  1352. p_output.append("namespace " BINDINGS_NAMESPACE ";\n\n");
  1353. p_output.append("using System;\n\n");
  1354. // The class where we put the extensions doesn't matter, so just use "GD".
  1355. p_output.append("public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n{");
  1356. #define ARRAY_IS_EMPTY(m_type) \
  1357. p_output.append("\n" INDENT1 "/// <summary>\n"); \
  1358. p_output.append(INDENT1 "/// Returns true if this " #m_type " array is empty or doesn't exist.\n"); \
  1359. p_output.append(INDENT1 "/// </summary>\n"); \
  1360. p_output.append(INDENT1 "/// <param name=\"instance\">The " #m_type " array check.</param>\n"); \
  1361. p_output.append(INDENT1 "/// <returns>Whether or not the array is empty.</returns>\n"); \
  1362. p_output.append(INDENT1 "public static bool IsEmpty(this " #m_type "[] instance)\n"); \
  1363. p_output.append(OPEN_BLOCK_L1); \
  1364. p_output.append(INDENT2 "return instance == null || instance.Length == 0;\n"); \
  1365. p_output.append(INDENT1 CLOSE_BLOCK);
  1366. #define ARRAY_JOIN(m_type) \
  1367. p_output.append("\n" INDENT1 "/// <summary>\n"); \
  1368. p_output.append(INDENT1 "/// Converts this " #m_type " array to a string delimited by the given string.\n"); \
  1369. p_output.append(INDENT1 "/// </summary>\n"); \
  1370. p_output.append(INDENT1 "/// <param name=\"instance\">The " #m_type " array to convert.</param>\n"); \
  1371. p_output.append(INDENT1 "/// <param name=\"delimiter\">The delimiter to use between items.</param>\n"); \
  1372. p_output.append(INDENT1 "/// <returns>A single string with all items.</returns>\n"); \
  1373. p_output.append(INDENT1 "public static string Join(this " #m_type "[] instance, string delimiter = \", \")\n"); \
  1374. p_output.append(OPEN_BLOCK_L1); \
  1375. p_output.append(INDENT2 "return String.Join(delimiter, instance);\n"); \
  1376. p_output.append(INDENT1 CLOSE_BLOCK);
  1377. #define ARRAY_STRINGIFY(m_type) \
  1378. p_output.append("\n" INDENT1 "/// <summary>\n"); \
  1379. p_output.append(INDENT1 "/// Converts this " #m_type " array to a string with brackets.\n"); \
  1380. p_output.append(INDENT1 "/// </summary>\n"); \
  1381. p_output.append(INDENT1 "/// <param name=\"instance\">The " #m_type " array to convert.</param>\n"); \
  1382. p_output.append(INDENT1 "/// <returns>A single string with all items.</returns>\n"); \
  1383. p_output.append(INDENT1 "public static string Stringify(this " #m_type "[] instance)\n"); \
  1384. p_output.append(OPEN_BLOCK_L1); \
  1385. p_output.append(INDENT2 "return \"[\" + instance.Join() + \"]\";\n"); \
  1386. p_output.append(INDENT1 CLOSE_BLOCK);
  1387. #define ARRAY_ALL(m_type) \
  1388. ARRAY_IS_EMPTY(m_type) \
  1389. ARRAY_JOIN(m_type) \
  1390. ARRAY_STRINGIFY(m_type)
  1391. ARRAY_ALL(byte);
  1392. ARRAY_ALL(int);
  1393. ARRAY_ALL(long);
  1394. ARRAY_ALL(float);
  1395. ARRAY_ALL(double);
  1396. ARRAY_ALL(string);
  1397. ARRAY_ALL(Color);
  1398. ARRAY_ALL(Vector2);
  1399. ARRAY_ALL(Vector2I);
  1400. ARRAY_ALL(Vector3);
  1401. ARRAY_ALL(Vector3I);
  1402. ARRAY_ALL(Vector4);
  1403. ARRAY_ALL(Vector4I);
  1404. #undef ARRAY_ALL
  1405. #undef ARRAY_IS_EMPTY
  1406. #undef ARRAY_JOIN
  1407. #undef ARRAY_STRINGIFY
  1408. p_output.append(CLOSE_BLOCK); // End of GD class.
  1409. }
  1410. void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
  1411. // Constants (in partial GD class)
  1412. p_output.append("namespace " BINDINGS_NAMESPACE ";\n\n");
  1413. p_output.append("public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n" OPEN_BLOCK);
  1414. for (const ConstantInterface &iconstant : global_constants) {
  1415. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  1416. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), nullptr);
  1417. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1418. if (summary_lines.size()) {
  1419. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  1420. for (int i = 0; i < summary_lines.size(); i++) {
  1421. p_output.append(INDENT1 "/// ");
  1422. p_output.append(summary_lines[i]);
  1423. p_output.append("\n");
  1424. }
  1425. p_output.append(INDENT1 "/// </summary>");
  1426. }
  1427. }
  1428. p_output.append(MEMBER_BEGIN "public const long ");
  1429. p_output.append(iconstant.proxy_name);
  1430. p_output.append(" = ");
  1431. p_output.append(itos(iconstant.value));
  1432. p_output.append(";");
  1433. }
  1434. if (!global_constants.is_empty()) {
  1435. p_output.append("\n");
  1436. }
  1437. p_output.append(CLOSE_BLOCK); // end of GD class
  1438. // Enums
  1439. for (const EnumInterface &ienum : global_enums) {
  1440. CRASH_COND(ienum.constants.is_empty());
  1441. String enum_proxy_name = ienum.proxy_name;
  1442. bool enum_in_static_class = false;
  1443. if (enum_proxy_name.find_char('.') > 0) {
  1444. enum_in_static_class = true;
  1445. String enum_class_name = enum_proxy_name.get_slicec('.', 0);
  1446. enum_proxy_name = enum_proxy_name.get_slicec('.', 1);
  1447. CRASH_COND(enum_class_name != "Variant"); // Hard-coded...
  1448. _log("Declaring global enum '%s' inside struct '%s'\n", enum_proxy_name.utf8().get_data(), enum_class_name.utf8().get_data());
  1449. p_output << "\npublic partial struct " << enum_class_name << "\n" OPEN_BLOCK;
  1450. }
  1451. const String maybe_indent = !enum_in_static_class ? "" : INDENT1;
  1452. if (ienum.is_flags) {
  1453. p_output << "\n"
  1454. << maybe_indent << "[System.Flags]";
  1455. }
  1456. p_output << "\n"
  1457. << maybe_indent << "public enum " << enum_proxy_name << " : long"
  1458. << "\n"
  1459. << maybe_indent << OPEN_BLOCK;
  1460. for (const ConstantInterface &iconstant : ienum.constants) {
  1461. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  1462. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), nullptr);
  1463. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1464. if (summary_lines.size()) {
  1465. p_output << maybe_indent << INDENT1 "/// <summary>\n";
  1466. for (int i = 0; i < summary_lines.size(); i++) {
  1467. p_output << maybe_indent << INDENT1 "/// " << summary_lines[i] << "\n";
  1468. }
  1469. p_output << maybe_indent << INDENT1 "/// </summary>\n";
  1470. }
  1471. }
  1472. p_output << maybe_indent << INDENT1
  1473. << iconstant.proxy_name
  1474. << " = "
  1475. << itos(iconstant.value)
  1476. << ",\n";
  1477. }
  1478. p_output << maybe_indent << CLOSE_BLOCK;
  1479. if (enum_in_static_class) {
  1480. p_output << CLOSE_BLOCK;
  1481. }
  1482. }
  1483. }
  1484. Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
  1485. ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
  1486. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  1487. ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE);
  1488. if (!DirAccess::exists(p_proj_dir)) {
  1489. Error err = da->make_dir_recursive(p_proj_dir);
  1490. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Cannot create directory '" + p_proj_dir + "'.");
  1491. }
  1492. da->change_dir(p_proj_dir);
  1493. da->make_dir("Generated");
  1494. da->make_dir("Generated/GodotObjects");
  1495. String base_gen_dir = path::join(p_proj_dir, "Generated");
  1496. String godot_objects_gen_dir = path::join(base_gen_dir, "GodotObjects");
  1497. Vector<String> compile_items;
  1498. // Generate source file for global scope constants and enums
  1499. {
  1500. StringBuilder constants_source;
  1501. _generate_global_constants(constants_source);
  1502. String output_file = path::join(base_gen_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_constants.cs");
  1503. Error save_err = _save_file(output_file, constants_source);
  1504. if (save_err != OK) {
  1505. return save_err;
  1506. }
  1507. compile_items.push_back(output_file);
  1508. }
  1509. // Generate source file for array extensions
  1510. {
  1511. StringBuilder extensions_source;
  1512. _generate_array_extensions(extensions_source);
  1513. String output_file = path::join(base_gen_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_extensions.cs");
  1514. Error save_err = _save_file(output_file, extensions_source);
  1515. if (save_err != OK) {
  1516. return save_err;
  1517. }
  1518. compile_items.push_back(output_file);
  1519. }
  1520. for (const KeyValue<StringName, TypeInterface> &E : obj_types) {
  1521. const TypeInterface &itype = E.value;
  1522. if (itype.api_type == ClassDB::API_EDITOR) {
  1523. continue;
  1524. }
  1525. String output_file = path::join(godot_objects_gen_dir, itype.proxy_name + ".cs");
  1526. Error err = _generate_cs_type(itype, output_file);
  1527. if (err == ERR_SKIP) {
  1528. continue;
  1529. }
  1530. if (err != OK) {
  1531. return err;
  1532. }
  1533. compile_items.push_back(output_file);
  1534. }
  1535. // Generate source file for built-in type constructor dictionary.
  1536. {
  1537. StringBuilder cs_built_in_ctors_content;
  1538. cs_built_in_ctors_content.append("namespace " BINDINGS_NAMESPACE ";\n\n");
  1539. cs_built_in_ctors_content.append("using System;\n"
  1540. "using System.Collections.Generic;\n"
  1541. "\n");
  1542. cs_built_in_ctors_content.append("internal static class " BINDINGS_CLASS_CONSTRUCTOR "\n{");
  1543. cs_built_in_ctors_content.append(MEMBER_BEGIN "internal static readonly Dictionary<string, Func<IntPtr, GodotObject>> " BINDINGS_CLASS_CONSTRUCTOR_DICTIONARY ";\n");
  1544. cs_built_in_ctors_content.append(MEMBER_BEGIN "public static GodotObject Invoke(string nativeTypeNameStr, IntPtr nativeObjectPtr)\n");
  1545. cs_built_in_ctors_content.append(INDENT1 OPEN_BLOCK);
  1546. cs_built_in_ctors_content.append(INDENT2 "if (!" BINDINGS_CLASS_CONSTRUCTOR_DICTIONARY ".TryGetValue(nativeTypeNameStr, out var constructor))\n");
  1547. cs_built_in_ctors_content.append(INDENT3 "throw new InvalidOperationException(\"Wrapper class not found for type: \" + nativeTypeNameStr);\n");
  1548. cs_built_in_ctors_content.append(INDENT2 "return constructor(nativeObjectPtr);\n");
  1549. cs_built_in_ctors_content.append(INDENT1 CLOSE_BLOCK);
  1550. cs_built_in_ctors_content.append(MEMBER_BEGIN "static " BINDINGS_CLASS_CONSTRUCTOR "()\n");
  1551. cs_built_in_ctors_content.append(INDENT1 OPEN_BLOCK);
  1552. cs_built_in_ctors_content.append(INDENT2 BINDINGS_CLASS_CONSTRUCTOR_DICTIONARY " = new();\n");
  1553. for (const KeyValue<StringName, TypeInterface> &E : obj_types) {
  1554. const TypeInterface &itype = E.value;
  1555. if (itype.api_type != ClassDB::API_CORE || itype.is_singleton_instance) {
  1556. continue;
  1557. }
  1558. if (itype.is_deprecated) {
  1559. cs_built_in_ctors_content.append("#pragma warning disable CS0618\n");
  1560. }
  1561. cs_built_in_ctors_content.append(INDENT2 BINDINGS_CLASS_CONSTRUCTOR_DICTIONARY ".Add(\"");
  1562. cs_built_in_ctors_content.append(itype.name);
  1563. cs_built_in_ctors_content.append("\", " CS_PARAM_INSTANCE " => new ");
  1564. cs_built_in_ctors_content.append(itype.proxy_name);
  1565. if (itype.is_singleton && !itype.is_compat_singleton) {
  1566. cs_built_in_ctors_content.append("Instance");
  1567. }
  1568. cs_built_in_ctors_content.append("(" CS_PARAM_INSTANCE "));\n");
  1569. if (itype.is_deprecated) {
  1570. cs_built_in_ctors_content.append("#pragma warning restore CS0618\n");
  1571. }
  1572. }
  1573. cs_built_in_ctors_content.append(INDENT1 CLOSE_BLOCK);
  1574. cs_built_in_ctors_content.append(CLOSE_BLOCK);
  1575. String constructors_file = path::join(base_gen_dir, BINDINGS_CLASS_CONSTRUCTOR ".cs");
  1576. Error err = _save_file(constructors_file, cs_built_in_ctors_content);
  1577. if (err != OK) {
  1578. return err;
  1579. }
  1580. compile_items.push_back(constructors_file);
  1581. }
  1582. // Generate native calls
  1583. StringBuilder cs_icalls_content;
  1584. cs_icalls_content.append("namespace " BINDINGS_NAMESPACE ";\n\n");
  1585. cs_icalls_content.append("using System;\n"
  1586. "using System.Diagnostics.CodeAnalysis;\n"
  1587. "using System.Runtime.InteropServices;\n"
  1588. "using Godot.NativeInterop;\n"
  1589. "\n");
  1590. cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"InconsistentNaming\")]\n");
  1591. cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantUnsafeContext\")]\n");
  1592. cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantNameQualifier\")]\n");
  1593. cs_icalls_content.append("[System.Runtime.CompilerServices.SkipLocalsInit]\n");
  1594. cs_icalls_content.append("internal static class " BINDINGS_CLASS_NATIVECALLS "\n{");
  1595. cs_icalls_content.append(MEMBER_BEGIN "internal static ulong godot_api_hash = ");
  1596. cs_icalls_content.append(String::num_uint64(ClassDB::get_api_hash(ClassDB::API_CORE)) + ";\n");
  1597. cs_icalls_content.append(MEMBER_BEGIN "private const int VarArgsSpanThreshold = 10;\n");
  1598. for (const InternalCall &icall : method_icalls) {
  1599. if (icall.editor_only) {
  1600. continue;
  1601. }
  1602. Error err = _generate_cs_native_calls(icall, cs_icalls_content);
  1603. if (err != OK) {
  1604. return err;
  1605. }
  1606. }
  1607. cs_icalls_content.append(CLOSE_BLOCK);
  1608. String internal_methods_file = path::join(base_gen_dir, BINDINGS_CLASS_NATIVECALLS ".cs");
  1609. Error err = _save_file(internal_methods_file, cs_icalls_content);
  1610. if (err != OK) {
  1611. return err;
  1612. }
  1613. compile_items.push_back(internal_methods_file);
  1614. // Generate GeneratedIncludes.props
  1615. StringBuilder includes_props_content;
  1616. includes_props_content.append("<Project>\n"
  1617. " <ItemGroup>\n");
  1618. for (int i = 0; i < compile_items.size(); i++) {
  1619. String include = path::relative_to(compile_items[i], p_proj_dir).replace("/", "\\");
  1620. includes_props_content.append(" <Compile Include=\"" + include + "\" />\n");
  1621. }
  1622. includes_props_content.append(" </ItemGroup>\n"
  1623. "</Project>\n");
  1624. String includes_props_file = path::join(base_gen_dir, "GeneratedIncludes.props");
  1625. err = _save_file(includes_props_file, includes_props_content);
  1626. if (err != OK) {
  1627. return err;
  1628. }
  1629. return OK;
  1630. }
  1631. Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) {
  1632. ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
  1633. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  1634. ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE);
  1635. if (!DirAccess::exists(p_proj_dir)) {
  1636. Error err = da->make_dir_recursive(p_proj_dir);
  1637. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  1638. }
  1639. da->change_dir(p_proj_dir);
  1640. da->make_dir("Generated");
  1641. da->make_dir("Generated/GodotObjects");
  1642. String base_gen_dir = path::join(p_proj_dir, "Generated");
  1643. String godot_objects_gen_dir = path::join(base_gen_dir, "GodotObjects");
  1644. Vector<String> compile_items;
  1645. for (const KeyValue<StringName, TypeInterface> &E : obj_types) {
  1646. const TypeInterface &itype = E.value;
  1647. if (itype.api_type != ClassDB::API_EDITOR) {
  1648. continue;
  1649. }
  1650. String output_file = path::join(godot_objects_gen_dir, itype.proxy_name + ".cs");
  1651. Error err = _generate_cs_type(itype, output_file);
  1652. if (err == ERR_SKIP) {
  1653. continue;
  1654. }
  1655. if (err != OK) {
  1656. return err;
  1657. }
  1658. compile_items.push_back(output_file);
  1659. }
  1660. // Generate source file for editor type constructor dictionary.
  1661. {
  1662. StringBuilder cs_built_in_ctors_content;
  1663. cs_built_in_ctors_content.append("namespace " BINDINGS_NAMESPACE ";\n\n");
  1664. cs_built_in_ctors_content.append("internal static class " BINDINGS_CLASS_CONSTRUCTOR_EDITOR "\n{");
  1665. cs_built_in_ctors_content.append(MEMBER_BEGIN "private static void AddEditorConstructors()\n");
  1666. cs_built_in_ctors_content.append(INDENT1 OPEN_BLOCK);
  1667. cs_built_in_ctors_content.append(INDENT2 "var builtInMethodConstructors = " BINDINGS_CLASS_CONSTRUCTOR "." BINDINGS_CLASS_CONSTRUCTOR_DICTIONARY ";\n");
  1668. for (const KeyValue<StringName, TypeInterface> &E : obj_types) {
  1669. const TypeInterface &itype = E.value;
  1670. if (itype.api_type != ClassDB::API_EDITOR || itype.is_singleton_instance) {
  1671. continue;
  1672. }
  1673. if (itype.is_deprecated) {
  1674. cs_built_in_ctors_content.append("#pragma warning disable CS0618\n");
  1675. }
  1676. cs_built_in_ctors_content.append(INDENT2 "builtInMethodConstructors.Add(\"");
  1677. cs_built_in_ctors_content.append(itype.name);
  1678. cs_built_in_ctors_content.append("\", " CS_PARAM_INSTANCE " => new ");
  1679. cs_built_in_ctors_content.append(itype.proxy_name);
  1680. if (itype.is_singleton && !itype.is_compat_singleton) {
  1681. cs_built_in_ctors_content.append("Instance");
  1682. }
  1683. cs_built_in_ctors_content.append("(" CS_PARAM_INSTANCE "));\n");
  1684. if (itype.is_deprecated) {
  1685. cs_built_in_ctors_content.append("#pragma warning restore CS0618\n");
  1686. }
  1687. }
  1688. cs_built_in_ctors_content.append(INDENT1 CLOSE_BLOCK);
  1689. cs_built_in_ctors_content.append(CLOSE_BLOCK);
  1690. String constructors_file = path::join(base_gen_dir, BINDINGS_CLASS_CONSTRUCTOR_EDITOR ".cs");
  1691. Error err = _save_file(constructors_file, cs_built_in_ctors_content);
  1692. if (err != OK) {
  1693. return err;
  1694. }
  1695. compile_items.push_back(constructors_file);
  1696. }
  1697. // Generate native calls
  1698. StringBuilder cs_icalls_content;
  1699. cs_icalls_content.append("namespace " BINDINGS_NAMESPACE ";\n\n");
  1700. cs_icalls_content.append("using System;\n"
  1701. "using System.Diagnostics.CodeAnalysis;\n"
  1702. "using System.Runtime.InteropServices;\n"
  1703. "using Godot.NativeInterop;\n"
  1704. "\n");
  1705. cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"InconsistentNaming\")]\n");
  1706. cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantUnsafeContext\")]\n");
  1707. cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantNameQualifier\")]\n");
  1708. cs_icalls_content.append("[System.Runtime.CompilerServices.SkipLocalsInit]\n");
  1709. cs_icalls_content.append("internal static class " BINDINGS_CLASS_NATIVECALLS_EDITOR "\n" OPEN_BLOCK);
  1710. cs_icalls_content.append(INDENT1 "internal static ulong godot_api_hash = ");
  1711. cs_icalls_content.append(String::num_uint64(ClassDB::get_api_hash(ClassDB::API_EDITOR)) + ";\n");
  1712. cs_icalls_content.append(MEMBER_BEGIN "private const int VarArgsSpanThreshold = 10;\n");
  1713. cs_icalls_content.append("\n");
  1714. for (const InternalCall &icall : method_icalls) {
  1715. if (!icall.editor_only) {
  1716. continue;
  1717. }
  1718. Error err = _generate_cs_native_calls(icall, cs_icalls_content);
  1719. if (err != OK) {
  1720. return err;
  1721. }
  1722. }
  1723. cs_icalls_content.append(CLOSE_BLOCK);
  1724. String internal_methods_file = path::join(base_gen_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs");
  1725. Error err = _save_file(internal_methods_file, cs_icalls_content);
  1726. if (err != OK) {
  1727. return err;
  1728. }
  1729. compile_items.push_back(internal_methods_file);
  1730. // Generate GeneratedIncludes.props
  1731. StringBuilder includes_props_content;
  1732. includes_props_content.append("<Project>\n"
  1733. " <ItemGroup>\n");
  1734. for (int i = 0; i < compile_items.size(); i++) {
  1735. String include = path::relative_to(compile_items[i], p_proj_dir).replace("/", "\\");
  1736. includes_props_content.append(" <Compile Include=\"" + include + "\" />\n");
  1737. }
  1738. includes_props_content.append(" </ItemGroup>\n"
  1739. "</Project>\n");
  1740. String includes_props_file = path::join(base_gen_dir, "GeneratedIncludes.props");
  1741. err = _save_file(includes_props_file, includes_props_content);
  1742. if (err != OK) {
  1743. return err;
  1744. }
  1745. return OK;
  1746. }
  1747. Error BindingsGenerator::generate_cs_api(const String &p_output_dir) {
  1748. ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
  1749. String output_dir = path::abspath(path::realpath(p_output_dir));
  1750. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  1751. ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE);
  1752. if (!DirAccess::exists(output_dir)) {
  1753. Error err = da->make_dir_recursive(output_dir);
  1754. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  1755. }
  1756. Error proj_err;
  1757. // Generate GodotSharp source files
  1758. String core_proj_dir = output_dir.path_join(CORE_API_ASSEMBLY_NAME);
  1759. proj_err = generate_cs_core_project(core_proj_dir);
  1760. if (proj_err != OK) {
  1761. ERR_PRINT("Generation of the Core API C# project failed.");
  1762. return proj_err;
  1763. }
  1764. // Generate GodotSharpEditor source files
  1765. String editor_proj_dir = output_dir.path_join(EDITOR_API_ASSEMBLY_NAME);
  1766. proj_err = generate_cs_editor_project(editor_proj_dir);
  1767. if (proj_err != OK) {
  1768. ERR_PRINT("Generation of the Editor API C# project failed.");
  1769. return proj_err;
  1770. }
  1771. _log("The Godot API sources were successfully generated\n");
  1772. return OK;
  1773. }
  1774. // FIXME: There are some members that hide other inherited members.
  1775. // - In the case of both members being the same kind, the new one must be declared
  1776. // explicitly as 'new' to avoid the warning (and we must print a message about it).
  1777. // - In the case of both members being of a different kind, then the new one must
  1778. // be renamed to avoid the name collision (and we must print a warning about it).
  1779. // - Csc warning e.g.:
  1780. // ObjectType/LineEdit.cs(140,38): warning CS0108: 'LineEdit.FocusMode' hides inherited member 'Control.FocusMode'. Use the new keyword if hiding was intended.
  1781. Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const String &p_output_file) {
  1782. CRASH_COND(!itype.is_object_type);
  1783. bool is_derived_type = itype.base_name != StringName();
  1784. if (!is_derived_type) {
  1785. // Some GodotObject assertions
  1786. CRASH_COND(itype.cname != name_cache.type_Object);
  1787. CRASH_COND(!itype.is_instantiable);
  1788. CRASH_COND(itype.api_type != ClassDB::API_CORE);
  1789. CRASH_COND(itype.is_ref_counted);
  1790. CRASH_COND(itype.is_singleton);
  1791. }
  1792. _log("Generating %s.cs...\n", itype.proxy_name.utf8().get_data());
  1793. StringBuilder output;
  1794. output.append("namespace " BINDINGS_NAMESPACE ";\n\n");
  1795. output.append("using System;\n"); // IntPtr
  1796. output.append("using System.ComponentModel;\n"); // EditorBrowsable
  1797. output.append("using System.Diagnostics;\n"); // DebuggerBrowsable
  1798. output.append("using Godot.NativeInterop;\n");
  1799. output.append("\n#nullable disable\n");
  1800. const DocData::ClassDoc *class_doc = itype.class_doc;
  1801. if (class_doc && class_doc->description.size()) {
  1802. String xml_summary = bbcode_to_xml(fix_doc_description(class_doc->description), &itype);
  1803. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1804. if (summary_lines.size()) {
  1805. output.append("/// <summary>\n");
  1806. for (int i = 0; i < summary_lines.size(); i++) {
  1807. output.append("/// ");
  1808. output.append(summary_lines[i]);
  1809. output.append("\n");
  1810. }
  1811. output.append("/// </summary>\n");
  1812. }
  1813. }
  1814. if (itype.is_deprecated) {
  1815. output.append("[Obsolete(\"");
  1816. output.append(bbcode_to_text(itype.deprecation_message, &itype));
  1817. output.append("\")]\n");
  1818. }
  1819. // We generate a `GodotClassName` attribute if the engine class name is not the same as the
  1820. // generated C# class name. This allows introspection code to find the name associated with
  1821. // the class. If the attribute is not present, the C# class name can be used instead.
  1822. if (itype.name != itype.proxy_name) {
  1823. output << "[GodotClassName(\"" << itype.name << "\")]\n";
  1824. }
  1825. output.append("public ");
  1826. if (itype.is_singleton) {
  1827. output.append("static partial class ");
  1828. } else {
  1829. // Even if the class is not instantiable, we can't declare it abstract because
  1830. // the engine can still instantiate them and return them via the scripting API.
  1831. // Example: `SceneTreeTimer` returned from `SceneTree.create_timer`.
  1832. // See the reverted commit: ef5672d3f94a7321ed779c922088bb72adbb1521
  1833. output.append("partial class ");
  1834. }
  1835. output.append(itype.proxy_name);
  1836. if (is_derived_type && !itype.is_singleton) {
  1837. if (obj_types.has(itype.base_name)) {
  1838. TypeInterface base_type = obj_types[itype.base_name];
  1839. output.append(" : ");
  1840. output.append(base_type.proxy_name);
  1841. if (base_type.is_singleton) {
  1842. // If the type is a singleton, use the instance type.
  1843. output.append(CS_SINGLETON_INSTANCE_SUFFIX);
  1844. }
  1845. } else {
  1846. ERR_PRINT("Base type '" + itype.base_name.operator String() + "' does not exist, for class '" + itype.name + "'.");
  1847. return ERR_INVALID_DATA;
  1848. }
  1849. }
  1850. output.append("\n{");
  1851. // Add constants
  1852. for (const ConstantInterface &iconstant : itype.constants) {
  1853. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  1854. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
  1855. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1856. if (summary_lines.size()) {
  1857. output.append(MEMBER_BEGIN "/// <summary>\n");
  1858. for (int i = 0; i < summary_lines.size(); i++) {
  1859. output.append(INDENT1 "/// ");
  1860. output.append(summary_lines[i]);
  1861. output.append("\n");
  1862. }
  1863. output.append(INDENT1 "/// </summary>");
  1864. }
  1865. }
  1866. if (iconstant.is_deprecated) {
  1867. output.append(MEMBER_BEGIN "[Obsolete(\"");
  1868. output.append(bbcode_to_text(iconstant.deprecation_message, &itype));
  1869. output.append("\")]");
  1870. }
  1871. output.append(MEMBER_BEGIN "public const long ");
  1872. output.append(iconstant.proxy_name);
  1873. output.append(" = ");
  1874. output.append(itos(iconstant.value));
  1875. output.append(";");
  1876. }
  1877. if (itype.constants.size()) {
  1878. output.append("\n");
  1879. }
  1880. // Add enums
  1881. for (const EnumInterface &ienum : itype.enums) {
  1882. ERR_FAIL_COND_V(ienum.constants.is_empty(), ERR_BUG);
  1883. if (ienum.is_flags) {
  1884. output.append(MEMBER_BEGIN "[System.Flags]");
  1885. }
  1886. output.append(MEMBER_BEGIN "public enum ");
  1887. output.append(ienum.proxy_name);
  1888. output.append(" : long");
  1889. output.append(MEMBER_BEGIN OPEN_BLOCK);
  1890. const ConstantInterface &last = ienum.constants.back()->get();
  1891. for (const ConstantInterface &iconstant : ienum.constants) {
  1892. if (iconstant.const_doc && iconstant.const_doc->description.size()) {
  1893. String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
  1894. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  1895. if (summary_lines.size()) {
  1896. output.append(INDENT2 "/// <summary>\n");
  1897. for (int i = 0; i < summary_lines.size(); i++) {
  1898. output.append(INDENT2 "/// ");
  1899. output.append(summary_lines[i]);
  1900. output.append("\n");
  1901. }
  1902. output.append(INDENT2 "/// </summary>\n");
  1903. }
  1904. }
  1905. if (iconstant.is_deprecated) {
  1906. output.append(INDENT2 "[Obsolete(\"");
  1907. output.append(bbcode_to_text(iconstant.deprecation_message, &itype));
  1908. output.append("\")]\n");
  1909. }
  1910. output.append(INDENT2);
  1911. output.append(iconstant.proxy_name);
  1912. output.append(" = ");
  1913. output.append(itos(iconstant.value));
  1914. output.append(&iconstant != &last ? ",\n" : "\n");
  1915. }
  1916. output.append(INDENT1 CLOSE_BLOCK);
  1917. }
  1918. // Add properties
  1919. for (const PropertyInterface &iprop : itype.properties) {
  1920. Error prop_err = _generate_cs_property(itype, iprop, output);
  1921. ERR_FAIL_COND_V_MSG(prop_err != OK, prop_err,
  1922. "Failed to generate property '" + iprop.cname.operator String() +
  1923. "' for class '" + itype.name + "'.");
  1924. }
  1925. // Add native name static field and cached type.
  1926. if (is_derived_type && !itype.is_singleton) {
  1927. output << MEMBER_BEGIN "private static readonly System.Type CachedType = typeof(" << itype.proxy_name << ");\n";
  1928. }
  1929. output.append(MEMBER_BEGIN "private static readonly StringName " BINDINGS_NATIVE_NAME_FIELD " = \"");
  1930. output.append(itype.name);
  1931. output.append("\";\n");
  1932. if (itype.is_singleton || itype.is_compat_singleton) {
  1933. // Add the Singleton static property.
  1934. String instance_type_name;
  1935. if (itype.is_singleton) {
  1936. StringName instance_name = itype.name + CS_SINGLETON_INSTANCE_SUFFIX;
  1937. instance_type_name = obj_types.has(instance_name)
  1938. ? obj_types[instance_name].proxy_name
  1939. : "GodotObject";
  1940. } else {
  1941. instance_type_name = itype.proxy_name;
  1942. }
  1943. output.append(MEMBER_BEGIN "private static " + instance_type_name + " singleton;\n");
  1944. output << MEMBER_BEGIN "public static " + instance_type_name + " " CS_PROPERTY_SINGLETON " =>\n"
  1945. << INDENT2 "singleton \?\?= (" + instance_type_name + ")"
  1946. << C_METHOD_ENGINE_GET_SINGLETON "(\"" << itype.name << "\");\n";
  1947. }
  1948. if (!itype.is_singleton) {
  1949. // IMPORTANT: We also generate the static fields for GodotObject instead of declaring
  1950. // them manually in the `GodotObject.base.cs` partial class declaration, because they're
  1951. // required by other static fields in this generated partial class declaration.
  1952. // Static fields are initialized in order of declaration, but when they're in different
  1953. // partial class declarations then it becomes harder to tell (Rider warns about this).
  1954. if (itype.is_instantiable) {
  1955. // Add native constructor static field
  1956. output << MEMBER_BEGIN << "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\n"
  1957. << INDENT1 "private static readonly unsafe delegate* unmanaged<godot_bool, IntPtr> "
  1958. << CS_STATIC_FIELD_NATIVE_CTOR " = " ICALL_CLASSDB_GET_CONSTRUCTOR
  1959. << "(" BINDINGS_NATIVE_NAME_FIELD ");\n";
  1960. }
  1961. if (is_derived_type) {
  1962. // Add default constructor
  1963. if (itype.is_instantiable) {
  1964. output << MEMBER_BEGIN "public " << itype.proxy_name << "() : this("
  1965. << (itype.memory_own ? "true" : "false") << ")\n" OPEN_BLOCK_L1
  1966. << INDENT2 "unsafe\n" INDENT2 OPEN_BLOCK
  1967. << INDENT3 "ConstructAndInitialize(" CS_STATIC_FIELD_NATIVE_CTOR ", "
  1968. << BINDINGS_NATIVE_NAME_FIELD ", CachedType, refCounted: "
  1969. << (itype.is_ref_counted ? "true" : "false") << ");\n"
  1970. << CLOSE_BLOCK_L2 CLOSE_BLOCK_L1;
  1971. } else {
  1972. // Hide the constructor
  1973. output << MEMBER_BEGIN "internal " << itype.proxy_name << "() : this("
  1974. << (itype.memory_own ? "true" : "false") << ")\n" OPEN_BLOCK_L1
  1975. << INDENT2 "unsafe\n" INDENT2 OPEN_BLOCK
  1976. << INDENT3 "ConstructAndInitialize(null, "
  1977. << BINDINGS_NATIVE_NAME_FIELD ", CachedType, refCounted: "
  1978. << (itype.is_ref_counted ? "true" : "false") << ");\n"
  1979. << CLOSE_BLOCK_L2 CLOSE_BLOCK_L1;
  1980. }
  1981. output << MEMBER_BEGIN "internal " << itype.proxy_name << "(IntPtr " CS_PARAM_INSTANCE ") : this("
  1982. << (itype.memory_own ? "true" : "false") << ")\n" OPEN_BLOCK_L1
  1983. << INDENT2 "NativePtr = " CS_PARAM_INSTANCE ";\n"
  1984. << INDENT2 "unsafe\n" INDENT2 OPEN_BLOCK
  1985. << INDENT3 "ConstructAndInitialize(null, "
  1986. << BINDINGS_NATIVE_NAME_FIELD ", CachedType, refCounted: "
  1987. << (itype.is_ref_counted ? "true" : "false") << ");\n"
  1988. << CLOSE_BLOCK_L2 CLOSE_BLOCK_L1;
  1989. // Add.. em.. trick constructor. Sort of.
  1990. output.append(MEMBER_BEGIN "internal ");
  1991. output.append(itype.proxy_name);
  1992. output.append("(bool " CS_PARAM_MEMORYOWN ") : base(" CS_PARAM_MEMORYOWN ") { }\n");
  1993. }
  1994. }
  1995. // Methods
  1996. int method_bind_count = 0;
  1997. for (const MethodInterface &imethod : itype.methods) {
  1998. Error method_err = _generate_cs_method(itype, imethod, method_bind_count, output, false);
  1999. ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
  2000. "Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'.");
  2001. if (imethod.is_internal) {
  2002. // No need to generate span overloads for internal methods.
  2003. continue;
  2004. }
  2005. method_err = _generate_cs_method(itype, imethod, method_bind_count, output, true);
  2006. ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
  2007. "Failed to generate span overload method '" + imethod.name + "' for class '" + itype.name + "'.");
  2008. }
  2009. // Signals
  2010. for (const SignalInterface &isignal : itype.signals_) {
  2011. Error method_err = _generate_cs_signal(itype, isignal, output);
  2012. ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
  2013. "Failed to generate signal '" + isignal.name + "' for class '" + itype.name + "'.");
  2014. }
  2015. // Script members look-up
  2016. if (!itype.is_singleton && (is_derived_type || itype.has_virtual_methods)) {
  2017. // Generate method names cache fields
  2018. for (const MethodInterface &imethod : itype.methods) {
  2019. if (!imethod.is_virtual) {
  2020. continue;
  2021. }
  2022. output << MEMBER_BEGIN "// ReSharper disable once InconsistentNaming\n"
  2023. << INDENT1 "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\n"
  2024. << INDENT1 "private static readonly StringName "
  2025. << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name
  2026. << " = \"" << imethod.proxy_name << "\";\n";
  2027. }
  2028. // Generate signal names cache fields
  2029. for (const SignalInterface &isignal : itype.signals_) {
  2030. output << MEMBER_BEGIN "// ReSharper disable once InconsistentNaming\n"
  2031. << INDENT1 "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\n"
  2032. << INDENT1 "private static readonly StringName "
  2033. << CS_STATIC_FIELD_SIGNAL_PROXY_NAME_PREFIX << isignal.name
  2034. << " = \"" << isignal.proxy_name << "\";\n";
  2035. }
  2036. // TODO: Only generate HasGodotClassMethod and InvokeGodotClassMethod if there's any method
  2037. // Generate InvokeGodotClassMethod
  2038. output << MEMBER_BEGIN "/// <summary>\n"
  2039. << INDENT1 "/// Invokes the method with the given name, using the given arguments.\n"
  2040. << INDENT1 "/// This method is used by Godot to invoke methods from the engine side.\n"
  2041. << INDENT1 "/// Do not call or override this method.\n"
  2042. << INDENT1 "/// </summary>\n"
  2043. << INDENT1 "/// <param name=\"method\">Name of the method to invoke.</param>\n"
  2044. << INDENT1 "/// <param name=\"args\">Arguments to use with the invoked method.</param>\n"
  2045. << INDENT1 "/// <param name=\"ret\">Value returned by the invoked method.</param>\n";
  2046. // Avoid raising diagnostics because of calls to obsolete methods.
  2047. output << "#pragma warning disable CS0618 // Member is obsolete\n";
  2048. output << INDENT1 "protected internal " << (is_derived_type ? "override" : "virtual")
  2049. << " bool " CS_METHOD_INVOKE_GODOT_CLASS_METHOD "(in godot_string_name method, "
  2050. << "NativeVariantPtrArgs args, out godot_variant ret)\n"
  2051. << INDENT1 "{\n";
  2052. for (const MethodInterface &imethod : itype.methods) {
  2053. if (!imethod.is_virtual) {
  2054. continue;
  2055. }
  2056. // We also call HasGodotClassMethod to ensure the method is overridden and avoid calling
  2057. // the stub implementation. This solution adds some extra overhead to calls, but it's
  2058. // much simpler than other solutions. This won't be a problem once we move to function
  2059. // pointers of generated wrappers for each method, as lookup will only happen once.
  2060. // We check both native names (snake_case) and proxy names (PascalCase)
  2061. output << INDENT2 "if ((method == " << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name
  2062. << " || method == MethodName." << imethod.proxy_name
  2063. << ") && args.Count == " << itos(imethod.arguments.size())
  2064. << " && " << CS_METHOD_HAS_GODOT_CLASS_METHOD << "((godot_string_name)"
  2065. << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name << ".NativeValue))\n"
  2066. << INDENT2 "{\n";
  2067. if (imethod.return_type.cname != name_cache.type_void) {
  2068. output << INDENT3 "var callRet = ";
  2069. } else {
  2070. output << INDENT3;
  2071. }
  2072. output << imethod.proxy_name << "(";
  2073. int i = 0;
  2074. for (List<BindingsGenerator::ArgumentInterface>::ConstIterator itr = imethod.arguments.begin(); itr != imethod.arguments.end(); ++itr, ++i) {
  2075. const ArgumentInterface &iarg = *itr;
  2076. const TypeInterface *arg_type = _get_type_or_null(iarg.type);
  2077. ERR_FAIL_NULL_V_MSG(arg_type, ERR_BUG, "Argument type '" + iarg.type.cname + "' was not found.");
  2078. if (i != 0) {
  2079. output << ", ";
  2080. }
  2081. if (arg_type->cname == name_cache.type_Array_generic || arg_type->cname == name_cache.type_Dictionary_generic) {
  2082. String arg_cs_type = arg_type->cs_type + _get_generic_type_parameters(*arg_type, iarg.type.generic_type_parameters);
  2083. output << "new " << arg_cs_type << "(" << sformat(arg_type->cs_variant_to_managed, "args[" + itos(i) + "]", arg_type->cs_type, arg_type->name) << ")";
  2084. } else {
  2085. output << sformat(arg_type->cs_variant_to_managed,
  2086. "args[" + itos(i) + "]", arg_type->cs_type, arg_type->name);
  2087. }
  2088. }
  2089. output << ");\n";
  2090. if (imethod.return_type.cname != name_cache.type_void) {
  2091. const TypeInterface *return_type = _get_type_or_null(imethod.return_type);
  2092. ERR_FAIL_NULL_V_MSG(return_type, ERR_BUG, "Return type '" + imethod.return_type.cname + "' was not found.");
  2093. output << INDENT3 "ret = "
  2094. << sformat(return_type->cs_managed_to_variant, "callRet", return_type->cs_type, return_type->name)
  2095. << ";\n"
  2096. << INDENT3 "return true;\n";
  2097. } else {
  2098. output << INDENT3 "ret = default;\n"
  2099. << INDENT3 "return true;\n";
  2100. }
  2101. output << INDENT2 "}\n";
  2102. }
  2103. if (is_derived_type) {
  2104. output << INDENT2 "return base." CS_METHOD_INVOKE_GODOT_CLASS_METHOD "(method, args, out ret);\n";
  2105. } else {
  2106. output << INDENT2 "ret = default;\n"
  2107. << INDENT2 "return false;\n";
  2108. }
  2109. output << INDENT1 "}\n";
  2110. output << "#pragma warning restore CS0618\n";
  2111. // Generate HasGodotClassMethod
  2112. output << MEMBER_BEGIN "/// <summary>\n"
  2113. << INDENT1 "/// Check if the type contains a method with the given name.\n"
  2114. << INDENT1 "/// This method is used by Godot to check if a method exists before invoking it.\n"
  2115. << INDENT1 "/// Do not call or override this method.\n"
  2116. << INDENT1 "/// </summary>\n"
  2117. << INDENT1 "/// <param name=\"method\">Name of the method to check for.</param>\n";
  2118. output << MEMBER_BEGIN "protected internal " << (is_derived_type ? "override" : "virtual")
  2119. << " bool " CS_METHOD_HAS_GODOT_CLASS_METHOD "(in godot_string_name method)\n"
  2120. << INDENT1 "{\n";
  2121. for (const MethodInterface &imethod : itype.methods) {
  2122. if (!imethod.is_virtual) {
  2123. continue;
  2124. }
  2125. // We check for native names (snake_case). If we detect one, we call HasGodotClassMethod
  2126. // again, but this time with the respective proxy name (PascalCase). It's the job of
  2127. // user derived classes to override the method and check for those. Our C# source
  2128. // generators take care of generating those override methods.
  2129. output << INDENT2 "if (method == MethodName." << imethod.proxy_name
  2130. << ")\n" INDENT2 "{\n"
  2131. << INDENT3 "if (" CS_METHOD_HAS_GODOT_CLASS_METHOD "("
  2132. << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name
  2133. << ".NativeValue.DangerousSelfRef))\n" INDENT3 "{\n"
  2134. << INDENT4 "return true;\n"
  2135. << INDENT3 "}\n" INDENT2 "}\n";
  2136. }
  2137. if (is_derived_type) {
  2138. output << INDENT2 "return base." CS_METHOD_HAS_GODOT_CLASS_METHOD "(method);\n";
  2139. } else {
  2140. output << INDENT2 "return false;\n";
  2141. }
  2142. output << INDENT1 "}\n";
  2143. // Generate HasGodotClassSignal
  2144. output << MEMBER_BEGIN "/// <summary>\n"
  2145. << INDENT1 "/// Check if the type contains a signal with the given name.\n"
  2146. << INDENT1 "/// This method is used by Godot to check if a signal exists before raising it.\n"
  2147. << INDENT1 "/// Do not call or override this method.\n"
  2148. << INDENT1 "/// </summary>\n"
  2149. << INDENT1 "/// <param name=\"signal\">Name of the signal to check for.</param>\n";
  2150. output << MEMBER_BEGIN "protected internal " << (is_derived_type ? "override" : "virtual")
  2151. << " bool " CS_METHOD_HAS_GODOT_CLASS_SIGNAL "(in godot_string_name signal)\n"
  2152. << INDENT1 "{\n";
  2153. for (const SignalInterface &isignal : itype.signals_) {
  2154. // We check for native names (snake_case). If we detect one, we call HasGodotClassSignal
  2155. // again, but this time with the respective proxy name (PascalCase). It's the job of
  2156. // user derived classes to override the method and check for those. Our C# source
  2157. // generators take care of generating those override methods.
  2158. output << INDENT2 "if (signal == SignalName." << isignal.proxy_name
  2159. << ")\n" INDENT2 "{\n"
  2160. << INDENT3 "if (" CS_METHOD_HAS_GODOT_CLASS_SIGNAL "("
  2161. << CS_STATIC_FIELD_SIGNAL_PROXY_NAME_PREFIX << isignal.name
  2162. << ".NativeValue.DangerousSelfRef))\n" INDENT3 "{\n"
  2163. << INDENT4 "return true;\n"
  2164. << INDENT3 "}\n" INDENT2 "}\n";
  2165. }
  2166. if (is_derived_type) {
  2167. output << INDENT2 "return base." CS_METHOD_HAS_GODOT_CLASS_SIGNAL "(signal);\n";
  2168. } else {
  2169. output << INDENT2 "return false;\n";
  2170. }
  2171. output << INDENT1 "}\n";
  2172. }
  2173. //Generate StringName for all class members
  2174. bool is_inherit = !itype.is_singleton && obj_types.has(itype.base_name);
  2175. //PropertyName
  2176. output << MEMBER_BEGIN "/// <summary>\n"
  2177. << INDENT1 "/// Cached StringNames for the properties and fields contained in this class, for fast lookup.\n"
  2178. << INDENT1 "/// </summary>\n";
  2179. if (is_inherit) {
  2180. output << INDENT1 "public new class PropertyName : " << obj_types[itype.base_name].proxy_name << ".PropertyName";
  2181. } else {
  2182. output << INDENT1 "public class PropertyName";
  2183. }
  2184. output << "\n"
  2185. << INDENT1 "{\n";
  2186. for (const PropertyInterface &iprop : itype.properties) {
  2187. output << INDENT2 "/// <summary>\n"
  2188. << INDENT2 "/// Cached name for the '" << iprop.cname << "' property.\n"
  2189. << INDENT2 "/// </summary>\n"
  2190. << INDENT2 "public static "
  2191. << (prop_allowed_inherited_member_hiding.has(itype.proxy_name + ".PropertyName." + iprop.proxy_name) ? "new " : "")
  2192. << "readonly StringName " << iprop.proxy_name << " = \"" << iprop.cname << "\";\n";
  2193. }
  2194. output << INDENT1 "}\n";
  2195. //MethodName
  2196. output << MEMBER_BEGIN "/// <summary>\n"
  2197. << INDENT1 "/// Cached StringNames for the methods contained in this class, for fast lookup.\n"
  2198. << INDENT1 "/// </summary>\n";
  2199. if (is_inherit) {
  2200. output << INDENT1 "public new class MethodName : " << obj_types[itype.base_name].proxy_name << ".MethodName";
  2201. } else {
  2202. output << INDENT1 "public class MethodName";
  2203. }
  2204. output << "\n"
  2205. << INDENT1 "{\n";
  2206. HashMap<String, StringName> method_names;
  2207. for (const MethodInterface &imethod : itype.methods) {
  2208. if (method_names.has(imethod.proxy_name)) {
  2209. ERR_FAIL_COND_V_MSG(method_names[imethod.proxy_name] != imethod.cname, ERR_BUG, "Method name '" + imethod.proxy_name + "' already exists with a different value.");
  2210. continue;
  2211. }
  2212. method_names[imethod.proxy_name] = imethod.cname;
  2213. output << INDENT2 "/// <summary>\n"
  2214. << INDENT2 "/// Cached name for the '" << imethod.cname << "' method.\n"
  2215. << INDENT2 "/// </summary>\n"
  2216. << INDENT2 "public static "
  2217. << (prop_allowed_inherited_member_hiding.has(itype.proxy_name + ".MethodName." + imethod.proxy_name) ? "new " : "")
  2218. << "readonly StringName " << imethod.proxy_name << " = \"" << imethod.cname << "\";\n";
  2219. }
  2220. output << INDENT1 "}\n";
  2221. //SignalName
  2222. output << MEMBER_BEGIN "/// <summary>\n"
  2223. << INDENT1 "/// Cached StringNames for the signals contained in this class, for fast lookup.\n"
  2224. << INDENT1 "/// </summary>\n";
  2225. if (is_inherit) {
  2226. output << INDENT1 "public new class SignalName : " << obj_types[itype.base_name].proxy_name << ".SignalName";
  2227. } else {
  2228. output << INDENT1 "public class SignalName";
  2229. }
  2230. output << "\n"
  2231. << INDENT1 "{\n";
  2232. for (const SignalInterface &isignal : itype.signals_) {
  2233. output << INDENT2 "/// <summary>\n"
  2234. << INDENT2 "/// Cached name for the '" << isignal.cname << "' signal.\n"
  2235. << INDENT2 "/// </summary>\n"
  2236. << INDENT2 "public static "
  2237. << (prop_allowed_inherited_member_hiding.has(itype.proxy_name + ".SignalName." + isignal.proxy_name) ? "new " : "")
  2238. << "readonly StringName " << isignal.proxy_name << " = \"" << isignal.cname << "\";\n";
  2239. }
  2240. output << INDENT1 "}\n";
  2241. output.append(CLOSE_BLOCK /* class */);
  2242. return _save_file(p_output_file, output);
  2243. }
  2244. Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInterface &p_itype, const PropertyInterface &p_iprop, StringBuilder &p_output) {
  2245. const MethodInterface *setter = p_itype.find_method_by_name(p_iprop.setter);
  2246. // Search it in base types too
  2247. const TypeInterface *current_type = &p_itype;
  2248. while (!setter && current_type->base_name != StringName()) {
  2249. HashMap<StringName, TypeInterface>::Iterator base_match = obj_types.find(current_type->base_name);
  2250. ERR_FAIL_COND_V_MSG(!base_match, ERR_BUG, "Type not found '" + current_type->base_name + "'. Inherited by '" + current_type->name + "'.");
  2251. current_type = &base_match->value;
  2252. setter = current_type->find_method_by_name(p_iprop.setter);
  2253. }
  2254. const MethodInterface *getter = p_itype.find_method_by_name(p_iprop.getter);
  2255. // Search it in base types too
  2256. current_type = &p_itype;
  2257. while (!getter && current_type->base_name != StringName()) {
  2258. HashMap<StringName, TypeInterface>::Iterator base_match = obj_types.find(current_type->base_name);
  2259. ERR_FAIL_COND_V_MSG(!base_match, ERR_BUG, "Type not found '" + current_type->base_name + "'. Inherited by '" + current_type->name + "'.");
  2260. current_type = &base_match->value;
  2261. getter = current_type->find_method_by_name(p_iprop.getter);
  2262. }
  2263. ERR_FAIL_COND_V(!setter && !getter, ERR_BUG);
  2264. if (setter) {
  2265. int setter_argc = p_iprop.index != -1 ? 2 : 1;
  2266. ERR_FAIL_COND_V(setter->arguments.size() != setter_argc, ERR_BUG);
  2267. }
  2268. if (getter) {
  2269. int getter_argc = p_iprop.index != -1 ? 1 : 0;
  2270. ERR_FAIL_COND_V(getter->arguments.size() != getter_argc, ERR_BUG);
  2271. }
  2272. if (getter && setter) {
  2273. const ArgumentInterface &setter_first_arg = setter->arguments.back()->get();
  2274. if (getter->return_type.cname != setter_first_arg.type.cname) {
  2275. // Special case for Node::set_name
  2276. bool whitelisted = getter->return_type.cname == name_cache.type_StringName &&
  2277. setter_first_arg.type.cname == name_cache.type_String;
  2278. ERR_FAIL_COND_V_MSG(!whitelisted, ERR_BUG,
  2279. "Return type from getter doesn't match first argument of setter for property: '" +
  2280. p_itype.name + "." + String(p_iprop.cname) + "'.");
  2281. }
  2282. }
  2283. const TypeReference &proptype_name = getter ? getter->return_type : setter->arguments.back()->get().type;
  2284. const TypeInterface *prop_itype = _get_type_or_singleton_or_null(proptype_name);
  2285. ERR_FAIL_NULL_V_MSG(prop_itype, ERR_BUG, "Property type '" + proptype_name.cname + "' was not found.");
  2286. ERR_FAIL_COND_V_MSG(prop_itype->is_singleton, ERR_BUG,
  2287. "Property type is a singleton: '" + p_itype.name + "." + String(p_iprop.cname) + "'.");
  2288. if (p_itype.api_type == ClassDB::API_CORE) {
  2289. ERR_FAIL_COND_V_MSG(prop_itype->api_type == ClassDB::API_EDITOR, ERR_BUG,
  2290. "Property '" + p_itype.name + "." + String(p_iprop.cname) + "' has type '" + prop_itype->name +
  2291. "' from the editor API. Core API cannot have dependencies on the editor API.");
  2292. }
  2293. if (p_iprop.prop_doc && p_iprop.prop_doc->description.size()) {
  2294. String xml_summary = bbcode_to_xml(fix_doc_description(p_iprop.prop_doc->description), &p_itype);
  2295. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  2296. if (summary_lines.size()) {
  2297. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  2298. for (int i = 0; i < summary_lines.size(); i++) {
  2299. p_output.append(INDENT1 "/// ");
  2300. p_output.append(summary_lines[i]);
  2301. p_output.append("\n");
  2302. }
  2303. p_output.append(INDENT1 "/// </summary>");
  2304. }
  2305. }
  2306. if (p_iprop.is_deprecated) {
  2307. p_output.append(MEMBER_BEGIN "[Obsolete(\"");
  2308. p_output.append(bbcode_to_text(p_iprop.deprecation_message, &p_itype));
  2309. p_output.append("\")]");
  2310. }
  2311. if (p_iprop.is_hidden) {
  2312. p_output.append(MEMBER_BEGIN "[EditorBrowsable(EditorBrowsableState.Never)]");
  2313. }
  2314. p_output.append(MEMBER_BEGIN "public ");
  2315. if (prop_allowed_inherited_member_hiding.has(p_itype.proxy_name + "." + p_iprop.proxy_name)) {
  2316. p_output.append("new ");
  2317. }
  2318. if (p_itype.is_singleton) {
  2319. p_output.append("static ");
  2320. }
  2321. String prop_cs_type = prop_itype->cs_type + _get_generic_type_parameters(*prop_itype, proptype_name.generic_type_parameters);
  2322. p_output.append(prop_cs_type);
  2323. p_output.append(" ");
  2324. p_output.append(p_iprop.proxy_name);
  2325. p_output.append("\n" OPEN_BLOCK_L1);
  2326. if (getter) {
  2327. p_output.append(INDENT2 "get\n" OPEN_BLOCK_L2 INDENT3);
  2328. p_output.append("return ");
  2329. p_output.append(getter->proxy_name + "(");
  2330. if (p_iprop.index != -1) {
  2331. const ArgumentInterface &idx_arg = getter->arguments.front()->get();
  2332. if (idx_arg.type.cname != name_cache.type_int) {
  2333. // Assume the index parameter is an enum
  2334. const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type);
  2335. CRASH_COND(idx_arg_type == nullptr);
  2336. p_output.append("(" + idx_arg_type->proxy_name + ")(" + itos(p_iprop.index) + ")");
  2337. } else {
  2338. p_output.append(itos(p_iprop.index));
  2339. }
  2340. }
  2341. p_output.append(");\n" CLOSE_BLOCK_L2);
  2342. }
  2343. if (setter) {
  2344. p_output.append(INDENT2 "set\n" OPEN_BLOCK_L2 INDENT3);
  2345. p_output.append(setter->proxy_name + "(");
  2346. if (p_iprop.index != -1) {
  2347. const ArgumentInterface &idx_arg = setter->arguments.front()->get();
  2348. if (idx_arg.type.cname != name_cache.type_int) {
  2349. // Assume the index parameter is an enum
  2350. const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type);
  2351. CRASH_COND(idx_arg_type == nullptr);
  2352. p_output.append("(" + idx_arg_type->proxy_name + ")(" + itos(p_iprop.index) + "), ");
  2353. } else {
  2354. p_output.append(itos(p_iprop.index) + ", ");
  2355. }
  2356. }
  2357. p_output.append("value);\n" CLOSE_BLOCK_L2);
  2358. }
  2359. p_output.append(CLOSE_BLOCK_L1);
  2360. return OK;
  2361. }
  2362. Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, int &p_method_bind_count, StringBuilder &p_output, bool p_use_span) {
  2363. const TypeInterface *return_type = _get_type_or_singleton_or_null(p_imethod.return_type);
  2364. ERR_FAIL_NULL_V_MSG(return_type, ERR_BUG, "Return type '" + p_imethod.return_type.cname + "' was not found.");
  2365. ERR_FAIL_COND_V_MSG(return_type->is_singleton, ERR_BUG,
  2366. "Method return type is a singleton: '" + p_itype.name + "." + p_imethod.name + "'.");
  2367. if (p_itype.api_type == ClassDB::API_CORE) {
  2368. ERR_FAIL_COND_V_MSG(return_type->api_type == ClassDB::API_EDITOR, ERR_BUG,
  2369. "Method '" + p_itype.name + "." + p_imethod.name + "' has return type '" + return_type->name +
  2370. "' from the editor API. Core API cannot have dependencies on the editor API.");
  2371. }
  2372. if (p_imethod.is_virtual && p_use_span) {
  2373. return OK;
  2374. }
  2375. bool has_span_argument = false;
  2376. if (p_use_span) {
  2377. if (p_imethod.is_vararg) {
  2378. has_span_argument = true;
  2379. } else {
  2380. for (const ArgumentInterface &iarg : p_imethod.arguments) {
  2381. const TypeInterface *arg_type = _get_type_or_singleton_or_null(iarg.type);
  2382. ERR_FAIL_NULL_V_MSG(arg_type, ERR_BUG, "Argument type '" + iarg.type.cname + "' was not found.");
  2383. if (arg_type->is_span_compatible) {
  2384. has_span_argument = true;
  2385. break;
  2386. }
  2387. }
  2388. }
  2389. if (has_span_argument) {
  2390. // Span overloads use the same method bind as the array overloads.
  2391. // Since both overloads are generated one after the other, we can decrease the count here
  2392. // to ensure the span overload uses the same method bind.
  2393. p_method_bind_count--;
  2394. }
  2395. }
  2396. String method_bind_field = CS_STATIC_FIELD_METHOD_BIND_PREFIX + itos(p_method_bind_count);
  2397. String arguments_sig;
  2398. StringBuilder cs_in_statements;
  2399. bool cs_in_expr_is_unsafe = false;
  2400. String icall_params = method_bind_field;
  2401. if (!p_imethod.is_static) {
  2402. String self_reference = "this";
  2403. if (p_itype.is_singleton) {
  2404. self_reference = CS_PROPERTY_SINGLETON;
  2405. }
  2406. if (p_itype.cs_in.size()) {
  2407. cs_in_statements << sformat(p_itype.cs_in, p_itype.c_type, self_reference,
  2408. String(), String(), String(), INDENT2);
  2409. }
  2410. icall_params += ", " + sformat(p_itype.cs_in_expr, self_reference);
  2411. }
  2412. StringBuilder default_args_doc;
  2413. // Retrieve information from the arguments
  2414. const ArgumentInterface &first = p_imethod.arguments.front()->get();
  2415. for (const ArgumentInterface &iarg : p_imethod.arguments) {
  2416. const TypeInterface *arg_type = _get_type_or_singleton_or_null(iarg.type);
  2417. ERR_FAIL_NULL_V_MSG(arg_type, ERR_BUG, "Argument type '" + iarg.type.cname + "' was not found.");
  2418. ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG,
  2419. "Argument type is a singleton: '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "'.");
  2420. if (p_itype.api_type == ClassDB::API_CORE) {
  2421. ERR_FAIL_COND_V_MSG(arg_type->api_type == ClassDB::API_EDITOR, ERR_BUG,
  2422. "Argument '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "' has type '" +
  2423. arg_type->name + "' from the editor API. Core API cannot have dependencies on the editor API.");
  2424. }
  2425. if (iarg.default_argument.size()) {
  2426. CRASH_COND_MSG(!_arg_default_value_is_assignable_to_type(iarg.def_param_value, *arg_type),
  2427. "Invalid default value for parameter '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "'.");
  2428. }
  2429. String arg_cs_type = arg_type->cs_type + _get_generic_type_parameters(*arg_type, iarg.type.generic_type_parameters);
  2430. bool use_span_for_arg = p_use_span && arg_type->is_span_compatible;
  2431. // Add the current arguments to the signature
  2432. // If the argument has a default value which is not a constant, we will make it Nullable
  2433. {
  2434. if (&iarg != &first) {
  2435. arguments_sig += ", ";
  2436. }
  2437. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  2438. arguments_sig += "Nullable<";
  2439. }
  2440. if (use_span_for_arg) {
  2441. arguments_sig += arg_type->c_type_in;
  2442. } else {
  2443. arguments_sig += arg_cs_type;
  2444. }
  2445. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  2446. arguments_sig += "> ";
  2447. } else {
  2448. arguments_sig += " ";
  2449. }
  2450. arguments_sig += iarg.name;
  2451. if (!p_use_span && !p_imethod.is_compat && iarg.default_argument.size()) {
  2452. if (iarg.def_param_mode != ArgumentInterface::CONSTANT) {
  2453. arguments_sig += " = null";
  2454. } else {
  2455. arguments_sig += " = " + sformat(iarg.default_argument, arg_type->cs_type);
  2456. }
  2457. }
  2458. }
  2459. icall_params += ", ";
  2460. if (iarg.default_argument.size() && iarg.def_param_mode != ArgumentInterface::CONSTANT && !use_span_for_arg) {
  2461. // The default value of an argument must be constant. Otherwise we make it Nullable and do the following:
  2462. // Type arg_in = arg.HasValue ? arg.Value : <non-const default value>;
  2463. String arg_or_defval_local = iarg.name;
  2464. arg_or_defval_local += "OrDefVal";
  2465. cs_in_statements << INDENT2 << arg_cs_type << " " << arg_or_defval_local << " = " << iarg.name;
  2466. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  2467. cs_in_statements << ".HasValue ? ";
  2468. } else {
  2469. cs_in_statements << " != null ? ";
  2470. }
  2471. cs_in_statements << iarg.name;
  2472. if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  2473. cs_in_statements << ".Value : ";
  2474. } else {
  2475. cs_in_statements << " : ";
  2476. }
  2477. String cs_type = arg_cs_type;
  2478. if (cs_type.ends_with("[]")) {
  2479. cs_type = cs_type.substr(0, cs_type.length() - 2);
  2480. }
  2481. String def_arg = sformat(iarg.default_argument, cs_type);
  2482. cs_in_statements << def_arg << ";\n";
  2483. if (arg_type->cs_in.size()) {
  2484. cs_in_statements << sformat(arg_type->cs_in, arg_type->c_type, arg_or_defval_local,
  2485. String(), String(), String(), INDENT2);
  2486. }
  2487. if (arg_type->cs_in_expr.is_empty()) {
  2488. icall_params += arg_or_defval_local;
  2489. } else {
  2490. icall_params += sformat(arg_type->cs_in_expr, arg_or_defval_local, arg_type->c_type);
  2491. }
  2492. // Apparently the name attribute must not include the @
  2493. String param_tag_name = iarg.name.begins_with("@") ? iarg.name.substr(1) : iarg.name;
  2494. // Escape < and > in the attribute default value
  2495. String param_def_arg = def_arg.replacen("<", "&lt;").replacen(">", "&gt;");
  2496. default_args_doc.append(MEMBER_BEGIN "/// <param name=\"" + param_tag_name + "\">If the parameter is null, then the default value is <c>" + param_def_arg + "</c>.</param>");
  2497. } else {
  2498. if (arg_type->cs_in.size()) {
  2499. cs_in_statements << sformat(arg_type->cs_in, arg_type->c_type, iarg.name,
  2500. String(), String(), String(), INDENT2);
  2501. }
  2502. icall_params += arg_type->cs_in_expr.is_empty() ? iarg.name : sformat(arg_type->cs_in_expr, iarg.name, arg_type->c_type);
  2503. }
  2504. cs_in_expr_is_unsafe |= arg_type->cs_in_expr_is_unsafe;
  2505. }
  2506. if (p_use_span && !has_span_argument) {
  2507. return OK;
  2508. }
  2509. // Collect caller name for MethodBind
  2510. if (p_imethod.is_vararg) {
  2511. icall_params += ", (godot_string_name)MethodName." + p_imethod.proxy_name + ".NativeValue";
  2512. }
  2513. // Generate method
  2514. {
  2515. if (!p_imethod.is_virtual && !p_imethod.requires_object_call && !p_use_span) {
  2516. p_output << MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\n"
  2517. << INDENT1 "private static readonly IntPtr " << method_bind_field << " = ";
  2518. if (p_itype.is_singleton) {
  2519. // Singletons are static classes. They don't derive GodotObject,
  2520. // so we need to specify the type to call the static method.
  2521. p_output << "GodotObject.";
  2522. }
  2523. p_output << ICALL_CLASSDB_GET_METHOD_WITH_COMPATIBILITY "(" BINDINGS_NATIVE_NAME_FIELD ", MethodName."
  2524. << p_imethod.proxy_name << ", " << itos(p_imethod.hash) << "ul"
  2525. << ");\n";
  2526. }
  2527. if (p_imethod.method_doc && p_imethod.method_doc->description.size()) {
  2528. String xml_summary = bbcode_to_xml(fix_doc_description(p_imethod.method_doc->description), &p_itype);
  2529. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  2530. if (summary_lines.size()) {
  2531. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  2532. for (int i = 0; i < summary_lines.size(); i++) {
  2533. p_output.append(INDENT1 "/// ");
  2534. p_output.append(summary_lines[i]);
  2535. p_output.append("\n");
  2536. }
  2537. p_output.append(INDENT1 "/// </summary>");
  2538. }
  2539. }
  2540. if (default_args_doc.get_string_length()) {
  2541. p_output.append(default_args_doc.as_string());
  2542. }
  2543. if (p_imethod.is_deprecated) {
  2544. p_output.append(MEMBER_BEGIN "[Obsolete(\"");
  2545. p_output.append(bbcode_to_text(p_imethod.deprecation_message, &p_itype));
  2546. p_output.append("\")]");
  2547. }
  2548. if (p_imethod.is_hidden) {
  2549. p_output.append(MEMBER_BEGIN "[EditorBrowsable(EditorBrowsableState.Never)]");
  2550. }
  2551. p_output.append(MEMBER_BEGIN);
  2552. p_output.append(p_imethod.is_internal ? "internal " : "public ");
  2553. if (prop_allowed_inherited_member_hiding.has(p_itype.proxy_name + "." + p_imethod.proxy_name)) {
  2554. p_output.append("new ");
  2555. }
  2556. if (p_itype.is_singleton || p_imethod.is_static) {
  2557. p_output.append("static ");
  2558. } else if (p_imethod.is_virtual) {
  2559. p_output.append("virtual ");
  2560. }
  2561. if (cs_in_expr_is_unsafe) {
  2562. p_output.append("unsafe ");
  2563. }
  2564. String return_cs_type = return_type->cs_type + _get_generic_type_parameters(*return_type, p_imethod.return_type.generic_type_parameters);
  2565. p_output.append(return_cs_type + " ");
  2566. p_output.append(p_imethod.proxy_name + "(");
  2567. p_output.append(arguments_sig + ")\n" OPEN_BLOCK_L1);
  2568. if (p_imethod.is_virtual) {
  2569. // Godot virtual method must be overridden, therefore we return a default value by default.
  2570. if (return_type->cname == name_cache.type_void) {
  2571. p_output.append(CLOSE_BLOCK_L1);
  2572. } else {
  2573. p_output.append(INDENT2 "return default;\n" CLOSE_BLOCK_L1);
  2574. }
  2575. return OK; // Won't increment method bind count
  2576. }
  2577. if (p_imethod.requires_object_call) {
  2578. // Fallback to Godot's object.Call(string, params)
  2579. p_output.append(INDENT2 CS_METHOD_CALL "(\"");
  2580. p_output.append(p_imethod.name);
  2581. p_output.append("\"");
  2582. for (const ArgumentInterface &iarg : p_imethod.arguments) {
  2583. p_output.append(", ");
  2584. p_output.append(iarg.name);
  2585. }
  2586. p_output.append(");\n" CLOSE_BLOCK_L1);
  2587. return OK; // Won't increment method bind count
  2588. }
  2589. HashMap<const MethodInterface *, const InternalCall *>::ConstIterator match = method_icalls_map.find(&p_imethod);
  2590. ERR_FAIL_NULL_V(match, ERR_BUG);
  2591. const InternalCall *im_icall = match->value;
  2592. String im_call = im_icall->editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS;
  2593. im_call += ".";
  2594. im_call += im_icall->name;
  2595. if (p_imethod.arguments.size() && cs_in_statements.get_string_length() > 0) {
  2596. p_output.append(cs_in_statements.as_string());
  2597. }
  2598. if (return_type->cname == name_cache.type_void) {
  2599. p_output << INDENT2 << im_call << "(" << icall_params << ");\n";
  2600. } else if (return_type->cs_out.is_empty()) {
  2601. p_output << INDENT2 "return " << im_call << "(" << icall_params << ");\n";
  2602. } else {
  2603. p_output.append(sformat(return_type->cs_out, im_call, icall_params,
  2604. return_cs_type, return_type->c_type_out, String(), INDENT2));
  2605. p_output.append("\n");
  2606. }
  2607. p_output.append(CLOSE_BLOCK_L1);
  2608. }
  2609. p_method_bind_count++;
  2610. return OK;
  2611. }
  2612. Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::SignalInterface &p_isignal, StringBuilder &p_output) {
  2613. String arguments_sig;
  2614. // Retrieve information from the arguments
  2615. const ArgumentInterface &first = p_isignal.arguments.front()->get();
  2616. for (const ArgumentInterface &iarg : p_isignal.arguments) {
  2617. const TypeInterface *arg_type = _get_type_or_singleton_or_null(iarg.type);
  2618. ERR_FAIL_NULL_V_MSG(arg_type, ERR_BUG, "Argument type '" + iarg.type.cname + "' was not found.");
  2619. ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG,
  2620. "Argument type is a singleton: '" + iarg.name + "' of signal '" + p_itype.name + "." + p_isignal.name + "'.");
  2621. if (p_itype.api_type == ClassDB::API_CORE) {
  2622. ERR_FAIL_COND_V_MSG(arg_type->api_type == ClassDB::API_EDITOR, ERR_BUG,
  2623. "Argument '" + iarg.name + "' of signal '" + p_itype.name + "." + p_isignal.name + "' has type '" +
  2624. arg_type->name + "' from the editor API. Core API cannot have dependencies on the editor API.");
  2625. }
  2626. // Add the current arguments to the signature
  2627. if (&iarg != &first) {
  2628. arguments_sig += ", ";
  2629. }
  2630. String arg_cs_type = arg_type->cs_type + _get_generic_type_parameters(*arg_type, iarg.type.generic_type_parameters);
  2631. arguments_sig += arg_cs_type;
  2632. arguments_sig += " ";
  2633. arguments_sig += iarg.name;
  2634. }
  2635. // Generate signal
  2636. {
  2637. bool is_parameterless = p_isignal.arguments.size() == 0;
  2638. // Delegate name is [SignalName]EventHandler
  2639. String delegate_name = is_parameterless ? "Action" : p_isignal.proxy_name + "EventHandler";
  2640. if (!is_parameterless) {
  2641. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  2642. p_output.append(INDENT1 "/// ");
  2643. p_output.append("Represents the method that handles the ");
  2644. p_output.append("<see cref=\"" BINDINGS_NAMESPACE "." + p_itype.proxy_name + "." + p_isignal.proxy_name + "\"/>");
  2645. p_output.append(" event of a ");
  2646. p_output.append("<see cref=\"" BINDINGS_NAMESPACE "." + p_itype.proxy_name + "\"/>");
  2647. p_output.append(" class.\n");
  2648. p_output.append(INDENT1 "/// </summary>");
  2649. // Generate delegate
  2650. if (p_isignal.is_deprecated) {
  2651. p_output.append(MEMBER_BEGIN "[Obsolete(\"");
  2652. p_output.append(bbcode_to_text(p_isignal.deprecation_message, &p_itype));
  2653. p_output.append("\")]");
  2654. }
  2655. p_output.append(MEMBER_BEGIN "public delegate void ");
  2656. p_output.append(delegate_name);
  2657. p_output.append("(");
  2658. p_output.append(arguments_sig);
  2659. p_output.append(");\n");
  2660. // Generate Callable trampoline for the delegate
  2661. if (p_isignal.is_deprecated) {
  2662. p_output.append(MEMBER_BEGIN "[Obsolete(\"");
  2663. p_output.append(bbcode_to_text(p_isignal.deprecation_message, &p_itype));
  2664. p_output.append("\")]");
  2665. }
  2666. p_output << MEMBER_BEGIN "private static void " << p_isignal.proxy_name << "Trampoline"
  2667. << "(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret)\n"
  2668. << INDENT1 "{\n"
  2669. << INDENT2 "Callable.ThrowIfArgCountMismatch(args, " << itos(p_isignal.arguments.size()) << ");\n"
  2670. << INDENT2 "((" << delegate_name << ")delegateObj)(";
  2671. int idx = 0;
  2672. for (const ArgumentInterface &iarg : p_isignal.arguments) {
  2673. const TypeInterface *arg_type = _get_type_or_null(iarg.type);
  2674. ERR_FAIL_NULL_V_MSG(arg_type, ERR_BUG, "Argument type '" + iarg.type.cname + "' was not found.");
  2675. if (idx != 0) {
  2676. p_output << ", ";
  2677. }
  2678. if (arg_type->cname == name_cache.type_Array_generic || arg_type->cname == name_cache.type_Dictionary_generic) {
  2679. String arg_cs_type = arg_type->cs_type + _get_generic_type_parameters(*arg_type, iarg.type.generic_type_parameters);
  2680. p_output << "new " << arg_cs_type << "(" << sformat(arg_type->cs_variant_to_managed, "args[" + itos(idx) + "]", arg_type->cs_type, arg_type->name) << ")";
  2681. } else {
  2682. p_output << sformat(arg_type->cs_variant_to_managed,
  2683. "args[" + itos(idx) + "]", arg_type->cs_type, arg_type->name);
  2684. }
  2685. idx++;
  2686. }
  2687. p_output << ");\n"
  2688. << INDENT2 "ret = default;\n"
  2689. << INDENT1 "}\n";
  2690. }
  2691. if (p_isignal.method_doc && p_isignal.method_doc->description.size()) {
  2692. String xml_summary = bbcode_to_xml(fix_doc_description(p_isignal.method_doc->description), &p_itype, true);
  2693. Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
  2694. if (summary_lines.size()) {
  2695. p_output.append(MEMBER_BEGIN "/// <summary>\n");
  2696. for (int i = 0; i < summary_lines.size(); i++) {
  2697. p_output.append(INDENT1 "/// ");
  2698. p_output.append(summary_lines[i]);
  2699. p_output.append("\n");
  2700. }
  2701. p_output.append(INDENT1 "/// </summary>");
  2702. }
  2703. }
  2704. // TODO:
  2705. // Could we assume the StringName instance of signal name will never be freed (it's stored in ClassDB) before the managed world is unloaded?
  2706. // If so, we could store the pointer we get from `data_unique_pointer()` instead of allocating StringName here.
  2707. // Generate event
  2708. if (p_isignal.is_deprecated) {
  2709. p_output.append(MEMBER_BEGIN "[Obsolete(\"");
  2710. p_output.append(bbcode_to_text(p_isignal.deprecation_message, &p_itype));
  2711. p_output.append("\")]");
  2712. }
  2713. p_output.append(MEMBER_BEGIN "public ");
  2714. if (p_itype.is_singleton) {
  2715. p_output.append("static ");
  2716. }
  2717. if (!is_parameterless) {
  2718. // `unsafe` is needed for taking the trampoline's function pointer
  2719. p_output << "unsafe ";
  2720. }
  2721. p_output.append("event ");
  2722. p_output.append(delegate_name);
  2723. p_output.append(" ");
  2724. p_output.append(p_isignal.proxy_name);
  2725. p_output.append("\n" OPEN_BLOCK_L1 INDENT2);
  2726. if (p_itype.is_singleton) {
  2727. p_output.append("add => " CS_PROPERTY_SINGLETON ".Connect(SignalName.");
  2728. } else {
  2729. p_output.append("add => Connect(SignalName.");
  2730. }
  2731. if (is_parameterless) {
  2732. // Delegate type is Action. No need for custom trampoline.
  2733. p_output << p_isignal.proxy_name << ", Callable.From(value));\n";
  2734. } else {
  2735. p_output << p_isignal.proxy_name
  2736. << ", Callable.CreateWithUnsafeTrampoline(value, &" << p_isignal.proxy_name << "Trampoline));\n";
  2737. }
  2738. if (p_itype.is_singleton) {
  2739. p_output.append(INDENT2 "remove => " CS_PROPERTY_SINGLETON ".Disconnect(SignalName.");
  2740. } else {
  2741. p_output.append(INDENT2 "remove => Disconnect(SignalName.");
  2742. }
  2743. if (is_parameterless) {
  2744. // Delegate type is Action. No need for custom trampoline.
  2745. p_output << p_isignal.proxy_name << ", Callable.From(value));\n";
  2746. } else {
  2747. p_output << p_isignal.proxy_name
  2748. << ", Callable.CreateWithUnsafeTrampoline(value, &" << p_isignal.proxy_name << "Trampoline));\n";
  2749. }
  2750. p_output.append(CLOSE_BLOCK_L1);
  2751. // Generate EmitSignal{EventName} method to raise the event.
  2752. if (!p_itype.is_singleton) {
  2753. if (p_isignal.is_deprecated) {
  2754. p_output.append(MEMBER_BEGIN "[Obsolete(\"");
  2755. p_output.append(bbcode_to_text(p_isignal.deprecation_message, &p_itype));
  2756. p_output.append("\")]");
  2757. }
  2758. p_output.append(MEMBER_BEGIN "protected void ");
  2759. p_output << "EmitSignal" << p_isignal.proxy_name;
  2760. if (is_parameterless) {
  2761. p_output.append("()\n" OPEN_BLOCK_L1 INDENT2);
  2762. p_output << "EmitSignal(SignalName." << p_isignal.proxy_name << ");\n";
  2763. p_output.append(CLOSE_BLOCK_L1);
  2764. } else {
  2765. p_output.append("(");
  2766. StringBuilder cs_emitsignal_params;
  2767. int idx = 0;
  2768. for (const ArgumentInterface &iarg : p_isignal.arguments) {
  2769. const TypeInterface *arg_type = _get_type_or_null(iarg.type);
  2770. ERR_FAIL_NULL_V_MSG(arg_type, ERR_BUG, "Argument type '" + iarg.type.cname + "' was not found.");
  2771. if (idx != 0) {
  2772. p_output << ", ";
  2773. cs_emitsignal_params << ", ";
  2774. }
  2775. String arg_cs_type = arg_type->cs_type + _get_generic_type_parameters(*arg_type, iarg.type.generic_type_parameters);
  2776. p_output << arg_cs_type << " " << iarg.name;
  2777. if (arg_type->is_enum) {
  2778. cs_emitsignal_params << "(long)";
  2779. }
  2780. cs_emitsignal_params << iarg.name;
  2781. idx++;
  2782. }
  2783. p_output.append(")\n" OPEN_BLOCK_L1 INDENT2);
  2784. p_output << "EmitSignal(SignalName." << p_isignal.proxy_name << ", " << cs_emitsignal_params << ");\n";
  2785. p_output.append(CLOSE_BLOCK_L1);
  2786. }
  2787. }
  2788. }
  2789. return OK;
  2790. }
  2791. Error BindingsGenerator::_generate_cs_native_calls(const InternalCall &p_icall, StringBuilder &r_output) {
  2792. bool ret_void = p_icall.return_type.cname == name_cache.type_void;
  2793. const TypeInterface *return_type = _get_type_or_null(p_icall.return_type);
  2794. ERR_FAIL_NULL_V_MSG(return_type, ERR_BUG, "Return type '" + p_icall.return_type.cname + "' was not found.");
  2795. StringBuilder c_func_sig;
  2796. StringBuilder c_in_statements;
  2797. StringBuilder c_args_var_content;
  2798. c_func_sig << "IntPtr " CS_PARAM_METHODBIND;
  2799. if (!p_icall.is_static) {
  2800. c_func_sig += ", IntPtr " CS_PARAM_INSTANCE;
  2801. }
  2802. // Get arguments information
  2803. int i = 0;
  2804. for (const TypeReference &arg_type_ref : p_icall.argument_types) {
  2805. const TypeInterface *arg_type = _get_type_or_null(arg_type_ref);
  2806. ERR_FAIL_NULL_V_MSG(arg_type, ERR_BUG, "Argument type '" + arg_type_ref.cname + "' was not found.");
  2807. String c_param_name = "arg" + itos(i + 1);
  2808. if (p_icall.is_vararg) {
  2809. if (i < p_icall.get_arguments_count() - 1) {
  2810. String c_in_vararg = arg_type->c_in_vararg;
  2811. if (arg_type->is_object_type) {
  2812. c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromGodotObjectPtr(%1);\n";
  2813. }
  2814. ERR_FAIL_COND_V_MSG(c_in_vararg.is_empty(), ERR_BUG,
  2815. "VarArg support not implemented for parameter type: " + arg_type->name);
  2816. c_in_statements
  2817. << sformat(c_in_vararg, return_type->c_type, c_param_name,
  2818. String(), String(), String(), INDENT3)
  2819. << INDENT3 C_LOCAL_PTRCALL_ARGS "[" << itos(i)
  2820. << "] = new IntPtr(&" << c_param_name << "_in);\n";
  2821. }
  2822. } else {
  2823. if (i > 0) {
  2824. c_args_var_content << ", ";
  2825. }
  2826. if (arg_type->c_in.size()) {
  2827. c_in_statements << sformat(arg_type->c_in, arg_type->c_type, c_param_name,
  2828. String(), String(), String(), INDENT2);
  2829. }
  2830. c_args_var_content << sformat(arg_type->c_arg_in, c_param_name);
  2831. }
  2832. c_func_sig << ", " << arg_type->c_type_in << " " << c_param_name;
  2833. i++;
  2834. }
  2835. // Collect caller name for MethodBind
  2836. if (p_icall.is_vararg) {
  2837. c_func_sig << ", godot_string_name caller";
  2838. }
  2839. String icall_method = p_icall.name;
  2840. // Generate icall function
  2841. r_output << MEMBER_BEGIN "internal static unsafe " << (ret_void ? "void" : return_type->c_type_out) << " "
  2842. << icall_method << "(" << c_func_sig.as_string() << ")\n" OPEN_BLOCK_L1;
  2843. if (!p_icall.is_static) {
  2844. r_output << INDENT2 "ExceptionUtils.ThrowIfNullPtr(" CS_PARAM_INSTANCE ");\n";
  2845. }
  2846. if (!ret_void && (!p_icall.is_vararg || return_type->cname != name_cache.type_Variant)) {
  2847. String ptrcall_return_type;
  2848. String initialization;
  2849. if (return_type->is_object_type) {
  2850. ptrcall_return_type = return_type->is_ref_counted ? "godot_ref" : return_type->c_type;
  2851. initialization = " = default";
  2852. } else {
  2853. ptrcall_return_type = return_type->c_type;
  2854. }
  2855. r_output << INDENT2;
  2856. if (return_type->is_ref_counted || return_type->c_type_is_disposable_struct) {
  2857. r_output << "using ";
  2858. if (initialization.is_empty()) {
  2859. initialization = " = default";
  2860. }
  2861. } else if (return_type->c_ret_needs_default_initialization) {
  2862. initialization = " = default";
  2863. }
  2864. r_output << ptrcall_return_type << " " C_LOCAL_RET << initialization << ";\n";
  2865. }
  2866. String argc_str = itos(p_icall.get_arguments_count());
  2867. auto generate_call_and_return_stmts = [&](const char *base_indent) {
  2868. if (p_icall.is_vararg) {
  2869. // MethodBind Call
  2870. r_output << base_indent;
  2871. // VarArg methods always return Variant, but there are some cases in which MethodInfo provides
  2872. // a specific return type. We trust this information is valid. We need a temporary local to keep
  2873. // the Variant alive until the method returns. Otherwise, if the returned Variant holds a RefPtr,
  2874. // it could be deleted too early. This is the case with GDScript.new() which returns OBJECT.
  2875. // Alternatively, we could just return Variant, but that would result in a worse API.
  2876. if (!ret_void) {
  2877. if (return_type->cname != name_cache.type_Variant) {
  2878. // Usually the return value takes ownership, but in this case the variant is only used
  2879. // for conversion to another return type. As such, the local variable takes ownership.
  2880. r_output << "using godot_variant " << C_LOCAL_VARARG_RET " = ";
  2881. } else {
  2882. // Variant's [c_out] takes ownership of the variant value
  2883. r_output << "godot_variant " << C_LOCAL_RET " = ";
  2884. }
  2885. }
  2886. r_output << C_CLASS_NATIVE_FUNCS ".godotsharp_method_bind_call("
  2887. << CS_PARAM_METHODBIND ", " << (p_icall.is_static ? "IntPtr.Zero" : CS_PARAM_INSTANCE)
  2888. << ", " << (p_icall.get_arguments_count() ? "(godot_variant**)" C_LOCAL_PTRCALL_ARGS : "null")
  2889. << ", total_length, out godot_variant_call_error vcall_error);\n";
  2890. r_output << base_indent << "ExceptionUtils.DebugCheckCallError(caller"
  2891. << ", " << (p_icall.is_static ? "IntPtr.Zero" : CS_PARAM_INSTANCE)
  2892. << ", " << (p_icall.get_arguments_count() ? "(godot_variant**)" C_LOCAL_PTRCALL_ARGS : "null")
  2893. << ", total_length, vcall_error);\n";
  2894. if (!ret_void) {
  2895. if (return_type->cname != name_cache.type_Variant) {
  2896. if (return_type->cname == name_cache.enum_Error) {
  2897. r_output << base_indent << C_LOCAL_RET " = VariantUtils.ConvertToInt64(" C_LOCAL_VARARG_RET ");\n";
  2898. } else {
  2899. // TODO: Use something similar to c_in_vararg (see usage above, with error if not implemented)
  2900. CRASH_NOW_MSG("Custom VarArg return type not implemented: " + return_type->name);
  2901. r_output << base_indent << C_LOCAL_RET " = " C_LOCAL_VARARG_RET ";\n";
  2902. }
  2903. }
  2904. }
  2905. } else {
  2906. // MethodBind PtrCall
  2907. r_output << base_indent << C_CLASS_NATIVE_FUNCS ".godotsharp_method_bind_ptrcall("
  2908. << CS_PARAM_METHODBIND ", " << (p_icall.is_static ? "IntPtr.Zero" : CS_PARAM_INSTANCE)
  2909. << ", " << (p_icall.get_arguments_count() ? C_LOCAL_PTRCALL_ARGS : "null")
  2910. << ", " << (!ret_void ? "&" C_LOCAL_RET ");\n" : "null);\n");
  2911. }
  2912. // Return statement
  2913. if (!ret_void) {
  2914. if (return_type->c_out.is_empty()) {
  2915. r_output << base_indent << "return " C_LOCAL_RET ";\n";
  2916. } else {
  2917. r_output << sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET,
  2918. return_type->name, String(), String(), base_indent);
  2919. }
  2920. }
  2921. };
  2922. if (p_icall.get_arguments_count()) {
  2923. if (p_icall.is_vararg) {
  2924. String vararg_arg = "arg" + argc_str;
  2925. String real_argc_str = itos(p_icall.get_arguments_count() - 1); // Arguments count without vararg
  2926. p_icall.get_arguments_count();
  2927. r_output << INDENT2 "int vararg_length = " << vararg_arg << ".Length;\n"
  2928. << INDENT2 "int total_length = " << real_argc_str << " + vararg_length;\n";
  2929. r_output << INDENT2 "Span<godot_variant.movable> varargs_span = vararg_length <= VarArgsSpanThreshold ?\n"
  2930. << INDENT3 "stackalloc godot_variant.movable[VarArgsSpanThreshold] :\n"
  2931. << INDENT3 "new godot_variant.movable[vararg_length];\n";
  2932. r_output << INDENT2 "Span<IntPtr> " C_LOCAL_PTRCALL_ARGS "_span = total_length <= VarArgsSpanThreshold ?\n"
  2933. << INDENT3 "stackalloc IntPtr[VarArgsSpanThreshold] :\n"
  2934. << INDENT3 "new IntPtr[total_length];\n";
  2935. r_output << INDENT2 "fixed (godot_variant.movable* varargs = &MemoryMarshal.GetReference(varargs_span))\n"
  2936. << INDENT2 "fixed (IntPtr* " C_LOCAL_PTRCALL_ARGS " = "
  2937. "&MemoryMarshal.GetReference(" C_LOCAL_PTRCALL_ARGS "_span))\n"
  2938. << OPEN_BLOCK_L2;
  2939. r_output << c_in_statements.as_string();
  2940. r_output << INDENT3 "for (int i = 0; i < vararg_length; i++)\n" OPEN_BLOCK_L3
  2941. << INDENT4 "varargs[i] = " << vararg_arg << "[i].NativeVar;\n"
  2942. << INDENT4 C_LOCAL_PTRCALL_ARGS "[" << real_argc_str << " + i] = new IntPtr(&varargs[i]);\n"
  2943. << CLOSE_BLOCK_L3;
  2944. generate_call_and_return_stmts(INDENT3);
  2945. r_output << CLOSE_BLOCK_L2;
  2946. } else {
  2947. r_output << c_in_statements.as_string();
  2948. r_output << INDENT2 "void** " C_LOCAL_PTRCALL_ARGS " = stackalloc void*["
  2949. << argc_str << "] { " << c_args_var_content.as_string() << " };\n";
  2950. generate_call_and_return_stmts(INDENT2);
  2951. }
  2952. } else {
  2953. generate_call_and_return_stmts(INDENT2);
  2954. }
  2955. r_output << CLOSE_BLOCK_L1;
  2956. return OK;
  2957. }
  2958. Error BindingsGenerator::_save_file(const String &p_path, const StringBuilder &p_content) {
  2959. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE);
  2960. ERR_FAIL_COND_V_MSG(file.is_null(), ERR_FILE_CANT_WRITE, "Cannot open file: '" + p_path + "'.");
  2961. file->store_string(p_content.as_string());
  2962. return OK;
  2963. }
  2964. const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_null(const TypeReference &p_typeref) {
  2965. HashMap<StringName, TypeInterface>::ConstIterator builtin_type_match = builtin_types.find(p_typeref.cname);
  2966. if (builtin_type_match) {
  2967. return &builtin_type_match->value;
  2968. }
  2969. HashMap<StringName, TypeInterface>::ConstIterator obj_type_match = obj_types.find(p_typeref.cname);
  2970. if (obj_type_match) {
  2971. return &obj_type_match->value;
  2972. }
  2973. if (p_typeref.is_enum) {
  2974. HashMap<StringName, TypeInterface>::ConstIterator enum_match = enum_types.find(p_typeref.cname);
  2975. if (enum_match) {
  2976. return &enum_match->value;
  2977. }
  2978. // Enum not found. Most likely because none of its constants were bound, so it's empty. That's fine. Use int instead.
  2979. HashMap<StringName, TypeInterface>::ConstIterator int_match = builtin_types.find(name_cache.type_int);
  2980. ERR_FAIL_NULL_V(int_match, nullptr);
  2981. return &int_match->value;
  2982. }
  2983. return nullptr;
  2984. }
  2985. const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_singleton_or_null(const TypeReference &p_typeref) {
  2986. const TypeInterface *itype = _get_type_or_null(p_typeref);
  2987. if (itype == nullptr) {
  2988. return nullptr;
  2989. }
  2990. if (itype->is_singleton) {
  2991. StringName instance_type_name = itype->name + CS_SINGLETON_INSTANCE_SUFFIX;
  2992. itype = &obj_types.find(instance_type_name)->value;
  2993. }
  2994. return itype;
  2995. }
  2996. const String BindingsGenerator::_get_generic_type_parameters(const TypeInterface &p_itype, const List<TypeReference> &p_generic_type_parameters) {
  2997. if (p_generic_type_parameters.is_empty()) {
  2998. return "";
  2999. }
  3000. ERR_FAIL_COND_V_MSG(p_itype.type_parameter_count != p_generic_type_parameters.size(), "",
  3001. "Generic type parameter count mismatch for type '" + p_itype.name + "'." +
  3002. " Found " + itos(p_generic_type_parameters.size()) + ", but requires " +
  3003. itos(p_itype.type_parameter_count) + ".");
  3004. int i = 0;
  3005. String params = "<";
  3006. for (const TypeReference &param_type : p_generic_type_parameters) {
  3007. const TypeInterface *param_itype = _get_type_or_singleton_or_null(param_type);
  3008. ERR_FAIL_NULL_V_MSG(param_itype, "", "Parameter type '" + param_type.cname + "' was not found.");
  3009. ERR_FAIL_COND_V_MSG(param_itype->is_singleton, "",
  3010. "Generic type parameter is a singleton: '" + param_itype->name + "'.");
  3011. if (p_itype.api_type == ClassDB::API_CORE) {
  3012. ERR_FAIL_COND_V_MSG(param_itype->api_type == ClassDB::API_EDITOR, "",
  3013. "Generic type parameter '" + param_itype->name + "' has type from the editor API." +
  3014. " Core API cannot have dependencies on the editor API.");
  3015. }
  3016. params += param_itype->cs_type;
  3017. if (i < p_generic_type_parameters.size() - 1) {
  3018. params += ", ";
  3019. }
  3020. i++;
  3021. }
  3022. params += ">";
  3023. return params;
  3024. }
  3025. StringName BindingsGenerator::_get_type_name_from_meta(Variant::Type p_type, GodotTypeInfo::Metadata p_meta) {
  3026. if (p_type == Variant::INT) {
  3027. return _get_int_type_name_from_meta(p_meta);
  3028. } else if (p_type == Variant::FLOAT) {
  3029. return _get_float_type_name_from_meta(p_meta);
  3030. } else {
  3031. return Variant::get_type_name(p_type);
  3032. }
  3033. }
  3034. StringName BindingsGenerator::_get_int_type_name_from_meta(GodotTypeInfo::Metadata p_meta) {
  3035. switch (p_meta) {
  3036. case GodotTypeInfo::METADATA_INT_IS_INT8:
  3037. return "sbyte";
  3038. break;
  3039. case GodotTypeInfo::METADATA_INT_IS_INT16:
  3040. return "short";
  3041. break;
  3042. case GodotTypeInfo::METADATA_INT_IS_INT32:
  3043. return "int";
  3044. break;
  3045. case GodotTypeInfo::METADATA_INT_IS_INT64:
  3046. return "long";
  3047. break;
  3048. case GodotTypeInfo::METADATA_INT_IS_UINT8:
  3049. return "byte";
  3050. break;
  3051. case GodotTypeInfo::METADATA_INT_IS_UINT16:
  3052. return "ushort";
  3053. break;
  3054. case GodotTypeInfo::METADATA_INT_IS_UINT32:
  3055. return "uint";
  3056. break;
  3057. case GodotTypeInfo::METADATA_INT_IS_UINT64:
  3058. return "ulong";
  3059. break;
  3060. case GodotTypeInfo::METADATA_INT_IS_CHAR16:
  3061. return "char";
  3062. break;
  3063. case GodotTypeInfo::METADATA_INT_IS_CHAR32:
  3064. // To prevent breaking compatibility, C# bindings need to keep using `long`.
  3065. return "long";
  3066. default:
  3067. // Assume INT64
  3068. return "long";
  3069. }
  3070. }
  3071. StringName BindingsGenerator::_get_float_type_name_from_meta(GodotTypeInfo::Metadata p_meta) {
  3072. switch (p_meta) {
  3073. case GodotTypeInfo::METADATA_REAL_IS_FLOAT:
  3074. return "float";
  3075. break;
  3076. case GodotTypeInfo::METADATA_REAL_IS_DOUBLE:
  3077. return "double";
  3078. break;
  3079. default:
  3080. // Assume FLOAT64
  3081. return "double";
  3082. }
  3083. }
  3084. bool BindingsGenerator::_arg_default_value_is_assignable_to_type(const Variant &p_val, const TypeInterface &p_arg_type) {
  3085. if (p_arg_type.name == name_cache.type_Variant) {
  3086. // Variant can take anything
  3087. return true;
  3088. }
  3089. switch (p_val.get_type()) {
  3090. case Variant::NIL:
  3091. return p_arg_type.is_object_type ||
  3092. name_cache.is_nullable_type(p_arg_type.name);
  3093. case Variant::BOOL:
  3094. return p_arg_type.name == name_cache.type_bool;
  3095. case Variant::INT:
  3096. return p_arg_type.name == name_cache.type_sbyte ||
  3097. p_arg_type.name == name_cache.type_short ||
  3098. p_arg_type.name == name_cache.type_int ||
  3099. p_arg_type.name == name_cache.type_byte ||
  3100. p_arg_type.name == name_cache.type_ushort ||
  3101. p_arg_type.name == name_cache.type_uint ||
  3102. p_arg_type.name == name_cache.type_long ||
  3103. p_arg_type.name == name_cache.type_ulong ||
  3104. p_arg_type.name == name_cache.type_float ||
  3105. p_arg_type.name == name_cache.type_double ||
  3106. p_arg_type.is_enum;
  3107. case Variant::FLOAT:
  3108. return p_arg_type.name == name_cache.type_float ||
  3109. p_arg_type.name == name_cache.type_double;
  3110. case Variant::STRING:
  3111. case Variant::STRING_NAME:
  3112. return p_arg_type.name == name_cache.type_String ||
  3113. p_arg_type.name == name_cache.type_StringName ||
  3114. p_arg_type.name == name_cache.type_NodePath;
  3115. case Variant::NODE_PATH:
  3116. return p_arg_type.name == name_cache.type_NodePath;
  3117. case Variant::TRANSFORM2D:
  3118. case Variant::TRANSFORM3D:
  3119. case Variant::BASIS:
  3120. case Variant::QUATERNION:
  3121. case Variant::PLANE:
  3122. case Variant::AABB:
  3123. case Variant::COLOR:
  3124. case Variant::VECTOR2:
  3125. case Variant::RECT2:
  3126. case Variant::VECTOR3:
  3127. case Variant::RID:
  3128. case Variant::PACKED_BYTE_ARRAY:
  3129. case Variant::PACKED_INT32_ARRAY:
  3130. case Variant::PACKED_INT64_ARRAY:
  3131. case Variant::PACKED_FLOAT32_ARRAY:
  3132. case Variant::PACKED_FLOAT64_ARRAY:
  3133. case Variant::PACKED_STRING_ARRAY:
  3134. case Variant::PACKED_VECTOR2_ARRAY:
  3135. case Variant::PACKED_VECTOR3_ARRAY:
  3136. case Variant::PACKED_VECTOR4_ARRAY:
  3137. case Variant::PACKED_COLOR_ARRAY:
  3138. case Variant::CALLABLE:
  3139. case Variant::SIGNAL:
  3140. return p_arg_type.name == Variant::get_type_name(p_val.get_type());
  3141. case Variant::ARRAY:
  3142. return p_arg_type.name == Variant::get_type_name(p_val.get_type()) || p_arg_type.cname == name_cache.type_Array_generic;
  3143. case Variant::DICTIONARY:
  3144. return p_arg_type.name == Variant::get_type_name(p_val.get_type()) || p_arg_type.cname == name_cache.type_Dictionary_generic;
  3145. case Variant::OBJECT:
  3146. return p_arg_type.is_object_type;
  3147. case Variant::VECTOR2I:
  3148. return p_arg_type.name == name_cache.type_Vector2 ||
  3149. p_arg_type.name == Variant::get_type_name(p_val.get_type());
  3150. case Variant::RECT2I:
  3151. return p_arg_type.name == name_cache.type_Rect2 ||
  3152. p_arg_type.name == Variant::get_type_name(p_val.get_type());
  3153. case Variant::VECTOR3I:
  3154. return p_arg_type.name == name_cache.type_Vector3 ||
  3155. p_arg_type.name == Variant::get_type_name(p_val.get_type());
  3156. default:
  3157. CRASH_NOW_MSG("Unexpected Variant type: " + itos(p_val.get_type()));
  3158. break;
  3159. }
  3160. return false;
  3161. }
  3162. bool method_has_ptr_parameter(MethodInfo p_method_info) {
  3163. if (p_method_info.return_val.type == Variant::INT && p_method_info.return_val.hint == PROPERTY_HINT_INT_IS_POINTER) {
  3164. return true;
  3165. }
  3166. for (PropertyInfo arg : p_method_info.arguments) {
  3167. if (arg.type == Variant::INT && arg.hint == PROPERTY_HINT_INT_IS_POINTER) {
  3168. return true;
  3169. }
  3170. }
  3171. return false;
  3172. }
  3173. struct SortMethodWithHashes {
  3174. _FORCE_INLINE_ bool operator()(const Pair<MethodInfo, uint32_t> &p_a, const Pair<MethodInfo, uint32_t> &p_b) const {
  3175. return p_a.first < p_b.first;
  3176. }
  3177. };
  3178. bool BindingsGenerator::_populate_object_type_interfaces() {
  3179. obj_types.clear();
  3180. List<StringName> class_list;
  3181. ClassDB::get_class_list(&class_list);
  3182. class_list.sort_custom<StringName::AlphCompare>();
  3183. while (class_list.size()) {
  3184. StringName type_cname = class_list.front()->get();
  3185. ClassDB::APIType api_type = ClassDB::get_api_type(type_cname);
  3186. if (api_type == ClassDB::API_NONE) {
  3187. class_list.pop_front();
  3188. continue;
  3189. }
  3190. if (ignored_types.has(type_cname)) {
  3191. _log("Ignoring type '%s' because it's in the list of ignored types\n", String(type_cname).utf8().get_data());
  3192. class_list.pop_front();
  3193. continue;
  3194. }
  3195. if (!ClassDB::is_class_exposed(type_cname)) {
  3196. _log("Ignoring type '%s' because it's not exposed\n", String(type_cname).utf8().get_data());
  3197. class_list.pop_front();
  3198. continue;
  3199. }
  3200. if (!ClassDB::is_class_enabled(type_cname)) {
  3201. _log("Ignoring type '%s' because it's not enabled\n", String(type_cname).utf8().get_data());
  3202. class_list.pop_front();
  3203. continue;
  3204. }
  3205. ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(type_cname);
  3206. TypeInterface itype = TypeInterface::create_object_type(type_cname, pascal_to_pascal_case(type_cname), api_type);
  3207. itype.base_name = ClassDB::get_parent_class(type_cname);
  3208. itype.is_singleton = Engine::get_singleton()->has_singleton(type_cname);
  3209. itype.is_instantiable = class_info->creation_func && !itype.is_singleton;
  3210. itype.is_ref_counted = ClassDB::is_parent_class(type_cname, name_cache.type_RefCounted);
  3211. itype.memory_own = itype.is_ref_counted;
  3212. if (itype.class_doc) {
  3213. itype.is_deprecated = itype.class_doc->is_deprecated;
  3214. itype.deprecation_message = itype.class_doc->deprecated_message;
  3215. if (itype.is_deprecated && itype.deprecation_message.is_empty()) {
  3216. WARN_PRINT("An empty deprecation message is discouraged. Type: '" + itype.proxy_name + "'.");
  3217. itype.deprecation_message = "This class is deprecated.";
  3218. }
  3219. }
  3220. if (itype.is_singleton && compat_singletons.has(itype.cname)) {
  3221. itype.is_singleton = false;
  3222. itype.is_compat_singleton = true;
  3223. }
  3224. itype.c_out = "%5return ";
  3225. itype.c_out += C_METHOD_UNMANAGED_GET_MANAGED;
  3226. itype.c_out += itype.is_ref_counted ? "(%1.Reference);\n" : "(%1);\n";
  3227. itype.cs_type = itype.proxy_name;
  3228. itype.cs_in_expr = "GodotObject." CS_STATIC_METHOD_GETINSTANCE "(%0)";
  3229. itype.cs_out = "%5return (%2)%0(%1);";
  3230. itype.c_arg_in = "&%s";
  3231. itype.c_type = "IntPtr";
  3232. itype.c_type_in = itype.c_type;
  3233. itype.c_type_out = "GodotObject";
  3234. // Populate properties
  3235. List<PropertyInfo> property_list;
  3236. ClassDB::get_property_list(type_cname, &property_list, true);
  3237. HashMap<StringName, StringName> accessor_methods;
  3238. for (const PropertyInfo &property : property_list) {
  3239. if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY || (property.type == Variant::NIL && property.usage & PROPERTY_USAGE_ARRAY)) {
  3240. continue;
  3241. }
  3242. if (property.name.contains_char('/')) {
  3243. // Ignore properties with '/' (slash) in the name. These are only meant for use in the inspector.
  3244. continue;
  3245. }
  3246. PropertyInterface iprop;
  3247. iprop.cname = property.name;
  3248. iprop.setter = ClassDB::get_property_setter(type_cname, iprop.cname);
  3249. iprop.getter = ClassDB::get_property_getter(type_cname, iprop.cname);
  3250. // If the property is internal hide it; otherwise, hide the getter and setter.
  3251. if (property.usage & PROPERTY_USAGE_INTERNAL) {
  3252. iprop.is_hidden = true;
  3253. } else {
  3254. if (iprop.setter != StringName()) {
  3255. accessor_methods[iprop.setter] = iprop.cname;
  3256. }
  3257. if (iprop.getter != StringName()) {
  3258. accessor_methods[iprop.getter] = iprop.cname;
  3259. }
  3260. }
  3261. bool valid = false;
  3262. iprop.index = ClassDB::get_property_index(type_cname, iprop.cname, &valid);
  3263. ERR_FAIL_COND_V_MSG(!valid, false, "Invalid property: '" + itype.name + "." + String(iprop.cname) + "'.");
  3264. iprop.proxy_name = escape_csharp_keyword(snake_to_pascal_case(iprop.cname));
  3265. // Prevent the property and its enclosing type from sharing the same name
  3266. if (iprop.proxy_name == itype.proxy_name) {
  3267. _log("Name of property '%s' is ambiguous with the name of its enclosing class '%s'. Renaming property to '%s_'\n",
  3268. iprop.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), iprop.proxy_name.utf8().get_data());
  3269. iprop.proxy_name += "_";
  3270. }
  3271. iprop.prop_doc = nullptr;
  3272. for (int i = 0; i < itype.class_doc->properties.size(); i++) {
  3273. const DocData::PropertyDoc &prop_doc = itype.class_doc->properties[i];
  3274. if (prop_doc.name == iprop.cname) {
  3275. iprop.prop_doc = &prop_doc;
  3276. break;
  3277. }
  3278. }
  3279. if (iprop.prop_doc) {
  3280. iprop.is_deprecated = iprop.prop_doc->is_deprecated;
  3281. iprop.deprecation_message = iprop.prop_doc->deprecated_message;
  3282. if (iprop.is_deprecated && iprop.deprecation_message.is_empty()) {
  3283. WARN_PRINT("An empty deprecation message is discouraged. Property: '" + itype.proxy_name + "." + iprop.proxy_name + "'.");
  3284. iprop.deprecation_message = "This property is deprecated.";
  3285. }
  3286. }
  3287. itype.properties.push_back(iprop);
  3288. }
  3289. // Populate methods
  3290. List<MethodInfo> virtual_method_list;
  3291. ClassDB::get_virtual_methods(type_cname, &virtual_method_list, true);
  3292. List<Pair<MethodInfo, uint32_t>> method_list_with_hashes;
  3293. ClassDB::get_method_list_with_compatibility(type_cname, &method_list_with_hashes, true);
  3294. method_list_with_hashes.sort_custom_inplace<SortMethodWithHashes>();
  3295. List<MethodInterface> compat_methods;
  3296. for (const Pair<MethodInfo, uint32_t> &E : method_list_with_hashes) {
  3297. const MethodInfo &method_info = E.first;
  3298. const uint32_t hash = E.second;
  3299. if (method_info.name.is_empty()) {
  3300. continue;
  3301. }
  3302. String cname = method_info.name;
  3303. if (blacklisted_methods.find(itype.cname) && blacklisted_methods[itype.cname].find(cname)) {
  3304. continue;
  3305. }
  3306. if (method_has_ptr_parameter(method_info)) {
  3307. // Pointers are not supported.
  3308. itype.ignored_members.insert(method_info.name);
  3309. continue;
  3310. }
  3311. MethodInterface imethod;
  3312. imethod.name = method_info.name;
  3313. imethod.cname = cname;
  3314. imethod.hash = hash;
  3315. if (method_info.flags & METHOD_FLAG_STATIC) {
  3316. imethod.is_static = true;
  3317. }
  3318. if (method_info.flags & METHOD_FLAG_VIRTUAL) {
  3319. imethod.is_virtual = true;
  3320. itype.has_virtual_methods = true;
  3321. }
  3322. PropertyInfo return_info = method_info.return_val;
  3323. MethodBind *m = nullptr;
  3324. if (!imethod.is_virtual) {
  3325. bool method_exists = false;
  3326. m = ClassDB::get_method_with_compatibility(type_cname, method_info.name, hash, &method_exists, &imethod.is_compat);
  3327. if (unlikely(!method_exists)) {
  3328. ERR_FAIL_COND_V_MSG(!virtual_method_list.find(method_info), false,
  3329. "Missing MethodBind for non-virtual method: '" + itype.name + "." + imethod.name + "'.");
  3330. }
  3331. }
  3332. imethod.is_vararg = m && m->is_vararg();
  3333. if (!m && !imethod.is_virtual) {
  3334. ERR_FAIL_COND_V_MSG(!virtual_method_list.find(method_info), false,
  3335. "Missing MethodBind for non-virtual method: '" + itype.name + "." + imethod.name + "'.");
  3336. // A virtual method without the virtual flag. This is a special case.
  3337. // There is no method bind, so let's fallback to Godot's object.Call(string, params)
  3338. imethod.requires_object_call = true;
  3339. // The method Object.free is registered as a virtual method, but without the virtual flag.
  3340. // This is because this method is not supposed to be overridden, but called.
  3341. // We assume the return type is void.
  3342. imethod.return_type.cname = name_cache.type_void;
  3343. // Actually, more methods like this may be added in the future, which could return
  3344. // something different. Let's put this check to notify us if that ever happens.
  3345. if (itype.cname != name_cache.type_Object || imethod.name != "free") {
  3346. WARN_PRINT("Notification: New unexpected virtual non-overridable method found."
  3347. " We only expected Object.free, but found '" +
  3348. itype.name + "." + imethod.name + "'.");
  3349. }
  3350. } else if (return_info.type == Variant::INT && return_info.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) {
  3351. imethod.return_type.cname = return_info.class_name;
  3352. imethod.return_type.is_enum = true;
  3353. } else if (return_info.class_name != StringName()) {
  3354. imethod.return_type.cname = return_info.class_name;
  3355. bool bad_reference_hint = !imethod.is_virtual && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE &&
  3356. ClassDB::is_parent_class(return_info.class_name, name_cache.type_RefCounted);
  3357. ERR_FAIL_COND_V_MSG(bad_reference_hint, false,
  3358. String() + "Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'." +
  3359. " Are you returning a reference type by pointer? Method: '" + itype.name + "." + imethod.name + "'.");
  3360. } else if (return_info.type == Variant::ARRAY && return_info.hint == PROPERTY_HINT_ARRAY_TYPE) {
  3361. imethod.return_type.cname = Variant::get_type_name(return_info.type) + "_@generic";
  3362. imethod.return_type.generic_type_parameters.push_back(TypeReference(return_info.hint_string));
  3363. } else if (return_info.type == Variant::DICTIONARY && return_info.hint == PROPERTY_HINT_DICTIONARY_TYPE) {
  3364. imethod.return_type.cname = Variant::get_type_name(return_info.type) + "_@generic";
  3365. Vector<String> split = return_info.hint_string.split(";");
  3366. imethod.return_type.generic_type_parameters.push_back(TypeReference(split.get(0)));
  3367. imethod.return_type.generic_type_parameters.push_back(TypeReference(split.get(1)));
  3368. } else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  3369. imethod.return_type.cname = return_info.hint_string;
  3370. } else if (return_info.type == Variant::NIL && return_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
  3371. imethod.return_type.cname = name_cache.type_Variant;
  3372. } else if (return_info.type == Variant::NIL) {
  3373. imethod.return_type.cname = name_cache.type_void;
  3374. } else {
  3375. imethod.return_type.cname = _get_type_name_from_meta(return_info.type, m ? m->get_argument_meta(-1) : (GodotTypeInfo::Metadata)method_info.return_val_metadata);
  3376. }
  3377. int idx = 0;
  3378. for (List<PropertyInfo>::ConstIterator itr = method_info.arguments.begin(); itr != method_info.arguments.end(); ++itr, ++idx) {
  3379. const PropertyInfo &arginfo = *itr;
  3380. String orig_arg_name = arginfo.name;
  3381. ArgumentInterface iarg;
  3382. iarg.name = orig_arg_name;
  3383. if (arginfo.type == Variant::INT && arginfo.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) {
  3384. iarg.type.cname = arginfo.class_name;
  3385. iarg.type.is_enum = true;
  3386. } else if (arginfo.class_name != StringName()) {
  3387. iarg.type.cname = arginfo.class_name;
  3388. } else if (arginfo.type == Variant::ARRAY && arginfo.hint == PROPERTY_HINT_ARRAY_TYPE) {
  3389. iarg.type.cname = Variant::get_type_name(arginfo.type) + "_@generic";
  3390. iarg.type.generic_type_parameters.push_back(TypeReference(arginfo.hint_string));
  3391. } else if (arginfo.type == Variant::DICTIONARY && arginfo.hint == PROPERTY_HINT_DICTIONARY_TYPE) {
  3392. iarg.type.cname = Variant::get_type_name(arginfo.type) + "_@generic";
  3393. Vector<String> split = arginfo.hint_string.split(";");
  3394. iarg.type.generic_type_parameters.push_back(TypeReference(split.get(0)));
  3395. iarg.type.generic_type_parameters.push_back(TypeReference(split.get(1)));
  3396. } else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  3397. iarg.type.cname = arginfo.hint_string;
  3398. } else if (arginfo.type == Variant::NIL) {
  3399. iarg.type.cname = name_cache.type_Variant;
  3400. } else {
  3401. iarg.type.cname = _get_type_name_from_meta(arginfo.type, m ? m->get_argument_meta(idx) : (GodotTypeInfo::Metadata)method_info.get_argument_meta(idx));
  3402. }
  3403. iarg.name = escape_csharp_keyword(snake_to_camel_case(iarg.name));
  3404. if (m && m->has_default_argument(idx)) {
  3405. bool defval_ok = _arg_default_value_from_variant(m->get_default_argument(idx), iarg);
  3406. ERR_FAIL_COND_V_MSG(!defval_ok, false,
  3407. "Cannot determine default value for argument '" + orig_arg_name + "' of method '" + itype.name + "." + imethod.name + "'.");
  3408. }
  3409. imethod.add_argument(iarg);
  3410. }
  3411. if (imethod.is_vararg) {
  3412. ArgumentInterface ivararg;
  3413. ivararg.type.cname = name_cache.type_VarArg;
  3414. ivararg.name = "@args";
  3415. imethod.add_argument(ivararg);
  3416. }
  3417. imethod.proxy_name = escape_csharp_keyword(snake_to_pascal_case(imethod.name));
  3418. // Prevent the method and its enclosing type from sharing the same name
  3419. if (imethod.proxy_name == itype.proxy_name) {
  3420. _log("Name of method '%s' is ambiguous with the name of its enclosing class '%s'. Renaming method to '%s_'\n",
  3421. imethod.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), imethod.proxy_name.utf8().get_data());
  3422. imethod.proxy_name += "_";
  3423. }
  3424. HashMap<StringName, StringName>::Iterator accessor = accessor_methods.find(imethod.cname);
  3425. if (accessor) {
  3426. // We only hide an accessor method if it's in the same class as the property.
  3427. // It's easier this way, but also we don't know if an accessor method in a different class
  3428. // could have other purposes, so better leave those untouched.
  3429. imethod.is_hidden = true;
  3430. }
  3431. if (itype.class_doc) {
  3432. for (int i = 0; i < itype.class_doc->methods.size(); i++) {
  3433. if (itype.class_doc->methods[i].name == imethod.name) {
  3434. imethod.method_doc = &itype.class_doc->methods[i];
  3435. break;
  3436. }
  3437. }
  3438. }
  3439. if (imethod.method_doc) {
  3440. imethod.is_deprecated = imethod.method_doc->is_deprecated;
  3441. imethod.deprecation_message = imethod.method_doc->deprecated_message;
  3442. if (imethod.is_deprecated && imethod.deprecation_message.is_empty()) {
  3443. WARN_PRINT("An empty deprecation message is discouraged. Method: '" + itype.proxy_name + "." + imethod.proxy_name + "'.");
  3444. imethod.deprecation_message = "This method is deprecated.";
  3445. }
  3446. }
  3447. ERR_FAIL_COND_V_MSG(itype.find_property_by_name(imethod.cname), false,
  3448. "Method name conflicts with property: '" + itype.name + "." + imethod.name + "'.");
  3449. // Compat methods aren't added to the type yet, they need to be checked for conflicts
  3450. // after all the non-compat methods have been added. The compat methods are added in
  3451. // reverse so the most recently added ones take precedence over older compat methods.
  3452. if (imethod.is_compat) {
  3453. imethod.is_hidden = true;
  3454. compat_methods.push_front(imethod);
  3455. continue;
  3456. }
  3457. // Methods starting with an underscore are ignored unless they're used as a property setter or getter
  3458. if (!imethod.is_virtual && imethod.name[0] == '_') {
  3459. for (const PropertyInterface &iprop : itype.properties) {
  3460. if (iprop.setter == imethod.name || iprop.getter == imethod.name) {
  3461. imethod.is_internal = true;
  3462. itype.methods.push_back(imethod);
  3463. break;
  3464. }
  3465. }
  3466. } else {
  3467. itype.methods.push_back(imethod);
  3468. }
  3469. }
  3470. // Add compat methods that don't conflict with other methods in the type.
  3471. for (const MethodInterface &imethod : compat_methods) {
  3472. if (_method_has_conflicting_signature(imethod, itype)) {
  3473. WARN_PRINT("Method '" + imethod.name + "' conflicts with an already existing method in type '" + itype.name + "' and has been ignored.");
  3474. continue;
  3475. }
  3476. itype.methods.push_back(imethod);
  3477. }
  3478. // Populate signals
  3479. const HashMap<StringName, MethodInfo> &signal_map = class_info->signal_map;
  3480. for (const KeyValue<StringName, MethodInfo> &E : signal_map) {
  3481. SignalInterface isignal;
  3482. const MethodInfo &method_info = E.value;
  3483. isignal.name = method_info.name;
  3484. isignal.cname = method_info.name;
  3485. int idx = 0;
  3486. for (List<PropertyInfo>::ConstIterator itr = method_info.arguments.begin(); itr != method_info.arguments.end(); ++itr, ++idx) {
  3487. const PropertyInfo &arginfo = *itr;
  3488. String orig_arg_name = arginfo.name;
  3489. ArgumentInterface iarg;
  3490. iarg.name = orig_arg_name;
  3491. if (arginfo.type == Variant::INT && arginfo.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) {
  3492. iarg.type.cname = arginfo.class_name;
  3493. iarg.type.is_enum = true;
  3494. } else if (arginfo.class_name != StringName()) {
  3495. iarg.type.cname = arginfo.class_name;
  3496. } else if (arginfo.type == Variant::ARRAY && arginfo.hint == PROPERTY_HINT_ARRAY_TYPE) {
  3497. iarg.type.cname = Variant::get_type_name(arginfo.type) + "_@generic";
  3498. iarg.type.generic_type_parameters.push_back(TypeReference(arginfo.hint_string));
  3499. } else if (arginfo.type == Variant::DICTIONARY && arginfo.hint == PROPERTY_HINT_DICTIONARY_TYPE) {
  3500. iarg.type.cname = Variant::get_type_name(arginfo.type) + "_@generic";
  3501. Vector<String> split = arginfo.hint_string.split(";");
  3502. iarg.type.generic_type_parameters.push_back(TypeReference(split.get(0)));
  3503. iarg.type.generic_type_parameters.push_back(TypeReference(split.get(1)));
  3504. } else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  3505. iarg.type.cname = arginfo.hint_string;
  3506. } else if (arginfo.type == Variant::NIL) {
  3507. iarg.type.cname = name_cache.type_Variant;
  3508. } else {
  3509. iarg.type.cname = _get_type_name_from_meta(arginfo.type, (GodotTypeInfo::Metadata)method_info.get_argument_meta(idx));
  3510. }
  3511. iarg.name = escape_csharp_keyword(snake_to_camel_case(iarg.name));
  3512. isignal.add_argument(iarg);
  3513. }
  3514. isignal.proxy_name = escape_csharp_keyword(snake_to_pascal_case(isignal.name));
  3515. // Prevent the signal and its enclosing type from sharing the same name
  3516. if (isignal.proxy_name == itype.proxy_name) {
  3517. _log("Name of signal '%s' is ambiguous with the name of its enclosing class '%s'. Renaming signal to '%s_'\n",
  3518. isignal.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), isignal.proxy_name.utf8().get_data());
  3519. isignal.proxy_name += "_";
  3520. }
  3521. if (itype.find_property_by_proxy_name(isignal.proxy_name) || itype.find_method_by_proxy_name(isignal.proxy_name)) {
  3522. // ClassDB allows signal names that conflict with method or property names.
  3523. // While registering a signal with a conflicting name is considered wrong,
  3524. // it may still happen and it may take some time until someone fixes the name.
  3525. // We can't allow the bindings to be in a broken state while we wait for a fix;
  3526. // that's why we must handle this possibility by renaming the signal.
  3527. isignal.proxy_name += "Signal";
  3528. }
  3529. if (itype.class_doc) {
  3530. for (int i = 0; i < itype.class_doc->signals.size(); i++) {
  3531. const DocData::MethodDoc &signal_doc = itype.class_doc->signals[i];
  3532. if (signal_doc.name == isignal.name) {
  3533. isignal.method_doc = &signal_doc;
  3534. break;
  3535. }
  3536. }
  3537. }
  3538. if (isignal.method_doc) {
  3539. isignal.is_deprecated = isignal.method_doc->is_deprecated;
  3540. isignal.deprecation_message = isignal.method_doc->deprecated_message;
  3541. if (isignal.is_deprecated && isignal.deprecation_message.is_empty()) {
  3542. WARN_PRINT("An empty deprecation message is discouraged. Signal: '" + itype.proxy_name + "." + isignal.proxy_name + "'.");
  3543. isignal.deprecation_message = "This signal is deprecated.";
  3544. }
  3545. }
  3546. itype.signals_.push_back(isignal);
  3547. }
  3548. // Populate enums and constants
  3549. List<String> constants;
  3550. ClassDB::get_integer_constant_list(type_cname, &constants, true);
  3551. const HashMap<StringName, ClassDB::ClassInfo::EnumInfo> &enum_map = class_info->enum_map;
  3552. for (const KeyValue<StringName, ClassDB::ClassInfo::EnumInfo> &E : enum_map) {
  3553. StringName enum_proxy_cname = E.key;
  3554. String enum_proxy_name = pascal_to_pascal_case(enum_proxy_cname.operator String());
  3555. if (itype.find_property_by_proxy_name(enum_proxy_name) || itype.find_method_by_proxy_name(enum_proxy_name) || itype.find_signal_by_proxy_name(enum_proxy_name)) {
  3556. // In case the enum name conflicts with other PascalCase members,
  3557. // we append 'Enum' to the enum name in those cases.
  3558. // We have several conflicts between enums and PascalCase properties.
  3559. enum_proxy_name += "Enum";
  3560. enum_proxy_cname = StringName(enum_proxy_name);
  3561. }
  3562. EnumInterface ienum(enum_proxy_cname, enum_proxy_name, E.value.is_bitfield);
  3563. const List<StringName> &enum_constants = E.value.constants;
  3564. for (const StringName &constant_cname : enum_constants) {
  3565. String constant_name = constant_cname.operator String();
  3566. int64_t *value = class_info->constant_map.getptr(constant_cname);
  3567. ERR_FAIL_NULL_V(value, false);
  3568. constants.erase(constant_name);
  3569. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value);
  3570. iconstant.const_doc = nullptr;
  3571. for (int i = 0; i < itype.class_doc->constants.size(); i++) {
  3572. const DocData::ConstantDoc &const_doc = itype.class_doc->constants[i];
  3573. if (const_doc.name == iconstant.name) {
  3574. iconstant.const_doc = &const_doc;
  3575. break;
  3576. }
  3577. }
  3578. if (iconstant.const_doc) {
  3579. iconstant.is_deprecated = iconstant.const_doc->is_deprecated;
  3580. iconstant.deprecation_message = iconstant.const_doc->deprecated_message;
  3581. if (iconstant.is_deprecated && iconstant.deprecation_message.is_empty()) {
  3582. WARN_PRINT("An empty deprecation message is discouraged. Enum member: '" + itype.proxy_name + "." + ienum.proxy_name + "." + iconstant.proxy_name + "'.");
  3583. iconstant.deprecation_message = "This enum member is deprecated.";
  3584. }
  3585. }
  3586. ienum.constants.push_back(iconstant);
  3587. }
  3588. int prefix_length = _determine_enum_prefix(ienum);
  3589. _apply_prefix_to_enum_constants(ienum, prefix_length);
  3590. itype.enums.push_back(ienum);
  3591. TypeInterface enum_itype;
  3592. enum_itype.is_enum = true;
  3593. enum_itype.name = itype.name + "." + String(E.key);
  3594. enum_itype.cname = StringName(enum_itype.name);
  3595. enum_itype.proxy_name = itype.proxy_name + "." + enum_proxy_name;
  3596. TypeInterface::postsetup_enum_type(enum_itype);
  3597. enum_types.insert(enum_itype.cname, enum_itype);
  3598. }
  3599. for (const String &constant_name : constants) {
  3600. int64_t *value = class_info->constant_map.getptr(StringName(constant_name));
  3601. ERR_FAIL_NULL_V(value, false);
  3602. String constant_proxy_name = snake_to_pascal_case(constant_name, true);
  3603. if (itype.find_property_by_proxy_name(constant_proxy_name) || itype.find_method_by_proxy_name(constant_proxy_name) || itype.find_signal_by_proxy_name(constant_proxy_name)) {
  3604. // In case the constant name conflicts with other PascalCase members,
  3605. // we append 'Constant' to the constant name in those cases.
  3606. constant_proxy_name += "Constant";
  3607. }
  3608. ConstantInterface iconstant(constant_name, constant_proxy_name, *value);
  3609. iconstant.const_doc = nullptr;
  3610. for (int i = 0; i < itype.class_doc->constants.size(); i++) {
  3611. const DocData::ConstantDoc &const_doc = itype.class_doc->constants[i];
  3612. if (const_doc.name == iconstant.name) {
  3613. iconstant.const_doc = &const_doc;
  3614. break;
  3615. }
  3616. }
  3617. if (iconstant.const_doc) {
  3618. iconstant.is_deprecated = iconstant.const_doc->is_deprecated;
  3619. iconstant.deprecation_message = iconstant.const_doc->deprecated_message;
  3620. if (iconstant.is_deprecated && iconstant.deprecation_message.is_empty()) {
  3621. WARN_PRINT("An empty deprecation message is discouraged. Constant: '" + itype.proxy_name + "." + iconstant.proxy_name + "'.");
  3622. iconstant.deprecation_message = "This constant is deprecated.";
  3623. }
  3624. }
  3625. itype.constants.push_back(iconstant);
  3626. }
  3627. obj_types.insert(itype.cname, itype);
  3628. if (itype.is_singleton) {
  3629. // Add singleton instance type.
  3630. itype.proxy_name += CS_SINGLETON_INSTANCE_SUFFIX;
  3631. itype.is_singleton = false;
  3632. itype.is_singleton_instance = true;
  3633. // Remove constants and enums, those will remain in the static class.
  3634. itype.constants.clear();
  3635. itype.enums.clear();
  3636. obj_types.insert(itype.name + CS_SINGLETON_INSTANCE_SUFFIX, itype);
  3637. }
  3638. class_list.pop_front();
  3639. }
  3640. return true;
  3641. }
  3642. static String _get_vector2_cs_ctor_args(const Vector2 &p_vec2) {
  3643. return String::num_real(p_vec2.x, true) + "f, " +
  3644. String::num_real(p_vec2.y, true) + "f";
  3645. }
  3646. static String _get_vector3_cs_ctor_args(const Vector3 &p_vec3) {
  3647. return String::num_real(p_vec3.x, true) + "f, " +
  3648. String::num_real(p_vec3.y, true) + "f, " +
  3649. String::num_real(p_vec3.z, true) + "f";
  3650. }
  3651. static String _get_vector4_cs_ctor_args(const Vector4 &p_vec4) {
  3652. return String::num_real(p_vec4.x, true) + "f, " +
  3653. String::num_real(p_vec4.y, true) + "f, " +
  3654. String::num_real(p_vec4.z, true) + "f, " +
  3655. String::num_real(p_vec4.w, true) + "f";
  3656. }
  3657. static String _get_vector2i_cs_ctor_args(const Vector2i &p_vec2i) {
  3658. return itos(p_vec2i.x) + ", " + itos(p_vec2i.y);
  3659. }
  3660. static String _get_vector3i_cs_ctor_args(const Vector3i &p_vec3i) {
  3661. return itos(p_vec3i.x) + ", " + itos(p_vec3i.y) + ", " + itos(p_vec3i.z);
  3662. }
  3663. static String _get_vector4i_cs_ctor_args(const Vector4i &p_vec4i) {
  3664. return itos(p_vec4i.x) + ", " + itos(p_vec4i.y) + ", " + itos(p_vec4i.z) + ", " + itos(p_vec4i.w);
  3665. }
  3666. static String _get_color_cs_ctor_args(const Color &p_color) {
  3667. return String::num(p_color.r, 4) + "f, " +
  3668. String::num(p_color.g, 4) + "f, " +
  3669. String::num(p_color.b, 4) + "f, " +
  3670. String::num(p_color.a, 4) + "f";
  3671. }
  3672. bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, ArgumentInterface &r_iarg) {
  3673. r_iarg.def_param_value = p_val;
  3674. switch (p_val.get_type()) {
  3675. case Variant::NIL:
  3676. // Either Object type or Variant
  3677. r_iarg.default_argument = "default";
  3678. break;
  3679. // Atomic types
  3680. case Variant::BOOL:
  3681. r_iarg.default_argument = bool(p_val) ? "true" : "false";
  3682. break;
  3683. case Variant::INT:
  3684. if (r_iarg.type.cname != name_cache.type_int) {
  3685. r_iarg.default_argument = "(%s)(" + p_val.operator String() + ")";
  3686. } else {
  3687. r_iarg.default_argument = p_val.operator String();
  3688. }
  3689. break;
  3690. case Variant::FLOAT:
  3691. r_iarg.default_argument = p_val.operator String();
  3692. if (r_iarg.type.cname == name_cache.type_float) {
  3693. r_iarg.default_argument += "f";
  3694. }
  3695. break;
  3696. case Variant::STRING:
  3697. case Variant::STRING_NAME:
  3698. case Variant::NODE_PATH:
  3699. if (r_iarg.type.cname == name_cache.type_StringName || r_iarg.type.cname == name_cache.type_NodePath) {
  3700. if (r_iarg.default_argument.length() > 0) {
  3701. r_iarg.default_argument = "(%s)\"" + p_val.operator String() + "\"";
  3702. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  3703. } else {
  3704. // No need for a special `in` statement to change `null` to `""`. Marshaling takes care of this already.
  3705. r_iarg.default_argument = "null";
  3706. }
  3707. } else {
  3708. CRASH_COND(r_iarg.type.cname != name_cache.type_String);
  3709. r_iarg.default_argument = "\"" + p_val.operator String() + "\"";
  3710. }
  3711. break;
  3712. case Variant::PLANE: {
  3713. Plane plane = p_val.operator Plane();
  3714. r_iarg.default_argument = "new Plane(new Vector3(" +
  3715. _get_vector3_cs_ctor_args(plane.normal) + "), " + rtos(plane.d) + "f)";
  3716. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3717. } break;
  3718. case Variant::AABB: {
  3719. AABB aabb = p_val.operator ::AABB();
  3720. r_iarg.default_argument = "new Aabb(new Vector3(" +
  3721. _get_vector3_cs_ctor_args(aabb.position) + "), new Vector3(" +
  3722. _get_vector3_cs_ctor_args(aabb.size) + "))";
  3723. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3724. } break;
  3725. case Variant::RECT2: {
  3726. Rect2 rect = p_val.operator Rect2();
  3727. r_iarg.default_argument = "new Rect2(new Vector2(" +
  3728. _get_vector2_cs_ctor_args(rect.position) + "), new Vector2(" +
  3729. _get_vector2_cs_ctor_args(rect.size) + "))";
  3730. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3731. } break;
  3732. case Variant::RECT2I: {
  3733. Rect2i rect = p_val.operator Rect2i();
  3734. r_iarg.default_argument = "new Rect2I(new Vector2I(" +
  3735. _get_vector2i_cs_ctor_args(rect.position) + "), new Vector2I(" +
  3736. _get_vector2i_cs_ctor_args(rect.size) + "))";
  3737. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3738. } break;
  3739. case Variant::COLOR:
  3740. r_iarg.default_argument = "new Color(" + _get_color_cs_ctor_args(p_val.operator Color()) + ")";
  3741. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3742. break;
  3743. case Variant::VECTOR2:
  3744. r_iarg.default_argument = "new Vector2(" + _get_vector2_cs_ctor_args(p_val.operator Vector2()) + ")";
  3745. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3746. break;
  3747. case Variant::VECTOR2I:
  3748. r_iarg.default_argument = "new Vector2I(" + _get_vector2i_cs_ctor_args(p_val.operator Vector2i()) + ")";
  3749. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3750. break;
  3751. case Variant::VECTOR3:
  3752. r_iarg.default_argument = "new Vector3(" + _get_vector3_cs_ctor_args(p_val.operator Vector3()) + ")";
  3753. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3754. break;
  3755. case Variant::VECTOR3I:
  3756. r_iarg.default_argument = "new Vector3I(" + _get_vector3i_cs_ctor_args(p_val.operator Vector3i()) + ")";
  3757. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3758. break;
  3759. case Variant::VECTOR4:
  3760. r_iarg.default_argument = "new Vector4(" + _get_vector4_cs_ctor_args(p_val.operator Vector4()) + ")";
  3761. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3762. break;
  3763. case Variant::VECTOR4I:
  3764. r_iarg.default_argument = "new Vector4I(" + _get_vector4i_cs_ctor_args(p_val.operator Vector4i()) + ")";
  3765. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3766. break;
  3767. case Variant::OBJECT:
  3768. ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
  3769. "Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
  3770. r_iarg.default_argument = "null";
  3771. break;
  3772. case Variant::DICTIONARY:
  3773. ERR_FAIL_COND_V_MSG(!p_val.operator Dictionary().is_empty(), false,
  3774. "Default value of type 'Dictionary' must be an empty dictionary.");
  3775. // The [cs_in] expression already interprets null values as empty dictionaries.
  3776. r_iarg.default_argument = "null";
  3777. r_iarg.def_param_mode = ArgumentInterface::CONSTANT;
  3778. break;
  3779. case Variant::RID:
  3780. ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_RID, false,
  3781. "Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_RID) + "'.");
  3782. ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
  3783. "Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
  3784. r_iarg.default_argument = "default";
  3785. break;
  3786. case Variant::ARRAY:
  3787. ERR_FAIL_COND_V_MSG(!p_val.operator Array().is_empty(), false,
  3788. "Default value of type 'Array' must be an empty array.");
  3789. // The [cs_in] expression already interprets null values as empty arrays.
  3790. r_iarg.default_argument = "null";
  3791. r_iarg.def_param_mode = ArgumentInterface::CONSTANT;
  3792. break;
  3793. case Variant::PACKED_BYTE_ARRAY:
  3794. case Variant::PACKED_INT32_ARRAY:
  3795. case Variant::PACKED_INT64_ARRAY:
  3796. case Variant::PACKED_FLOAT32_ARRAY:
  3797. case Variant::PACKED_FLOAT64_ARRAY:
  3798. case Variant::PACKED_STRING_ARRAY:
  3799. case Variant::PACKED_VECTOR2_ARRAY:
  3800. case Variant::PACKED_VECTOR3_ARRAY:
  3801. case Variant::PACKED_VECTOR4_ARRAY:
  3802. case Variant::PACKED_COLOR_ARRAY:
  3803. r_iarg.default_argument = "Array.Empty<%s>()";
  3804. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
  3805. break;
  3806. case Variant::TRANSFORM2D: {
  3807. Transform2D transform = p_val.operator Transform2D();
  3808. if (transform == Transform2D()) {
  3809. r_iarg.default_argument = "Transform2D.Identity";
  3810. } else {
  3811. r_iarg.default_argument = "new Transform2D(new Vector2(" +
  3812. _get_vector2_cs_ctor_args(transform.columns[0]) + "), new Vector2(" +
  3813. _get_vector2_cs_ctor_args(transform.columns[1]) + "), new Vector2(" +
  3814. _get_vector2_cs_ctor_args(transform.columns[2]) + "))";
  3815. }
  3816. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3817. } break;
  3818. case Variant::TRANSFORM3D: {
  3819. Transform3D transform = p_val.operator Transform3D();
  3820. if (transform == Transform3D()) {
  3821. r_iarg.default_argument = "Transform3D.Identity";
  3822. } else {
  3823. Basis basis = transform.basis;
  3824. r_iarg.default_argument = "new Transform3D(new Vector3(" +
  3825. _get_vector3_cs_ctor_args(basis.get_column(0)) + "), new Vector3(" +
  3826. _get_vector3_cs_ctor_args(basis.get_column(1)) + "), new Vector3(" +
  3827. _get_vector3_cs_ctor_args(basis.get_column(2)) + "), new Vector3(" +
  3828. _get_vector3_cs_ctor_args(transform.origin) + "))";
  3829. }
  3830. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3831. } break;
  3832. case Variant::PROJECTION: {
  3833. Projection projection = p_val.operator Projection();
  3834. if (projection == Projection()) {
  3835. r_iarg.default_argument = "Projection.Identity";
  3836. } else {
  3837. r_iarg.default_argument = "new Projection(new Vector4(" +
  3838. _get_vector4_cs_ctor_args(projection.columns[0]) + "), new Vector4(" +
  3839. _get_vector4_cs_ctor_args(projection.columns[1]) + "), new Vector4(" +
  3840. _get_vector4_cs_ctor_args(projection.columns[2]) + "), new Vector4(" +
  3841. _get_vector4_cs_ctor_args(projection.columns[3]) + "))";
  3842. }
  3843. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3844. } break;
  3845. case Variant::BASIS: {
  3846. Basis basis = p_val.operator Basis();
  3847. if (basis == Basis()) {
  3848. r_iarg.default_argument = "Basis.Identity";
  3849. } else {
  3850. r_iarg.default_argument = "new Basis(new Vector3(" +
  3851. _get_vector3_cs_ctor_args(basis.get_column(0)) + "), new Vector3(" +
  3852. _get_vector3_cs_ctor_args(basis.get_column(1)) + "), new Vector3(" +
  3853. _get_vector3_cs_ctor_args(basis.get_column(2)) + "))";
  3854. }
  3855. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3856. } break;
  3857. case Variant::QUATERNION: {
  3858. Quaternion quaternion = p_val.operator Quaternion();
  3859. if (quaternion == Quaternion()) {
  3860. r_iarg.default_argument = "Quaternion.Identity";
  3861. } else {
  3862. r_iarg.default_argument = "new Quaternion(" +
  3863. String::num_real(quaternion.x, false) + "f, " +
  3864. String::num_real(quaternion.y, false) + "f, " +
  3865. String::num_real(quaternion.z, false) + "f, " +
  3866. String::num_real(quaternion.w, false) + "f)";
  3867. }
  3868. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3869. } break;
  3870. case Variant::CALLABLE:
  3871. ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_Callable, false,
  3872. "Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_Callable) + "'.");
  3873. ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
  3874. "Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
  3875. r_iarg.default_argument = "default";
  3876. break;
  3877. case Variant::SIGNAL:
  3878. ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_Signal, false,
  3879. "Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_Signal) + "'.");
  3880. ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
  3881. "Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
  3882. r_iarg.default_argument = "default";
  3883. break;
  3884. default:
  3885. ERR_FAIL_V_MSG(false, "Unexpected Variant type: " + itos(p_val.get_type()));
  3886. break;
  3887. }
  3888. if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "default") {
  3889. r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
  3890. }
  3891. return true;
  3892. }
  3893. void BindingsGenerator::_populate_builtin_type_interfaces() {
  3894. builtin_types.clear();
  3895. TypeInterface itype;
  3896. #define INSERT_STRUCT_TYPE(m_type, m_proxy_name) \
  3897. { \
  3898. itype = TypeInterface::create_value_type(String(#m_type), String(#m_proxy_name)); \
  3899. itype.cs_in_expr = "&%0"; \
  3900. itype.cs_in_expr_is_unsafe = true; \
  3901. builtin_types.insert(itype.cname, itype); \
  3902. }
  3903. INSERT_STRUCT_TYPE(Vector2, Vector2)
  3904. INSERT_STRUCT_TYPE(Vector2i, Vector2I)
  3905. INSERT_STRUCT_TYPE(Rect2, Rect2)
  3906. INSERT_STRUCT_TYPE(Rect2i, Rect2I)
  3907. INSERT_STRUCT_TYPE(Transform2D, Transform2D)
  3908. INSERT_STRUCT_TYPE(Vector3, Vector3)
  3909. INSERT_STRUCT_TYPE(Vector3i, Vector3I)
  3910. INSERT_STRUCT_TYPE(Basis, Basis)
  3911. INSERT_STRUCT_TYPE(Quaternion, Quaternion)
  3912. INSERT_STRUCT_TYPE(Transform3D, Transform3D)
  3913. INSERT_STRUCT_TYPE(AABB, Aabb)
  3914. INSERT_STRUCT_TYPE(Color, Color)
  3915. INSERT_STRUCT_TYPE(Plane, Plane)
  3916. INSERT_STRUCT_TYPE(Vector4, Vector4)
  3917. INSERT_STRUCT_TYPE(Vector4i, Vector4I)
  3918. INSERT_STRUCT_TYPE(Projection, Projection)
  3919. #undef INSERT_STRUCT_TYPE
  3920. // bool
  3921. itype = TypeInterface::create_value_type(String("bool"));
  3922. itype.cs_in_expr = "%0.ToGodotBool()";
  3923. itype.cs_out = "%5return %0(%1).ToBool();";
  3924. itype.c_type = "godot_bool";
  3925. itype.c_type_in = itype.c_type;
  3926. itype.c_type_out = itype.c_type;
  3927. itype.c_arg_in = "&%s";
  3928. itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromBool(%1);\n";
  3929. builtin_types.insert(itype.cname, itype);
  3930. // Integer types
  3931. {
  3932. // C interface for 'uint32_t' is the same as that of enums. Remember to apply
  3933. // any of the changes done here to 'TypeInterface::postsetup_enum_type' as well.
  3934. #define INSERT_INT_TYPE(m_name, m_int_struct_name) \
  3935. { \
  3936. itype = TypeInterface::create_value_type(String(m_name)); \
  3937. if (itype.name != "long" && itype.name != "ulong") { \
  3938. itype.c_in = "%5%0 %1_in = %1;\n"; \
  3939. itype.c_out = "%5return (%0)(%1);\n"; \
  3940. itype.c_type = "long"; \
  3941. itype.c_arg_in = "&%s_in"; \
  3942. } else { \
  3943. itype.c_arg_in = "&%s"; \
  3944. } \
  3945. itype.c_type_in = itype.name; \
  3946. itype.c_type_out = itype.name; \
  3947. itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromInt(%1);\n"; \
  3948. builtin_types.insert(itype.cname, itype); \
  3949. }
  3950. // The expected type for all integers in ptrcall is 'int64_t', so that's what we use for 'c_type'
  3951. INSERT_INT_TYPE("sbyte", "Int8");
  3952. INSERT_INT_TYPE("short", "Int16");
  3953. INSERT_INT_TYPE("int", "Int32");
  3954. INSERT_INT_TYPE("long", "Int64");
  3955. INSERT_INT_TYPE("byte", "UInt8");
  3956. INSERT_INT_TYPE("ushort", "UInt16");
  3957. INSERT_INT_TYPE("uint", "UInt32");
  3958. INSERT_INT_TYPE("ulong", "UInt64");
  3959. #undef INSERT_INT_TYPE
  3960. }
  3961. // Floating point types
  3962. {
  3963. // float
  3964. itype = TypeInterface();
  3965. itype.name = "float";
  3966. itype.cname = itype.name;
  3967. itype.proxy_name = "float";
  3968. itype.cs_type = itype.proxy_name;
  3969. {
  3970. // The expected type for 'float' in ptrcall is 'double'
  3971. itype.c_in = "%5%0 %1_in = %1;\n";
  3972. itype.c_out = "%5return (%0)%1;\n";
  3973. itype.c_type = "double";
  3974. itype.c_arg_in = "&%s_in";
  3975. }
  3976. itype.c_type_in = itype.proxy_name;
  3977. itype.c_type_out = itype.proxy_name;
  3978. itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromFloat(%1);\n";
  3979. builtin_types.insert(itype.cname, itype);
  3980. // double
  3981. itype = TypeInterface();
  3982. itype.name = "double";
  3983. itype.cname = itype.name;
  3984. itype.proxy_name = "double";
  3985. itype.cs_type = itype.proxy_name;
  3986. itype.c_type = "double";
  3987. itype.c_arg_in = "&%s";
  3988. itype.c_type_in = itype.proxy_name;
  3989. itype.c_type_out = itype.proxy_name;
  3990. itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromFloat(%1);\n";
  3991. builtin_types.insert(itype.cname, itype);
  3992. }
  3993. // String
  3994. itype = TypeInterface();
  3995. itype.name = "String";
  3996. itype.cname = itype.name;
  3997. itype.proxy_name = "string";
  3998. itype.cs_type = itype.proxy_name;
  3999. itype.c_in = "%5using %0 %1_in = " C_METHOD_MONOSTR_TO_GODOT "(%1);\n";
  4000. itype.c_out = "%5return " C_METHOD_MONOSTR_FROM_GODOT "(%1);\n";
  4001. itype.c_arg_in = "&%s_in";
  4002. itype.c_type = "godot_string";
  4003. itype.c_type_in = itype.cs_type;
  4004. itype.c_type_out = itype.cs_type;
  4005. itype.c_type_is_disposable_struct = true;
  4006. itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromString(%1);\n";
  4007. builtin_types.insert(itype.cname, itype);
  4008. // StringName
  4009. itype = TypeInterface();
  4010. itype.name = "StringName";
  4011. itype.cname = itype.name;
  4012. itype.proxy_name = "StringName";
  4013. itype.cs_type = itype.proxy_name;
  4014. itype.cs_in_expr = "(%1)(%0?.NativeValue ?? default)";
  4015. // Cannot pass null StringName to ptrcall
  4016. itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
  4017. itype.c_arg_in = "&%s";
  4018. itype.c_type = "godot_string_name";
  4019. itype.c_type_in = itype.c_type;
  4020. itype.c_type_out = itype.cs_type;
  4021. itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromStringName(%1);\n";
  4022. itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
  4023. itype.c_ret_needs_default_initialization = true;
  4024. builtin_types.insert(itype.cname, itype);
  4025. // NodePath
  4026. itype = TypeInterface();
  4027. itype.name = "NodePath";
  4028. itype.cname = itype.name;
  4029. itype.proxy_name = "NodePath";
  4030. itype.cs_type = itype.proxy_name;
  4031. itype.cs_in_expr = "(%1)(%0?.NativeValue ?? default)";
  4032. // Cannot pass null NodePath to ptrcall
  4033. itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
  4034. itype.c_arg_in = "&%s";
  4035. itype.c_type = "godot_node_path";
  4036. itype.c_type_in = itype.c_type;
  4037. itype.c_type_out = itype.cs_type;
  4038. itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
  4039. itype.c_ret_needs_default_initialization = true;
  4040. builtin_types.insert(itype.cname, itype);
  4041. // RID
  4042. itype = TypeInterface();
  4043. itype.name = "RID";
  4044. itype.cname = itype.name;
  4045. itype.proxy_name = "Rid";
  4046. itype.cs_type = itype.proxy_name;
  4047. itype.c_arg_in = "&%s";
  4048. itype.c_type = itype.cs_type;
  4049. itype.c_type_in = itype.c_type;
  4050. itype.c_type_out = itype.c_type;
  4051. builtin_types.insert(itype.cname, itype);
  4052. // Variant
  4053. itype = TypeInterface();
  4054. itype.name = "Variant";
  4055. itype.cname = itype.name;
  4056. itype.proxy_name = "Variant";
  4057. itype.cs_type = itype.proxy_name;
  4058. itype.c_in = "%5%0 %1_in = (%0)%1.NativeVar;\n";
  4059. itype.c_out = "%5return Variant.CreateTakingOwnershipOfDisposableValue(%1);\n";
  4060. itype.c_arg_in = "&%s_in";
  4061. itype.c_type = "godot_variant";
  4062. itype.c_type_in = itype.cs_type;
  4063. itype.c_type_out = itype.cs_type;
  4064. itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
  4065. itype.c_ret_needs_default_initialization = true;
  4066. builtin_types.insert(itype.cname, itype);
  4067. // Callable
  4068. itype = TypeInterface::create_value_type(String("Callable"));
  4069. itype.cs_in_expr = "%0";
  4070. itype.c_in = "%5using %0 %1_in = " C_METHOD_MANAGED_TO_CALLABLE "(in %1);\n";
  4071. itype.c_out = "%5return " C_METHOD_MANAGED_FROM_CALLABLE "(in %1);\n";
  4072. itype.c_arg_in = "&%s_in";
  4073. itype.c_type = "godot_callable";
  4074. itype.c_type_in = "in " + itype.cs_type;
  4075. itype.c_type_out = itype.cs_type;
  4076. itype.c_type_is_disposable_struct = true;
  4077. builtin_types.insert(itype.cname, itype);
  4078. // Signal
  4079. itype = TypeInterface();
  4080. itype.name = "Signal";
  4081. itype.cname = itype.name;
  4082. itype.proxy_name = "Signal";
  4083. itype.cs_type = itype.proxy_name;
  4084. itype.cs_in_expr = "%0";
  4085. itype.c_in = "%5using %0 %1_in = " C_METHOD_MANAGED_TO_SIGNAL "(in %1);\n";
  4086. itype.c_out = "%5return " C_METHOD_MANAGED_FROM_SIGNAL "(in %1);\n";
  4087. itype.c_arg_in = "&%s_in";
  4088. itype.c_type = "godot_signal";
  4089. itype.c_type_in = "in " + itype.cs_type;
  4090. itype.c_type_out = itype.cs_type;
  4091. itype.c_type_is_disposable_struct = true;
  4092. builtin_types.insert(itype.cname, itype);
  4093. // VarArg (fictitious type to represent variable arguments)
  4094. itype = TypeInterface();
  4095. itype.name = "VarArg";
  4096. itype.cname = itype.name;
  4097. itype.proxy_name = "ReadOnlySpan<Variant>";
  4098. itype.cs_type = "params Variant[]";
  4099. itype.cs_in_expr = "%0";
  4100. // c_type, c_in and c_arg_in are hard-coded in the generator.
  4101. // c_out and c_type_out are not applicable to VarArg.
  4102. itype.c_arg_in = "&%s_in";
  4103. itype.c_type_in = "ReadOnlySpan<Variant>";
  4104. itype.is_span_compatible = true;
  4105. builtin_types.insert(itype.cname, itype);
  4106. #define INSERT_ARRAY_FULL(m_name, m_type, m_managed_type, m_proxy_t) \
  4107. { \
  4108. itype = TypeInterface(); \
  4109. itype.name = #m_name; \
  4110. itype.cname = itype.name; \
  4111. itype.proxy_name = #m_proxy_t "[]"; \
  4112. itype.cs_type = itype.proxy_name; \
  4113. itype.c_in = "%5using %0 %1_in = " C_METHOD_MONOARRAY_TO(m_type) "(%1);\n"; \
  4114. itype.c_out = "%5return " C_METHOD_MONOARRAY_FROM(m_type) "(%1);\n"; \
  4115. itype.c_arg_in = "&%s_in"; \
  4116. itype.c_type = #m_managed_type; \
  4117. itype.c_type_in = "ReadOnlySpan<" #m_proxy_t ">"; \
  4118. itype.c_type_out = itype.proxy_name; \
  4119. itype.c_type_is_disposable_struct = true; \
  4120. itype.is_span_compatible = true; \
  4121. builtin_types.insert(itype.name, itype); \
  4122. }
  4123. #define INSERT_ARRAY(m_type, m_managed_type, m_proxy_t) INSERT_ARRAY_FULL(m_type, m_type, m_managed_type, m_proxy_t)
  4124. INSERT_ARRAY(PackedInt32Array, godot_packed_int32_array, int);
  4125. INSERT_ARRAY(PackedInt64Array, godot_packed_int64_array, long);
  4126. INSERT_ARRAY_FULL(PackedByteArray, PackedByteArray, godot_packed_byte_array, byte);
  4127. INSERT_ARRAY(PackedFloat32Array, godot_packed_float32_array, float);
  4128. INSERT_ARRAY(PackedFloat64Array, godot_packed_float64_array, double);
  4129. INSERT_ARRAY(PackedStringArray, godot_packed_string_array, string);
  4130. INSERT_ARRAY(PackedColorArray, godot_packed_color_array, Color);
  4131. INSERT_ARRAY(PackedVector2Array, godot_packed_vector2_array, Vector2);
  4132. INSERT_ARRAY(PackedVector3Array, godot_packed_vector3_array, Vector3);
  4133. INSERT_ARRAY(PackedVector4Array, godot_packed_vector4_array, Vector4);
  4134. #undef INSERT_ARRAY
  4135. // Array
  4136. itype = TypeInterface();
  4137. itype.name = "Array";
  4138. itype.cname = itype.name;
  4139. itype.proxy_name = itype.name;
  4140. itype.type_parameter_count = 1;
  4141. itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
  4142. itype.cs_in_expr = "(%1)(%0 ?? new()).NativeValue";
  4143. itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
  4144. itype.c_arg_in = "&%s";
  4145. itype.c_type = "godot_array";
  4146. itype.c_type_in = itype.c_type;
  4147. itype.c_type_out = itype.cs_type;
  4148. itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
  4149. itype.c_ret_needs_default_initialization = true;
  4150. builtin_types.insert(itype.cname, itype);
  4151. // Array_@generic
  4152. // Reuse Array's itype
  4153. itype.name = "Array_@generic";
  4154. itype.cname = itype.name;
  4155. itype.cs_out = "%5return new %2(%0(%1));";
  4156. // For generic Godot collections, Variant.From<T>/As<T> is slower, so we need this special case
  4157. itype.cs_variant_to_managed = "VariantUtils.ConvertToArray(%0)";
  4158. itype.cs_managed_to_variant = "VariantUtils.CreateFromArray(%0)";
  4159. builtin_types.insert(itype.cname, itype);
  4160. // Dictionary
  4161. itype = TypeInterface();
  4162. itype.name = "Dictionary";
  4163. itype.cname = itype.name;
  4164. itype.proxy_name = itype.name;
  4165. itype.type_parameter_count = 2;
  4166. itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
  4167. itype.cs_in_expr = "(%1)(%0 ?? new()).NativeValue";
  4168. itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
  4169. itype.c_arg_in = "&%s";
  4170. itype.c_type = "godot_dictionary";
  4171. itype.c_type_in = itype.c_type;
  4172. itype.c_type_out = itype.cs_type;
  4173. itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
  4174. itype.c_ret_needs_default_initialization = true;
  4175. builtin_types.insert(itype.cname, itype);
  4176. // Dictionary_@generic
  4177. // Reuse Dictionary's itype
  4178. itype.name = "Dictionary_@generic";
  4179. itype.cname = itype.name;
  4180. itype.cs_out = "%5return new %2(%0(%1));";
  4181. // For generic Godot collections, Variant.From<T>/As<T> is slower, so we need this special case
  4182. itype.cs_variant_to_managed = "VariantUtils.ConvertToDictionary(%0)";
  4183. itype.cs_managed_to_variant = "VariantUtils.CreateFromDictionary(%0)";
  4184. builtin_types.insert(itype.cname, itype);
  4185. // void (fictitious type to represent the return type of methods that do not return anything)
  4186. itype = TypeInterface();
  4187. itype.name = "void";
  4188. itype.cname = itype.name;
  4189. itype.proxy_name = itype.name;
  4190. itype.cs_type = itype.proxy_name;
  4191. itype.c_type = itype.proxy_name;
  4192. itype.c_type_in = itype.c_type;
  4193. itype.c_type_out = itype.c_type;
  4194. builtin_types.insert(itype.cname, itype);
  4195. }
  4196. void BindingsGenerator::_populate_global_constants() {
  4197. int global_constants_count = CoreConstants::get_global_constant_count();
  4198. if (global_constants_count > 0) {
  4199. HashMap<String, DocData::ClassDoc>::Iterator match = EditorHelp::get_doc_data()->class_list.find("@GlobalScope");
  4200. CRASH_COND_MSG(!match, "Could not find '@GlobalScope' in DocData.");
  4201. const DocData::ClassDoc &global_scope_doc = match->value;
  4202. for (int i = 0; i < global_constants_count; i++) {
  4203. String constant_name = CoreConstants::get_global_constant_name(i);
  4204. const DocData::ConstantDoc *const_doc = nullptr;
  4205. for (int j = 0; j < global_scope_doc.constants.size(); j++) {
  4206. const DocData::ConstantDoc &curr_const_doc = global_scope_doc.constants[j];
  4207. if (curr_const_doc.name == constant_name) {
  4208. const_doc = &curr_const_doc;
  4209. break;
  4210. }
  4211. }
  4212. int64_t constant_value = CoreConstants::get_global_constant_value(i);
  4213. StringName enum_name = CoreConstants::get_global_constant_enum(i);
  4214. ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), constant_value);
  4215. iconstant.const_doc = const_doc;
  4216. if (enum_name != StringName()) {
  4217. EnumInterface ienum(enum_name, pascal_to_pascal_case(enum_name.operator String()), CoreConstants::is_global_constant_bitfield(i));
  4218. List<EnumInterface>::Element *enum_match = global_enums.find(ienum);
  4219. if (enum_match) {
  4220. enum_match->get().constants.push_back(iconstant);
  4221. } else {
  4222. ienum.constants.push_back(iconstant);
  4223. global_enums.push_back(ienum);
  4224. }
  4225. } else {
  4226. global_constants.push_back(iconstant);
  4227. }
  4228. }
  4229. for (EnumInterface &ienum : global_enums) {
  4230. TypeInterface enum_itype;
  4231. enum_itype.is_enum = true;
  4232. enum_itype.name = ienum.cname.operator String();
  4233. enum_itype.cname = ienum.cname;
  4234. enum_itype.proxy_name = ienum.proxy_name;
  4235. TypeInterface::postsetup_enum_type(enum_itype);
  4236. enum_types.insert(enum_itype.cname, enum_itype);
  4237. int prefix_length = _determine_enum_prefix(ienum);
  4238. // HARDCODED: The Error enum have the prefix 'ERR_' for everything except 'OK' and 'FAILED'.
  4239. if (ienum.cname == name_cache.enum_Error) {
  4240. if (prefix_length > 0) { // Just in case it ever changes
  4241. ERR_PRINT("Prefix for enum '" _STR(Error) "' is not empty.");
  4242. }
  4243. prefix_length = 1; // 'ERR_'
  4244. }
  4245. _apply_prefix_to_enum_constants(ienum, prefix_length);
  4246. }
  4247. }
  4248. for (int i = 0; i < Variant::VARIANT_MAX; i++) {
  4249. if (i == Variant::OBJECT) {
  4250. continue;
  4251. }
  4252. const Variant::Type type = Variant::Type(i);
  4253. List<StringName> enum_names;
  4254. Variant::get_enums_for_type(type, &enum_names);
  4255. for (const StringName &enum_name : enum_names) {
  4256. TypeInterface enum_itype;
  4257. enum_itype.is_enum = true;
  4258. enum_itype.name = Variant::get_type_name(type) + "." + enum_name;
  4259. enum_itype.cname = enum_itype.name;
  4260. enum_itype.proxy_name = pascal_to_pascal_case(enum_itype.name);
  4261. TypeInterface::postsetup_enum_type(enum_itype);
  4262. enum_types.insert(enum_itype.cname, enum_itype);
  4263. }
  4264. }
  4265. }
  4266. bool BindingsGenerator::_method_has_conflicting_signature(const MethodInterface &p_imethod, const TypeInterface &p_itype) {
  4267. // Compare p_imethod with all the methods already registered in p_itype.
  4268. for (const MethodInterface &method : p_itype.methods) {
  4269. if (method.proxy_name == p_imethod.proxy_name) {
  4270. if (_method_has_conflicting_signature(p_imethod, method)) {
  4271. return true;
  4272. }
  4273. }
  4274. }
  4275. return false;
  4276. }
  4277. bool BindingsGenerator::_method_has_conflicting_signature(const MethodInterface &p_imethod_left, const MethodInterface &p_imethod_right) {
  4278. // Check if a method already exists in p_itype with a method signature that would conflict with p_imethod.
  4279. // The return type is ignored because only changing the return type is not enough to avoid conflicts.
  4280. // The const keyword is also ignored since it doesn't generate different C# code.
  4281. if (p_imethod_left.arguments.size() != p_imethod_right.arguments.size()) {
  4282. // Different argument count, so no conflict.
  4283. return false;
  4284. }
  4285. List<BindingsGenerator::ArgumentInterface>::ConstIterator left_itr = p_imethod_left.arguments.begin();
  4286. List<BindingsGenerator::ArgumentInterface>::ConstIterator right_itr = p_imethod_right.arguments.begin();
  4287. for (; left_itr != p_imethod_left.arguments.end(); ++left_itr, ++right_itr) {
  4288. const ArgumentInterface &iarg_left = *left_itr;
  4289. const ArgumentInterface &iarg_right = *right_itr;
  4290. if (iarg_left.type.cname != iarg_right.type.cname) {
  4291. // Different types for arguments in the same position, so no conflict.
  4292. return false;
  4293. }
  4294. if (iarg_left.def_param_mode != iarg_right.def_param_mode) {
  4295. // If the argument is a value type and nullable, it will be 'Nullable<T>' instead of 'T'
  4296. // and will not create a conflict.
  4297. if (iarg_left.def_param_mode == ArgumentInterface::NULLABLE_VAL || iarg_right.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
  4298. return false;
  4299. }
  4300. }
  4301. }
  4302. return true;
  4303. }
  4304. void BindingsGenerator::_initialize_blacklisted_methods() {
  4305. blacklisted_methods["Object"].push_back("to_string"); // there is already ToString
  4306. blacklisted_methods["Object"].push_back("_to_string"); // override ToString instead
  4307. blacklisted_methods["Object"].push_back("_init"); // never called in C# (TODO: implement it)
  4308. }
  4309. void BindingsGenerator::_initialize_compat_singletons() {
  4310. compat_singletons.insert("EditorInterface");
  4311. }
  4312. void BindingsGenerator::_log(const char *p_format, ...) {
  4313. if (log_print_enabled) {
  4314. va_list list;
  4315. va_start(list, p_format);
  4316. OS::get_singleton()->print("%s", str_format(p_format, list).utf8().get_data());
  4317. va_end(list);
  4318. }
  4319. }
  4320. void BindingsGenerator::_initialize() {
  4321. initialized = false;
  4322. EditorHelp::generate_doc(false);
  4323. enum_types.clear();
  4324. _initialize_blacklisted_methods();
  4325. _initialize_compat_singletons();
  4326. bool obj_type_ok = _populate_object_type_interfaces();
  4327. ERR_FAIL_COND_MSG(!obj_type_ok, "Failed to generate object type interfaces");
  4328. _populate_builtin_type_interfaces();
  4329. _populate_global_constants();
  4330. // Generate internal calls (after populating type interfaces and global constants)
  4331. for (const KeyValue<StringName, TypeInterface> &E : obj_types) {
  4332. const TypeInterface &itype = E.value;
  4333. Error err = _populate_method_icalls_table(itype);
  4334. ERR_FAIL_COND_MSG(err != OK, "Failed to generate icalls table for type: " + itype.name);
  4335. }
  4336. initialized = true;
  4337. }
  4338. static String generate_all_glue_option = "--generate-mono-glue";
  4339. static void handle_cmdline_options(String glue_dir_path) {
  4340. BindingsGenerator bindings_generator;
  4341. bindings_generator.set_log_print_enabled(true);
  4342. if (!bindings_generator.is_initialized()) {
  4343. ERR_PRINT("Failed to initialize the bindings generator");
  4344. return;
  4345. }
  4346. CRASH_COND(glue_dir_path.is_empty());
  4347. if (bindings_generator.generate_cs_api(glue_dir_path.path_join(API_SOLUTION_NAME)) != OK) {
  4348. ERR_PRINT(generate_all_glue_option + ": Failed to generate the C# API.");
  4349. }
  4350. }
  4351. static void cleanup_and_exit_godot() {
  4352. // Exit once done.
  4353. Main::cleanup(true);
  4354. ::exit(0);
  4355. }
  4356. void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) {
  4357. String glue_dir_path;
  4358. const List<String>::Element *elem = p_cmdline_args.front();
  4359. while (elem) {
  4360. if (elem->get() == generate_all_glue_option) {
  4361. const List<String>::Element *path_elem = elem->next();
  4362. if (path_elem) {
  4363. glue_dir_path = path_elem->get();
  4364. elem = elem->next();
  4365. } else {
  4366. ERR_PRINT(generate_all_glue_option + ": No output directory specified (expected path to '{GODOT_ROOT}/modules/mono/glue').");
  4367. // Exit once done with invalid command line arguments.
  4368. cleanup_and_exit_godot();
  4369. }
  4370. break;
  4371. }
  4372. elem = elem->next();
  4373. }
  4374. if (glue_dir_path.length()) {
  4375. if (Engine::get_singleton()->is_editor_hint() ||
  4376. Engine::get_singleton()->is_project_manager_hint()) {
  4377. handle_cmdline_options(glue_dir_path);
  4378. } else {
  4379. // Running from a project folder, which doesn't make sense and crashes.
  4380. ERR_PRINT(generate_all_glue_option + ": Cannot generate Mono glue while running a game project. Change current directory or enable --editor.");
  4381. }
  4382. // Exit once done.
  4383. cleanup_and_exit_godot();
  4384. }
  4385. }
  4386. #endif