gdscript_analyzer.cpp 159 KB

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