gdscript_analyzer.cpp 175 KB

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