gdscript_analyzer.cpp 166 KB

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