gdscript_analyzer.cpp 168 KB

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