bindings_generator.cpp 193 KB

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