bindings_generator.cpp 193 KB

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