gdscript_analyzer.cpp 166 KB

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