gdscript_analyzer.cpp 201 KB

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