2
0

gdscript_analyzer.cpp 174 KB

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