gdscript_analyzer.cpp 202 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190
  1. /**************************************************************************/
  2. /* gdscript_analyzer.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 "gdscript_analyzer.h"
  31. #include "core/config/engine.h"
  32. #include "core/config/project_settings.h"
  33. #include "core/core_constants.h"
  34. #include "core/core_string_names.h"
  35. #include "core/io/file_access.h"
  36. #include "core/io/resource_loader.h"
  37. #include "core/object/class_db.h"
  38. #include "core/object/script_language.h"
  39. #include "core/templates/hash_map.h"
  40. #include "gdscript.h"
  41. #include "gdscript_utility_functions.h"
  42. #include "scene/resources/packed_scene.h"
  43. #if defined(TOOLS_ENABLED) && !defined(DISABLE_DEPRECATED)
  44. #define SUGGEST_GODOT4_RENAMES
  45. #include "editor/renames_map_3_to_4.h"
  46. #endif
  47. #define UNNAMED_ENUM "<anonymous enum>"
  48. #define ENUM_SEPARATOR "."
  49. static MethodInfo info_from_utility_func(const StringName &p_function) {
  50. ERR_FAIL_COND_V(!Variant::has_utility_function(p_function), MethodInfo());
  51. MethodInfo info(p_function);
  52. if (Variant::has_utility_function_return_value(p_function)) {
  53. info.return_val.type = Variant::get_utility_function_return_type(p_function);
  54. if (info.return_val.type == Variant::NIL) {
  55. info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  56. }
  57. }
  58. if (Variant::is_utility_function_vararg(p_function)) {
  59. info.flags |= METHOD_FLAG_VARARG;
  60. } else {
  61. for (int i = 0; i < Variant::get_utility_function_argument_count(p_function); i++) {
  62. PropertyInfo pi;
  63. #ifdef DEBUG_METHODS_ENABLED
  64. pi.name = Variant::get_utility_function_argument_name(p_function, i);
  65. #else
  66. pi.name = "arg" + itos(i + 1);
  67. #endif
  68. pi.type = Variant::get_utility_function_argument_type(p_function, i);
  69. info.arguments.push_back(pi);
  70. }
  71. }
  72. return info;
  73. }
  74. static GDScriptParser::DataType make_callable_type(const MethodInfo &p_info) {
  75. GDScriptParser::DataType type;
  76. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  77. type.kind = GDScriptParser::DataType::BUILTIN;
  78. type.builtin_type = Variant::CALLABLE;
  79. type.is_constant = true;
  80. type.method_info = p_info;
  81. return type;
  82. }
  83. static GDScriptParser::DataType make_signal_type(const MethodInfo &p_info) {
  84. GDScriptParser::DataType type;
  85. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  86. type.kind = GDScriptParser::DataType::BUILTIN;
  87. type.builtin_type = Variant::SIGNAL;
  88. type.is_constant = true;
  89. type.method_info = p_info;
  90. return type;
  91. }
  92. static GDScriptParser::DataType make_native_meta_type(const StringName &p_class_name) {
  93. GDScriptParser::DataType type;
  94. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  95. type.kind = GDScriptParser::DataType::NATIVE;
  96. type.builtin_type = Variant::OBJECT;
  97. type.native_type = p_class_name;
  98. type.is_constant = true;
  99. type.is_meta_type = true;
  100. return type;
  101. }
  102. static GDScriptParser::DataType make_script_meta_type(const Ref<Script> &p_script) {
  103. GDScriptParser::DataType type;
  104. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  105. type.kind = GDScriptParser::DataType::SCRIPT;
  106. type.builtin_type = Variant::OBJECT;
  107. type.native_type = p_script->get_instance_base_type();
  108. type.script_type = p_script;
  109. type.script_path = p_script->get_path();
  110. type.is_constant = true;
  111. type.is_meta_type = true;
  112. return type;
  113. }
  114. // In enum types, native_type is used to store the class (native or otherwise) that the enum belongs to.
  115. // This disambiguates between similarly named enums in base classes or outer classes
  116. static GDScriptParser::DataType make_enum_type(const StringName &p_enum_name, const String &p_base_name, const bool p_meta = false) {
  117. GDScriptParser::DataType type;
  118. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  119. type.kind = GDScriptParser::DataType::ENUM;
  120. type.builtin_type = p_meta ? Variant::DICTIONARY : Variant::INT;
  121. type.enum_type = p_enum_name;
  122. type.is_constant = true;
  123. type.is_meta_type = p_meta;
  124. // For enums, native_type is only used to check compatibility in is_type_compatible()
  125. // We can set anything readable here for error messages, as long as it uniquely identifies the type of the enum
  126. if (p_base_name.is_empty()) {
  127. type.native_type = p_enum_name;
  128. } else {
  129. type.native_type = p_base_name + ENUM_SEPARATOR + p_enum_name;
  130. }
  131. return type;
  132. }
  133. static GDScriptParser::DataType make_native_enum_type(const StringName &p_enum_name, const StringName &p_native_class, bool p_meta = true) {
  134. // Find out which base class declared the enum, so the name is always the same even when coming from other contexts.
  135. StringName native_base = p_native_class;
  136. while (true && native_base != StringName()) {
  137. if (ClassDB::has_enum(native_base, p_enum_name, true)) {
  138. break;
  139. }
  140. native_base = ClassDB::get_parent_class_nocheck(native_base);
  141. }
  142. GDScriptParser::DataType type = make_enum_type(p_enum_name, native_base, p_meta);
  143. if (p_meta) {
  144. type.builtin_type = Variant::NIL; // Native enum types are not Dictionaries.
  145. }
  146. List<StringName> enum_values;
  147. ClassDB::get_enum_constants(native_base, p_enum_name, &enum_values, true);
  148. for (const StringName &E : enum_values) {
  149. type.enum_values[E] = ClassDB::get_integer_constant(native_base, E);
  150. }
  151. return type;
  152. }
  153. static GDScriptParser::DataType make_global_enum_type(const StringName &p_enum_name, const StringName &p_base, bool p_meta = true) {
  154. GDScriptParser::DataType type = make_enum_type(p_enum_name, p_base, p_meta);
  155. if (p_meta) {
  156. type.builtin_type = Variant::NIL; // Native enum types are not Dictionaries.
  157. type.is_pseudo_type = true;
  158. }
  159. HashMap<StringName, int64_t> enum_values;
  160. CoreConstants::get_enum_values(type.native_type, &enum_values);
  161. for (const KeyValue<StringName, int64_t> &element : enum_values) {
  162. type.enum_values[element.key] = element.value;
  163. }
  164. return type;
  165. }
  166. static GDScriptParser::DataType make_builtin_meta_type(Variant::Type p_type) {
  167. GDScriptParser::DataType type;
  168. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  169. type.kind = GDScriptParser::DataType::BUILTIN;
  170. type.builtin_type = p_type;
  171. type.is_constant = true;
  172. type.is_meta_type = true;
  173. return type;
  174. }
  175. bool GDScriptAnalyzer::has_member_name_conflict_in_script_class(const StringName &p_member_name, const GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_member) {
  176. if (p_class->members_indices.has(p_member_name)) {
  177. int index = p_class->members_indices[p_member_name];
  178. const GDScriptParser::ClassNode::Member *member = &p_class->members[index];
  179. if (member->type == GDScriptParser::ClassNode::Member::VARIABLE ||
  180. member->type == GDScriptParser::ClassNode::Member::CONSTANT ||
  181. member->type == GDScriptParser::ClassNode::Member::ENUM ||
  182. member->type == GDScriptParser::ClassNode::Member::ENUM_VALUE ||
  183. member->type == GDScriptParser::ClassNode::Member::CLASS ||
  184. member->type == GDScriptParser::ClassNode::Member::SIGNAL) {
  185. return true;
  186. }
  187. if (p_member->type != GDScriptParser::Node::FUNCTION && member->type == GDScriptParser::ClassNode::Member::FUNCTION) {
  188. return true;
  189. }
  190. }
  191. return false;
  192. }
  193. bool GDScriptAnalyzer::has_member_name_conflict_in_native_type(const StringName &p_member_name, const StringName &p_native_type_string) {
  194. if (ClassDB::has_signal(p_native_type_string, p_member_name)) {
  195. return true;
  196. }
  197. if (ClassDB::has_property(p_native_type_string, p_member_name)) {
  198. return true;
  199. }
  200. if (ClassDB::has_integer_constant(p_native_type_string, p_member_name)) {
  201. return true;
  202. }
  203. if (p_member_name == CoreStringNames::get_singleton()->_script) {
  204. return true;
  205. }
  206. return false;
  207. }
  208. Error GDScriptAnalyzer::check_native_member_name_conflict(const StringName &p_member_name, const GDScriptParser::Node *p_member_node, const StringName &p_native_type_string) {
  209. if (has_member_name_conflict_in_native_type(p_member_name, p_native_type_string)) {
  210. push_error(vformat(R"(Member "%s" redefined (original in native class '%s'))", p_member_name, p_native_type_string), p_member_node);
  211. return ERR_PARSE_ERROR;
  212. }
  213. if (class_exists(p_member_name)) {
  214. push_error(vformat(R"(The member "%s" shadows a native class.)", p_member_name), p_member_node);
  215. return ERR_PARSE_ERROR;
  216. }
  217. if (GDScriptParser::get_builtin_type(p_member_name) != Variant::VARIANT_MAX) {
  218. push_error(vformat(R"(The member "%s" cannot have the same name as a builtin type.)", p_member_name), p_member_node);
  219. return ERR_PARSE_ERROR;
  220. }
  221. return OK;
  222. }
  223. Error GDScriptAnalyzer::check_class_member_name_conflict(const GDScriptParser::ClassNode *p_class_node, const StringName &p_member_name, const GDScriptParser::Node *p_member_node) {
  224. // TODO check outer classes for static members only
  225. const GDScriptParser::DataType *current_data_type = &p_class_node->base_type;
  226. while (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::CLASS) {
  227. GDScriptParser::ClassNode *current_class_node = current_data_type->class_type;
  228. if (has_member_name_conflict_in_script_class(p_member_name, current_class_node, p_member_node)) {
  229. String parent_class_name = current_class_node->fqcn;
  230. if (current_class_node->identifier != nullptr) {
  231. parent_class_name = current_class_node->identifier->name;
  232. }
  233. push_error(vformat(R"(The member "%s" already exists in parent class %s.)", p_member_name, parent_class_name), p_member_node);
  234. return ERR_PARSE_ERROR;
  235. }
  236. current_data_type = &current_class_node->base_type;
  237. }
  238. // No need for native class recursion because Node exposes all Object's properties.
  239. if (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::NATIVE) {
  240. if (current_data_type->native_type != StringName()) {
  241. return check_native_member_name_conflict(
  242. p_member_name,
  243. p_member_node,
  244. current_data_type->native_type);
  245. }
  246. }
  247. return OK;
  248. }
  249. void GDScriptAnalyzer::get_class_node_current_scope_classes(GDScriptParser::ClassNode *p_node, List<GDScriptParser::ClassNode *> *p_list) {
  250. ERR_FAIL_NULL(p_node);
  251. ERR_FAIL_NULL(p_list);
  252. if (p_list->find(p_node) != nullptr) {
  253. return;
  254. }
  255. p_list->push_back(p_node);
  256. // TODO: Try to solve class inheritance if not yet resolving.
  257. // Prioritize node base type over its outer class
  258. if (p_node->base_type.class_type != nullptr) {
  259. get_class_node_current_scope_classes(p_node->base_type.class_type, p_list);
  260. }
  261. if (p_node->outer != nullptr) {
  262. get_class_node_current_scope_classes(p_node->outer, p_list);
  263. }
  264. }
  265. Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  266. if (p_source == nullptr && parser->has_class(p_class)) {
  267. p_source = p_class;
  268. }
  269. if (p_class->base_type.is_resolving()) {
  270. push_error(vformat(R"(Could not resolve class "%s": Cyclic reference.)", type_from_metatype(p_class->get_datatype()).to_string()), p_source);
  271. return ERR_PARSE_ERROR;
  272. }
  273. if (!p_class->base_type.has_no_type()) {
  274. // Already resolved.
  275. return OK;
  276. }
  277. if (!parser->has_class(p_class)) {
  278. String script_path = p_class->get_datatype().script_path;
  279. Ref<GDScriptParserRef> parser_ref = get_parser_for(script_path);
  280. if (parser_ref.is_null()) {
  281. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  282. return ERR_PARSE_ERROR;
  283. }
  284. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  285. if (err) {
  286. push_error(vformat(R"(Could not parse script "%s": %s.)", script_path, error_names[err]), p_source);
  287. return ERR_PARSE_ERROR;
  288. }
  289. ERR_FAIL_COND_V_MSG(!parser_ref->get_parser()->has_class(p_class), ERR_PARSE_ERROR, R"(Parser bug: Mismatched external parser.)");
  290. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  291. GDScriptParser *other_parser = parser_ref->get_parser();
  292. int error_count = other_parser->errors.size();
  293. other_analyzer->resolve_class_inheritance(p_class);
  294. if (other_parser->errors.size() > error_count) {
  295. push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->fqcn), p_source);
  296. return ERR_PARSE_ERROR;
  297. }
  298. return OK;
  299. }
  300. GDScriptParser::ClassNode *previous_class = parser->current_class;
  301. parser->current_class = p_class;
  302. if (p_class->identifier) {
  303. StringName class_name = p_class->identifier->name;
  304. if (GDScriptParser::get_builtin_type(class_name) < Variant::VARIANT_MAX) {
  305. push_error(vformat(R"(Class "%s" hides a built-in type.)", class_name), p_class->identifier);
  306. } else if (class_exists(class_name)) {
  307. push_error(vformat(R"(Class "%s" hides a native class.)", class_name), p_class->identifier);
  308. } else if (ScriptServer::is_global_class(class_name) && (ScriptServer::get_global_class_path(class_name) != parser->script_path || p_class != parser->head)) {
  309. push_error(vformat(R"(Class "%s" hides a global script class.)", class_name), p_class->identifier);
  310. } else if (ProjectSettings::get_singleton()->has_autoload(class_name) && ProjectSettings::get_singleton()->get_autoload(class_name).is_singleton) {
  311. push_error(vformat(R"(Class "%s" hides an autoload singleton.)", class_name), p_class->identifier);
  312. }
  313. }
  314. GDScriptParser::DataType resolving_datatype;
  315. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  316. p_class->base_type = resolving_datatype;
  317. // Set datatype for class.
  318. GDScriptParser::DataType class_type;
  319. class_type.is_constant = true;
  320. class_type.is_meta_type = true;
  321. class_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  322. class_type.kind = GDScriptParser::DataType::CLASS;
  323. class_type.class_type = p_class;
  324. class_type.script_path = parser->script_path;
  325. class_type.builtin_type = Variant::OBJECT;
  326. p_class->set_datatype(class_type);
  327. GDScriptParser::DataType result;
  328. if (!p_class->extends_used) {
  329. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  330. result.kind = GDScriptParser::DataType::NATIVE;
  331. result.native_type = SNAME("RefCounted");
  332. } else {
  333. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  334. GDScriptParser::DataType base;
  335. int extends_index = 0;
  336. if (!p_class->extends_path.is_empty()) {
  337. if (p_class->extends_path.is_relative_path()) {
  338. p_class->extends_path = class_type.script_path.get_base_dir().path_join(p_class->extends_path).simplify_path();
  339. }
  340. Ref<GDScriptParserRef> ext_parser = get_parser_for(p_class->extends_path);
  341. if (ext_parser.is_null()) {
  342. push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class);
  343. return ERR_PARSE_ERROR;
  344. }
  345. Error err = ext_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  346. if (err != OK) {
  347. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", p_class->extends_path), p_class);
  348. return err;
  349. }
  350. base = ext_parser->get_parser()->head->get_datatype();
  351. } else {
  352. if (p_class->extends.is_empty()) {
  353. push_error("Could not resolve an empty super class path.", p_class);
  354. return ERR_PARSE_ERROR;
  355. }
  356. const StringName &name = p_class->extends[extends_index++];
  357. base.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  358. if (ScriptServer::is_global_class(name)) {
  359. String base_path = ScriptServer::get_global_class_path(name);
  360. if (base_path == parser->script_path) {
  361. base = parser->head->get_datatype();
  362. } else {
  363. Ref<GDScriptParserRef> base_parser = get_parser_for(base_path);
  364. if (base_parser.is_null()) {
  365. push_error(vformat(R"(Could not resolve super class "%s".)", name), p_class);
  366. return ERR_PARSE_ERROR;
  367. }
  368. Error err = base_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  369. if (err != OK) {
  370. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
  371. return err;
  372. }
  373. base = base_parser->get_parser()->head->get_datatype();
  374. }
  375. } else if (ProjectSettings::get_singleton()->has_autoload(name) && ProjectSettings::get_singleton()->get_autoload(name).is_singleton) {
  376. const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(name);
  377. if (info.path.get_extension().to_lower() != GDScriptLanguage::get_singleton()->get_extension()) {
  378. push_error(vformat(R"(Singleton %s is not a GDScript.)", info.name), p_class);
  379. return ERR_PARSE_ERROR;
  380. }
  381. Ref<GDScriptParserRef> info_parser = get_parser_for(info.path);
  382. if (info_parser.is_null()) {
  383. push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), p_class);
  384. return ERR_PARSE_ERROR;
  385. }
  386. Error err = info_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  387. if (err != OK) {
  388. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
  389. return err;
  390. }
  391. base = info_parser->get_parser()->head->get_datatype();
  392. } else if (class_exists(name)) {
  393. base.kind = GDScriptParser::DataType::NATIVE;
  394. base.native_type = name;
  395. } else {
  396. // Look for other classes in script.
  397. bool found = false;
  398. List<GDScriptParser::ClassNode *> script_classes;
  399. get_class_node_current_scope_classes(p_class, &script_classes);
  400. for (GDScriptParser::ClassNode *look_class : script_classes) {
  401. if (look_class->identifier && look_class->identifier->name == name) {
  402. if (!look_class->get_datatype().is_set()) {
  403. Error err = resolve_class_inheritance(look_class, p_class);
  404. if (err) {
  405. return err;
  406. }
  407. }
  408. base = look_class->get_datatype();
  409. found = true;
  410. break;
  411. }
  412. if (look_class->has_member(name)) {
  413. resolve_class_member(look_class, name, p_class);
  414. GDScriptParser::ClassNode::Member member = look_class->get_member(name);
  415. GDScriptParser::DataType member_datatype = member.get_datatype();
  416. switch (member.type) {
  417. case GDScriptParser::ClassNode::Member::CLASS:
  418. break; // OK.
  419. case GDScriptParser::ClassNode::Member::CONSTANT:
  420. if (member_datatype.kind != GDScriptParser::DataType::SCRIPT && member_datatype.kind != GDScriptParser::DataType::CLASS) {
  421. push_error(vformat(R"(Constant "%s" is not a preloaded script or class.)", name), p_class);
  422. return ERR_PARSE_ERROR;
  423. }
  424. break;
  425. default:
  426. push_error(vformat(R"(Cannot use %s "%s" in extends chain.)", member.get_type_name(), name), p_class);
  427. return ERR_PARSE_ERROR;
  428. }
  429. base = member_datatype;
  430. found = true;
  431. break;
  432. }
  433. }
  434. if (!found) {
  435. push_error(vformat(R"(Could not find base class "%s".)", name), p_class);
  436. return ERR_PARSE_ERROR;
  437. }
  438. }
  439. }
  440. for (int index = extends_index; index < p_class->extends.size(); index++) {
  441. if (base.kind != GDScriptParser::DataType::CLASS) {
  442. push_error(R"(Super type "%s" is not a GDScript. Cannot get nested types.)", p_class);
  443. return ERR_PARSE_ERROR;
  444. }
  445. // TODO: Extends could use identifier nodes. That way errors can be pointed out properly and it can be used here.
  446. GDScriptParser::IdentifierNode *id = parser->alloc_node<GDScriptParser::IdentifierNode>();
  447. id->name = p_class->extends[index];
  448. reduce_identifier_from_base(id, &base);
  449. GDScriptParser::DataType id_type = id->get_datatype();
  450. if (!id_type.is_set()) {
  451. push_error(vformat(R"(Could not find type "%s" under base "%s".)", id->name, base.to_string()), p_class);
  452. return ERR_PARSE_ERROR;
  453. } else if (id_type.kind != GDScriptParser::DataType::SCRIPT && id_type.kind != GDScriptParser::DataType::CLASS) {
  454. push_error(vformat(R"(Identifier "%s" is not a preloaded script or class.)", id->name), p_class);
  455. return ERR_PARSE_ERROR;
  456. }
  457. base = id_type;
  458. }
  459. result = base;
  460. }
  461. if (!result.is_set() || result.has_no_type()) {
  462. // TODO: More specific error messages.
  463. push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->identifier == nullptr ? "<main>" : p_class->identifier->name), p_class);
  464. return ERR_PARSE_ERROR;
  465. }
  466. // Check for cyclic inheritance.
  467. const GDScriptParser::ClassNode *base_class = result.class_type;
  468. while (base_class) {
  469. if (base_class->fqcn == p_class->fqcn) {
  470. push_error("Cyclic inheritance.", p_class);
  471. return ERR_PARSE_ERROR;
  472. }
  473. base_class = base_class->base_type.class_type;
  474. }
  475. p_class->base_type = result;
  476. class_type.native_type = result.native_type;
  477. p_class->set_datatype(class_type);
  478. parser->current_class = previous_class;
  479. return OK;
  480. }
  481. Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  482. Error err = resolve_class_inheritance(p_class);
  483. if (err) {
  484. return err;
  485. }
  486. if (p_recursive) {
  487. for (int i = 0; i < p_class->members.size(); i++) {
  488. if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {
  489. err = resolve_class_inheritance(p_class->members[i].m_class, true);
  490. if (err) {
  491. return err;
  492. }
  493. }
  494. }
  495. }
  496. return OK;
  497. }
  498. GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::TypeNode *p_type) {
  499. GDScriptParser::DataType bad_type;
  500. bad_type.kind = GDScriptParser::DataType::VARIANT;
  501. bad_type.type_source = GDScriptParser::DataType::INFERRED;
  502. if (p_type == nullptr) {
  503. return bad_type;
  504. }
  505. if (p_type->get_datatype().is_resolving()) {
  506. push_error(R"(Could not resolve datatype: Cyclic reference.)", p_type);
  507. return bad_type;
  508. }
  509. if (!p_type->get_datatype().has_no_type()) {
  510. return p_type->get_datatype();
  511. }
  512. GDScriptParser::DataType resolving_datatype;
  513. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  514. p_type->set_datatype(resolving_datatype);
  515. GDScriptParser::DataType result;
  516. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  517. if (p_type->type_chain.is_empty()) {
  518. // void.
  519. result.kind = GDScriptParser::DataType::BUILTIN;
  520. result.builtin_type = Variant::NIL;
  521. p_type->set_datatype(result);
  522. return result;
  523. }
  524. StringName first = p_type->type_chain[0]->name;
  525. if (first == SNAME("Variant")) {
  526. if (p_type->type_chain.size() == 2) {
  527. // May be nested enum.
  528. StringName enum_name = p_type->type_chain[1]->name;
  529. StringName qualified_name = String(first) + ENUM_SEPARATOR + String(p_type->type_chain[1]->name);
  530. if (CoreConstants::is_global_enum(qualified_name)) {
  531. result = make_global_enum_type(enum_name, first, true);
  532. return result;
  533. } else {
  534. push_error(vformat(R"(Name "%s" is not a nested type of "Variant".)", enum_name), p_type->type_chain[1]);
  535. return bad_type;
  536. }
  537. } else if (p_type->type_chain.size() > 2) {
  538. push_error(R"(Variant only contains enum types, which do not have nested types.)", p_type->type_chain[2]);
  539. return bad_type;
  540. }
  541. result.kind = GDScriptParser::DataType::VARIANT;
  542. } else if (first == SNAME("Object")) {
  543. // Object is treated like a native type, not a built-in.
  544. result.kind = GDScriptParser::DataType::NATIVE;
  545. result.builtin_type = Variant::OBJECT;
  546. result.native_type = SNAME("Object");
  547. } else if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) {
  548. // Built-in types.
  549. if (p_type->type_chain.size() > 1) {
  550. push_error(R"(Built-in types don't contain nested types.)", p_type->type_chain[1]);
  551. return bad_type;
  552. }
  553. result.kind = GDScriptParser::DataType::BUILTIN;
  554. result.builtin_type = GDScriptParser::get_builtin_type(first);
  555. if (result.builtin_type == Variant::ARRAY) {
  556. GDScriptParser::DataType container_type = type_from_metatype(resolve_datatype(p_type->container_type));
  557. if (container_type.kind != GDScriptParser::DataType::VARIANT) {
  558. container_type.is_constant = false;
  559. result.set_container_element_type(container_type);
  560. }
  561. }
  562. } else if (class_exists(first)) {
  563. // Native engine classes.
  564. result.kind = GDScriptParser::DataType::NATIVE;
  565. result.builtin_type = Variant::OBJECT;
  566. result.native_type = first;
  567. } else if (ScriptServer::is_global_class(first)) {
  568. if (parser->script_path == ScriptServer::get_global_class_path(first)) {
  569. result = parser->head->get_datatype();
  570. } else {
  571. String path = ScriptServer::get_global_class_path(first);
  572. String ext = path.get_extension();
  573. if (ext == GDScriptLanguage::get_singleton()->get_extension()) {
  574. Ref<GDScriptParserRef> ref = get_parser_for(path);
  575. if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {
  576. push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type);
  577. return bad_type;
  578. }
  579. result = ref->get_parser()->head->get_datatype();
  580. } else {
  581. result = make_script_meta_type(ResourceLoader::load(path, "Script"));
  582. }
  583. }
  584. } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) {
  585. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first);
  586. Ref<GDScriptParserRef> ref = get_parser_for(autoload.path);
  587. if (ref.is_null()) {
  588. push_error(vformat(R"(The referenced autoload "%s" (from "%s") could not be loaded.)", first, autoload.path), p_type);
  589. return bad_type;
  590. }
  591. if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {
  592. push_error(vformat(R"(Could not parse singleton "%s" from "%s".)", first, autoload.path), p_type);
  593. return bad_type;
  594. }
  595. result = ref->get_parser()->head->get_datatype();
  596. } else if (ClassDB::has_enum(parser->current_class->base_type.native_type, first)) {
  597. // Native enum in current class.
  598. result = make_native_enum_type(first, parser->current_class->base_type.native_type);
  599. } else if (CoreConstants::is_global_enum(first)) {
  600. if (p_type->type_chain.size() > 1) {
  601. push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[1]);
  602. return bad_type;
  603. }
  604. result = make_global_enum_type(first, StringName());
  605. } else {
  606. // Classes in current scope.
  607. List<GDScriptParser::ClassNode *> script_classes;
  608. bool found = false;
  609. get_class_node_current_scope_classes(parser->current_class, &script_classes);
  610. for (GDScriptParser::ClassNode *script_class : script_classes) {
  611. if (found) {
  612. break;
  613. }
  614. if (script_class->identifier && script_class->identifier->name == first) {
  615. result = script_class->get_datatype();
  616. break;
  617. }
  618. if (script_class->members_indices.has(first)) {
  619. resolve_class_member(script_class, first, p_type);
  620. GDScriptParser::ClassNode::Member member = script_class->get_member(first);
  621. switch (member.type) {
  622. case GDScriptParser::ClassNode::Member::CLASS:
  623. result = member.get_datatype();
  624. found = true;
  625. break;
  626. case GDScriptParser::ClassNode::Member::ENUM:
  627. result = member.get_datatype();
  628. found = true;
  629. break;
  630. case GDScriptParser::ClassNode::Member::CONSTANT:
  631. if (member.get_datatype().is_meta_type) {
  632. result = member.get_datatype();
  633. found = true;
  634. break;
  635. } else if (Ref<Script>(member.constant->initializer->reduced_value).is_valid()) {
  636. Ref<GDScript> gdscript = member.constant->initializer->reduced_value;
  637. if (gdscript.is_valid()) {
  638. Ref<GDScriptParserRef> ref = get_parser_for(gdscript->get_script_path());
  639. if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {
  640. push_error(vformat(R"(Could not parse script from "%s".)", gdscript->get_script_path()), p_type);
  641. return bad_type;
  642. }
  643. result = ref->get_parser()->head->get_datatype();
  644. } else {
  645. result = make_script_meta_type(member.constant->initializer->reduced_value);
  646. }
  647. found = true;
  648. break;
  649. }
  650. [[fallthrough]];
  651. default:
  652. push_error(vformat(R"("%s" is a %s but does not contain a type.)", first, member.get_type_name()), p_type);
  653. return bad_type;
  654. }
  655. }
  656. }
  657. }
  658. if (!result.is_set()) {
  659. push_error(vformat(R"(Could not find type "%s" in the current scope.)", first), p_type);
  660. return bad_type;
  661. }
  662. if (p_type->type_chain.size() > 1) {
  663. if (result.kind == GDScriptParser::DataType::CLASS) {
  664. for (int i = 1; i < p_type->type_chain.size(); i++) {
  665. GDScriptParser::DataType base = result;
  666. reduce_identifier_from_base(p_type->type_chain[i], &base);
  667. result = p_type->type_chain[i]->get_datatype();
  668. if (!result.is_set()) {
  669. push_error(vformat(R"(Could not find type "%s" under base "%s".)", p_type->type_chain[i]->name, base.to_string()), p_type->type_chain[1]);
  670. return bad_type;
  671. } else if (!result.is_meta_type) {
  672. push_error(vformat(R"(Member "%s" under base "%s" is not a valid type.)", p_type->type_chain[i]->name, base.to_string()), p_type->type_chain[1]);
  673. return bad_type;
  674. }
  675. }
  676. } else if (result.kind == GDScriptParser::DataType::NATIVE) {
  677. // Only enums allowed for native.
  678. if (ClassDB::has_enum(result.native_type, p_type->type_chain[1]->name)) {
  679. if (p_type->type_chain.size() > 2) {
  680. push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[2]);
  681. return bad_type;
  682. } else {
  683. result = make_native_enum_type(p_type->type_chain[1]->name, result.native_type);
  684. }
  685. } else {
  686. push_error(vformat(R"(Could not find type "%s" in "%s".)", p_type->type_chain[1]->name, first), p_type->type_chain[1]);
  687. return bad_type;
  688. }
  689. } else {
  690. push_error(vformat(R"(Could not find nested type "%s" under base "%s".)", p_type->type_chain[1]->name, result.to_string()), p_type->type_chain[1]);
  691. return bad_type;
  692. }
  693. }
  694. if (result.builtin_type != Variant::ARRAY && p_type->container_type != nullptr) {
  695. push_error("Only arrays can specify the collection element type.", p_type);
  696. }
  697. p_type->set_datatype(result);
  698. return result;
  699. }
  700. void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, StringName p_name, const GDScriptParser::Node *p_source) {
  701. ERR_FAIL_COND(!p_class->has_member(p_name));
  702. resolve_class_member(p_class, p_class->members_indices[p_name], p_source);
  703. }
  704. void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, int p_index, const GDScriptParser::Node *p_source) {
  705. ERR_FAIL_INDEX(p_index, p_class->members.size());
  706. GDScriptParser::ClassNode::Member &member = p_class->members.write[p_index];
  707. if (p_source == nullptr && parser->has_class(p_class)) {
  708. p_source = member.get_source_node();
  709. }
  710. if (member.get_datatype().is_resolving()) {
  711. push_error(vformat(R"(Could not resolve member "%s": Cyclic reference.)", member.get_name()), p_source);
  712. return;
  713. }
  714. if (member.get_datatype().is_set()) {
  715. return;
  716. }
  717. if (!parser->has_class(p_class)) {
  718. String script_path = p_class->get_datatype().script_path;
  719. Ref<GDScriptParserRef> parser_ref = get_parser_for(script_path);
  720. if (parser_ref.is_null()) {
  721. push_error(vformat(R"(Could not find script "%s" (While resolving "%s").)", script_path, member.get_name()), p_source);
  722. return;
  723. }
  724. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  725. if (err) {
  726. push_error(vformat(R"(Could not resolve script "%s": %s (While resolving "%s").)", script_path, error_names[err], member.get_name()), p_source);
  727. return;
  728. }
  729. ERR_FAIL_COND_MSG(!parser_ref->get_parser()->has_class(p_class), R"(Parser bug: Mismatched external parser.)");
  730. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  731. GDScriptParser *other_parser = parser_ref->get_parser();
  732. int error_count = other_parser->errors.size();
  733. other_analyzer->resolve_class_member(p_class, p_index);
  734. if (other_parser->errors.size() > error_count) {
  735. push_error(vformat(R"(Could not resolve member "%s".)", member.get_name()), p_source);
  736. }
  737. return;
  738. }
  739. // If it's already resolving, that's ok.
  740. if (!p_class->base_type.is_resolving()) {
  741. Error err = resolve_class_inheritance(p_class);
  742. if (err) {
  743. return;
  744. }
  745. }
  746. GDScriptParser::ClassNode *previous_class = parser->current_class;
  747. parser->current_class = p_class;
  748. GDScriptParser::DataType resolving_datatype;
  749. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  750. {
  751. #ifdef DEBUG_ENABLED
  752. HashSet<GDScriptWarning::Code> previously_ignored_warnings = parser->ignored_warnings;
  753. GDScriptParser::Node *member_node = member.get_source_node();
  754. if (member_node && member_node->type != GDScriptParser::Node::ANNOTATION) {
  755. // Apply @warning_ignore annotations before resolving member.
  756. for (GDScriptParser::AnnotationNode *&E : member_node->annotations) {
  757. if (E->name == SNAME("@warning_ignore")) {
  758. resolve_annotation(E);
  759. E->apply(parser, member.variable);
  760. }
  761. }
  762. for (GDScriptWarning::Code ignored_warning : member_node->ignored_warnings) {
  763. parser->ignored_warnings.insert(ignored_warning);
  764. }
  765. }
  766. #endif
  767. switch (member.type) {
  768. case GDScriptParser::ClassNode::Member::VARIABLE: {
  769. check_class_member_name_conflict(p_class, member.variable->identifier->name, member.variable);
  770. member.variable->set_datatype(resolving_datatype);
  771. resolve_variable(member.variable, false);
  772. // Apply annotations.
  773. for (GDScriptParser::AnnotationNode *&E : member.variable->annotations) {
  774. if (E->name != SNAME("@warning_ignore")) {
  775. resolve_annotation(E);
  776. E->apply(parser, member.variable);
  777. }
  778. }
  779. #ifdef DEBUG_ENABLED
  780. if (member.variable->exported && member.variable->onready) {
  781. parser->push_warning(member.variable, GDScriptWarning::ONREADY_WITH_EXPORT);
  782. }
  783. if (member.variable->initializer) {
  784. // Check if it is call to get_node() on self (using shorthand $ or not), so we can check if @onready is needed.
  785. // This could be improved by traversing the expression fully and checking the presence of get_node at any level.
  786. if (!member.variable->onready && member.variable->initializer && (member.variable->initializer->type == GDScriptParser::Node::GET_NODE || member.variable->initializer->type == GDScriptParser::Node::CALL || member.variable->initializer->type == GDScriptParser::Node::CAST)) {
  787. GDScriptParser::Node *expr = member.variable->initializer;
  788. if (expr->type == GDScriptParser::Node::CAST) {
  789. expr = static_cast<GDScriptParser::CastNode *>(expr)->operand;
  790. }
  791. bool is_get_node = expr->type == GDScriptParser::Node::GET_NODE;
  792. bool is_using_shorthand = is_get_node;
  793. if (!is_get_node && expr->type == GDScriptParser::Node::CALL) {
  794. is_using_shorthand = false;
  795. GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(expr);
  796. if (call->function_name == SNAME("get_node")) {
  797. switch (call->get_callee_type()) {
  798. case GDScriptParser::Node::IDENTIFIER: {
  799. is_get_node = true;
  800. } break;
  801. case GDScriptParser::Node::SUBSCRIPT: {
  802. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(call->callee);
  803. is_get_node = subscript->is_attribute && subscript->base->type == GDScriptParser::Node::SELF;
  804. } break;
  805. default:
  806. break;
  807. }
  808. }
  809. }
  810. if (is_get_node) {
  811. parser->push_warning(member.variable, GDScriptWarning::GET_NODE_DEFAULT_WITHOUT_ONREADY, is_using_shorthand ? "$" : "get_node()");
  812. }
  813. }
  814. }
  815. #endif
  816. } break;
  817. case GDScriptParser::ClassNode::Member::CONSTANT: {
  818. check_class_member_name_conflict(p_class, member.constant->identifier->name, member.constant);
  819. member.constant->set_datatype(resolving_datatype);
  820. resolve_constant(member.constant, false);
  821. // Apply annotations.
  822. for (GDScriptParser::AnnotationNode *&E : member.constant->annotations) {
  823. resolve_annotation(E);
  824. E->apply(parser, member.constant);
  825. }
  826. } break;
  827. case GDScriptParser::ClassNode::Member::SIGNAL: {
  828. check_class_member_name_conflict(p_class, member.signal->identifier->name, member.signal);
  829. member.signal->set_datatype(resolving_datatype);
  830. // This is the _only_ way to declare a signal. Therefore, we can generate its
  831. // MethodInfo inline so it's a tiny bit more efficient.
  832. MethodInfo mi = MethodInfo(member.signal->identifier->name);
  833. for (int j = 0; j < member.signal->parameters.size(); j++) {
  834. GDScriptParser::ParameterNode *param = member.signal->parameters[j];
  835. GDScriptParser::DataType param_type = type_from_metatype(resolve_datatype(param->datatype_specifier));
  836. param->set_datatype(param_type);
  837. mi.arguments.push_back(PropertyInfo(param_type.builtin_type, param->identifier->name));
  838. // TODO: add signal parameter default values
  839. }
  840. member.signal->set_datatype(make_signal_type(mi));
  841. // Apply annotations.
  842. for (GDScriptParser::AnnotationNode *&E : member.signal->annotations) {
  843. resolve_annotation(E);
  844. E->apply(parser, member.signal);
  845. }
  846. } break;
  847. case GDScriptParser::ClassNode::Member::ENUM: {
  848. check_class_member_name_conflict(p_class, member.m_enum->identifier->name, member.m_enum);
  849. member.m_enum->set_datatype(resolving_datatype);
  850. GDScriptParser::DataType enum_type = make_enum_type(member.m_enum->identifier->name, p_class->fqcn, true);
  851. const GDScriptParser::EnumNode *prev_enum = current_enum;
  852. current_enum = member.m_enum;
  853. Dictionary dictionary;
  854. for (int j = 0; j < member.m_enum->values.size(); j++) {
  855. GDScriptParser::EnumNode::Value &element = member.m_enum->values.write[j];
  856. if (element.custom_value) {
  857. reduce_expression(element.custom_value);
  858. if (!element.custom_value->is_constant) {
  859. push_error(R"(Enum values must be constant.)", element.custom_value);
  860. } else if (element.custom_value->reduced_value.get_type() != Variant::INT) {
  861. push_error(R"(Enum values must be integers.)", element.custom_value);
  862. } else {
  863. element.value = element.custom_value->reduced_value;
  864. element.resolved = true;
  865. }
  866. } else {
  867. if (element.index > 0) {
  868. element.value = element.parent_enum->values[element.index - 1].value + 1;
  869. } else {
  870. element.value = 0;
  871. }
  872. element.resolved = true;
  873. }
  874. enum_type.enum_values[element.identifier->name] = element.value;
  875. dictionary[String(element.identifier->name)] = element.value;
  876. }
  877. current_enum = prev_enum;
  878. dictionary.make_read_only();
  879. member.m_enum->set_datatype(enum_type);
  880. member.m_enum->dictionary = dictionary;
  881. // Apply annotations.
  882. for (GDScriptParser::AnnotationNode *&E : member.m_enum->annotations) {
  883. resolve_annotation(E);
  884. E->apply(parser, member.m_enum);
  885. }
  886. } break;
  887. case GDScriptParser::ClassNode::Member::FUNCTION:
  888. for (GDScriptParser::AnnotationNode *&E : member.function->annotations) {
  889. resolve_annotation(E);
  890. E->apply(parser, member.function);
  891. }
  892. resolve_function_signature(member.function, p_source);
  893. break;
  894. case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
  895. member.enum_value.identifier->set_datatype(resolving_datatype);
  896. if (member.enum_value.custom_value) {
  897. check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.custom_value);
  898. const GDScriptParser::EnumNode *prev_enum = current_enum;
  899. current_enum = member.enum_value.parent_enum;
  900. reduce_expression(member.enum_value.custom_value);
  901. current_enum = prev_enum;
  902. if (!member.enum_value.custom_value->is_constant) {
  903. push_error(R"(Enum values must be constant.)", member.enum_value.custom_value);
  904. } else if (member.enum_value.custom_value->reduced_value.get_type() != Variant::INT) {
  905. push_error(R"(Enum values must be integers.)", member.enum_value.custom_value);
  906. } else {
  907. member.enum_value.value = member.enum_value.custom_value->reduced_value;
  908. member.enum_value.resolved = true;
  909. }
  910. } else {
  911. check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.parent_enum);
  912. if (member.enum_value.index > 0) {
  913. const GDScriptParser::EnumNode::Value &prev_value = member.enum_value.parent_enum->values[member.enum_value.index - 1];
  914. resolve_class_member(p_class, prev_value.identifier->name, member.enum_value.identifier);
  915. member.enum_value.value = prev_value.value + 1;
  916. } else {
  917. member.enum_value.value = 0;
  918. }
  919. member.enum_value.resolved = true;
  920. }
  921. // Also update the original references.
  922. member.enum_value.parent_enum->values.set(member.enum_value.index, member.enum_value);
  923. member.enum_value.identifier->set_datatype(make_enum_type(UNNAMED_ENUM, p_class->fqcn, false));
  924. } break;
  925. case GDScriptParser::ClassNode::Member::CLASS:
  926. check_class_member_name_conflict(p_class, member.m_class->identifier->name, member.m_class);
  927. // If it's already resolving, that's ok.
  928. if (!member.m_class->base_type.is_resolving()) {
  929. resolve_class_inheritance(member.m_class, p_source);
  930. }
  931. break;
  932. case GDScriptParser::ClassNode::Member::GROUP:
  933. // No-op, but needed to silence warnings.
  934. break;
  935. case GDScriptParser::ClassNode::Member::UNDEFINED:
  936. ERR_PRINT("Trying to resolve undefined member.");
  937. break;
  938. }
  939. #ifdef DEBUG_ENABLED
  940. parser->ignored_warnings = previously_ignored_warnings;
  941. #endif
  942. }
  943. parser->current_class = previous_class;
  944. }
  945. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  946. if (p_source == nullptr && parser->has_class(p_class)) {
  947. p_source = p_class;
  948. }
  949. if (!p_class->resolved_interface) {
  950. if (!parser->has_class(p_class)) {
  951. String script_path = p_class->get_datatype().script_path;
  952. Ref<GDScriptParserRef> parser_ref = get_parser_for(script_path);
  953. if (parser_ref.is_null()) {
  954. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  955. return;
  956. }
  957. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  958. if (err) {
  959. push_error(vformat(R"(Could not resolve script "%s": %s.)", script_path, error_names[err]), p_source);
  960. return;
  961. }
  962. ERR_FAIL_COND_MSG(!parser_ref->get_parser()->has_class(p_class), R"(Parser bug: Mismatched external parser.)");
  963. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  964. GDScriptParser *other_parser = parser_ref->get_parser();
  965. int error_count = other_parser->errors.size();
  966. other_analyzer->resolve_class_interface(p_class);
  967. if (other_parser->errors.size() > error_count) {
  968. push_error(vformat(R"(Could not resolve class "%s".)", p_class->fqcn), p_source);
  969. }
  970. return;
  971. }
  972. p_class->resolved_interface = true;
  973. if (resolve_class_inheritance(p_class) != OK) {
  974. return;
  975. }
  976. GDScriptParser::DataType base_type = p_class->base_type;
  977. if (base_type.kind == GDScriptParser::DataType::CLASS) {
  978. GDScriptParser::ClassNode *base_class = base_type.class_type;
  979. resolve_class_interface(base_class, p_class);
  980. }
  981. for (int i = 0; i < p_class->members.size(); i++) {
  982. resolve_class_member(p_class, i);
  983. }
  984. }
  985. }
  986. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  987. resolve_class_interface(p_class);
  988. if (p_recursive) {
  989. for (int i = 0; i < p_class->members.size(); i++) {
  990. GDScriptParser::ClassNode::Member member = p_class->members[i];
  991. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  992. resolve_class_interface(member.m_class, true);
  993. }
  994. }
  995. }
  996. }
  997. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  998. if (p_source == nullptr && parser->has_class(p_class)) {
  999. p_source = p_class;
  1000. }
  1001. if (p_class->resolved_body) {
  1002. return;
  1003. }
  1004. if (!parser->has_class(p_class)) {
  1005. String script_path = p_class->get_datatype().script_path;
  1006. Ref<GDScriptParserRef> parser_ref = get_parser_for(script_path);
  1007. if (parser_ref.is_null()) {
  1008. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  1009. return;
  1010. }
  1011. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  1012. if (err) {
  1013. push_error(vformat(R"(Could not resolve script "%s": %s.)", script_path, error_names[err]), p_source);
  1014. return;
  1015. }
  1016. ERR_FAIL_COND_MSG(!parser_ref->get_parser()->has_class(p_class), R"(Parser bug: Mismatched external parser.)");
  1017. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  1018. GDScriptParser *other_parser = parser_ref->get_parser();
  1019. int error_count = other_parser->errors.size();
  1020. other_analyzer->resolve_class_body(p_class);
  1021. if (other_parser->errors.size() > error_count) {
  1022. push_error(vformat(R"(Could not resolve class "%s".)", p_class->fqcn), p_source);
  1023. }
  1024. return;
  1025. }
  1026. p_class->resolved_body = true;
  1027. GDScriptParser::ClassNode *previous_class = parser->current_class;
  1028. parser->current_class = p_class;
  1029. resolve_class_interface(p_class, p_source);
  1030. GDScriptParser::DataType base_type = p_class->base_type;
  1031. if (base_type.kind == GDScriptParser::DataType::CLASS) {
  1032. GDScriptParser::ClassNode *base_class = base_type.class_type;
  1033. resolve_class_body(base_class, p_class);
  1034. }
  1035. // Do functions, properties, and groups now.
  1036. for (int i = 0; i < p_class->members.size(); i++) {
  1037. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1038. if (member.type == GDScriptParser::ClassNode::Member::FUNCTION) {
  1039. // Apply annotations.
  1040. for (GDScriptParser::AnnotationNode *&E : member.function->annotations) {
  1041. resolve_annotation(E);
  1042. E->apply(parser, member.function);
  1043. }
  1044. resolve_function_body(member.function);
  1045. } else if (member.type == GDScriptParser::ClassNode::Member::VARIABLE && member.variable->property != GDScriptParser::VariableNode::PROP_NONE) {
  1046. if (member.variable->property == GDScriptParser::VariableNode::PROP_INLINE) {
  1047. if (member.variable->getter != nullptr) {
  1048. member.variable->getter->set_datatype(member.variable->datatype);
  1049. resolve_function_body(member.variable->getter);
  1050. }
  1051. if (member.variable->setter != nullptr) {
  1052. resolve_function_signature(member.variable->setter);
  1053. if (member.variable->setter->parameters.size() > 0) {
  1054. member.variable->setter->parameters[0]->datatype_specifier = member.variable->datatype_specifier;
  1055. member.variable->setter->parameters[0]->set_datatype(member.get_datatype());
  1056. }
  1057. resolve_function_body(member.variable->setter);
  1058. }
  1059. }
  1060. } else if (member.type == GDScriptParser::ClassNode::Member::GROUP) {
  1061. // Apply annotation (`@export_{category,group,subgroup}`).
  1062. resolve_annotation(member.annotation);
  1063. member.annotation->apply(parser, nullptr);
  1064. }
  1065. }
  1066. // Check unused variables and datatypes of property getters and setters.
  1067. for (int i = 0; i < p_class->members.size(); i++) {
  1068. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1069. if (member.type == GDScriptParser::ClassNode::Member::VARIABLE) {
  1070. #ifdef DEBUG_ENABLED
  1071. HashSet<GDScriptWarning::Code> previously_ignored_warnings = parser->ignored_warnings;
  1072. for (GDScriptWarning::Code ignored_warning : member.variable->ignored_warnings) {
  1073. parser->ignored_warnings.insert(ignored_warning);
  1074. }
  1075. if (member.variable->usages == 0 && String(member.variable->identifier->name).begins_with("_")) {
  1076. parser->push_warning(member.variable->identifier, GDScriptWarning::UNUSED_PRIVATE_CLASS_VARIABLE, member.variable->identifier->name);
  1077. }
  1078. #endif
  1079. if (member.variable->property == GDScriptParser::VariableNode::PROP_SETGET) {
  1080. GDScriptParser::FunctionNode *getter_function = nullptr;
  1081. GDScriptParser::FunctionNode *setter_function = nullptr;
  1082. bool has_valid_getter = false;
  1083. bool has_valid_setter = false;
  1084. if (member.variable->getter_pointer != nullptr) {
  1085. if (p_class->has_function(member.variable->getter_pointer->name)) {
  1086. getter_function = p_class->get_member(member.variable->getter_pointer->name).function;
  1087. }
  1088. if (getter_function == nullptr) {
  1089. push_error(vformat(R"(Getter "%s" not found.)", member.variable->getter_pointer->name), member.variable);
  1090. } else {
  1091. GDScriptParser::DataType return_datatype = getter_function->datatype;
  1092. if (getter_function->return_type != nullptr) {
  1093. return_datatype = getter_function->return_type->datatype;
  1094. return_datatype.is_meta_type = false;
  1095. }
  1096. if (getter_function->parameters.size() != 0 || return_datatype.has_no_type()) {
  1097. push_error(vformat(R"(Function "%s" cannot be used as getter because of its signature.)", getter_function->identifier->name), member.variable);
  1098. } else if (!is_type_compatible(member.variable->datatype, return_datatype, true)) {
  1099. push_error(vformat(R"(Function with return type "%s" cannot be used as getter for a property of type "%s".)", return_datatype.to_string(), member.variable->datatype.to_string()), member.variable);
  1100. } else {
  1101. has_valid_getter = true;
  1102. #ifdef DEBUG_ENABLED
  1103. if (member.variable->datatype.builtin_type == Variant::INT && return_datatype.builtin_type == Variant::FLOAT) {
  1104. parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION);
  1105. }
  1106. #endif
  1107. }
  1108. }
  1109. }
  1110. if (member.variable->setter_pointer != nullptr) {
  1111. if (p_class->has_function(member.variable->setter_pointer->name)) {
  1112. setter_function = p_class->get_member(member.variable->setter_pointer->name).function;
  1113. }
  1114. if (setter_function == nullptr) {
  1115. push_error(vformat(R"(Setter "%s" not found.)", member.variable->setter_pointer->name), member.variable);
  1116. } else if (setter_function->parameters.size() != 1) {
  1117. push_error(vformat(R"(Function "%s" cannot be used as setter because of its signature.)", setter_function->identifier->name), member.variable);
  1118. } else if (!is_type_compatible(member.variable->datatype, setter_function->parameters[0]->datatype, true)) {
  1119. push_error(vformat(R"(Function with argument type "%s" cannot be used as setter for a property of type "%s".)", setter_function->parameters[0]->datatype.to_string(), member.variable->datatype.to_string()), member.variable);
  1120. } else {
  1121. has_valid_setter = true;
  1122. #ifdef DEBUG_ENABLED
  1123. if (member.variable->datatype.builtin_type == Variant::FLOAT && setter_function->parameters[0]->datatype.builtin_type == Variant::INT) {
  1124. parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION);
  1125. }
  1126. #endif
  1127. }
  1128. }
  1129. if (member.variable->datatype.is_variant() && has_valid_getter && has_valid_setter) {
  1130. if (!is_type_compatible(getter_function->datatype, setter_function->parameters[0]->datatype, true)) {
  1131. push_error(vformat(R"(Getter with type "%s" cannot be used along with setter of type "%s".)", getter_function->datatype.to_string(), setter_function->parameters[0]->datatype.to_string()), member.variable);
  1132. }
  1133. }
  1134. }
  1135. #ifdef DEBUG_ENABLED
  1136. parser->ignored_warnings = previously_ignored_warnings;
  1137. #endif // DEBUG_ENABLED
  1138. }
  1139. }
  1140. parser->current_class = previous_class;
  1141. }
  1142. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  1143. resolve_class_body(p_class);
  1144. if (p_recursive) {
  1145. for (int i = 0; i < p_class->members.size(); i++) {
  1146. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1147. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  1148. resolve_class_body(member.m_class, true);
  1149. }
  1150. }
  1151. }
  1152. }
  1153. void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node, bool p_is_root) {
  1154. ERR_FAIL_COND_MSG(p_node == nullptr, "Trying to resolve type of a null node.");
  1155. switch (p_node->type) {
  1156. case GDScriptParser::Node::NONE:
  1157. break; // Unreachable.
  1158. case GDScriptParser::Node::CLASS:
  1159. if (OK == resolve_class_inheritance(static_cast<GDScriptParser::ClassNode *>(p_node), true)) {
  1160. resolve_class_interface(static_cast<GDScriptParser::ClassNode *>(p_node), true);
  1161. resolve_class_body(static_cast<GDScriptParser::ClassNode *>(p_node), true);
  1162. }
  1163. break;
  1164. case GDScriptParser::Node::CONSTANT:
  1165. resolve_constant(static_cast<GDScriptParser::ConstantNode *>(p_node), true);
  1166. break;
  1167. case GDScriptParser::Node::FOR:
  1168. resolve_for(static_cast<GDScriptParser::ForNode *>(p_node));
  1169. break;
  1170. case GDScriptParser::Node::IF:
  1171. resolve_if(static_cast<GDScriptParser::IfNode *>(p_node));
  1172. break;
  1173. case GDScriptParser::Node::SUITE:
  1174. resolve_suite(static_cast<GDScriptParser::SuiteNode *>(p_node));
  1175. break;
  1176. case GDScriptParser::Node::VARIABLE:
  1177. resolve_variable(static_cast<GDScriptParser::VariableNode *>(p_node), true);
  1178. break;
  1179. case GDScriptParser::Node::WHILE:
  1180. resolve_while(static_cast<GDScriptParser::WhileNode *>(p_node));
  1181. break;
  1182. case GDScriptParser::Node::ANNOTATION:
  1183. resolve_annotation(static_cast<GDScriptParser::AnnotationNode *>(p_node));
  1184. break;
  1185. case GDScriptParser::Node::ASSERT:
  1186. resolve_assert(static_cast<GDScriptParser::AssertNode *>(p_node));
  1187. break;
  1188. case GDScriptParser::Node::MATCH:
  1189. resolve_match(static_cast<GDScriptParser::MatchNode *>(p_node));
  1190. break;
  1191. case GDScriptParser::Node::MATCH_BRANCH:
  1192. resolve_match_branch(static_cast<GDScriptParser::MatchBranchNode *>(p_node), nullptr);
  1193. break;
  1194. case GDScriptParser::Node::PARAMETER:
  1195. resolve_parameter(static_cast<GDScriptParser::ParameterNode *>(p_node));
  1196. break;
  1197. case GDScriptParser::Node::PATTERN:
  1198. resolve_match_pattern(static_cast<GDScriptParser::PatternNode *>(p_node), nullptr);
  1199. break;
  1200. case GDScriptParser::Node::RETURN:
  1201. resolve_return(static_cast<GDScriptParser::ReturnNode *>(p_node));
  1202. break;
  1203. case GDScriptParser::Node::TYPE:
  1204. resolve_datatype(static_cast<GDScriptParser::TypeNode *>(p_node));
  1205. break;
  1206. // Resolving expression is the same as reducing them.
  1207. case GDScriptParser::Node::ARRAY:
  1208. case GDScriptParser::Node::ASSIGNMENT:
  1209. case GDScriptParser::Node::AWAIT:
  1210. case GDScriptParser::Node::BINARY_OPERATOR:
  1211. case GDScriptParser::Node::CALL:
  1212. case GDScriptParser::Node::CAST:
  1213. case GDScriptParser::Node::DICTIONARY:
  1214. case GDScriptParser::Node::GET_NODE:
  1215. case GDScriptParser::Node::IDENTIFIER:
  1216. case GDScriptParser::Node::LAMBDA:
  1217. case GDScriptParser::Node::LITERAL:
  1218. case GDScriptParser::Node::PRELOAD:
  1219. case GDScriptParser::Node::SELF:
  1220. case GDScriptParser::Node::SUBSCRIPT:
  1221. case GDScriptParser::Node::TERNARY_OPERATOR:
  1222. case GDScriptParser::Node::TYPE_TEST:
  1223. case GDScriptParser::Node::UNARY_OPERATOR:
  1224. reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), p_is_root);
  1225. break;
  1226. case GDScriptParser::Node::BREAK:
  1227. case GDScriptParser::Node::BREAKPOINT:
  1228. case GDScriptParser::Node::CONTINUE:
  1229. case GDScriptParser::Node::ENUM:
  1230. case GDScriptParser::Node::FUNCTION:
  1231. case GDScriptParser::Node::PASS:
  1232. case GDScriptParser::Node::SIGNAL:
  1233. // Nothing to do.
  1234. break;
  1235. }
  1236. }
  1237. void GDScriptAnalyzer::resolve_annotation(GDScriptParser::AnnotationNode *p_annotation) {
  1238. ERR_FAIL_COND_MSG(!parser->valid_annotations.has(p_annotation->name), vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  1239. if (p_annotation->is_resolved) {
  1240. return;
  1241. }
  1242. p_annotation->is_resolved = true;
  1243. const MethodInfo &annotation_info = parser->valid_annotations[p_annotation->name].info;
  1244. const List<PropertyInfo>::Element *E = annotation_info.arguments.front();
  1245. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  1246. GDScriptParser::ExpressionNode *argument = p_annotation->arguments[i];
  1247. const PropertyInfo &argument_info = E->get();
  1248. if (E->next() != nullptr) {
  1249. E = E->next();
  1250. }
  1251. reduce_expression(argument);
  1252. if (!argument->is_constant) {
  1253. push_error(vformat(R"(Argument %d of annotation "%s" isn't a constant expression.)", i + 1, p_annotation->name), argument);
  1254. return;
  1255. }
  1256. Variant value = argument->reduced_value;
  1257. if (value.get_type() != argument_info.type) {
  1258. #ifdef DEBUG_ENABLED
  1259. if (argument_info.type == Variant::INT && value.get_type() == Variant::FLOAT) {
  1260. parser->push_warning(argument, GDScriptWarning::NARROWING_CONVERSION);
  1261. }
  1262. #endif
  1263. if (!Variant::can_convert_strict(value.get_type(), argument_info.type)) {
  1264. push_error(vformat(R"(Invalid argument for annotation "%s": argument %d should be "%s" but is "%s".)", p_annotation->name, i + 1, Variant::get_type_name(argument_info.type), argument->get_datatype().to_string()), argument);
  1265. return;
  1266. }
  1267. Variant converted_to;
  1268. const Variant *converted_from = &value;
  1269. Callable::CallError call_error;
  1270. Variant::construct(argument_info.type, converted_to, &converted_from, 1, call_error);
  1271. if (call_error.error != Callable::CallError::CALL_OK) {
  1272. push_error(vformat(R"(Cannot convert argument %d of annotation "%s" from "%s" to "%s".)", i + 1, p_annotation->name, Variant::get_type_name(value.get_type()), Variant::get_type_name(argument_info.type)), argument);
  1273. return;
  1274. }
  1275. value = converted_to;
  1276. }
  1277. p_annotation->resolved_arguments.push_back(value);
  1278. }
  1279. }
  1280. void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode *p_function, const GDScriptParser::Node *p_source, bool p_is_lambda) {
  1281. if (p_source == nullptr) {
  1282. p_source = p_function;
  1283. }
  1284. StringName function_name = p_function->identifier != nullptr ? p_function->identifier->name : StringName();
  1285. if (p_function->get_datatype().is_resolving()) {
  1286. push_error(vformat(R"(Could not resolve function "%s": Cyclic reference.)", function_name), p_source);
  1287. return;
  1288. }
  1289. if (p_function->resolved_signature) {
  1290. return;
  1291. }
  1292. p_function->resolved_signature = true;
  1293. #ifdef DEBUG_ENABLED
  1294. HashSet<GDScriptWarning::Code> previously_ignored_warnings = parser->ignored_warnings;
  1295. for (GDScriptWarning::Code ignored_warning : p_function->ignored_warnings) {
  1296. parser->ignored_warnings.insert(ignored_warning);
  1297. }
  1298. #endif
  1299. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  1300. parser->current_function = p_function;
  1301. GDScriptParser::DataType prev_datatype = p_function->get_datatype();
  1302. GDScriptParser::DataType resolving_datatype;
  1303. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  1304. p_function->set_datatype(resolving_datatype);
  1305. #ifdef TOOLS_ENABLED
  1306. int default_value_count = 0;
  1307. #endif // TOOLS_ENABLED
  1308. for (int i = 0; i < p_function->parameters.size(); i++) {
  1309. resolve_parameter(p_function->parameters[i]);
  1310. #ifdef DEBUG_ENABLED
  1311. if (p_function->parameters[i]->usages == 0 && !String(p_function->parameters[i]->identifier->name).begins_with("_")) {
  1312. parser->push_warning(p_function->parameters[i]->identifier, GDScriptWarning::UNUSED_PARAMETER, function_name, p_function->parameters[i]->identifier->name);
  1313. }
  1314. is_shadowing(p_function->parameters[i]->identifier, "function parameter");
  1315. #endif // DEBUG_ENABLED
  1316. #ifdef TOOLS_ENABLED
  1317. if (p_function->parameters[i]->initializer) {
  1318. default_value_count++;
  1319. if (p_function->parameters[i]->initializer->is_constant) {
  1320. p_function->default_arg_values.push_back(p_function->parameters[i]->initializer->reduced_value);
  1321. } else {
  1322. p_function->default_arg_values.push_back(Variant()); // Prevent shift.
  1323. }
  1324. }
  1325. #endif // TOOLS_ENABLED
  1326. }
  1327. if (!p_is_lambda && function_name == GDScriptLanguage::get_singleton()->strings._init) {
  1328. // Constructor.
  1329. GDScriptParser::DataType return_type = parser->current_class->get_datatype();
  1330. return_type.is_meta_type = false;
  1331. p_function->set_datatype(return_type);
  1332. if (p_function->return_type) {
  1333. GDScriptParser::DataType declared_return = resolve_datatype(p_function->return_type);
  1334. if (declared_return.kind != GDScriptParser::DataType::BUILTIN || declared_return.builtin_type != Variant::NIL) {
  1335. push_error("Constructor cannot have an explicit return type.", p_function->return_type);
  1336. }
  1337. }
  1338. } else {
  1339. if (p_function->return_type != nullptr) {
  1340. p_function->set_datatype(type_from_metatype(resolve_datatype(p_function->return_type)));
  1341. } else {
  1342. // In case the function is not typed, we can safely assume it's a Variant, so it's okay to mark as "inferred" here.
  1343. // It's not "undetected" to not mix up with unknown functions.
  1344. GDScriptParser::DataType return_type;
  1345. return_type.type_source = GDScriptParser::DataType::INFERRED;
  1346. return_type.kind = GDScriptParser::DataType::VARIANT;
  1347. p_function->set_datatype(return_type);
  1348. }
  1349. #ifdef TOOLS_ENABLED
  1350. // Check if the function signature matches the parent. If not it's an error since it breaks polymorphism.
  1351. // Not for the constructor which can vary in signature.
  1352. GDScriptParser::DataType base_type = parser->current_class->base_type;
  1353. base_type.is_meta_type = false;
  1354. GDScriptParser::DataType parent_return_type;
  1355. List<GDScriptParser::DataType> parameters_types;
  1356. int default_par_count = 0;
  1357. bool is_static = false;
  1358. bool is_vararg = false;
  1359. StringName native_base;
  1360. if (!p_is_lambda && get_function_signature(p_function, false, base_type, function_name, parent_return_type, parameters_types, default_par_count, is_static, is_vararg, &native_base)) {
  1361. bool valid = p_function->is_static == is_static;
  1362. valid = valid && parent_return_type == p_function->get_datatype();
  1363. int par_count_diff = p_function->parameters.size() - parameters_types.size();
  1364. valid = valid && par_count_diff >= 0;
  1365. valid = valid && default_value_count >= default_par_count + par_count_diff;
  1366. int i = 0;
  1367. for (const GDScriptParser::DataType &par_type : parameters_types) {
  1368. valid = valid && par_type == p_function->parameters[i++]->get_datatype();
  1369. }
  1370. if (!valid) {
  1371. // Compute parent signature as a string to show in the error message.
  1372. String parent_signature = String(function_name) + "(";
  1373. int j = 0;
  1374. for (const GDScriptParser::DataType &par_type : parameters_types) {
  1375. if (j > 0) {
  1376. parent_signature += ", ";
  1377. }
  1378. String parameter = par_type.to_string();
  1379. if (parameter == "null") {
  1380. parameter = "Variant";
  1381. }
  1382. parent_signature += parameter;
  1383. if (j >= parameters_types.size() - default_par_count) {
  1384. parent_signature += " = <default>";
  1385. }
  1386. j++;
  1387. }
  1388. parent_signature += ") -> ";
  1389. const String return_type = parent_return_type.is_hard_type() ? parent_return_type.to_string() : "Variant";
  1390. if (return_type == "null") {
  1391. parent_signature += "void";
  1392. } else {
  1393. parent_signature += return_type;
  1394. }
  1395. push_error(vformat(R"(The function signature doesn't match the parent. Parent signature is "%s".)", parent_signature), p_function);
  1396. }
  1397. #ifdef DEBUG_ENABLED
  1398. if (native_base != StringName()) {
  1399. parser->push_warning(p_function, GDScriptWarning::NATIVE_METHOD_OVERRIDE, function_name, native_base);
  1400. }
  1401. #endif
  1402. }
  1403. #endif // TOOLS_ENABLED
  1404. }
  1405. if (p_function->get_datatype().is_resolving()) {
  1406. p_function->set_datatype(prev_datatype);
  1407. }
  1408. #ifdef DEBUG_ENABLED
  1409. parser->ignored_warnings = previously_ignored_warnings;
  1410. #endif
  1411. parser->current_function = previous_function;
  1412. }
  1413. void GDScriptAnalyzer::resolve_function_body(GDScriptParser::FunctionNode *p_function, bool p_is_lambda) {
  1414. if (p_function->resolved_body) {
  1415. return;
  1416. }
  1417. p_function->resolved_body = true;
  1418. #ifdef DEBUG_ENABLED
  1419. HashSet<GDScriptWarning::Code> previously_ignored_warnings = parser->ignored_warnings;
  1420. for (GDScriptWarning::Code ignored_warning : p_function->ignored_warnings) {
  1421. parser->ignored_warnings.insert(ignored_warning);
  1422. }
  1423. #endif
  1424. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  1425. parser->current_function = p_function;
  1426. resolve_suite(p_function->body);
  1427. if (!p_function->get_datatype().is_hard_type() && p_function->body->get_datatype().is_set()) {
  1428. // Use the suite inferred type if return isn't explicitly set.
  1429. p_function->set_datatype(p_function->body->get_datatype());
  1430. } else if (p_function->get_datatype().is_hard_type() && (p_function->get_datatype().kind != GDScriptParser::DataType::BUILTIN || p_function->get_datatype().builtin_type != Variant::NIL)) {
  1431. if (!p_function->body->has_return && (p_is_lambda || p_function->identifier->name != GDScriptLanguage::get_singleton()->strings._init)) {
  1432. push_error(R"(Not all code paths return a value.)", p_function);
  1433. }
  1434. }
  1435. #ifdef DEBUG_ENABLED
  1436. parser->ignored_warnings = previously_ignored_warnings;
  1437. #endif
  1438. parser->current_function = previous_function;
  1439. }
  1440. void GDScriptAnalyzer::decide_suite_type(GDScriptParser::Node *p_suite, GDScriptParser::Node *p_statement) {
  1441. if (p_statement == nullptr) {
  1442. return;
  1443. }
  1444. switch (p_statement->type) {
  1445. case GDScriptParser::Node::IF:
  1446. case GDScriptParser::Node::FOR:
  1447. case GDScriptParser::Node::MATCH:
  1448. case GDScriptParser::Node::PATTERN:
  1449. case GDScriptParser::Node::RETURN:
  1450. case GDScriptParser::Node::WHILE:
  1451. // Use return or nested suite type as this suite type.
  1452. if (p_suite->get_datatype().is_set() && (p_suite->get_datatype() != p_statement->get_datatype())) {
  1453. // Mixed types.
  1454. // TODO: This could use the common supertype instead.
  1455. p_suite->datatype.kind = GDScriptParser::DataType::VARIANT;
  1456. p_suite->datatype.type_source = GDScriptParser::DataType::UNDETECTED;
  1457. } else {
  1458. p_suite->set_datatype(p_statement->get_datatype());
  1459. p_suite->datatype.type_source = GDScriptParser::DataType::INFERRED;
  1460. }
  1461. break;
  1462. default:
  1463. break;
  1464. }
  1465. }
  1466. void GDScriptAnalyzer::resolve_suite(GDScriptParser::SuiteNode *p_suite) {
  1467. for (int i = 0; i < p_suite->statements.size(); i++) {
  1468. GDScriptParser::Node *stmt = p_suite->statements[i];
  1469. // Apply annotations.
  1470. for (GDScriptParser::AnnotationNode *&E : stmt->annotations) {
  1471. resolve_annotation(E);
  1472. E->apply(parser, stmt);
  1473. }
  1474. #ifdef DEBUG_ENABLED
  1475. HashSet<GDScriptWarning::Code> previously_ignored_warnings = parser->ignored_warnings;
  1476. for (GDScriptWarning::Code ignored_warning : stmt->ignored_warnings) {
  1477. parser->ignored_warnings.insert(ignored_warning);
  1478. }
  1479. #endif // DEBUG_ENABLED
  1480. resolve_node(stmt);
  1481. #ifdef DEBUG_ENABLED
  1482. parser->ignored_warnings = previously_ignored_warnings;
  1483. #endif // DEBUG_ENABLED
  1484. decide_suite_type(p_suite, stmt);
  1485. }
  1486. }
  1487. void GDScriptAnalyzer::resolve_assignable(GDScriptParser::AssignableNode *p_assignable, const char *p_kind) {
  1488. GDScriptParser::DataType type;
  1489. type.kind = GDScriptParser::DataType::VARIANT;
  1490. bool is_constant = p_assignable->type == GDScriptParser::Node::CONSTANT;
  1491. GDScriptParser::DataType specified_type;
  1492. bool has_specified_type = p_assignable->datatype_specifier != nullptr;
  1493. if (has_specified_type) {
  1494. specified_type = type_from_metatype(resolve_datatype(p_assignable->datatype_specifier));
  1495. type = specified_type;
  1496. }
  1497. if (p_assignable->initializer != nullptr) {
  1498. reduce_expression(p_assignable->initializer);
  1499. if (p_assignable->initializer->type == GDScriptParser::Node::ARRAY) {
  1500. GDScriptParser::ArrayNode *array = static_cast<GDScriptParser::ArrayNode *>(p_assignable->initializer);
  1501. if (has_specified_type && specified_type.has_container_element_type()) {
  1502. update_array_literal_element_type(array, specified_type.get_container_element_type());
  1503. }
  1504. }
  1505. if (is_constant && !p_assignable->initializer->is_constant) {
  1506. bool is_initializer_value_reduced = false;
  1507. Variant initializer_value = make_expression_reduced_value(p_assignable->initializer, is_initializer_value_reduced);
  1508. if (is_initializer_value_reduced) {
  1509. p_assignable->initializer->is_constant = true;
  1510. p_assignable->initializer->reduced_value = initializer_value;
  1511. } else {
  1512. push_error(vformat(R"(Assigned value for %s "%s" isn't a constant expression.)", p_kind, p_assignable->identifier->name), p_assignable->initializer);
  1513. }
  1514. }
  1515. if (has_specified_type && p_assignable->initializer->is_constant) {
  1516. update_const_expression_builtin_type(p_assignable->initializer, specified_type, "assign");
  1517. }
  1518. GDScriptParser::DataType initializer_type = p_assignable->initializer->get_datatype();
  1519. if (p_assignable->infer_datatype) {
  1520. if (!initializer_type.is_set() || initializer_type.has_no_type() || !initializer_type.is_hard_type()) {
  1521. push_error(vformat(R"(Cannot infer the type of "%s" %s because the value doesn't have a set type.)", p_assignable->identifier->name, p_kind), p_assignable->initializer);
  1522. } else if (initializer_type.kind == GDScriptParser::DataType::BUILTIN && initializer_type.builtin_type == Variant::NIL && !is_constant) {
  1523. push_error(vformat(R"(Cannot infer the type of "%s" %s because the value is "null".)", p_assignable->identifier->name, p_kind), p_assignable->initializer);
  1524. }
  1525. #ifdef DEBUG_ENABLED
  1526. if (initializer_type.is_hard_type() && initializer_type.is_variant()) {
  1527. parser->push_warning(p_assignable, GDScriptWarning::INFERENCE_ON_VARIANT, p_kind);
  1528. }
  1529. #endif
  1530. } else {
  1531. if (!initializer_type.is_set()) {
  1532. push_error(vformat(R"(Could not resolve type for %s "%s".)", p_kind, p_assignable->identifier->name), p_assignable->initializer);
  1533. }
  1534. }
  1535. if (!has_specified_type) {
  1536. type = initializer_type;
  1537. if (!type.is_set() || (type.is_hard_type() && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL && !is_constant)) {
  1538. type.kind = GDScriptParser::DataType::VARIANT;
  1539. }
  1540. if (p_assignable->infer_datatype || is_constant) {
  1541. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1542. } else {
  1543. type.type_source = GDScriptParser::DataType::INFERRED;
  1544. }
  1545. } else if (!specified_type.is_variant()) {
  1546. if (initializer_type.is_variant() || !initializer_type.is_hard_type()) {
  1547. mark_node_unsafe(p_assignable->initializer);
  1548. p_assignable->use_conversion_assign = true;
  1549. if (!initializer_type.is_variant() && !is_type_compatible(specified_type, initializer_type, true, p_assignable->initializer)) {
  1550. downgrade_node_type_source(p_assignable->initializer);
  1551. }
  1552. } else if (!is_type_compatible(specified_type, initializer_type, true, p_assignable->initializer)) {
  1553. if (!is_constant && is_type_compatible(initializer_type, specified_type)) {
  1554. mark_node_unsafe(p_assignable->initializer);
  1555. p_assignable->use_conversion_assign = true;
  1556. } else {
  1557. push_error(vformat(R"(Cannot assign a value of type %s to %s "%s" with specified type %s.)", initializer_type.to_string(), p_kind, p_assignable->identifier->name, specified_type.to_string()), p_assignable->initializer);
  1558. }
  1559. } else if (specified_type.has_container_element_type() && !initializer_type.has_container_element_type()) {
  1560. mark_node_unsafe(p_assignable->initializer);
  1561. #ifdef DEBUG_ENABLED
  1562. } else if (specified_type.builtin_type == Variant::INT && initializer_type.builtin_type == Variant::FLOAT) {
  1563. parser->push_warning(p_assignable->initializer, GDScriptWarning::NARROWING_CONVERSION);
  1564. #endif
  1565. }
  1566. }
  1567. }
  1568. type.is_constant = is_constant;
  1569. type.is_read_only = false;
  1570. p_assignable->set_datatype(type);
  1571. }
  1572. void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable, bool p_is_local) {
  1573. static constexpr const char *kind = "variable";
  1574. resolve_assignable(p_variable, kind);
  1575. #ifdef DEBUG_ENABLED
  1576. if (p_is_local) {
  1577. if (p_variable->usages == 0 && !String(p_variable->identifier->name).begins_with("_")) {
  1578. parser->push_warning(p_variable, GDScriptWarning::UNUSED_VARIABLE, p_variable->identifier->name);
  1579. } else if (p_variable->assignments == 0) {
  1580. parser->push_warning(p_variable, GDScriptWarning::UNASSIGNED_VARIABLE, p_variable->identifier->name);
  1581. }
  1582. is_shadowing(p_variable->identifier, kind);
  1583. }
  1584. #endif
  1585. }
  1586. void GDScriptAnalyzer::resolve_constant(GDScriptParser::ConstantNode *p_constant, bool p_is_local) {
  1587. static constexpr const char *kind = "constant";
  1588. resolve_assignable(p_constant, kind);
  1589. #ifdef DEBUG_ENABLED
  1590. if (p_is_local) {
  1591. if (p_constant->usages == 0) {
  1592. parser->push_warning(p_constant, GDScriptWarning::UNUSED_LOCAL_CONSTANT, p_constant->identifier->name);
  1593. }
  1594. is_shadowing(p_constant->identifier, kind);
  1595. }
  1596. #endif
  1597. }
  1598. void GDScriptAnalyzer::resolve_parameter(GDScriptParser::ParameterNode *p_parameter) {
  1599. static constexpr const char *kind = "parameter";
  1600. resolve_assignable(p_parameter, kind);
  1601. }
  1602. void GDScriptAnalyzer::resolve_if(GDScriptParser::IfNode *p_if) {
  1603. reduce_expression(p_if->condition);
  1604. resolve_suite(p_if->true_block);
  1605. p_if->set_datatype(p_if->true_block->get_datatype());
  1606. if (p_if->false_block != nullptr) {
  1607. resolve_suite(p_if->false_block);
  1608. decide_suite_type(p_if, p_if->false_block);
  1609. }
  1610. }
  1611. void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {
  1612. bool list_resolved = false;
  1613. // Optimize constant range() call to not allocate an array.
  1614. // Use int, Vector2i, Vector3i instead, which also can be used as range iterators.
  1615. if (p_for->list && p_for->list->type == GDScriptParser::Node::CALL) {
  1616. GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(p_for->list);
  1617. GDScriptParser::Node::Type callee_type = call->get_callee_type();
  1618. if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  1619. GDScriptParser::IdentifierNode *callee = static_cast<GDScriptParser::IdentifierNode *>(call->callee);
  1620. if (callee->name == "range") {
  1621. list_resolved = true;
  1622. if (call->arguments.size() < 1) {
  1623. push_error(R"*(Invalid call for "range()" function. Expected at least 1 argument, none given.)*", call->callee);
  1624. } else if (call->arguments.size() > 3) {
  1625. push_error(vformat(R"*(Invalid call for "range()" function. Expected at most 3 arguments, %d given.)*", call->arguments.size()), call->callee);
  1626. } else {
  1627. // Now we can optimize it.
  1628. bool can_reduce = true;
  1629. Vector<Variant> args;
  1630. args.resize(call->arguments.size());
  1631. for (int i = 0; i < call->arguments.size(); i++) {
  1632. GDScriptParser::ExpressionNode *argument = call->arguments[i];
  1633. reduce_expression(argument);
  1634. if (argument->is_constant) {
  1635. if (argument->reduced_value.get_type() != Variant::INT && argument->reduced_value.get_type() != Variant::FLOAT) {
  1636. can_reduce = false;
  1637. push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, Variant::get_type_name(argument->reduced_value.get_type())), argument);
  1638. }
  1639. if (can_reduce) {
  1640. args.write[i] = argument->reduced_value;
  1641. }
  1642. } else {
  1643. can_reduce = false;
  1644. GDScriptParser::DataType argument_type = argument->get_datatype();
  1645. if (argument_type.is_variant() || !argument_type.is_hard_type()) {
  1646. mark_node_unsafe(argument);
  1647. }
  1648. if (!argument_type.is_variant() && (argument_type.builtin_type != Variant::INT && argument_type.builtin_type != Variant::FLOAT)) {
  1649. if (!argument_type.is_hard_type()) {
  1650. downgrade_node_type_source(argument);
  1651. } else {
  1652. push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, argument_type.to_string()), argument);
  1653. }
  1654. }
  1655. }
  1656. }
  1657. Variant reduced;
  1658. if (can_reduce) {
  1659. switch (args.size()) {
  1660. case 1:
  1661. reduced = (int32_t)args[0];
  1662. break;
  1663. case 2:
  1664. reduced = Vector2i(args[0], args[1]);
  1665. break;
  1666. case 3:
  1667. reduced = Vector3i(args[0], args[1], args[2]);
  1668. break;
  1669. }
  1670. p_for->list->is_constant = true;
  1671. p_for->list->reduced_value = reduced;
  1672. }
  1673. }
  1674. if (p_for->list->is_constant) {
  1675. p_for->list->set_datatype(type_from_variant(p_for->list->reduced_value, p_for->list));
  1676. } else {
  1677. GDScriptParser::DataType list_type;
  1678. list_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1679. list_type.kind = GDScriptParser::DataType::BUILTIN;
  1680. list_type.builtin_type = Variant::ARRAY;
  1681. p_for->list->set_datatype(list_type);
  1682. }
  1683. }
  1684. }
  1685. }
  1686. GDScriptParser::DataType variable_type;
  1687. if (list_resolved) {
  1688. variable_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1689. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1690. variable_type.builtin_type = Variant::INT;
  1691. } else if (p_for->list) {
  1692. resolve_node(p_for->list, false);
  1693. GDScriptParser::DataType list_type = p_for->list->get_datatype();
  1694. if (!list_type.is_hard_type()) {
  1695. mark_node_unsafe(p_for->list);
  1696. }
  1697. if (list_type.is_variant()) {
  1698. variable_type.kind = GDScriptParser::DataType::VARIANT;
  1699. mark_node_unsafe(p_for->list);
  1700. } else if (list_type.has_container_element_type()) {
  1701. variable_type = list_type.get_container_element_type();
  1702. variable_type.type_source = list_type.type_source;
  1703. } else if (list_type.is_typed_container_type()) {
  1704. variable_type = list_type.get_typed_container_type();
  1705. variable_type.type_source = list_type.type_source;
  1706. } else if (list_type.builtin_type == Variant::INT || list_type.builtin_type == Variant::FLOAT || list_type.builtin_type == Variant::STRING) {
  1707. variable_type.type_source = list_type.type_source;
  1708. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1709. variable_type.builtin_type = list_type.builtin_type;
  1710. } else if (list_type.builtin_type == Variant::VECTOR2I || list_type.builtin_type == Variant::VECTOR3I) {
  1711. variable_type.type_source = list_type.type_source;
  1712. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1713. variable_type.builtin_type = Variant::INT;
  1714. } else if (list_type.builtin_type == Variant::VECTOR2 || list_type.builtin_type == Variant::VECTOR3) {
  1715. variable_type.type_source = list_type.type_source;
  1716. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1717. variable_type.builtin_type = Variant::FLOAT;
  1718. } else if (list_type.builtin_type == Variant::OBJECT) {
  1719. GDScriptParser::DataType return_type;
  1720. List<GDScriptParser::DataType> par_types;
  1721. int default_arg_count = 0;
  1722. bool is_static = false;
  1723. bool is_vararg = false;
  1724. if (get_function_signature(p_for->list, false, list_type, CoreStringNames::get_singleton()->_iter_get, return_type, par_types, default_arg_count, is_static, is_vararg)) {
  1725. variable_type = return_type;
  1726. variable_type.type_source = list_type.type_source;
  1727. } else if (!list_type.is_hard_type()) {
  1728. variable_type.kind = GDScriptParser::DataType::VARIANT;
  1729. } else {
  1730. push_error(vformat(R"(Unable to iterate on object of type "%s".)", list_type.to_string()), p_for->list);
  1731. }
  1732. } else if (list_type.builtin_type == Variant::ARRAY || list_type.builtin_type == Variant::DICTIONARY || !list_type.is_hard_type()) {
  1733. variable_type.kind = GDScriptParser::DataType::VARIANT;
  1734. } else {
  1735. push_error(vformat(R"(Unable to iterate on value of type "%s".)", list_type.to_string()), p_for->list);
  1736. }
  1737. }
  1738. if (p_for->variable) {
  1739. p_for->variable->set_datatype(variable_type);
  1740. }
  1741. resolve_suite(p_for->loop);
  1742. p_for->set_datatype(p_for->loop->get_datatype());
  1743. #ifdef DEBUG_ENABLED
  1744. if (p_for->variable) {
  1745. is_shadowing(p_for->variable, R"("for" iterator variable)");
  1746. }
  1747. #endif
  1748. }
  1749. void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) {
  1750. resolve_node(p_while->condition, false);
  1751. resolve_suite(p_while->loop);
  1752. p_while->set_datatype(p_while->loop->get_datatype());
  1753. }
  1754. void GDScriptAnalyzer::resolve_assert(GDScriptParser::AssertNode *p_assert) {
  1755. reduce_expression(p_assert->condition);
  1756. if (p_assert->message != nullptr) {
  1757. reduce_expression(p_assert->message);
  1758. if (!p_assert->message->get_datatype().has_no_type() && (p_assert->message->get_datatype().kind != GDScriptParser::DataType::BUILTIN || p_assert->message->get_datatype().builtin_type != Variant::STRING)) {
  1759. push_error(R"(Expected string for assert error message.)", p_assert->message);
  1760. }
  1761. }
  1762. p_assert->set_datatype(p_assert->condition->get_datatype());
  1763. #ifdef DEBUG_ENABLED
  1764. if (p_assert->condition->is_constant) {
  1765. if (p_assert->condition->reduced_value.booleanize()) {
  1766. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_TRUE);
  1767. } else {
  1768. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_FALSE);
  1769. }
  1770. }
  1771. #endif
  1772. }
  1773. void GDScriptAnalyzer::resolve_match(GDScriptParser::MatchNode *p_match) {
  1774. reduce_expression(p_match->test);
  1775. for (int i = 0; i < p_match->branches.size(); i++) {
  1776. resolve_match_branch(p_match->branches[i], p_match->test);
  1777. decide_suite_type(p_match, p_match->branches[i]);
  1778. }
  1779. }
  1780. void GDScriptAnalyzer::resolve_match_branch(GDScriptParser::MatchBranchNode *p_match_branch, GDScriptParser::ExpressionNode *p_match_test) {
  1781. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  1782. resolve_match_pattern(p_match_branch->patterns[i], p_match_test);
  1783. }
  1784. resolve_suite(p_match_branch->block);
  1785. decide_suite_type(p_match_branch, p_match_branch->block);
  1786. }
  1787. void GDScriptAnalyzer::resolve_match_pattern(GDScriptParser::PatternNode *p_match_pattern, GDScriptParser::ExpressionNode *p_match_test) {
  1788. if (p_match_pattern == nullptr) {
  1789. return;
  1790. }
  1791. GDScriptParser::DataType result;
  1792. switch (p_match_pattern->pattern_type) {
  1793. case GDScriptParser::PatternNode::PT_LITERAL:
  1794. if (p_match_pattern->literal) {
  1795. reduce_literal(p_match_pattern->literal);
  1796. result = p_match_pattern->literal->get_datatype();
  1797. }
  1798. break;
  1799. case GDScriptParser::PatternNode::PT_EXPRESSION:
  1800. if (p_match_pattern->expression) {
  1801. GDScriptParser::ExpressionNode *expr = p_match_pattern->expression;
  1802. reduce_expression(expr);
  1803. result = expr->get_datatype();
  1804. if (!expr->is_constant) {
  1805. while (expr && expr->type == GDScriptParser::Node::SUBSCRIPT) {
  1806. GDScriptParser::SubscriptNode *sub = static_cast<GDScriptParser::SubscriptNode *>(expr);
  1807. if (!sub->is_attribute) {
  1808. expr = nullptr;
  1809. } else {
  1810. expr = sub->base;
  1811. }
  1812. }
  1813. if (!expr || expr->type != GDScriptParser::Node::IDENTIFIER) {
  1814. push_error(R"(Expression in match pattern must be a constant expression, an identifier, or an attribute access ("A.B").)", expr);
  1815. }
  1816. }
  1817. }
  1818. break;
  1819. case GDScriptParser::PatternNode::PT_BIND:
  1820. if (p_match_test != nullptr) {
  1821. result = p_match_test->get_datatype();
  1822. } else {
  1823. result.kind = GDScriptParser::DataType::VARIANT;
  1824. }
  1825. p_match_pattern->bind->set_datatype(result);
  1826. #ifdef DEBUG_ENABLED
  1827. is_shadowing(p_match_pattern->bind, "pattern bind");
  1828. if (p_match_pattern->bind->usages == 0 && !String(p_match_pattern->bind->name).begins_with("_")) {
  1829. parser->push_warning(p_match_pattern->bind, GDScriptWarning::UNUSED_VARIABLE, p_match_pattern->bind->name);
  1830. }
  1831. #endif
  1832. break;
  1833. case GDScriptParser::PatternNode::PT_ARRAY:
  1834. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  1835. resolve_match_pattern(p_match_pattern->array[i], nullptr);
  1836. decide_suite_type(p_match_pattern, p_match_pattern->array[i]);
  1837. }
  1838. result = p_match_pattern->get_datatype();
  1839. break;
  1840. case GDScriptParser::PatternNode::PT_DICTIONARY:
  1841. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  1842. if (p_match_pattern->dictionary[i].key) {
  1843. reduce_expression(p_match_pattern->dictionary[i].key);
  1844. if (!p_match_pattern->dictionary[i].key->is_constant) {
  1845. push_error(R"(Expression in dictionary pattern key must be a constant.)", p_match_pattern->dictionary[i].key);
  1846. }
  1847. }
  1848. if (p_match_pattern->dictionary[i].value_pattern) {
  1849. resolve_match_pattern(p_match_pattern->dictionary[i].value_pattern, nullptr);
  1850. decide_suite_type(p_match_pattern, p_match_pattern->dictionary[i].value_pattern);
  1851. }
  1852. }
  1853. result = p_match_pattern->get_datatype();
  1854. break;
  1855. case GDScriptParser::PatternNode::PT_WILDCARD:
  1856. case GDScriptParser::PatternNode::PT_REST:
  1857. result.kind = GDScriptParser::DataType::VARIANT;
  1858. break;
  1859. }
  1860. p_match_pattern->set_datatype(result);
  1861. }
  1862. void GDScriptAnalyzer::resolve_return(GDScriptParser::ReturnNode *p_return) {
  1863. GDScriptParser::DataType result;
  1864. GDScriptParser::DataType expected_type;
  1865. bool has_expected_type = parser->current_function != nullptr;
  1866. if (has_expected_type) {
  1867. expected_type = parser->current_function->get_datatype();
  1868. }
  1869. if (p_return->return_value != nullptr) {
  1870. bool is_void_function = has_expected_type && expected_type.is_hard_type() && expected_type.kind == GDScriptParser::DataType::BUILTIN && expected_type.builtin_type == Variant::NIL;
  1871. bool is_call = p_return->return_value->type == GDScriptParser::Node::CALL;
  1872. if (is_void_function && is_call) {
  1873. // Pretend the call is a root expression to allow those that are "void".
  1874. reduce_call(static_cast<GDScriptParser::CallNode *>(p_return->return_value), false, true);
  1875. } else {
  1876. reduce_expression(p_return->return_value);
  1877. }
  1878. if (is_void_function) {
  1879. p_return->void_return = true;
  1880. const GDScriptParser::DataType &return_type = p_return->return_value->datatype;
  1881. if (is_call && !return_type.is_hard_type()) {
  1882. String function_name = parser->current_function->identifier ? parser->current_function->identifier->name.operator String() : String("<anonymous function>");
  1883. String called_function_name = static_cast<GDScriptParser::CallNode *>(p_return->return_value)->function_name.operator String();
  1884. #ifdef DEBUG_ENABLED
  1885. parser->push_warning(p_return, GDScriptWarning::UNSAFE_VOID_RETURN, function_name, called_function_name);
  1886. #endif
  1887. mark_node_unsafe(p_return);
  1888. } else if (!is_call) {
  1889. push_error("A void function cannot return a value.", p_return);
  1890. }
  1891. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1892. result.kind = GDScriptParser::DataType::BUILTIN;
  1893. result.builtin_type = Variant::NIL;
  1894. result.is_constant = true;
  1895. } else {
  1896. if (p_return->return_value->type == GDScriptParser::Node::ARRAY && has_expected_type && expected_type.has_container_element_type()) {
  1897. update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_return->return_value), expected_type.get_container_element_type());
  1898. }
  1899. if (has_expected_type && expected_type.is_hard_type() && p_return->return_value->is_constant) {
  1900. update_const_expression_builtin_type(p_return->return_value, expected_type, "return");
  1901. }
  1902. result = p_return->return_value->get_datatype();
  1903. }
  1904. } else {
  1905. // Return type is null by default.
  1906. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1907. result.kind = GDScriptParser::DataType::BUILTIN;
  1908. result.builtin_type = Variant::NIL;
  1909. result.is_constant = true;
  1910. }
  1911. if (has_expected_type && !expected_type.is_variant()) {
  1912. if (result.is_variant() || !result.is_hard_type()) {
  1913. mark_node_unsafe(p_return);
  1914. if (!is_type_compatible(expected_type, result, true, p_return)) {
  1915. downgrade_node_type_source(p_return);
  1916. }
  1917. } else if (!is_type_compatible(expected_type, result, true, p_return)) {
  1918. mark_node_unsafe(p_return);
  1919. if (!is_type_compatible(result, expected_type)) {
  1920. push_error(vformat(R"(Cannot return value of type "%s" because the function return type is "%s".)", result.to_string(), expected_type.to_string()), p_return);
  1921. }
  1922. #ifdef DEBUG_ENABLED
  1923. } else if (expected_type.builtin_type == Variant::INT && result.builtin_type == Variant::FLOAT) {
  1924. parser->push_warning(p_return, GDScriptWarning::NARROWING_CONVERSION);
  1925. #endif
  1926. }
  1927. }
  1928. p_return->set_datatype(result);
  1929. }
  1930. void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expression, bool p_is_root) {
  1931. // This one makes some magic happen.
  1932. if (p_expression == nullptr) {
  1933. return;
  1934. }
  1935. if (p_expression->reduced) {
  1936. // Don't do this more than once.
  1937. return;
  1938. }
  1939. p_expression->reduced = true;
  1940. switch (p_expression->type) {
  1941. case GDScriptParser::Node::ARRAY:
  1942. reduce_array(static_cast<GDScriptParser::ArrayNode *>(p_expression));
  1943. break;
  1944. case GDScriptParser::Node::ASSIGNMENT:
  1945. reduce_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
  1946. break;
  1947. case GDScriptParser::Node::AWAIT:
  1948. reduce_await(static_cast<GDScriptParser::AwaitNode *>(p_expression));
  1949. break;
  1950. case GDScriptParser::Node::BINARY_OPERATOR:
  1951. reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));
  1952. break;
  1953. case GDScriptParser::Node::CALL:
  1954. reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), false, p_is_root);
  1955. break;
  1956. case GDScriptParser::Node::CAST:
  1957. reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));
  1958. break;
  1959. case GDScriptParser::Node::DICTIONARY:
  1960. reduce_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_expression));
  1961. break;
  1962. case GDScriptParser::Node::GET_NODE:
  1963. reduce_get_node(static_cast<GDScriptParser::GetNodeNode *>(p_expression));
  1964. break;
  1965. case GDScriptParser::Node::IDENTIFIER:
  1966. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression));
  1967. break;
  1968. case GDScriptParser::Node::LAMBDA:
  1969. reduce_lambda(static_cast<GDScriptParser::LambdaNode *>(p_expression));
  1970. break;
  1971. case GDScriptParser::Node::LITERAL:
  1972. reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression));
  1973. break;
  1974. case GDScriptParser::Node::PRELOAD:
  1975. reduce_preload(static_cast<GDScriptParser::PreloadNode *>(p_expression));
  1976. break;
  1977. case GDScriptParser::Node::SELF:
  1978. reduce_self(static_cast<GDScriptParser::SelfNode *>(p_expression));
  1979. break;
  1980. case GDScriptParser::Node::SUBSCRIPT:
  1981. reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_expression));
  1982. break;
  1983. case GDScriptParser::Node::TERNARY_OPERATOR:
  1984. reduce_ternary_op(static_cast<GDScriptParser::TernaryOpNode *>(p_expression), p_is_root);
  1985. break;
  1986. case GDScriptParser::Node::TYPE_TEST:
  1987. reduce_type_test(static_cast<GDScriptParser::TypeTestNode *>(p_expression));
  1988. break;
  1989. case GDScriptParser::Node::UNARY_OPERATOR:
  1990. reduce_unary_op(static_cast<GDScriptParser::UnaryOpNode *>(p_expression));
  1991. break;
  1992. // Non-expressions. Here only to make sure new nodes aren't forgotten.
  1993. case GDScriptParser::Node::NONE:
  1994. case GDScriptParser::Node::ANNOTATION:
  1995. case GDScriptParser::Node::ASSERT:
  1996. case GDScriptParser::Node::BREAK:
  1997. case GDScriptParser::Node::BREAKPOINT:
  1998. case GDScriptParser::Node::CLASS:
  1999. case GDScriptParser::Node::CONSTANT:
  2000. case GDScriptParser::Node::CONTINUE:
  2001. case GDScriptParser::Node::ENUM:
  2002. case GDScriptParser::Node::FOR:
  2003. case GDScriptParser::Node::FUNCTION:
  2004. case GDScriptParser::Node::IF:
  2005. case GDScriptParser::Node::MATCH:
  2006. case GDScriptParser::Node::MATCH_BRANCH:
  2007. case GDScriptParser::Node::PARAMETER:
  2008. case GDScriptParser::Node::PASS:
  2009. case GDScriptParser::Node::PATTERN:
  2010. case GDScriptParser::Node::RETURN:
  2011. case GDScriptParser::Node::SIGNAL:
  2012. case GDScriptParser::Node::SUITE:
  2013. case GDScriptParser::Node::TYPE:
  2014. case GDScriptParser::Node::VARIABLE:
  2015. case GDScriptParser::Node::WHILE:
  2016. ERR_FAIL_MSG("Reaching unreachable case");
  2017. }
  2018. }
  2019. void GDScriptAnalyzer::reduce_array(GDScriptParser::ArrayNode *p_array) {
  2020. for (int i = 0; i < p_array->elements.size(); i++) {
  2021. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  2022. reduce_expression(element);
  2023. }
  2024. // It's array in any case.
  2025. GDScriptParser::DataType arr_type;
  2026. arr_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2027. arr_type.kind = GDScriptParser::DataType::BUILTIN;
  2028. arr_type.builtin_type = Variant::ARRAY;
  2029. arr_type.is_constant = true;
  2030. p_array->set_datatype(arr_type);
  2031. }
  2032. #ifdef DEBUG_ENABLED
  2033. static bool enum_has_value(const GDScriptParser::DataType p_type, int64_t p_value) {
  2034. for (const KeyValue<StringName, int64_t> &E : p_type.enum_values) {
  2035. if (E.value == p_value) {
  2036. return true;
  2037. }
  2038. }
  2039. return false;
  2040. }
  2041. #endif
  2042. void GDScriptAnalyzer::update_const_expression_builtin_type(GDScriptParser::ExpressionNode *p_expression, const GDScriptParser::DataType &p_type, const char *p_usage, bool p_is_cast) {
  2043. if (p_expression->get_datatype() == p_type) {
  2044. return;
  2045. }
  2046. if (p_type.kind != GDScriptParser::DataType::BUILTIN && p_type.kind != GDScriptParser::DataType::ENUM) {
  2047. return;
  2048. }
  2049. GDScriptParser::DataType expression_type = p_expression->get_datatype();
  2050. bool is_enum_cast = p_is_cast && p_type.kind == GDScriptParser::DataType::ENUM && p_type.is_meta_type == false && expression_type.builtin_type == Variant::INT;
  2051. if (!is_enum_cast && !is_type_compatible(p_type, expression_type, true, p_expression)) {
  2052. push_error(vformat(R"(Cannot %s a value of type "%s" as "%s".)", p_usage, expression_type.to_string(), p_type.to_string()), p_expression);
  2053. return;
  2054. }
  2055. GDScriptParser::DataType value_type = type_from_variant(p_expression->reduced_value, p_expression);
  2056. if (expression_type.is_variant() && !is_enum_cast && !is_type_compatible(p_type, value_type, true, p_expression)) {
  2057. push_error(vformat(R"(Cannot %s a value of type "%s" as "%s".)", p_usage, value_type.to_string(), p_type.to_string()), p_expression);
  2058. return;
  2059. }
  2060. #ifdef DEBUG_ENABLED
  2061. if (p_type.kind == GDScriptParser::DataType::ENUM && value_type.builtin_type == Variant::INT && !enum_has_value(p_type, p_expression->reduced_value)) {
  2062. parser->push_warning(p_expression, GDScriptWarning::INT_AS_ENUM_WITHOUT_MATCH, p_usage, p_expression->reduced_value.stringify(), p_type.to_string());
  2063. }
  2064. #endif
  2065. if (value_type.builtin_type == p_type.builtin_type) {
  2066. p_expression->set_datatype(p_type);
  2067. return;
  2068. }
  2069. Variant converted_to;
  2070. const Variant *converted_from = &p_expression->reduced_value;
  2071. Callable::CallError call_error;
  2072. Variant::construct(p_type.builtin_type, converted_to, &converted_from, 1, call_error);
  2073. if (call_error.error) {
  2074. push_error(vformat(R"(Failed to convert a value of type "%s" to "%s".)", value_type.to_string(), p_type.to_string()), p_expression);
  2075. return;
  2076. }
  2077. #ifdef DEBUG_ENABLED
  2078. if (p_type.builtin_type == Variant::INT && value_type.builtin_type == Variant::FLOAT) {
  2079. parser->push_warning(p_expression, GDScriptWarning::NARROWING_CONVERSION);
  2080. }
  2081. #endif
  2082. p_expression->reduced_value = converted_to;
  2083. p_expression->set_datatype(p_type);
  2084. }
  2085. // When an array literal is stored (or passed as function argument) to a typed context, we then assume the array is typed.
  2086. // This function determines which type is that (if any).
  2087. void GDScriptAnalyzer::update_array_literal_element_type(GDScriptParser::ArrayNode *p_array, const GDScriptParser::DataType &p_element_type) {
  2088. for (int i = 0; i < p_array->elements.size(); i++) {
  2089. GDScriptParser::ExpressionNode *element_node = p_array->elements[i];
  2090. if (element_node->is_constant) {
  2091. update_const_expression_builtin_type(element_node, p_element_type, "include");
  2092. }
  2093. const GDScriptParser::DataType &element_type = element_node->get_datatype();
  2094. if (element_type.has_no_type() || element_type.is_variant() || !element_type.is_hard_type()) {
  2095. mark_node_unsafe(element_node);
  2096. continue;
  2097. }
  2098. if (!is_type_compatible(p_element_type, element_type, true, p_array)) {
  2099. push_error(vformat(R"(Cannot have an element of type "%s" in an array of type "Array[%s]".)", element_type.to_string(), p_element_type.to_string()), element_node);
  2100. return;
  2101. }
  2102. }
  2103. GDScriptParser::DataType array_type = p_array->get_datatype();
  2104. array_type.set_container_element_type(p_element_type);
  2105. p_array->set_datatype(array_type);
  2106. }
  2107. void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assignment) {
  2108. reduce_expression(p_assignment->assignee);
  2109. reduce_expression(p_assignment->assigned_value);
  2110. if (p_assignment->assigned_value == nullptr || p_assignment->assignee == nullptr) {
  2111. return;
  2112. }
  2113. GDScriptParser::DataType assignee_type = p_assignment->assignee->get_datatype();
  2114. if (assignee_type.is_constant || (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT && static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee)->base->is_constant)) {
  2115. push_error("Cannot assign a new value to a constant.", p_assignment->assignee);
  2116. return;
  2117. } else if (assignee_type.is_read_only) {
  2118. push_error("Cannot assign a new value to a read-only property.", p_assignment->assignee);
  2119. return;
  2120. } else if (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {
  2121. GDScriptParser::SubscriptNode *sub = static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee);
  2122. while (sub) {
  2123. const GDScriptParser::DataType &base_type = sub->base->datatype;
  2124. if (base_type.is_hard_type() && base_type.is_read_only) {
  2125. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !Variant::is_type_shared(base_type.builtin_type)) {
  2126. push_error("Cannot assign a new value to a read-only property.", p_assignment->assignee);
  2127. return;
  2128. }
  2129. } else {
  2130. break;
  2131. }
  2132. if (sub->base->type == GDScriptParser::Node::SUBSCRIPT) {
  2133. sub = static_cast<GDScriptParser::SubscriptNode *>(sub->base);
  2134. } else {
  2135. sub = nullptr;
  2136. }
  2137. }
  2138. }
  2139. // Check if assigned value is an array literal, so we can make it a typed array too if appropriate.
  2140. if (p_assignment->assigned_value->type == GDScriptParser::Node::ARRAY && assignee_type.has_container_element_type()) {
  2141. update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_assignment->assigned_value), assignee_type.get_container_element_type());
  2142. }
  2143. if (p_assignment->operation == GDScriptParser::AssignmentNode::OP_NONE && assignee_type.is_hard_type() && p_assignment->assigned_value->is_constant) {
  2144. update_const_expression_builtin_type(p_assignment->assigned_value, assignee_type, "assign");
  2145. }
  2146. GDScriptParser::DataType assigned_value_type = p_assignment->assigned_value->get_datatype();
  2147. bool assignee_is_variant = assignee_type.is_variant();
  2148. bool assignee_is_hard = assignee_type.is_hard_type();
  2149. bool assigned_is_variant = assigned_value_type.is_variant();
  2150. bool assigned_is_hard = assigned_value_type.is_hard_type();
  2151. bool compatible = true;
  2152. bool downgrades_assignee = false;
  2153. bool downgrades_assigned = false;
  2154. GDScriptParser::DataType op_type = assigned_value_type;
  2155. if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE && !op_type.is_variant()) {
  2156. op_type = get_operation_type(p_assignment->variant_op, assignee_type, assigned_value_type, compatible, p_assignment->assigned_value);
  2157. if (assignee_is_variant) {
  2158. // variant assignee
  2159. mark_node_unsafe(p_assignment);
  2160. } else if (!compatible) {
  2161. // incompatible hard types and non-variant assignee
  2162. mark_node_unsafe(p_assignment);
  2163. if (assigned_is_variant) {
  2164. // incompatible hard non-variant assignee and hard variant assigned
  2165. p_assignment->use_conversion_assign = true;
  2166. } else {
  2167. // incompatible hard non-variant types
  2168. push_error(vformat(R"(Invalid operands "%s" and "%s" for assignment operator.)", assignee_type.to_string(), assigned_value_type.to_string()), p_assignment);
  2169. }
  2170. } else if (op_type.type_source == GDScriptParser::DataType::UNDETECTED && !assigned_is_variant) {
  2171. // incompatible non-variant types (at least one weak)
  2172. downgrades_assignee = !assignee_is_hard;
  2173. downgrades_assigned = !assigned_is_hard;
  2174. }
  2175. }
  2176. p_assignment->set_datatype(op_type);
  2177. if (assignee_is_variant) {
  2178. if (!assignee_is_hard) {
  2179. // weak variant assignee
  2180. mark_node_unsafe(p_assignment);
  2181. }
  2182. } else {
  2183. if (assignee_is_hard && !assigned_is_hard) {
  2184. // hard non-variant assignee and weak assigned
  2185. mark_node_unsafe(p_assignment);
  2186. p_assignment->use_conversion_assign = true;
  2187. downgrades_assigned = downgrades_assigned || (!assigned_is_variant && !is_type_compatible(assignee_type, op_type, true, p_assignment->assigned_value));
  2188. } else if (compatible) {
  2189. if (op_type.is_variant()) {
  2190. // non-variant assignee and variant result
  2191. mark_node_unsafe(p_assignment);
  2192. if (assignee_is_hard) {
  2193. // hard non-variant assignee and variant result
  2194. p_assignment->use_conversion_assign = true;
  2195. } else {
  2196. // weak non-variant assignee and variant result
  2197. downgrades_assignee = true;
  2198. }
  2199. } else if (!is_type_compatible(assignee_type, op_type, assignee_is_hard, p_assignment->assigned_value)) {
  2200. // non-variant assignee and incompatible result
  2201. mark_node_unsafe(p_assignment);
  2202. if (assignee_is_hard) {
  2203. if (is_type_compatible(op_type, assignee_type)) {
  2204. // hard non-variant assignee and maybe compatible result
  2205. p_assignment->use_conversion_assign = true;
  2206. } else {
  2207. // hard non-variant assignee and incompatible result
  2208. push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", assigned_value_type.to_string(), assignee_type.to_string()), p_assignment->assigned_value);
  2209. }
  2210. } else {
  2211. // weak non-variant assignee and incompatible result
  2212. downgrades_assignee = true;
  2213. }
  2214. } else if (assignee_type.has_container_element_type() && !op_type.has_container_element_type()) {
  2215. // typed array assignee and untyped array result
  2216. mark_node_unsafe(p_assignment);
  2217. }
  2218. }
  2219. }
  2220. if (downgrades_assignee) {
  2221. downgrade_node_type_source(p_assignment->assignee);
  2222. }
  2223. if (downgrades_assigned) {
  2224. downgrade_node_type_source(p_assignment->assigned_value);
  2225. }
  2226. #ifdef DEBUG_ENABLED
  2227. if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_value_type.builtin_type == Variant::FLOAT) {
  2228. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION);
  2229. }
  2230. #endif
  2231. }
  2232. void GDScriptAnalyzer::reduce_await(GDScriptParser::AwaitNode *p_await) {
  2233. if (p_await->to_await == nullptr) {
  2234. GDScriptParser::DataType await_type;
  2235. await_type.kind = GDScriptParser::DataType::VARIANT;
  2236. p_await->set_datatype(await_type);
  2237. return;
  2238. }
  2239. if (p_await->to_await->type == GDScriptParser::Node::CALL) {
  2240. reduce_call(static_cast<GDScriptParser::CallNode *>(p_await->to_await), true);
  2241. } else {
  2242. reduce_expression(p_await->to_await);
  2243. }
  2244. GDScriptParser::DataType await_type = p_await->to_await->get_datatype();
  2245. // We cannot infer the type of the result of waiting for a signal.
  2246. if (await_type.is_hard_type() && await_type.kind == GDScriptParser::DataType::BUILTIN && await_type.builtin_type == Variant::SIGNAL) {
  2247. await_type.kind = GDScriptParser::DataType::VARIANT;
  2248. await_type.type_source = GDScriptParser::DataType::UNDETECTED;
  2249. } else if (p_await->to_await->is_constant) {
  2250. p_await->is_constant = p_await->to_await->is_constant;
  2251. p_await->reduced_value = p_await->to_await->reduced_value;
  2252. }
  2253. await_type.is_coroutine = false;
  2254. p_await->set_datatype(await_type);
  2255. #ifdef DEBUG_ENABLED
  2256. GDScriptParser::DataType to_await_type = p_await->to_await->get_datatype();
  2257. if (!to_await_type.is_coroutine && !to_await_type.is_variant() && to_await_type.builtin_type != Variant::SIGNAL) {
  2258. parser->push_warning(p_await, GDScriptWarning::REDUNDANT_AWAIT);
  2259. }
  2260. #endif
  2261. }
  2262. void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op) {
  2263. reduce_expression(p_binary_op->left_operand);
  2264. reduce_expression(p_binary_op->right_operand);
  2265. GDScriptParser::DataType left_type;
  2266. if (p_binary_op->left_operand) {
  2267. left_type = p_binary_op->left_operand->get_datatype();
  2268. }
  2269. GDScriptParser::DataType right_type;
  2270. if (p_binary_op->right_operand) {
  2271. right_type = p_binary_op->right_operand->get_datatype();
  2272. }
  2273. if (!left_type.is_set() || !right_type.is_set()) {
  2274. return;
  2275. }
  2276. #ifdef DEBUG_ENABLED
  2277. if (p_binary_op->variant_op == Variant::OP_DIVIDE && left_type.builtin_type == Variant::INT && right_type.builtin_type == Variant::INT) {
  2278. parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);
  2279. }
  2280. #endif
  2281. if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {
  2282. p_binary_op->is_constant = true;
  2283. if (p_binary_op->variant_op < Variant::OP_MAX) {
  2284. bool valid = false;
  2285. Variant::evaluate(p_binary_op->variant_op, p_binary_op->left_operand->reduced_value, p_binary_op->right_operand->reduced_value, p_binary_op->reduced_value, valid);
  2286. if (!valid) {
  2287. if (p_binary_op->reduced_value.get_type() == Variant::STRING) {
  2288. push_error(vformat(R"(%s in operator %s.)", p_binary_op->reduced_value, Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);
  2289. } else {
  2290. push_error(vformat(R"(Invalid operands to operator %s, %s and %s.)",
  2291. Variant::get_operator_name(p_binary_op->variant_op),
  2292. Variant::get_type_name(p_binary_op->left_operand->reduced_value.get_type()),
  2293. Variant::get_type_name(p_binary_op->right_operand->reduced_value.get_type())),
  2294. p_binary_op);
  2295. }
  2296. }
  2297. } else {
  2298. ERR_PRINT("Parser bug: unknown binary operation.");
  2299. }
  2300. p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value, p_binary_op));
  2301. return;
  2302. }
  2303. GDScriptParser::DataType result;
  2304. if ((p_binary_op->variant_op == Variant::OP_EQUAL || p_binary_op->variant_op == Variant::OP_NOT_EQUAL) &&
  2305. ((left_type.kind == GDScriptParser::DataType::BUILTIN && left_type.builtin_type == Variant::NIL) || (right_type.kind == GDScriptParser::DataType::BUILTIN && right_type.builtin_type == Variant::NIL))) {
  2306. // "==" and "!=" operators always return a boolean when comparing to null.
  2307. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2308. result.kind = GDScriptParser::DataType::BUILTIN;
  2309. result.builtin_type = Variant::BOOL;
  2310. } else if (left_type.is_variant() || right_type.is_variant()) {
  2311. // Cannot infer type because one operand can be anything.
  2312. result.kind = GDScriptParser::DataType::VARIANT;
  2313. mark_node_unsafe(p_binary_op);
  2314. } else if (p_binary_op->variant_op < Variant::OP_MAX) {
  2315. bool valid = false;
  2316. result = get_operation_type(p_binary_op->variant_op, left_type, right_type, valid, p_binary_op);
  2317. if (!valid) {
  2318. push_error(vformat(R"(Invalid operands "%s" and "%s" for "%s" operator.)", left_type.to_string(), right_type.to_string(), Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);
  2319. } else if (!result.is_hard_type()) {
  2320. mark_node_unsafe(p_binary_op);
  2321. }
  2322. } else {
  2323. ERR_PRINT("Parser bug: unknown binary operation.");
  2324. }
  2325. p_binary_op->set_datatype(result);
  2326. }
  2327. #ifdef SUGGEST_GODOT4_RENAMES
  2328. const char *get_rename_from_map(const char *map[][2], String key) {
  2329. for (int index = 0; map[index][0]; index++) {
  2330. if (map[index][0] == key) {
  2331. return map[index][1];
  2332. }
  2333. }
  2334. return nullptr;
  2335. }
  2336. // Checks if an identifier/function name has been renamed in Godot 4, uses ProjectConverter3To4 for rename map.
  2337. // Returns the new name if found, nullptr otherwise.
  2338. const char *check_for_renamed_identifier(String identifier, GDScriptParser::Node::Type type) {
  2339. switch (type) {
  2340. case GDScriptParser::Node::IDENTIFIER: {
  2341. // Check properties
  2342. const char *result = get_rename_from_map(RenamesMap3To4::gdscript_properties_renames, identifier);
  2343. if (result) {
  2344. return result;
  2345. }
  2346. // Check enum values
  2347. result = get_rename_from_map(RenamesMap3To4::enum_renames, identifier);
  2348. if (result) {
  2349. return result;
  2350. }
  2351. // Check color constants
  2352. result = get_rename_from_map(RenamesMap3To4::color_renames, identifier);
  2353. if (result) {
  2354. return result;
  2355. }
  2356. // Check type names
  2357. result = get_rename_from_map(RenamesMap3To4::class_renames, identifier);
  2358. if (result) {
  2359. return result;
  2360. }
  2361. return get_rename_from_map(RenamesMap3To4::builtin_types_renames, identifier);
  2362. }
  2363. case GDScriptParser::Node::CALL: {
  2364. const char *result = get_rename_from_map(RenamesMap3To4::gdscript_function_renames, identifier);
  2365. if (result) {
  2366. return result;
  2367. }
  2368. // Built-in Types are mistaken for function calls when the built-in type is not found.
  2369. // Check built-in types if function rename not found
  2370. return get_rename_from_map(RenamesMap3To4::builtin_types_renames, identifier);
  2371. }
  2372. // Signal references don't get parsed through the GDScriptAnalyzer. No support for signal rename hints.
  2373. default:
  2374. // No rename found, return null
  2375. return nullptr;
  2376. }
  2377. }
  2378. #endif // SUGGEST_GODOT4_RENAMES
  2379. void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_await, bool p_is_root) {
  2380. bool all_is_constant = true;
  2381. HashMap<int, GDScriptParser::ArrayNode *> arrays; // For array literal to potentially type when passing.
  2382. for (int i = 0; i < p_call->arguments.size(); i++) {
  2383. reduce_expression(p_call->arguments[i]);
  2384. if (p_call->arguments[i]->type == GDScriptParser::Node::ARRAY) {
  2385. arrays[i] = static_cast<GDScriptParser::ArrayNode *>(p_call->arguments[i]);
  2386. }
  2387. all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;
  2388. }
  2389. GDScriptParser::Node::Type callee_type = p_call->get_callee_type();
  2390. GDScriptParser::DataType call_type;
  2391. if (!p_call->is_super && callee_type == GDScriptParser::Node::IDENTIFIER) {
  2392. // Call to name directly.
  2393. StringName function_name = p_call->function_name;
  2394. Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);
  2395. if (builtin_type < Variant::VARIANT_MAX) {
  2396. // Is a builtin constructor.
  2397. call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2398. call_type.kind = GDScriptParser::DataType::BUILTIN;
  2399. call_type.builtin_type = builtin_type;
  2400. if (builtin_type == Variant::OBJECT) {
  2401. call_type.kind = GDScriptParser::DataType::NATIVE;
  2402. call_type.native_type = function_name; // "Object".
  2403. }
  2404. bool safe_to_fold = true;
  2405. switch (builtin_type) {
  2406. // Those are stored by reference so not suited for compile-time construction.
  2407. // Because in this case they would be the same reference in all constructed values.
  2408. case Variant::OBJECT:
  2409. case Variant::DICTIONARY:
  2410. case Variant::ARRAY:
  2411. case Variant::PACKED_BYTE_ARRAY:
  2412. case Variant::PACKED_INT32_ARRAY:
  2413. case Variant::PACKED_INT64_ARRAY:
  2414. case Variant::PACKED_FLOAT32_ARRAY:
  2415. case Variant::PACKED_FLOAT64_ARRAY:
  2416. case Variant::PACKED_STRING_ARRAY:
  2417. case Variant::PACKED_VECTOR2_ARRAY:
  2418. case Variant::PACKED_VECTOR3_ARRAY:
  2419. case Variant::PACKED_COLOR_ARRAY:
  2420. safe_to_fold = false;
  2421. break;
  2422. default:
  2423. break;
  2424. }
  2425. if (all_is_constant && safe_to_fold) {
  2426. // Construct here.
  2427. Vector<const Variant *> args;
  2428. for (int i = 0; i < p_call->arguments.size(); i++) {
  2429. args.push_back(&(p_call->arguments[i]->reduced_value));
  2430. }
  2431. Callable::CallError err;
  2432. Variant value;
  2433. Variant::construct(builtin_type, value, (const Variant **)args.ptr(), args.size(), err);
  2434. switch (err.error) {
  2435. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  2436. push_error(vformat(R"(Invalid argument for %s constructor: argument %d should be "%s" but is "%s".)", Variant::get_type_name(builtin_type), err.argument + 1,
  2437. Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),
  2438. p_call->arguments[err.argument]);
  2439. break;
  2440. case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
  2441. String signature = Variant::get_type_name(builtin_type) + "(";
  2442. for (int i = 0; i < p_call->arguments.size(); i++) {
  2443. if (i > 0) {
  2444. signature += ", ";
  2445. }
  2446. signature += p_call->arguments[i]->get_datatype().to_string();
  2447. }
  2448. signature += ")";
  2449. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);
  2450. } break;
  2451. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2452. push_error(vformat(R"(Too many arguments for %s constructor. Received %d but expected %d.)", Variant::get_type_name(builtin_type), p_call->arguments.size(), err.expected), p_call);
  2453. break;
  2454. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2455. push_error(vformat(R"(Too few arguments for %s constructor. Received %d but expected %d.)", Variant::get_type_name(builtin_type), p_call->arguments.size(), err.expected), p_call);
  2456. break;
  2457. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2458. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2459. break; // Can't happen in a builtin constructor.
  2460. case Callable::CallError::CALL_OK:
  2461. p_call->is_constant = true;
  2462. p_call->reduced_value = value;
  2463. break;
  2464. }
  2465. } else {
  2466. // TODO: Check constructors without constants.
  2467. // If there's one argument, try to use copy constructor (those aren't explicitly defined).
  2468. if (p_call->arguments.size() == 1) {
  2469. GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();
  2470. if (arg_type.is_variant()) {
  2471. mark_node_unsafe(p_call->arguments[0]);
  2472. } else {
  2473. if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {
  2474. // Okay.
  2475. p_call->set_datatype(call_type);
  2476. return;
  2477. }
  2478. }
  2479. }
  2480. List<MethodInfo> constructors;
  2481. Variant::get_constructor_list(builtin_type, &constructors);
  2482. bool match = false;
  2483. for (const MethodInfo &info : constructors) {
  2484. if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  2485. continue;
  2486. }
  2487. if (p_call->arguments.size() > info.arguments.size()) {
  2488. continue;
  2489. }
  2490. bool types_match = true;
  2491. for (int i = 0; i < p_call->arguments.size(); i++) {
  2492. GDScriptParser::DataType par_type = type_from_property(info.arguments[i], true);
  2493. if (!is_type_compatible(par_type, p_call->arguments[i]->get_datatype(), true)) {
  2494. types_match = false;
  2495. break;
  2496. #ifdef DEBUG_ENABLED
  2497. } else {
  2498. if (par_type.builtin_type == Variant::INT && p_call->arguments[i]->get_datatype().builtin_type == Variant::FLOAT && builtin_type != Variant::INT) {
  2499. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  2500. }
  2501. #endif
  2502. }
  2503. }
  2504. if (types_match) {
  2505. for (int i = 0; i < p_call->arguments.size(); i++) {
  2506. if (p_call->arguments[i]->is_constant) {
  2507. update_const_expression_builtin_type(p_call->arguments[i], type_from_property(info.arguments[i], true), "pass");
  2508. }
  2509. }
  2510. match = true;
  2511. call_type = type_from_property(info.return_val);
  2512. break;
  2513. }
  2514. }
  2515. if (!match) {
  2516. String signature = Variant::get_type_name(builtin_type) + "(";
  2517. for (int i = 0; i < p_call->arguments.size(); i++) {
  2518. if (i > 0) {
  2519. signature += ", ";
  2520. }
  2521. signature += p_call->arguments[i]->get_datatype().to_string();
  2522. }
  2523. signature += ")";
  2524. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);
  2525. }
  2526. }
  2527. p_call->set_datatype(call_type);
  2528. return;
  2529. } else if (GDScriptUtilityFunctions::function_exists(function_name)) {
  2530. MethodInfo function_info = GDScriptUtilityFunctions::get_function_info(function_name);
  2531. if (!p_is_root && !p_is_await && function_info.return_val.type == Variant::NIL && ((function_info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) == 0)) {
  2532. push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", function_name), p_call);
  2533. }
  2534. if (all_is_constant && GDScriptUtilityFunctions::is_function_constant(function_name)) {
  2535. // Can call on compilation.
  2536. Vector<const Variant *> args;
  2537. for (int i = 0; i < p_call->arguments.size(); i++) {
  2538. args.push_back(&(p_call->arguments[i]->reduced_value));
  2539. }
  2540. Variant value;
  2541. Callable::CallError err;
  2542. GDScriptUtilityFunctions::get_function(function_name)(&value, (const Variant **)args.ptr(), args.size(), err);
  2543. switch (err.error) {
  2544. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  2545. PropertyInfo wrong_arg = function_info.arguments[err.argument];
  2546. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1,
  2547. type_from_property(wrong_arg, true).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()),
  2548. p_call->arguments[err.argument]);
  2549. } break;
  2550. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  2551. push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
  2552. break;
  2553. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2554. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  2555. break;
  2556. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2557. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  2558. break;
  2559. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2560. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2561. break; // Can't happen in a builtin constructor.
  2562. case Callable::CallError::CALL_OK:
  2563. p_call->is_constant = true;
  2564. p_call->reduced_value = value;
  2565. break;
  2566. }
  2567. } else {
  2568. validate_call_arg(function_info, p_call);
  2569. }
  2570. p_call->set_datatype(type_from_property(function_info.return_val));
  2571. return;
  2572. } else if (Variant::has_utility_function(function_name)) {
  2573. MethodInfo function_info = info_from_utility_func(function_name);
  2574. if (!p_is_root && !p_is_await && function_info.return_val.type == Variant::NIL && ((function_info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) == 0)) {
  2575. push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", function_name), p_call);
  2576. }
  2577. if (all_is_constant && Variant::get_utility_function_type(function_name) == Variant::UTILITY_FUNC_TYPE_MATH) {
  2578. // Can call on compilation.
  2579. Vector<const Variant *> args;
  2580. for (int i = 0; i < p_call->arguments.size(); i++) {
  2581. args.push_back(&(p_call->arguments[i]->reduced_value));
  2582. }
  2583. Variant value;
  2584. Callable::CallError err;
  2585. Variant::call_utility_function(function_name, &value, (const Variant **)args.ptr(), args.size(), err);
  2586. switch (err.error) {
  2587. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  2588. String expected_type_name;
  2589. if (err.argument < function_info.arguments.size()) {
  2590. expected_type_name = type_from_property(function_info.arguments[err.argument], true).to_string();
  2591. } else {
  2592. expected_type_name = Variant::get_type_name((Variant::Type)err.expected);
  2593. }
  2594. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1,
  2595. expected_type_name, p_call->arguments[err.argument]->get_datatype().to_string()),
  2596. p_call->arguments[err.argument]);
  2597. } break;
  2598. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  2599. push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
  2600. break;
  2601. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2602. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  2603. break;
  2604. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2605. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  2606. break;
  2607. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2608. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2609. break; // Can't happen in a builtin constructor.
  2610. case Callable::CallError::CALL_OK:
  2611. p_call->is_constant = true;
  2612. p_call->reduced_value = value;
  2613. break;
  2614. }
  2615. } else {
  2616. validate_call_arg(function_info, p_call);
  2617. }
  2618. p_call->set_datatype(type_from_property(function_info.return_val));
  2619. return;
  2620. }
  2621. }
  2622. GDScriptParser::DataType base_type;
  2623. call_type.kind = GDScriptParser::DataType::VARIANT;
  2624. bool is_self = false;
  2625. if (p_call->is_super) {
  2626. base_type = parser->current_class->base_type;
  2627. base_type.is_meta_type = false;
  2628. is_self = true;
  2629. if (p_call->callee == nullptr && !lambda_stack.is_empty()) {
  2630. push_error("Cannot use `super()` inside a lambda.", p_call);
  2631. }
  2632. } else if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  2633. base_type = parser->current_class->get_datatype();
  2634. base_type.is_meta_type = false;
  2635. is_self = true;
  2636. } else if (callee_type == GDScriptParser::Node::SUBSCRIPT) {
  2637. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);
  2638. if (subscript->base == nullptr) {
  2639. // Invalid syntax, error already set on parser.
  2640. p_call->set_datatype(call_type);
  2641. mark_node_unsafe(p_call);
  2642. return;
  2643. }
  2644. if (!subscript->is_attribute) {
  2645. // Invalid call. Error already sent in parser.
  2646. // TODO: Could check if Callable here.
  2647. p_call->set_datatype(call_type);
  2648. mark_node_unsafe(p_call);
  2649. return;
  2650. }
  2651. if (subscript->attribute == nullptr) {
  2652. // Invalid call. Error already sent in parser.
  2653. p_call->set_datatype(call_type);
  2654. mark_node_unsafe(p_call);
  2655. return;
  2656. }
  2657. GDScriptParser::IdentifierNode *base_id = nullptr;
  2658. if (subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  2659. base_id = static_cast<GDScriptParser::IdentifierNode *>(subscript->base);
  2660. }
  2661. if (base_id && GDScriptParser::get_builtin_type(base_id->name) < Variant::VARIANT_MAX) {
  2662. base_type = make_builtin_meta_type(GDScriptParser::get_builtin_type(base_id->name));
  2663. } else {
  2664. reduce_expression(subscript->base);
  2665. base_type = subscript->base->get_datatype();
  2666. is_self = subscript->base->type == GDScriptParser::Node::SELF;
  2667. }
  2668. } else {
  2669. // Invalid call. Error already sent in parser.
  2670. // TODO: Could check if Callable here too.
  2671. p_call->set_datatype(call_type);
  2672. mark_node_unsafe(p_call);
  2673. return;
  2674. }
  2675. bool is_static = false;
  2676. bool is_vararg = false;
  2677. int default_arg_count = 0;
  2678. GDScriptParser::DataType return_type;
  2679. List<GDScriptParser::DataType> par_types;
  2680. bool is_constructor = (base_type.is_meta_type || (p_call->callee && p_call->callee->type == GDScriptParser::Node::IDENTIFIER)) && p_call->function_name == SNAME("new");
  2681. if (get_function_signature(p_call, is_constructor, base_type, p_call->function_name, return_type, par_types, default_arg_count, is_static, is_vararg)) {
  2682. // If the function require typed arrays we must make literals be typed.
  2683. for (const KeyValue<int, GDScriptParser::ArrayNode *> &E : arrays) {
  2684. int index = E.key;
  2685. if (index < par_types.size() && par_types[index].has_container_element_type()) {
  2686. update_array_literal_element_type(E.value, par_types[index].get_container_element_type());
  2687. }
  2688. }
  2689. validate_call_arg(par_types, default_arg_count, is_vararg, p_call);
  2690. if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {
  2691. // Enum type is treated as a dictionary value for function calls.
  2692. base_type.is_meta_type = false;
  2693. }
  2694. if (is_self && parser->current_function != nullptr && parser->current_function->is_static && !is_static) {
  2695. // Get the parent function above any lambda.
  2696. GDScriptParser::FunctionNode *parent_function = parser->current_function;
  2697. while (parent_function->source_lambda) {
  2698. parent_function = parent_function->source_lambda->parent_function;
  2699. }
  2700. push_error(vformat(R"*(Cannot call non-static function "%s()" from static function "%s()".)*", p_call->function_name, parent_function->identifier->name), p_call);
  2701. } else if (!is_self && base_type.is_meta_type && !is_static) {
  2702. base_type.is_meta_type = false; // For `to_string()`.
  2703. push_error(vformat(R"*(Cannot call non-static function "%s()" on the class "%s" directly. Make an instance instead.)*", p_call->function_name, base_type.to_string()), p_call);
  2704. } else if (is_self && !is_static) {
  2705. mark_lambda_use_self();
  2706. }
  2707. if (!p_is_root && !p_is_await && return_type.is_hard_type() && return_type.kind == GDScriptParser::DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {
  2708. push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", p_call->function_name), p_call);
  2709. }
  2710. #ifdef DEBUG_ENABLED
  2711. if (p_is_root && return_type.kind != GDScriptParser::DataType::UNRESOLVED && return_type.builtin_type != Variant::NIL) {
  2712. parser->push_warning(p_call, GDScriptWarning::RETURN_VALUE_DISCARDED, p_call->function_name);
  2713. }
  2714. if (is_static && !base_type.is_meta_type && !(is_self && parser->current_function != nullptr && parser->current_function->is_static)) {
  2715. String caller_type = String(base_type.native_type);
  2716. if (caller_type.is_empty()) {
  2717. caller_type = base_type.to_string();
  2718. }
  2719. parser->push_warning(p_call, GDScriptWarning::STATIC_CALLED_ON_INSTANCE, p_call->function_name, caller_type);
  2720. }
  2721. #endif // DEBUG_ENABLED
  2722. call_type = return_type;
  2723. } else {
  2724. bool found = false;
  2725. // Enums do not have functions other than the built-in dictionary ones.
  2726. if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {
  2727. if (base_type.builtin_type == Variant::DICTIONARY) {
  2728. push_error(vformat(R"*(Enums only have Dictionary built-in methods. Function "%s()" does not exist for enum "%s".)*", p_call->function_name, base_type.enum_type), p_call->callee);
  2729. } else {
  2730. push_error(vformat(R"*(The native enum "%s" does not behave like Dictionary and does not have methods of its own.)*", base_type.enum_type), p_call->callee);
  2731. }
  2732. } else if (!p_call->is_super && callee_type != GDScriptParser::Node::NONE) { // Check if the name exists as something else.
  2733. GDScriptParser::IdentifierNode *callee_id;
  2734. if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  2735. callee_id = static_cast<GDScriptParser::IdentifierNode *>(p_call->callee);
  2736. } else {
  2737. // Can only be attribute.
  2738. callee_id = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee)->attribute;
  2739. }
  2740. if (callee_id) {
  2741. reduce_identifier_from_base(callee_id, &base_type);
  2742. GDScriptParser::DataType callee_datatype = callee_id->get_datatype();
  2743. if (callee_datatype.is_set() && !callee_datatype.is_variant()) {
  2744. found = true;
  2745. if (callee_datatype.builtin_type == Variant::CALLABLE) {
  2746. push_error(vformat(R"*(Name "%s" is a Callable. You can call it with "%s.call()" instead.)*", p_call->function_name, p_call->function_name), p_call->callee);
  2747. } else {
  2748. push_error(vformat(R"*(Name "%s" called as a function but is a "%s".)*", p_call->function_name, callee_datatype.to_string()), p_call->callee);
  2749. }
  2750. #ifdef DEBUG_ENABLED
  2751. } else if (!is_self && !(base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN)) {
  2752. parser->push_warning(p_call, GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->function_name, base_type.to_string());
  2753. mark_node_unsafe(p_call);
  2754. #endif
  2755. }
  2756. }
  2757. }
  2758. if (!found && (is_self || (base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN))) {
  2759. String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string();
  2760. #ifdef SUGGEST_GODOT4_RENAMES
  2761. String rename_hint = String();
  2762. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::Code::RENAMED_IN_GD4_HINT)).booleanize()) {
  2763. const char *renamed_function_name = check_for_renamed_identifier(p_call->function_name, p_call->type);
  2764. if (renamed_function_name) {
  2765. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", String(renamed_function_name) + "()");
  2766. }
  2767. }
  2768. push_error(vformat(R"*(Function "%s()" not found in base %s.%s)*", p_call->function_name, base_name, rename_hint), p_call->is_super ? p_call : p_call->callee);
  2769. #else
  2770. push_error(vformat(R"*(Function "%s()" not found in base %s.)*", p_call->function_name, base_name), p_call->is_super ? p_call : p_call->callee);
  2771. #endif // SUGGEST_GODOT4_RENAMES
  2772. } else if (!found && (!p_call->is_super && base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::NATIVE && base_type.is_meta_type)) {
  2773. push_error(vformat(R"*(Static function "%s()" not found in base "%s".)*", p_call->function_name, base_type.native_type), p_call);
  2774. }
  2775. }
  2776. if (call_type.is_coroutine && !p_is_await && !p_is_root) {
  2777. push_error(vformat(R"*(Function "%s()" is a coroutine, so it must be called with "await".)*", p_call->function_name), p_call);
  2778. }
  2779. p_call->set_datatype(call_type);
  2780. }
  2781. void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) {
  2782. reduce_expression(p_cast->operand);
  2783. GDScriptParser::DataType cast_type = type_from_metatype(resolve_datatype(p_cast->cast_type));
  2784. if (!cast_type.is_set()) {
  2785. mark_node_unsafe(p_cast);
  2786. return;
  2787. }
  2788. p_cast->set_datatype(cast_type);
  2789. if (p_cast->operand->is_constant) {
  2790. update_const_expression_builtin_type(p_cast->operand, cast_type, "cast", true);
  2791. if (cast_type.is_variant() || p_cast->operand->get_datatype() == cast_type) {
  2792. p_cast->is_constant = true;
  2793. p_cast->reduced_value = p_cast->operand->reduced_value;
  2794. }
  2795. }
  2796. if (p_cast->operand->type == GDScriptParser::Node::ARRAY && cast_type.has_container_element_type()) {
  2797. update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_cast->operand), cast_type.get_container_element_type());
  2798. }
  2799. if (!cast_type.is_variant()) {
  2800. GDScriptParser::DataType op_type = p_cast->operand->get_datatype();
  2801. if (op_type.is_variant() || !op_type.is_hard_type()) {
  2802. mark_node_unsafe(p_cast);
  2803. #ifdef DEBUG_ENABLED
  2804. if (op_type.is_variant() && !op_type.is_hard_type()) {
  2805. parser->push_warning(p_cast, GDScriptWarning::UNSAFE_CAST, cast_type.to_string());
  2806. }
  2807. #endif
  2808. } else {
  2809. bool valid = false;
  2810. if (op_type.builtin_type == Variant::INT && cast_type.kind == GDScriptParser::DataType::ENUM) {
  2811. mark_node_unsafe(p_cast);
  2812. valid = true;
  2813. } else if (op_type.kind == GDScriptParser::DataType::BUILTIN && cast_type.kind == GDScriptParser::DataType::BUILTIN) {
  2814. valid = Variant::can_convert(op_type.builtin_type, cast_type.builtin_type);
  2815. } else if (op_type.kind != GDScriptParser::DataType::BUILTIN && cast_type.kind != GDScriptParser::DataType::BUILTIN) {
  2816. valid = is_type_compatible(cast_type, op_type) || is_type_compatible(op_type, cast_type);
  2817. }
  2818. if (!valid) {
  2819. push_error(vformat(R"(Invalid cast. Cannot convert from "%s" to "%s".)", op_type.to_string(), cast_type.to_string()), p_cast->cast_type);
  2820. }
  2821. }
  2822. }
  2823. }
  2824. void GDScriptAnalyzer::reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
  2825. HashMap<Variant, GDScriptParser::ExpressionNode *, VariantHasher, StringLikeVariantComparator> elements;
  2826. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  2827. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  2828. if (p_dictionary->style == GDScriptParser::DictionaryNode::PYTHON_DICT) {
  2829. reduce_expression(element.key);
  2830. }
  2831. reduce_expression(element.value);
  2832. if (element.key->is_constant) {
  2833. if (elements.has(element.key->reduced_value)) {
  2834. push_error(vformat(R"(Key "%s" was already used in this dictionary (at line %d).)", element.key->reduced_value, elements[element.key->reduced_value]->start_line), element.key);
  2835. } else {
  2836. elements[element.key->reduced_value] = element.value;
  2837. }
  2838. }
  2839. }
  2840. // It's dictionary in any case.
  2841. GDScriptParser::DataType dict_type;
  2842. dict_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2843. dict_type.kind = GDScriptParser::DataType::BUILTIN;
  2844. dict_type.builtin_type = Variant::DICTIONARY;
  2845. dict_type.is_constant = true;
  2846. p_dictionary->set_datatype(dict_type);
  2847. }
  2848. void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) {
  2849. GDScriptParser::DataType result;
  2850. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2851. result.kind = GDScriptParser::DataType::NATIVE;
  2852. result.native_type = SNAME("Node");
  2853. result.builtin_type = Variant::OBJECT;
  2854. if (!ClassDB::is_parent_class(parser->current_class->base_type.native_type, result.native_type)) {
  2855. push_error(R"*(Cannot use shorthand "get_node()" notation ("$") on a class that isn't a node.)*", p_get_node);
  2856. }
  2857. mark_lambda_use_self();
  2858. p_get_node->set_datatype(result);
  2859. }
  2860. GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) {
  2861. GDScriptParser::DataType type;
  2862. String path = ScriptServer::get_global_class_path(p_class_name);
  2863. String ext = path.get_extension();
  2864. if (ext == GDScriptLanguage::get_singleton()->get_extension()) {
  2865. Ref<GDScriptParserRef> ref = get_parser_for(path);
  2866. if (ref.is_null()) {
  2867. push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source);
  2868. type.type_source = GDScriptParser::DataType::UNDETECTED;
  2869. type.kind = GDScriptParser::DataType::VARIANT;
  2870. return type;
  2871. }
  2872. Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  2873. if (err) {
  2874. push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source);
  2875. type.type_source = GDScriptParser::DataType::UNDETECTED;
  2876. type.kind = GDScriptParser::DataType::VARIANT;
  2877. return type;
  2878. }
  2879. return ref->get_parser()->head->get_datatype();
  2880. } else {
  2881. return make_script_meta_type(ResourceLoader::load(path, "Script"));
  2882. }
  2883. }
  2884. void GDScriptAnalyzer::reduce_identifier_from_base_set_class(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType p_identifier_datatype) {
  2885. ERR_FAIL_NULL(p_identifier);
  2886. p_identifier->set_datatype(p_identifier_datatype);
  2887. Error err = OK;
  2888. Ref<GDScript> scr = GDScriptCache::get_shallow_script(p_identifier_datatype.script_path, err);
  2889. if (err) {
  2890. push_error(vformat(R"(Error while getting cache for script "%s".)", p_identifier_datatype.script_path), p_identifier);
  2891. return;
  2892. }
  2893. p_identifier->reduced_value = scr->find_class(p_identifier_datatype.class_type->fqcn);
  2894. p_identifier->is_constant = true;
  2895. }
  2896. void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) {
  2897. if (!p_identifier->get_datatype().has_no_type()) {
  2898. return;
  2899. }
  2900. GDScriptParser::DataType base;
  2901. if (p_base == nullptr) {
  2902. base = type_from_metatype(parser->current_class->get_datatype());
  2903. } else {
  2904. base = *p_base;
  2905. }
  2906. const StringName &name = p_identifier->name;
  2907. if (base.kind == GDScriptParser::DataType::ENUM) {
  2908. if (base.is_meta_type) {
  2909. if (base.enum_values.has(name)) {
  2910. p_identifier->set_datatype(type_from_metatype(base));
  2911. p_identifier->is_constant = true;
  2912. p_identifier->reduced_value = base.enum_values[name];
  2913. return;
  2914. }
  2915. // Enum does not have this value, return.
  2916. return;
  2917. } else {
  2918. push_error(R"(Cannot get property from enum value.)", p_identifier);
  2919. return;
  2920. }
  2921. }
  2922. if (base.kind == GDScriptParser::DataType::BUILTIN) {
  2923. if (base.is_meta_type) {
  2924. bool valid = true;
  2925. Variant result = Variant::get_constant_value(base.builtin_type, name, &valid);
  2926. if (valid) {
  2927. p_identifier->is_constant = true;
  2928. p_identifier->reduced_value = result;
  2929. p_identifier->set_datatype(type_from_variant(result, p_identifier));
  2930. } else if (base.is_hard_type()) {
  2931. #ifdef SUGGEST_GODOT4_RENAMES
  2932. String rename_hint = String();
  2933. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::Code::RENAMED_IN_GD4_HINT)).booleanize()) {
  2934. const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);
  2935. if (renamed_identifier_name) {
  2936. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);
  2937. }
  2938. }
  2939. push_error(vformat(R"(Cannot find constant "%s" on base "%s".%s)", name, base.to_string(), rename_hint), p_identifier);
  2940. #else
  2941. push_error(vformat(R"(Cannot find constant "%s" on base "%s".)", name, base.to_string()), p_identifier);
  2942. #endif // SUGGEST_GODOT4_RENAMES
  2943. }
  2944. } else {
  2945. switch (base.builtin_type) {
  2946. case Variant::NIL: {
  2947. if (base.is_hard_type()) {
  2948. push_error(vformat(R"(Invalid get index "%s" on base Nil)", name), p_identifier);
  2949. }
  2950. return;
  2951. }
  2952. case Variant::DICTIONARY: {
  2953. GDScriptParser::DataType dummy;
  2954. dummy.kind = GDScriptParser::DataType::VARIANT;
  2955. p_identifier->set_datatype(dummy);
  2956. return;
  2957. }
  2958. default: {
  2959. Callable::CallError temp;
  2960. Variant dummy;
  2961. Variant::construct(base.builtin_type, dummy, nullptr, 0, temp);
  2962. List<PropertyInfo> properties;
  2963. dummy.get_property_list(&properties);
  2964. for (const PropertyInfo &prop : properties) {
  2965. if (prop.name == name) {
  2966. p_identifier->set_datatype(type_from_property(prop));
  2967. return;
  2968. }
  2969. }
  2970. if (base.is_hard_type()) {
  2971. #ifdef SUGGEST_GODOT4_RENAMES
  2972. String rename_hint = String();
  2973. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::Code::RENAMED_IN_GD4_HINT)).booleanize()) {
  2974. const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);
  2975. if (renamed_identifier_name) {
  2976. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);
  2977. }
  2978. }
  2979. push_error(vformat(R"(Cannot find property "%s" on base "%s".%s)", name, base.to_string(), rename_hint), p_identifier);
  2980. #else
  2981. push_error(vformat(R"(Cannot find property "%s" on base "%s".)", name, base.to_string()), p_identifier);
  2982. #endif // SUGGEST_GODOT4_RENAMES
  2983. }
  2984. }
  2985. }
  2986. }
  2987. return;
  2988. }
  2989. GDScriptParser::ClassNode *base_class = base.class_type;
  2990. List<GDScriptParser::ClassNode *> script_classes;
  2991. bool is_base = true;
  2992. if (base_class != nullptr) {
  2993. get_class_node_current_scope_classes(base_class, &script_classes);
  2994. }
  2995. for (GDScriptParser::ClassNode *script_class : script_classes) {
  2996. if (p_base == nullptr && script_class->identifier && script_class->identifier->name == name) {
  2997. reduce_identifier_from_base_set_class(p_identifier, script_class->get_datatype());
  2998. return;
  2999. }
  3000. if (script_class->has_member(name)) {
  3001. resolve_class_member(script_class, name, p_identifier);
  3002. GDScriptParser::ClassNode::Member member = script_class->get_member(name);
  3003. switch (member.type) {
  3004. case GDScriptParser::ClassNode::Member::CONSTANT: {
  3005. p_identifier->set_datatype(member.get_datatype());
  3006. p_identifier->is_constant = true;
  3007. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  3008. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3009. p_identifier->constant_source = member.constant;
  3010. return;
  3011. }
  3012. case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
  3013. p_identifier->set_datatype(member.get_datatype());
  3014. p_identifier->is_constant = true;
  3015. p_identifier->reduced_value = member.enum_value.value;
  3016. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3017. return;
  3018. }
  3019. case GDScriptParser::ClassNode::Member::ENUM: {
  3020. p_identifier->set_datatype(member.get_datatype());
  3021. p_identifier->is_constant = true;
  3022. p_identifier->reduced_value = member.m_enum->dictionary;
  3023. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3024. return;
  3025. }
  3026. case GDScriptParser::ClassNode::Member::VARIABLE: {
  3027. if (is_base && !base.is_meta_type) {
  3028. p_identifier->set_datatype(member.get_datatype());
  3029. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;
  3030. p_identifier->variable_source = member.variable;
  3031. member.variable->usages += 1;
  3032. return;
  3033. }
  3034. } break;
  3035. case GDScriptParser::ClassNode::Member::SIGNAL: {
  3036. if (is_base && !base.is_meta_type) {
  3037. p_identifier->set_datatype(member.get_datatype());
  3038. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_SIGNAL;
  3039. return;
  3040. }
  3041. } break;
  3042. case GDScriptParser::ClassNode::Member::FUNCTION: {
  3043. if (is_base && !base.is_meta_type) {
  3044. p_identifier->set_datatype(make_callable_type(member.function->info));
  3045. return;
  3046. }
  3047. } break;
  3048. case GDScriptParser::ClassNode::Member::CLASS: {
  3049. reduce_identifier_from_base_set_class(p_identifier, member.get_datatype());
  3050. return;
  3051. }
  3052. default: {
  3053. // Do nothing
  3054. }
  3055. }
  3056. }
  3057. if (is_base) {
  3058. is_base = script_class->base_type.class_type != nullptr;
  3059. if (!is_base && p_base != nullptr) {
  3060. break;
  3061. }
  3062. }
  3063. }
  3064. // Check native members. No need for native class recursion because Node exposes all Object's properties.
  3065. const StringName &native = base.native_type;
  3066. if (class_exists(native)) {
  3067. MethodInfo method_info;
  3068. if (ClassDB::has_property(native, name)) {
  3069. StringName getter_name = ClassDB::get_property_getter(native, name);
  3070. MethodBind *getter = ClassDB::get_method(native, getter_name);
  3071. if (getter != nullptr) {
  3072. bool has_setter = ClassDB::get_property_setter(native, name) != StringName();
  3073. p_identifier->set_datatype(type_from_property(getter->get_return_info(), false, !has_setter));
  3074. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3075. }
  3076. return;
  3077. }
  3078. if (ClassDB::get_method_info(native, name, &method_info)) {
  3079. // Method is callable.
  3080. p_identifier->set_datatype(make_callable_type(method_info));
  3081. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3082. return;
  3083. }
  3084. if (ClassDB::get_signal(native, name, &method_info)) {
  3085. // Signal is a type too.
  3086. p_identifier->set_datatype(make_signal_type(method_info));
  3087. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3088. return;
  3089. }
  3090. if (ClassDB::has_enum(native, name)) {
  3091. p_identifier->set_datatype(make_native_enum_type(name, native));
  3092. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3093. return;
  3094. }
  3095. bool valid = false;
  3096. int64_t int_constant = ClassDB::get_integer_constant(native, name, &valid);
  3097. if (valid) {
  3098. p_identifier->is_constant = true;
  3099. p_identifier->reduced_value = int_constant;
  3100. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3101. // Check whether this constant, which exists, belongs to an enum
  3102. StringName enum_name = ClassDB::get_integer_constant_enum(native, name);
  3103. if (enum_name != StringName()) {
  3104. p_identifier->set_datatype(make_native_enum_type(enum_name, native, false));
  3105. } else {
  3106. p_identifier->set_datatype(type_from_variant(int_constant, p_identifier));
  3107. }
  3108. }
  3109. }
  3110. }
  3111. void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin) {
  3112. // TODO: This is an opportunity to further infer types.
  3113. // Check if we are inside an enum. This allows enum values to access other elements of the same enum.
  3114. if (current_enum) {
  3115. for (int i = 0; i < current_enum->values.size(); i++) {
  3116. const GDScriptParser::EnumNode::Value &element = current_enum->values[i];
  3117. if (element.identifier->name == p_identifier->name) {
  3118. StringName enum_name = current_enum->identifier ? current_enum->identifier->name : UNNAMED_ENUM;
  3119. GDScriptParser::DataType type = make_enum_type(enum_name, parser->current_class->fqcn, false);
  3120. if (element.parent_enum->identifier) {
  3121. type.enum_type = element.parent_enum->identifier->name;
  3122. }
  3123. p_identifier->set_datatype(type);
  3124. if (element.resolved) {
  3125. p_identifier->is_constant = true;
  3126. p_identifier->reduced_value = element.value;
  3127. } else {
  3128. push_error(R"(Cannot use another enum element before it was declared.)", p_identifier);
  3129. }
  3130. return; // Found anyway.
  3131. }
  3132. }
  3133. }
  3134. bool found_source = false;
  3135. // Check if identifier is local.
  3136. // If that's the case, the declaration already was solved before.
  3137. switch (p_identifier->source) {
  3138. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:
  3139. p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());
  3140. found_source = true;
  3141. break;
  3142. case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:
  3143. case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:
  3144. p_identifier->set_datatype(p_identifier->constant_source->get_datatype());
  3145. p_identifier->is_constant = true;
  3146. // TODO: Constant should have a value on the node itself.
  3147. p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;
  3148. found_source = true;
  3149. break;
  3150. case GDScriptParser::IdentifierNode::MEMBER_SIGNAL:
  3151. case GDScriptParser::IdentifierNode::INHERITED_VARIABLE:
  3152. mark_lambda_use_self();
  3153. break;
  3154. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
  3155. mark_lambda_use_self();
  3156. p_identifier->variable_source->usages++;
  3157. [[fallthrough]];
  3158. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
  3159. p_identifier->set_datatype(p_identifier->variable_source->get_datatype());
  3160. found_source = true;
  3161. break;
  3162. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:
  3163. p_identifier->set_datatype(p_identifier->bind_source->get_datatype());
  3164. found_source = true;
  3165. break;
  3166. case GDScriptParser::IdentifierNode::LOCAL_BIND: {
  3167. GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();
  3168. result.is_constant = true;
  3169. p_identifier->set_datatype(result);
  3170. found_source = true;
  3171. } break;
  3172. case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:
  3173. break;
  3174. }
  3175. // Not a local, so check members.
  3176. if (!found_source) {
  3177. reduce_identifier_from_base(p_identifier);
  3178. if (p_identifier->source != GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->get_datatype().is_set()) {
  3179. // Found.
  3180. found_source = true;
  3181. }
  3182. }
  3183. if (found_source) {
  3184. bool source_is_variable = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_VARIABLE || p_identifier->source == GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3185. bool source_is_signal = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_SIGNAL;
  3186. if ((source_is_variable || source_is_signal) && parser->current_function && parser->current_function->is_static) {
  3187. // Get the parent function above any lambda.
  3188. GDScriptParser::FunctionNode *parent_function = parser->current_function;
  3189. while (parent_function->source_lambda) {
  3190. parent_function = parent_function->source_lambda->parent_function;
  3191. }
  3192. push_error(vformat(R"*(Cannot access %s "%s" from the static function "%s()".)*", source_is_signal ? "signal" : "instance variable", p_identifier->name, parent_function->identifier->name), p_identifier);
  3193. }
  3194. if (!lambda_stack.is_empty()) {
  3195. // If the identifier is a member variable (including the native class properties) or a signal, we consider the lambda to be using `self`, so we keep a reference to the current instance.
  3196. if (source_is_variable || source_is_signal) {
  3197. mark_lambda_use_self();
  3198. return; // No need to capture.
  3199. }
  3200. // If the identifier is local, check if it's any kind of capture by comparing their source function.
  3201. // Only capture locals and enum values. Constants are still accessible from the lambda using the script reference. If not, this method is done.
  3202. if (p_identifier->source == GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_CONSTANT) {
  3203. return;
  3204. }
  3205. GDScriptParser::FunctionNode *function_test = lambda_stack.back()->get()->function;
  3206. // Make sure we aren't capturing variable in the same lambda.
  3207. // This also add captures for nested lambdas.
  3208. while (function_test != nullptr && function_test != p_identifier->source_function && function_test->source_lambda != nullptr && !function_test->source_lambda->captures_indices.has(p_identifier->name)) {
  3209. function_test->source_lambda->captures_indices[p_identifier->name] = function_test->source_lambda->captures.size();
  3210. function_test->source_lambda->captures.push_back(p_identifier);
  3211. function_test = function_test->source_lambda->parent_function;
  3212. }
  3213. }
  3214. return;
  3215. }
  3216. StringName name = p_identifier->name;
  3217. p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;
  3218. // Check globals. We make an exception for Variant::OBJECT because it's the base class for
  3219. // non-builtin types so we allow doing e.g. Object.new()
  3220. Variant::Type builtin_type = GDScriptParser::get_builtin_type(name);
  3221. if (builtin_type != Variant::OBJECT && builtin_type < Variant::VARIANT_MAX) {
  3222. if (can_be_builtin) {
  3223. p_identifier->set_datatype(make_builtin_meta_type(builtin_type));
  3224. return;
  3225. } else {
  3226. push_error(R"(Builtin type cannot be used as a name on its own.)", p_identifier);
  3227. }
  3228. }
  3229. if (class_exists(name)) {
  3230. p_identifier->set_datatype(make_native_meta_type(name));
  3231. return;
  3232. }
  3233. if (ScriptServer::is_global_class(name)) {
  3234. p_identifier->set_datatype(make_global_class_meta_type(name, p_identifier));
  3235. return;
  3236. }
  3237. // Try singletons.
  3238. // Do this before globals because this might be a singleton loading another one before it's compiled.
  3239. if (ProjectSettings::get_singleton()->has_autoload(name)) {
  3240. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(name);
  3241. if (autoload.is_singleton) {
  3242. // Singleton exists, so it's at least a Node.
  3243. GDScriptParser::DataType result;
  3244. result.kind = GDScriptParser::DataType::NATIVE;
  3245. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3246. if (ResourceLoader::get_resource_type(autoload.path) == "GDScript") {
  3247. Ref<GDScriptParserRef> singl_parser = get_parser_for(autoload.path);
  3248. if (singl_parser.is_valid()) {
  3249. Error err = singl_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3250. if (err == OK) {
  3251. result = type_from_metatype(singl_parser->get_parser()->head->get_datatype());
  3252. }
  3253. }
  3254. } else if (ResourceLoader::get_resource_type(autoload.path) == "PackedScene") {
  3255. if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {
  3256. Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);
  3257. Node *node = Object::cast_to<Node>(constant);
  3258. if (node != nullptr) {
  3259. Ref<GDScript> scr = node->get_script();
  3260. if (scr.is_valid()) {
  3261. Ref<GDScriptParserRef> singl_parser = get_parser_for(scr->get_script_path());
  3262. if (singl_parser.is_valid()) {
  3263. Error err = singl_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3264. if (err == OK) {
  3265. result = type_from_metatype(singl_parser->get_parser()->head->get_datatype());
  3266. }
  3267. }
  3268. }
  3269. }
  3270. }
  3271. }
  3272. result.is_constant = true;
  3273. p_identifier->set_datatype(result);
  3274. return;
  3275. }
  3276. }
  3277. if (CoreConstants::is_global_constant(name)) {
  3278. int index = CoreConstants::get_global_constant_index(name);
  3279. StringName enum_name = CoreConstants::get_global_constant_enum(index);
  3280. int64_t value = CoreConstants::get_global_constant_value(index);
  3281. if (enum_name != StringName()) {
  3282. p_identifier->set_datatype(make_global_enum_type(enum_name, StringName(), false));
  3283. } else {
  3284. p_identifier->set_datatype(type_from_variant(value, p_identifier));
  3285. }
  3286. p_identifier->is_constant = true;
  3287. p_identifier->reduced_value = value;
  3288. return;
  3289. }
  3290. if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {
  3291. Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);
  3292. p_identifier->set_datatype(type_from_variant(constant, p_identifier));
  3293. p_identifier->is_constant = true;
  3294. p_identifier->reduced_value = constant;
  3295. return;
  3296. }
  3297. if (CoreConstants::is_global_enum(name)) {
  3298. p_identifier->set_datatype(make_global_enum_type(name, StringName(), true));
  3299. if (!can_be_builtin) {
  3300. push_error(vformat(R"(Global enum "%s" cannot be used on its own.)", name), p_identifier);
  3301. }
  3302. return;
  3303. }
  3304. // Allow "Variant" here since it might be used for nested enums.
  3305. if (can_be_builtin && name == SNAME("Variant")) {
  3306. GDScriptParser::DataType variant;
  3307. variant.kind = GDScriptParser::DataType::VARIANT;
  3308. variant.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3309. variant.is_meta_type = true;
  3310. variant.is_pseudo_type = true;
  3311. p_identifier->set_datatype(variant);
  3312. return;
  3313. }
  3314. // Not found.
  3315. // Check if it's a builtin function.
  3316. if (GDScriptUtilityFunctions::function_exists(name)) {
  3317. push_error(vformat(R"(Built-in function "%s" cannot be used as an identifier.)", name), p_identifier);
  3318. } else {
  3319. #ifdef SUGGEST_GODOT4_RENAMES
  3320. String rename_hint = String();
  3321. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::Code::RENAMED_IN_GD4_HINT)).booleanize()) {
  3322. const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);
  3323. if (renamed_identifier_name) {
  3324. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);
  3325. }
  3326. }
  3327. push_error(vformat(R"(Identifier "%s" not declared in the current scope.%s)", name, rename_hint), p_identifier);
  3328. #else
  3329. push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);
  3330. #endif // SUGGEST_GODOT4_RENAMES
  3331. }
  3332. GDScriptParser::DataType dummy;
  3333. dummy.kind = GDScriptParser::DataType::VARIANT;
  3334. p_identifier->set_datatype(dummy); // Just so type is set to something.
  3335. }
  3336. void GDScriptAnalyzer::reduce_lambda(GDScriptParser::LambdaNode *p_lambda) {
  3337. // Lambda is always a Callable.
  3338. GDScriptParser::DataType lambda_type;
  3339. lambda_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  3340. lambda_type.kind = GDScriptParser::DataType::BUILTIN;
  3341. lambda_type.builtin_type = Variant::CALLABLE;
  3342. p_lambda->set_datatype(lambda_type);
  3343. if (p_lambda->function == nullptr) {
  3344. return;
  3345. }
  3346. lambda_stack.push_back(p_lambda);
  3347. resolve_function_signature(p_lambda->function, p_lambda, true);
  3348. resolve_function_body(p_lambda->function, true);
  3349. lambda_stack.pop_back();
  3350. int captures_amount = p_lambda->captures.size();
  3351. if (captures_amount > 0) {
  3352. // Create space for lambda parameters.
  3353. // At the beginning to not mess with optional parameters.
  3354. int param_count = p_lambda->function->parameters.size();
  3355. p_lambda->function->parameters.resize(param_count + captures_amount);
  3356. for (int i = param_count - 1; i >= 0; i--) {
  3357. p_lambda->function->parameters.write[i + captures_amount] = p_lambda->function->parameters[i];
  3358. p_lambda->function->parameters_indices[p_lambda->function->parameters[i]->identifier->name] = i + captures_amount;
  3359. }
  3360. // Add captures as extra parameters at the beginning.
  3361. for (int i = 0; i < p_lambda->captures.size(); i++) {
  3362. GDScriptParser::IdentifierNode *capture = p_lambda->captures[i];
  3363. GDScriptParser::ParameterNode *capture_param = parser->alloc_node<GDScriptParser::ParameterNode>();
  3364. capture_param->identifier = capture;
  3365. capture_param->usages = capture->usages;
  3366. capture_param->set_datatype(capture->get_datatype());
  3367. p_lambda->function->parameters.write[i] = capture_param;
  3368. p_lambda->function->parameters_indices[capture->name] = i;
  3369. }
  3370. }
  3371. }
  3372. void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {
  3373. p_literal->reduced_value = p_literal->value;
  3374. p_literal->is_constant = true;
  3375. p_literal->set_datatype(type_from_variant(p_literal->reduced_value, p_literal));
  3376. }
  3377. void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
  3378. if (!p_preload->path) {
  3379. return;
  3380. }
  3381. reduce_expression(p_preload->path);
  3382. if (!p_preload->path->is_constant) {
  3383. push_error("Preloaded path must be a constant string.", p_preload->path);
  3384. return;
  3385. }
  3386. if (p_preload->path->reduced_value.get_type() != Variant::STRING) {
  3387. push_error("Preloaded path must be a constant string.", p_preload->path);
  3388. } else {
  3389. p_preload->resolved_path = p_preload->path->reduced_value;
  3390. // TODO: Save this as script dependency.
  3391. if (p_preload->resolved_path.is_relative_path()) {
  3392. p_preload->resolved_path = parser->script_path.get_base_dir().path_join(p_preload->resolved_path);
  3393. }
  3394. p_preload->resolved_path = p_preload->resolved_path.simplify_path();
  3395. if (!ResourceLoader::exists(p_preload->resolved_path)) {
  3396. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  3397. if (file_check->file_exists(p_preload->resolved_path)) {
  3398. push_error(vformat(R"(Preload file "%s" has no resource loaders (unrecognized file extension).)", p_preload->resolved_path), p_preload->path);
  3399. } else {
  3400. push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path);
  3401. }
  3402. } else {
  3403. // TODO: Don't load if validating: use completion cache.
  3404. // Must load GDScript and PackedScenes separately to permit cyclic references
  3405. // as ResourceLoader::load() detect and reject those.
  3406. if (ResourceLoader::get_resource_type(p_preload->resolved_path) == "GDScript") {
  3407. Error err = OK;
  3408. Ref<GDScript> res = GDScriptCache::get_shallow_script(p_preload->resolved_path, err, parser->script_path);
  3409. p_preload->resource = res;
  3410. if (err != OK) {
  3411. push_error(vformat(R"(Could not preload resource script "%s".)", p_preload->resolved_path), p_preload->path);
  3412. }
  3413. } else if (ResourceLoader::get_resource_type(p_preload->resolved_path) == "PackedScene") {
  3414. Error err = OK;
  3415. Ref<PackedScene> res = GDScriptCache::get_packed_scene(p_preload->resolved_path, err, parser->script_path);
  3416. p_preload->resource = res;
  3417. if (err != OK) {
  3418. push_error(vformat(R"(Could not preload resource scene "%s".)", p_preload->resolved_path), p_preload->path);
  3419. }
  3420. } else {
  3421. p_preload->resource = ResourceLoader::load(p_preload->resolved_path);
  3422. if (p_preload->resource.is_null()) {
  3423. push_error(vformat(R"(Could not preload resource file "%s".)", p_preload->resolved_path), p_preload->path);
  3424. }
  3425. }
  3426. }
  3427. }
  3428. p_preload->is_constant = true;
  3429. p_preload->reduced_value = p_preload->resource;
  3430. p_preload->set_datatype(type_from_variant(p_preload->reduced_value, p_preload));
  3431. }
  3432. void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
  3433. p_self->is_constant = false;
  3434. p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));
  3435. mark_lambda_use_self();
  3436. }
  3437. void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript, bool p_can_be_pseudo_type) {
  3438. if (p_subscript->base == nullptr) {
  3439. return;
  3440. }
  3441. if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  3442. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);
  3443. } else if (p_subscript->base->type == GDScriptParser::Node::SUBSCRIPT) {
  3444. reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_subscript->base), true);
  3445. } else {
  3446. reduce_expression(p_subscript->base);
  3447. }
  3448. GDScriptParser::DataType result_type;
  3449. if (p_subscript->is_attribute) {
  3450. if (p_subscript->attribute == nullptr) {
  3451. return;
  3452. }
  3453. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  3454. bool valid = false;
  3455. // If the base is a metatype, use the analyzer instead.
  3456. if (p_subscript->base->is_constant && !base_type.is_meta_type) {
  3457. // Just try to get it.
  3458. Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, valid);
  3459. if (valid) {
  3460. p_subscript->is_constant = true;
  3461. p_subscript->reduced_value = value;
  3462. result_type = type_from_variant(value, p_subscript);
  3463. }
  3464. } else if (base_type.is_variant() || !base_type.is_hard_type()) {
  3465. valid = !base_type.is_pseudo_type || p_can_be_pseudo_type;
  3466. result_type.kind = GDScriptParser::DataType::VARIANT;
  3467. if (base_type.is_variant() && base_type.is_hard_type() && base_type.is_meta_type && base_type.is_pseudo_type) {
  3468. // Special case: it may be a global enum with pseudo base (e.g. Variant.Type).
  3469. String enum_name;
  3470. if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  3471. enum_name = String(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base)->name) + ENUM_SEPARATOR + String(p_subscript->attribute->name);
  3472. }
  3473. if (CoreConstants::is_global_enum(enum_name)) {
  3474. result_type = make_global_enum_type(enum_name, StringName());
  3475. } else {
  3476. valid = false;
  3477. mark_node_unsafe(p_subscript);
  3478. }
  3479. } else {
  3480. mark_node_unsafe(p_subscript);
  3481. }
  3482. } else {
  3483. reduce_identifier_from_base(p_subscript->attribute, &base_type);
  3484. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  3485. if (attr_type.is_set()) {
  3486. valid = !attr_type.is_pseudo_type || p_can_be_pseudo_type;
  3487. result_type = attr_type;
  3488. p_subscript->is_constant = p_subscript->attribute->is_constant;
  3489. p_subscript->reduced_value = p_subscript->attribute->reduced_value;
  3490. } else if (!base_type.is_meta_type || !base_type.is_constant) {
  3491. valid = base_type.kind != GDScriptParser::DataType::BUILTIN;
  3492. #ifdef DEBUG_ENABLED
  3493. if (valid) {
  3494. parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());
  3495. }
  3496. #endif
  3497. result_type.kind = GDScriptParser::DataType::VARIANT;
  3498. mark_node_unsafe(p_subscript);
  3499. }
  3500. }
  3501. if (!valid) {
  3502. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  3503. if (!p_can_be_pseudo_type && (attr_type.is_pseudo_type || result_type.is_pseudo_type)) {
  3504. push_error(vformat(R"(Type "%s" in base "%s" cannot be used on its own.)", p_subscript->attribute->name, type_from_metatype(base_type).to_string()), p_subscript->attribute);
  3505. } else {
  3506. push_error(vformat(R"(Cannot find member "%s" in base "%s".)", p_subscript->attribute->name, type_from_metatype(base_type).to_string()), p_subscript->attribute);
  3507. }
  3508. result_type.kind = GDScriptParser::DataType::VARIANT;
  3509. }
  3510. } else {
  3511. if (p_subscript->index == nullptr) {
  3512. return;
  3513. }
  3514. reduce_expression(p_subscript->index);
  3515. if (p_subscript->base->is_constant && p_subscript->index->is_constant) {
  3516. // Just try to get it.
  3517. bool valid = false;
  3518. Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);
  3519. if (!valid) {
  3520. push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);
  3521. result_type.kind = GDScriptParser::DataType::VARIANT;
  3522. } else {
  3523. p_subscript->is_constant = true;
  3524. p_subscript->reduced_value = value;
  3525. result_type = type_from_variant(value, p_subscript);
  3526. }
  3527. } else {
  3528. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  3529. GDScriptParser::DataType index_type = p_subscript->index->get_datatype();
  3530. if (base_type.is_variant()) {
  3531. result_type.kind = GDScriptParser::DataType::VARIANT;
  3532. mark_node_unsafe(p_subscript);
  3533. } else {
  3534. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  3535. // Check if indexing is valid.
  3536. bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;
  3537. if (!error) {
  3538. switch (base_type.builtin_type) {
  3539. // Expect int or real as index.
  3540. case Variant::PACKED_BYTE_ARRAY:
  3541. case Variant::PACKED_COLOR_ARRAY:
  3542. case Variant::PACKED_FLOAT32_ARRAY:
  3543. case Variant::PACKED_FLOAT64_ARRAY:
  3544. case Variant::PACKED_INT32_ARRAY:
  3545. case Variant::PACKED_INT64_ARRAY:
  3546. case Variant::PACKED_STRING_ARRAY:
  3547. case Variant::PACKED_VECTOR2_ARRAY:
  3548. case Variant::PACKED_VECTOR3_ARRAY:
  3549. case Variant::ARRAY:
  3550. case Variant::STRING:
  3551. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;
  3552. break;
  3553. // Expect String only.
  3554. case Variant::RECT2:
  3555. case Variant::RECT2I:
  3556. case Variant::PLANE:
  3557. case Variant::QUATERNION:
  3558. case Variant::AABB:
  3559. case Variant::OBJECT:
  3560. error = index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  3561. break;
  3562. // Expect String or number.
  3563. case Variant::BASIS:
  3564. case Variant::VECTOR2:
  3565. case Variant::VECTOR2I:
  3566. case Variant::VECTOR3:
  3567. case Variant::VECTOR3I:
  3568. case Variant::VECTOR4:
  3569. case Variant::VECTOR4I:
  3570. case Variant::TRANSFORM2D:
  3571. case Variant::TRANSFORM3D:
  3572. case Variant::PROJECTION:
  3573. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&
  3574. index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  3575. break;
  3576. // Expect String or int.
  3577. case Variant::COLOR:
  3578. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  3579. break;
  3580. // Don't support indexing, but we will check it later.
  3581. case Variant::RID:
  3582. case Variant::BOOL:
  3583. case Variant::CALLABLE:
  3584. case Variant::FLOAT:
  3585. case Variant::INT:
  3586. case Variant::NIL:
  3587. case Variant::NODE_PATH:
  3588. case Variant::SIGNAL:
  3589. case Variant::STRING_NAME:
  3590. break;
  3591. // Here for completeness.
  3592. case Variant::DICTIONARY:
  3593. case Variant::VARIANT_MAX:
  3594. break;
  3595. }
  3596. if (error) {
  3597. push_error(vformat(R"(Invalid index type "%s" for a base of type "%s".)", index_type.to_string(), base_type.to_string()), p_subscript->index);
  3598. }
  3599. }
  3600. } else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  3601. if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {
  3602. push_error(vformat(R"(Only String or StringName can be used as index for type "%s", but received a "%s".)", base_type.to_string(), index_type.to_string()), p_subscript->index);
  3603. }
  3604. }
  3605. // Check resulting type if possible.
  3606. result_type.builtin_type = Variant::NIL;
  3607. result_type.kind = GDScriptParser::DataType::BUILTIN;
  3608. result_type.type_source = base_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  3609. if (base_type.kind != GDScriptParser::DataType::BUILTIN) {
  3610. base_type.builtin_type = Variant::OBJECT;
  3611. }
  3612. switch (base_type.builtin_type) {
  3613. // Can't index at all.
  3614. case Variant::RID:
  3615. case Variant::BOOL:
  3616. case Variant::CALLABLE:
  3617. case Variant::FLOAT:
  3618. case Variant::INT:
  3619. case Variant::NIL:
  3620. case Variant::NODE_PATH:
  3621. case Variant::SIGNAL:
  3622. case Variant::STRING_NAME:
  3623. result_type.kind = GDScriptParser::DataType::VARIANT;
  3624. push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);
  3625. break;
  3626. // Return int.
  3627. case Variant::PACKED_BYTE_ARRAY:
  3628. case Variant::PACKED_INT32_ARRAY:
  3629. case Variant::PACKED_INT64_ARRAY:
  3630. case Variant::VECTOR2I:
  3631. case Variant::VECTOR3I:
  3632. case Variant::VECTOR4I:
  3633. result_type.builtin_type = Variant::INT;
  3634. break;
  3635. // Return float.
  3636. case Variant::PACKED_FLOAT32_ARRAY:
  3637. case Variant::PACKED_FLOAT64_ARRAY:
  3638. case Variant::VECTOR2:
  3639. case Variant::VECTOR3:
  3640. case Variant::VECTOR4:
  3641. case Variant::QUATERNION:
  3642. result_type.builtin_type = Variant::FLOAT;
  3643. break;
  3644. // Return Color.
  3645. case Variant::PACKED_COLOR_ARRAY:
  3646. result_type.builtin_type = Variant::COLOR;
  3647. break;
  3648. // Return String.
  3649. case Variant::PACKED_STRING_ARRAY:
  3650. case Variant::STRING:
  3651. result_type.builtin_type = Variant::STRING;
  3652. break;
  3653. // Return Vector2.
  3654. case Variant::PACKED_VECTOR2_ARRAY:
  3655. case Variant::TRANSFORM2D:
  3656. case Variant::RECT2:
  3657. result_type.builtin_type = Variant::VECTOR2;
  3658. break;
  3659. // Return Vector2I.
  3660. case Variant::RECT2I:
  3661. result_type.builtin_type = Variant::VECTOR2I;
  3662. break;
  3663. // Return Vector3.
  3664. case Variant::PACKED_VECTOR3_ARRAY:
  3665. case Variant::AABB:
  3666. case Variant::BASIS:
  3667. result_type.builtin_type = Variant::VECTOR3;
  3668. break;
  3669. // Depends on the index.
  3670. case Variant::TRANSFORM3D:
  3671. case Variant::PROJECTION:
  3672. case Variant::PLANE:
  3673. case Variant::COLOR:
  3674. case Variant::DICTIONARY:
  3675. case Variant::OBJECT:
  3676. result_type.kind = GDScriptParser::DataType::VARIANT;
  3677. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  3678. break;
  3679. // Can have an element type.
  3680. case Variant::ARRAY:
  3681. if (base_type.has_container_element_type()) {
  3682. result_type = base_type.get_container_element_type();
  3683. result_type.type_source = base_type.type_source;
  3684. } else {
  3685. result_type.kind = GDScriptParser::DataType::VARIANT;
  3686. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  3687. }
  3688. break;
  3689. // Here for completeness.
  3690. case Variant::VARIANT_MAX:
  3691. break;
  3692. }
  3693. }
  3694. }
  3695. }
  3696. p_subscript->set_datatype(result_type);
  3697. }
  3698. void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op, bool p_is_root) {
  3699. reduce_expression(p_ternary_op->condition);
  3700. reduce_expression(p_ternary_op->true_expr, p_is_root);
  3701. reduce_expression(p_ternary_op->false_expr, p_is_root);
  3702. GDScriptParser::DataType result;
  3703. if (p_ternary_op->condition && p_ternary_op->condition->is_constant && p_ternary_op->true_expr->is_constant && p_ternary_op->false_expr && p_ternary_op->false_expr->is_constant) {
  3704. p_ternary_op->is_constant = true;
  3705. if (p_ternary_op->condition->reduced_value.booleanize()) {
  3706. p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;
  3707. } else {
  3708. p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;
  3709. }
  3710. }
  3711. GDScriptParser::DataType true_type;
  3712. if (p_ternary_op->true_expr) {
  3713. true_type = p_ternary_op->true_expr->get_datatype();
  3714. } else {
  3715. true_type.kind = GDScriptParser::DataType::VARIANT;
  3716. }
  3717. GDScriptParser::DataType false_type;
  3718. if (p_ternary_op->false_expr) {
  3719. false_type = p_ternary_op->false_expr->get_datatype();
  3720. } else {
  3721. false_type.kind = GDScriptParser::DataType::VARIANT;
  3722. }
  3723. if (true_type.is_variant() || false_type.is_variant()) {
  3724. result.kind = GDScriptParser::DataType::VARIANT;
  3725. } else {
  3726. result = true_type;
  3727. if (!is_type_compatible(true_type, false_type)) {
  3728. result = false_type;
  3729. if (!is_type_compatible(false_type, true_type)) {
  3730. result.kind = GDScriptParser::DataType::VARIANT;
  3731. #ifdef DEBUG_ENABLED
  3732. parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);
  3733. #endif
  3734. }
  3735. }
  3736. }
  3737. result.type_source = true_type.is_hard_type() && false_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  3738. p_ternary_op->set_datatype(result);
  3739. }
  3740. void GDScriptAnalyzer::reduce_type_test(GDScriptParser::TypeTestNode *p_type_test) {
  3741. GDScriptParser::DataType result;
  3742. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3743. result.kind = GDScriptParser::DataType::BUILTIN;
  3744. result.builtin_type = Variant::BOOL;
  3745. p_type_test->set_datatype(result);
  3746. if (!p_type_test->operand || !p_type_test->test_type) {
  3747. return;
  3748. }
  3749. reduce_expression(p_type_test->operand);
  3750. GDScriptParser::DataType operand_type = p_type_test->operand->get_datatype();
  3751. GDScriptParser::DataType test_type = type_from_metatype(resolve_datatype(p_type_test->test_type));
  3752. p_type_test->test_datatype = test_type;
  3753. if (!operand_type.is_set() || !test_type.is_set()) {
  3754. return;
  3755. }
  3756. if (p_type_test->operand->is_constant) {
  3757. p_type_test->is_constant = true;
  3758. p_type_test->reduced_value = false;
  3759. if (!is_type_compatible(test_type, operand_type)) {
  3760. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)", operand_type.to_string(), test_type.to_string()), p_type_test->operand);
  3761. } else if (is_type_compatible(test_type, type_from_variant(p_type_test->operand->reduced_value, p_type_test->operand))) {
  3762. p_type_test->reduced_value = test_type.builtin_type != Variant::OBJECT || !p_type_test->operand->reduced_value.is_null();
  3763. }
  3764. return;
  3765. }
  3766. if (!is_type_compatible(test_type, operand_type) && !is_type_compatible(operand_type, test_type)) {
  3767. if (operand_type.is_hard_type()) {
  3768. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)", operand_type.to_string(), test_type.to_string()), p_type_test->operand);
  3769. } else {
  3770. downgrade_node_type_source(p_type_test->operand);
  3771. }
  3772. }
  3773. }
  3774. void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {
  3775. reduce_expression(p_unary_op->operand);
  3776. GDScriptParser::DataType result;
  3777. if (p_unary_op->operand == nullptr) {
  3778. result.kind = GDScriptParser::DataType::VARIANT;
  3779. p_unary_op->set_datatype(result);
  3780. return;
  3781. }
  3782. GDScriptParser::DataType operand_type = p_unary_op->operand->get_datatype();
  3783. if (p_unary_op->operand->is_constant) {
  3784. p_unary_op->is_constant = true;
  3785. p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());
  3786. result = type_from_variant(p_unary_op->reduced_value, p_unary_op);
  3787. }
  3788. if (operand_type.is_variant()) {
  3789. result.kind = GDScriptParser::DataType::VARIANT;
  3790. mark_node_unsafe(p_unary_op);
  3791. } else {
  3792. bool valid = false;
  3793. result = get_operation_type(p_unary_op->variant_op, operand_type, valid, p_unary_op);
  3794. if (!valid) {
  3795. push_error(vformat(R"(Invalid operand of type "%s" for unary operator "%s".)", operand_type.to_string(), Variant::get_operator_name(p_unary_op->variant_op)), p_unary_op);
  3796. }
  3797. }
  3798. p_unary_op->set_datatype(result);
  3799. }
  3800. Variant GDScriptAnalyzer::make_expression_reduced_value(GDScriptParser::ExpressionNode *p_expression, bool &is_reduced) {
  3801. Variant value;
  3802. if (p_expression == nullptr) {
  3803. return value;
  3804. }
  3805. if (p_expression->is_constant) {
  3806. is_reduced = true;
  3807. value = p_expression->reduced_value;
  3808. } else if (p_expression->type == GDScriptParser::Node::ARRAY) {
  3809. value = make_array_reduced_value(static_cast<GDScriptParser::ArrayNode *>(p_expression), is_reduced);
  3810. } else if (p_expression->type == GDScriptParser::Node::DICTIONARY) {
  3811. value = make_dictionary_reduced_value(static_cast<GDScriptParser::DictionaryNode *>(p_expression), is_reduced);
  3812. } else if (p_expression->type == GDScriptParser::Node::SUBSCRIPT) {
  3813. value = make_subscript_reduced_value(static_cast<GDScriptParser::SubscriptNode *>(p_expression), is_reduced);
  3814. }
  3815. return value;
  3816. }
  3817. Variant GDScriptAnalyzer::make_array_reduced_value(GDScriptParser::ArrayNode *p_array, bool &is_reduced) {
  3818. Array array = p_array->get_datatype().has_container_element_type() ? make_array_from_element_datatype(p_array->get_datatype().get_container_element_type()) : Array();
  3819. array.resize(p_array->elements.size());
  3820. for (int i = 0; i < p_array->elements.size(); i++) {
  3821. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  3822. bool is_element_value_reduced = false;
  3823. Variant element_value = make_expression_reduced_value(element, is_element_value_reduced);
  3824. if (!is_element_value_reduced) {
  3825. return Variant();
  3826. }
  3827. array[i] = element_value;
  3828. }
  3829. array.make_read_only();
  3830. is_reduced = true;
  3831. return array;
  3832. }
  3833. Variant GDScriptAnalyzer::make_dictionary_reduced_value(GDScriptParser::DictionaryNode *p_dictionary, bool &is_reduced) {
  3834. Dictionary dictionary;
  3835. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  3836. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  3837. bool is_element_key_reduced = false;
  3838. Variant element_key = make_expression_reduced_value(element.key, is_element_key_reduced);
  3839. if (!is_element_key_reduced) {
  3840. return Variant();
  3841. }
  3842. bool is_element_value_reduced = false;
  3843. Variant element_value = make_expression_reduced_value(element.value, is_element_value_reduced);
  3844. if (!is_element_value_reduced) {
  3845. return Variant();
  3846. }
  3847. dictionary[element_key] = element_value;
  3848. }
  3849. dictionary.make_read_only();
  3850. is_reduced = true;
  3851. return dictionary;
  3852. }
  3853. Variant GDScriptAnalyzer::make_subscript_reduced_value(GDScriptParser::SubscriptNode *p_subscript, bool &is_reduced) {
  3854. if (p_subscript->base == nullptr || p_subscript->index == nullptr) {
  3855. return Variant();
  3856. }
  3857. bool is_base_value_reduced = false;
  3858. Variant base_value = make_expression_reduced_value(p_subscript->base, is_base_value_reduced);
  3859. if (!is_base_value_reduced) {
  3860. return Variant();
  3861. }
  3862. if (p_subscript->is_attribute) {
  3863. bool is_valid = false;
  3864. Variant value = base_value.get_named(p_subscript->attribute->name, is_valid);
  3865. if (is_valid) {
  3866. is_reduced = true;
  3867. return value;
  3868. } else {
  3869. return Variant();
  3870. }
  3871. } else {
  3872. bool is_index_value_reduced = false;
  3873. Variant index_value = make_expression_reduced_value(p_subscript->index, is_index_value_reduced);
  3874. if (!is_index_value_reduced) {
  3875. return Variant();
  3876. }
  3877. bool is_valid = false;
  3878. Variant value = base_value.get(index_value, &is_valid);
  3879. if (is_valid) {
  3880. is_reduced = true;
  3881. return value;
  3882. } else {
  3883. return Variant();
  3884. }
  3885. }
  3886. }
  3887. Array GDScriptAnalyzer::make_array_from_element_datatype(const GDScriptParser::DataType &p_element_datatype, const GDScriptParser::Node *p_source_node) {
  3888. Array array;
  3889. if (p_element_datatype.builtin_type == Variant::OBJECT) {
  3890. Ref<Script> script_type = p_element_datatype.script_type;
  3891. if (p_element_datatype.kind == GDScriptParser::DataType::CLASS && script_type.is_null()) {
  3892. Error err = OK;
  3893. Ref<GDScript> scr = GDScriptCache::get_shallow_script(p_element_datatype.script_path, err);
  3894. if (err) {
  3895. push_error(vformat(R"(Error while getting cache for script "%s".)", p_element_datatype.script_path), p_source_node);
  3896. return array;
  3897. }
  3898. script_type.reference_ptr(scr->find_class(p_element_datatype.class_type->fqcn));
  3899. }
  3900. array.set_typed(p_element_datatype.builtin_type, p_element_datatype.native_type, script_type);
  3901. } else {
  3902. array.set_typed(p_element_datatype.builtin_type, StringName(), Variant());
  3903. }
  3904. return array;
  3905. }
  3906. Variant GDScriptAnalyzer::make_variable_default_value(GDScriptParser::VariableNode *p_variable) {
  3907. Variant result = Variant();
  3908. if (p_variable->initializer) {
  3909. bool is_initializer_value_reduced = false;
  3910. Variant initializer_value = make_expression_reduced_value(p_variable->initializer, is_initializer_value_reduced);
  3911. if (is_initializer_value_reduced) {
  3912. result = initializer_value;
  3913. }
  3914. } else {
  3915. GDScriptParser::DataType datatype = p_variable->get_datatype();
  3916. if (datatype.is_hard_type()) {
  3917. if (datatype.kind == GDScriptParser::DataType::BUILTIN && datatype.builtin_type != Variant::OBJECT) {
  3918. if (datatype.builtin_type == Variant::ARRAY && datatype.has_container_element_type()) {
  3919. result = make_array_from_element_datatype(datatype.get_container_element_type());
  3920. } else {
  3921. VariantInternal::initialize(&result, datatype.builtin_type);
  3922. }
  3923. } else if (datatype.kind == GDScriptParser::DataType::ENUM) {
  3924. result = 0;
  3925. }
  3926. }
  3927. }
  3928. return result;
  3929. }
  3930. GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source) {
  3931. GDScriptParser::DataType result;
  3932. result.is_constant = true;
  3933. result.kind = GDScriptParser::DataType::BUILTIN;
  3934. result.builtin_type = p_value.get_type();
  3935. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.
  3936. if (p_value.get_type() == Variant::OBJECT) {
  3937. // Object is treated as a native type, not a builtin type.
  3938. result.kind = GDScriptParser::DataType::NATIVE;
  3939. Object *obj = p_value;
  3940. if (!obj) {
  3941. return GDScriptParser::DataType();
  3942. }
  3943. result.native_type = obj->get_class_name();
  3944. Ref<Script> scr = p_value; // Check if value is a script itself.
  3945. if (scr.is_valid()) {
  3946. result.is_meta_type = true;
  3947. } else {
  3948. result.is_meta_type = false;
  3949. scr = obj->get_script();
  3950. }
  3951. if (scr.is_valid()) {
  3952. Ref<GDScript> gds = scr;
  3953. if (gds.is_valid()) {
  3954. // This might be an inner class, so we want to get the parser for the root.
  3955. // But still get the inner class from that tree.
  3956. String script_path = gds->get_script_path();
  3957. Ref<GDScriptParserRef> ref = get_parser_for(script_path);
  3958. if (ref.is_null()) {
  3959. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  3960. GDScriptParser::DataType error_type;
  3961. error_type.kind = GDScriptParser::DataType::VARIANT;
  3962. return error_type;
  3963. }
  3964. Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3965. GDScriptParser::ClassNode *found = nullptr;
  3966. if (err == OK) {
  3967. found = ref->get_parser()->find_class(gds->fully_qualified_name);
  3968. if (found != nullptr) {
  3969. err = resolve_class_inheritance(found, p_source);
  3970. }
  3971. }
  3972. if (err || found == nullptr) {
  3973. push_error(vformat(R"(Could not resolve script "%s".)", script_path), p_source);
  3974. GDScriptParser::DataType error_type;
  3975. error_type.kind = GDScriptParser::DataType::VARIANT;
  3976. return error_type;
  3977. }
  3978. result.kind = GDScriptParser::DataType::CLASS;
  3979. result.native_type = found->get_datatype().native_type;
  3980. result.class_type = found;
  3981. result.script_path = ref->get_parser()->script_path;
  3982. } else {
  3983. result.kind = GDScriptParser::DataType::SCRIPT;
  3984. result.native_type = scr->get_instance_base_type();
  3985. result.script_path = scr->get_path();
  3986. }
  3987. result.script_type = scr;
  3988. } else {
  3989. result.kind = GDScriptParser::DataType::NATIVE;
  3990. if (result.native_type == GDScriptNativeClass::get_class_static()) {
  3991. result.is_meta_type = true;
  3992. }
  3993. }
  3994. }
  3995. return result;
  3996. }
  3997. GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) {
  3998. GDScriptParser::DataType result = p_meta_type;
  3999. result.is_meta_type = false;
  4000. result.is_pseudo_type = false;
  4001. if (p_meta_type.kind == GDScriptParser::DataType::ENUM) {
  4002. result.builtin_type = Variant::INT;
  4003. } else {
  4004. result.is_constant = false;
  4005. }
  4006. return result;
  4007. }
  4008. GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property, bool p_is_arg, bool p_is_readonly) const {
  4009. GDScriptParser::DataType result;
  4010. result.is_read_only = p_is_readonly;
  4011. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  4012. if (p_property.type == Variant::NIL && (p_is_arg || (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) {
  4013. // Variant
  4014. result.kind = GDScriptParser::DataType::VARIANT;
  4015. return result;
  4016. }
  4017. result.builtin_type = p_property.type;
  4018. if (p_property.type == Variant::OBJECT) {
  4019. result.kind = GDScriptParser::DataType::NATIVE;
  4020. result.native_type = p_property.class_name == StringName() ? SNAME("Object") : p_property.class_name;
  4021. } else {
  4022. result.kind = GDScriptParser::DataType::BUILTIN;
  4023. result.builtin_type = p_property.type;
  4024. if (p_property.type == Variant::ARRAY && p_property.hint == PROPERTY_HINT_ARRAY_TYPE) {
  4025. // Check element type.
  4026. StringName elem_type_name = p_property.hint_string;
  4027. GDScriptParser::DataType elem_type;
  4028. elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  4029. Variant::Type elem_builtin_type = GDScriptParser::get_builtin_type(elem_type_name);
  4030. if (elem_builtin_type < Variant::VARIANT_MAX) {
  4031. // Builtin type.
  4032. elem_type.kind = GDScriptParser::DataType::BUILTIN;
  4033. elem_type.builtin_type = elem_builtin_type;
  4034. } else if (class_exists(elem_type_name)) {
  4035. elem_type.kind = GDScriptParser::DataType::NATIVE;
  4036. elem_type.builtin_type = Variant::OBJECT;
  4037. elem_type.native_type = p_property.hint_string;
  4038. } else if (ScriptServer::is_global_class(elem_type_name)) {
  4039. // Just load this as it shouldn't be a GDScript.
  4040. Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(elem_type_name));
  4041. elem_type.kind = GDScriptParser::DataType::SCRIPT;
  4042. elem_type.builtin_type = Variant::OBJECT;
  4043. elem_type.native_type = script->get_instance_base_type();
  4044. elem_type.script_type = script;
  4045. } else {
  4046. ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed array.");
  4047. }
  4048. elem_type.is_constant = false;
  4049. result.set_container_element_type(elem_type);
  4050. } else if (p_property.type == Variant::INT) {
  4051. // Check if it's enum.
  4052. if ((p_property.usage & PROPERTY_USAGE_CLASS_IS_ENUM) && p_property.class_name != StringName()) {
  4053. if (CoreConstants::is_global_enum(p_property.class_name)) {
  4054. result = make_global_enum_type(p_property.class_name, StringName(), false);
  4055. result.is_constant = false;
  4056. } else {
  4057. Vector<String> names = String(p_property.class_name).split(ENUM_SEPARATOR);
  4058. if (names.size() == 2) {
  4059. result = make_native_enum_type(names[1], names[0], false);
  4060. result.is_constant = false;
  4061. }
  4062. }
  4063. }
  4064. // PROPERTY_USAGE_CLASS_IS_BITFIELD: BitField[T] isn't supported (yet?), use plain int.
  4065. }
  4066. }
  4067. return result;
  4068. }
  4069. bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, bool p_is_constructor, GDScriptParser::DataType p_base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg, StringName *r_native_class) {
  4070. r_static = false;
  4071. r_vararg = false;
  4072. r_default_arg_count = 0;
  4073. if (r_native_class) {
  4074. *r_native_class = StringName();
  4075. }
  4076. StringName function_name = p_function;
  4077. bool was_enum = false;
  4078. if (p_base_type.kind == GDScriptParser::DataType::ENUM) {
  4079. was_enum = true;
  4080. if (p_base_type.is_meta_type) {
  4081. // Enum type can be treated as a dictionary value.
  4082. p_base_type.kind = GDScriptParser::DataType::BUILTIN;
  4083. p_base_type.is_meta_type = false;
  4084. } else {
  4085. push_error("Cannot call function on enum value.", p_source);
  4086. return false;
  4087. }
  4088. }
  4089. if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {
  4090. // Construct a base type to get methods.
  4091. Callable::CallError err;
  4092. Variant dummy;
  4093. Variant::construct(p_base_type.builtin_type, dummy, nullptr, 0, err);
  4094. if (err.error != Callable::CallError::CALL_OK) {
  4095. ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");
  4096. }
  4097. List<MethodInfo> methods;
  4098. dummy.get_method_list(&methods);
  4099. for (const MethodInfo &E : methods) {
  4100. if (E.name == p_function) {
  4101. function_signature_from_info(E, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  4102. r_static = Variant::is_builtin_method_static(p_base_type.builtin_type, function_name);
  4103. // Cannot use non-const methods on enums.
  4104. if (!r_static && was_enum && !(E.flags & METHOD_FLAG_CONST)) {
  4105. push_error(vformat(R"*(Cannot call non-const Dictionary function "%s()" on enum "%s".)*", p_function, p_base_type.enum_type), p_source);
  4106. }
  4107. return true;
  4108. }
  4109. }
  4110. return false;
  4111. }
  4112. StringName base_native = p_base_type.native_type;
  4113. if (base_native != StringName()) {
  4114. // Empty native class might happen in some Script implementations.
  4115. // Just ignore it.
  4116. if (!class_exists(base_native)) {
  4117. push_error(vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native), p_source);
  4118. return false;
  4119. } else if (p_is_constructor && !ClassDB::can_instantiate(base_native)) {
  4120. if (p_base_type.kind == GDScriptParser::DataType::CLASS) {
  4121. push_error(vformat(R"(Class "%s" cannot be constructed as it is based on abstract native class "%s".)", p_base_type.class_type->fqcn.get_file(), base_native), p_source);
  4122. } else if (p_base_type.kind == GDScriptParser::DataType::SCRIPT) {
  4123. push_error(vformat(R"(Script "%s" cannot be constructed as it is based on abstract native class "%s".)", p_base_type.script_path.get_file(), base_native), p_source);
  4124. } else {
  4125. push_error(vformat(R"(Native class "%s" cannot be constructed as it is abstract.)", base_native), p_source);
  4126. }
  4127. return false;
  4128. }
  4129. }
  4130. if (p_is_constructor) {
  4131. function_name = "_init";
  4132. r_static = true;
  4133. }
  4134. GDScriptParser::ClassNode *base_class = p_base_type.class_type;
  4135. GDScriptParser::FunctionNode *found_function = nullptr;
  4136. while (found_function == nullptr && base_class != nullptr) {
  4137. if (base_class->has_member(function_name)) {
  4138. if (base_class->get_member(function_name).type != GDScriptParser::ClassNode::Member::FUNCTION) {
  4139. // TODO: If this is Callable it can have a better error message.
  4140. push_error(vformat(R"(Member "%s" is not a function.)", function_name), p_source);
  4141. return false;
  4142. }
  4143. resolve_class_member(base_class, function_name, p_source);
  4144. found_function = base_class->get_member(function_name).function;
  4145. }
  4146. resolve_class_inheritance(base_class, p_source);
  4147. base_class = base_class->base_type.class_type;
  4148. }
  4149. if (found_function != nullptr) {
  4150. r_static = p_is_constructor || found_function->is_static;
  4151. for (int i = 0; i < found_function->parameters.size(); i++) {
  4152. r_par_types.push_back(found_function->parameters[i]->get_datatype());
  4153. if (found_function->parameters[i]->initializer != nullptr) {
  4154. r_default_arg_count++;
  4155. }
  4156. }
  4157. r_return_type = p_is_constructor ? p_base_type : found_function->get_datatype();
  4158. r_return_type.is_meta_type = false;
  4159. r_return_type.is_coroutine = found_function->is_coroutine;
  4160. return true;
  4161. }
  4162. Ref<Script> base_script = p_base_type.script_type;
  4163. while (base_script.is_valid() && base_script->has_method(function_name)) {
  4164. MethodInfo info = base_script->get_method_info(function_name);
  4165. if (!(info == MethodInfo())) {
  4166. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  4167. }
  4168. base_script = base_script->get_base_script();
  4169. }
  4170. // If the base is a script, it might be trying to access members of the Script class itself.
  4171. if (p_base_type.is_meta_type && !p_is_constructor && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {
  4172. MethodInfo info;
  4173. StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());
  4174. if (ClassDB::get_method_info(script_class, function_name, &info)) {
  4175. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  4176. }
  4177. }
  4178. if (p_is_constructor) {
  4179. // Native types always have a default constructor.
  4180. r_return_type = p_base_type;
  4181. r_return_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  4182. r_return_type.is_meta_type = false;
  4183. return true;
  4184. }
  4185. MethodInfo info;
  4186. if (ClassDB::get_method_info(base_native, function_name, &info)) {
  4187. bool valid = function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  4188. if (valid && Engine::get_singleton()->has_singleton(base_native)) {
  4189. r_static = true;
  4190. }
  4191. #ifdef DEBUG_ENABLED
  4192. MethodBind *native_method = ClassDB::get_method(base_native, function_name);
  4193. if (native_method && r_native_class) {
  4194. *r_native_class = native_method->get_instance_class();
  4195. }
  4196. #endif
  4197. return valid;
  4198. }
  4199. return false;
  4200. }
  4201. bool GDScriptAnalyzer::function_signature_from_info(const MethodInfo &p_info, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) {
  4202. r_return_type = type_from_property(p_info.return_val);
  4203. r_default_arg_count = p_info.default_arguments.size();
  4204. r_vararg = (p_info.flags & METHOD_FLAG_VARARG) != 0;
  4205. r_static = (p_info.flags & METHOD_FLAG_STATIC) != 0;
  4206. for (const PropertyInfo &E : p_info.arguments) {
  4207. r_par_types.push_back(type_from_property(E, true));
  4208. }
  4209. return true;
  4210. }
  4211. void GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {
  4212. List<GDScriptParser::DataType> arg_types;
  4213. for (const PropertyInfo &E : p_method.arguments) {
  4214. arg_types.push_back(type_from_property(E, true));
  4215. }
  4216. validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);
  4217. }
  4218. void GDScriptAnalyzer::validate_call_arg(const List<GDScriptParser::DataType> &p_par_types, int p_default_args_count, bool p_is_vararg, const GDScriptParser::CallNode *p_call) {
  4219. if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {
  4220. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", p_call->function_name, p_par_types.size() - p_default_args_count, p_call->arguments.size()), p_call);
  4221. }
  4222. if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {
  4223. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", p_call->function_name, p_par_types.size(), p_call->arguments.size()), p_call->arguments[p_par_types.size()]);
  4224. }
  4225. for (int i = 0; i < p_call->arguments.size(); i++) {
  4226. if (i >= p_par_types.size()) {
  4227. // Already on vararg place.
  4228. break;
  4229. }
  4230. GDScriptParser::DataType par_type = p_par_types[i];
  4231. if (par_type.is_hard_type() && p_call->arguments[i]->is_constant) {
  4232. update_const_expression_builtin_type(p_call->arguments[i], par_type, "pass");
  4233. }
  4234. GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
  4235. if (arg_type.is_variant() || !arg_type.is_hard_type()) {
  4236. // Argument can be anything, so this is unsafe (unless the parameter is a hard variant).
  4237. if (!(par_type.is_hard_type() && par_type.is_variant())) {
  4238. mark_node_unsafe(p_call->arguments[i]);
  4239. }
  4240. } else if (par_type.is_hard_type() && !is_type_compatible(par_type, arg_type, true)) {
  4241. // Supertypes are acceptable for dynamic compliance, but it's unsafe.
  4242. mark_node_unsafe(p_call);
  4243. if (!is_type_compatible(arg_type, par_type)) {
  4244. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*",
  4245. p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),
  4246. p_call->arguments[i]);
  4247. }
  4248. #ifdef DEBUG_ENABLED
  4249. } else if (par_type.kind == GDScriptParser::DataType::BUILTIN && par_type.builtin_type == Variant::INT && arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == Variant::FLOAT) {
  4250. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  4251. #endif
  4252. }
  4253. }
  4254. }
  4255. #ifdef DEBUG_ENABLED
  4256. bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context) {
  4257. const StringName &name = p_local->name;
  4258. GDScriptParser::DataType base = parser->current_class->get_datatype();
  4259. GDScriptParser::ClassNode *base_class = base.class_type;
  4260. {
  4261. List<MethodInfo> gdscript_funcs;
  4262. GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);
  4263. for (MethodInfo &info : gdscript_funcs) {
  4264. if (info.name == name) {
  4265. parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");
  4266. return true;
  4267. }
  4268. }
  4269. if (Variant::has_utility_function(name)) {
  4270. parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");
  4271. return true;
  4272. } else if (ClassDB::class_exists(name)) {
  4273. parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "global class");
  4274. return true;
  4275. }
  4276. }
  4277. while (base_class != nullptr) {
  4278. if (base_class->has_member(name)) {
  4279. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE, p_context, p_local->name, base_class->get_member(name).get_type_name(), itos(base_class->get_member(name).get_line()));
  4280. return true;
  4281. }
  4282. base_class = base_class->base_type.class_type;
  4283. }
  4284. StringName parent = base.native_type;
  4285. while (parent != StringName()) {
  4286. ERR_FAIL_COND_V_MSG(!class_exists(parent), false, "Non-existent native base class.");
  4287. if (ClassDB::has_method(parent, name, true)) {
  4288. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "method", parent);
  4289. return true;
  4290. } else if (ClassDB::has_signal(parent, name, true)) {
  4291. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "signal", parent);
  4292. return true;
  4293. } else if (ClassDB::has_property(parent, name, true)) {
  4294. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "property", parent);
  4295. return true;
  4296. } else if (ClassDB::has_integer_constant(parent, name, true)) {
  4297. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "constant", parent);
  4298. return true;
  4299. } else if (ClassDB::has_enum(parent, name, true)) {
  4300. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "enum", parent);
  4301. return true;
  4302. }
  4303. parent = ClassDB::get_parent_class(parent);
  4304. }
  4305. return false;
  4306. }
  4307. #endif
  4308. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source) {
  4309. // Unary version.
  4310. GDScriptParser::DataType nil_type;
  4311. nil_type.builtin_type = Variant::NIL;
  4312. nil_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  4313. return get_operation_type(p_operation, p_a, nil_type, r_valid, p_source);
  4314. }
  4315. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid, const GDScriptParser::Node *p_source) {
  4316. Variant::Type a_type = p_a.builtin_type;
  4317. Variant::Type b_type = p_b.builtin_type;
  4318. if (p_a.kind == GDScriptParser::DataType::ENUM) {
  4319. if (p_a.is_meta_type) {
  4320. a_type = Variant::DICTIONARY;
  4321. } else {
  4322. a_type = Variant::INT;
  4323. }
  4324. }
  4325. if (p_b.kind == GDScriptParser::DataType::ENUM) {
  4326. if (p_b.is_meta_type) {
  4327. b_type = Variant::DICTIONARY;
  4328. } else {
  4329. b_type = Variant::INT;
  4330. }
  4331. }
  4332. Variant::ValidatedOperatorEvaluator op_eval = Variant::get_validated_operator_evaluator(p_operation, a_type, b_type);
  4333. bool hard_operation = p_a.is_hard_type() && p_b.is_hard_type();
  4334. bool validated = op_eval != nullptr;
  4335. GDScriptParser::DataType result;
  4336. if (validated) {
  4337. r_valid = true;
  4338. result.type_source = hard_operation ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  4339. result.kind = GDScriptParser::DataType::BUILTIN;
  4340. result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type);
  4341. } else {
  4342. r_valid = !hard_operation;
  4343. result.kind = GDScriptParser::DataType::VARIANT;
  4344. }
  4345. return result;
  4346. }
  4347. // TODO: Add safe/unsafe return variable (for variant cases)
  4348. bool GDScriptAnalyzer::is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion, const GDScriptParser::Node *p_source_node) {
  4349. // These return "true" so it doesn't affect users negatively.
  4350. ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");
  4351. ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");
  4352. if (p_target.kind == GDScriptParser::DataType::VARIANT) {
  4353. // Variant can receive anything.
  4354. return true;
  4355. }
  4356. if (p_source.kind == GDScriptParser::DataType::VARIANT) {
  4357. // TODO: This is acceptable but unsafe. Make sure unsafe line is set.
  4358. return true;
  4359. }
  4360. if (p_target.kind == GDScriptParser::DataType::BUILTIN) {
  4361. bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;
  4362. if (!valid && p_allow_implicit_conversion) {
  4363. valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);
  4364. }
  4365. if (!valid && p_target.builtin_type == Variant::INT && p_source.kind == GDScriptParser::DataType::ENUM && !p_source.is_meta_type) {
  4366. // Enum value is also integer.
  4367. valid = true;
  4368. }
  4369. if (valid && p_target.builtin_type == Variant::ARRAY && p_source.builtin_type == Variant::ARRAY) {
  4370. // Check the element type.
  4371. if (p_target.has_container_element_type() && p_source.has_container_element_type()) {
  4372. valid = p_target.get_container_element_type() == p_source.get_container_element_type();
  4373. }
  4374. }
  4375. return valid;
  4376. }
  4377. if (p_target.kind == GDScriptParser::DataType::ENUM) {
  4378. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {
  4379. #ifdef DEBUG_ENABLED
  4380. if (p_source_node) {
  4381. parser->push_warning(p_source_node, GDScriptWarning::INT_AS_ENUM_WITHOUT_CAST);
  4382. }
  4383. #endif
  4384. return true;
  4385. }
  4386. if (p_source.kind == GDScriptParser::DataType::ENUM) {
  4387. if (p_source.native_type == p_target.native_type) {
  4388. return true;
  4389. }
  4390. }
  4391. return false;
  4392. }
  4393. // From here on the target type is an object, so we have to test polymorphism.
  4394. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {
  4395. // null is acceptable in object.
  4396. return true;
  4397. }
  4398. StringName src_native;
  4399. Ref<Script> src_script;
  4400. const GDScriptParser::ClassNode *src_class = nullptr;
  4401. switch (p_source.kind) {
  4402. case GDScriptParser::DataType::NATIVE:
  4403. if (p_target.kind != GDScriptParser::DataType::NATIVE) {
  4404. // Non-native class cannot be supertype of native.
  4405. return false;
  4406. }
  4407. if (p_source.is_meta_type) {
  4408. src_native = GDScriptNativeClass::get_class_static();
  4409. } else {
  4410. src_native = p_source.native_type;
  4411. }
  4412. break;
  4413. case GDScriptParser::DataType::SCRIPT:
  4414. if (p_target.kind == GDScriptParser::DataType::CLASS) {
  4415. // A script type cannot be a subtype of a GDScript class.
  4416. return false;
  4417. }
  4418. if (p_source.is_meta_type) {
  4419. src_native = p_source.script_type->get_class_name();
  4420. } else {
  4421. src_script = p_source.script_type;
  4422. src_native = src_script->get_instance_base_type();
  4423. }
  4424. break;
  4425. case GDScriptParser::DataType::CLASS:
  4426. if (p_source.is_meta_type) {
  4427. src_native = GDScript::get_class_static();
  4428. } else {
  4429. src_class = p_source.class_type;
  4430. const GDScriptParser::ClassNode *base = src_class;
  4431. while (base->base_type.kind == GDScriptParser::DataType::CLASS) {
  4432. base = base->base_type.class_type;
  4433. }
  4434. src_native = base->base_type.native_type;
  4435. src_script = base->base_type.script_type;
  4436. }
  4437. break;
  4438. case GDScriptParser::DataType::VARIANT:
  4439. case GDScriptParser::DataType::BUILTIN:
  4440. case GDScriptParser::DataType::ENUM:
  4441. case GDScriptParser::DataType::RESOLVING:
  4442. case GDScriptParser::DataType::UNRESOLVED:
  4443. break; // Already solved before.
  4444. }
  4445. switch (p_target.kind) {
  4446. case GDScriptParser::DataType::NATIVE: {
  4447. if (p_target.is_meta_type) {
  4448. return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());
  4449. }
  4450. return ClassDB::is_parent_class(src_native, p_target.native_type);
  4451. }
  4452. case GDScriptParser::DataType::SCRIPT:
  4453. if (p_target.is_meta_type) {
  4454. return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());
  4455. }
  4456. while (src_script.is_valid()) {
  4457. if (src_script == p_target.script_type) {
  4458. return true;
  4459. }
  4460. src_script = src_script->get_base_script();
  4461. }
  4462. return false;
  4463. case GDScriptParser::DataType::CLASS:
  4464. if (p_target.is_meta_type) {
  4465. return ClassDB::is_parent_class(src_native, GDScript::get_class_static());
  4466. }
  4467. while (src_class != nullptr) {
  4468. if (src_class == p_target.class_type || src_class->fqcn == p_target.class_type->fqcn) {
  4469. return true;
  4470. }
  4471. src_class = src_class->base_type.class_type;
  4472. }
  4473. return false;
  4474. case GDScriptParser::DataType::VARIANT:
  4475. case GDScriptParser::DataType::BUILTIN:
  4476. case GDScriptParser::DataType::ENUM:
  4477. case GDScriptParser::DataType::RESOLVING:
  4478. case GDScriptParser::DataType::UNRESOLVED:
  4479. break; // Already solved before.
  4480. }
  4481. return false;
  4482. }
  4483. void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {
  4484. mark_node_unsafe(p_origin);
  4485. parser->push_error(p_message, p_origin);
  4486. }
  4487. void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {
  4488. #ifdef DEBUG_ENABLED
  4489. if (p_node == nullptr) {
  4490. return;
  4491. }
  4492. for (int i = p_node->start_line; i <= p_node->end_line; i++) {
  4493. parser->unsafe_lines.insert(i);
  4494. }
  4495. #endif
  4496. }
  4497. void GDScriptAnalyzer::downgrade_node_type_source(GDScriptParser::Node *p_node) {
  4498. GDScriptParser::IdentifierNode *identifier = nullptr;
  4499. if (p_node->type == GDScriptParser::Node::IDENTIFIER) {
  4500. identifier = static_cast<GDScriptParser::IdentifierNode *>(p_node);
  4501. } else if (p_node->type == GDScriptParser::Node::SUBSCRIPT) {
  4502. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_node);
  4503. if (subscript->is_attribute) {
  4504. identifier = subscript->attribute;
  4505. }
  4506. }
  4507. if (identifier == nullptr) {
  4508. return;
  4509. }
  4510. GDScriptParser::Node *source = nullptr;
  4511. switch (identifier->source) {
  4512. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {
  4513. source = identifier->variable_source;
  4514. } break;
  4515. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER: {
  4516. source = identifier->parameter_source;
  4517. } break;
  4518. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {
  4519. source = identifier->variable_source;
  4520. } break;
  4521. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {
  4522. source = identifier->bind_source;
  4523. } break;
  4524. default:
  4525. break;
  4526. }
  4527. if (source == nullptr) {
  4528. return;
  4529. }
  4530. GDScriptParser::DataType datatype;
  4531. datatype.kind = GDScriptParser::DataType::VARIANT;
  4532. source->set_datatype(datatype);
  4533. }
  4534. void GDScriptAnalyzer::mark_lambda_use_self() {
  4535. for (GDScriptParser::LambdaNode *lambda : lambda_stack) {
  4536. lambda->use_self = true;
  4537. }
  4538. }
  4539. bool GDScriptAnalyzer::class_exists(const StringName &p_class) const {
  4540. return ClassDB::class_exists(p_class) && ClassDB::is_class_exposed(p_class);
  4541. }
  4542. Ref<GDScriptParserRef> GDScriptAnalyzer::get_parser_for(const String &p_path) {
  4543. Ref<GDScriptParserRef> ref;
  4544. if (depended_parsers.has(p_path)) {
  4545. ref = depended_parsers[p_path];
  4546. } else {
  4547. Error err = OK;
  4548. ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err, parser->script_path);
  4549. if (ref.is_valid()) {
  4550. depended_parsers[p_path] = ref;
  4551. }
  4552. }
  4553. return ref;
  4554. }
  4555. Error GDScriptAnalyzer::resolve_inheritance() {
  4556. return resolve_class_inheritance(parser->head, true);
  4557. }
  4558. Error GDScriptAnalyzer::resolve_interface() {
  4559. resolve_class_interface(parser->head, true);
  4560. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  4561. }
  4562. Error GDScriptAnalyzer::resolve_body() {
  4563. resolve_class_body(parser->head, true);
  4564. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  4565. }
  4566. Error GDScriptAnalyzer::resolve_dependencies() {
  4567. for (KeyValue<String, Ref<GDScriptParserRef>> &K : depended_parsers) {
  4568. if (K.value.is_null()) {
  4569. return ERR_PARSE_ERROR;
  4570. }
  4571. K.value->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  4572. }
  4573. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  4574. }
  4575. Error GDScriptAnalyzer::analyze() {
  4576. parser->errors.clear();
  4577. Error err = OK;
  4578. err = resolve_inheritance();
  4579. if (err) {
  4580. return err;
  4581. }
  4582. // Apply annotations.
  4583. for (GDScriptParser::AnnotationNode *&E : parser->head->annotations) {
  4584. resolve_annotation(E);
  4585. E->apply(parser, parser->head);
  4586. }
  4587. resolve_interface();
  4588. resolve_body();
  4589. if (!parser->errors.is_empty()) {
  4590. return ERR_PARSE_ERROR;
  4591. }
  4592. return resolve_dependencies();
  4593. }
  4594. GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {
  4595. parser = p_parser;
  4596. }