bindings_generator.cpp 185 KB

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