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