bindings_generator.cpp 195 KB

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