gdscript_analyzer.cpp 141 KB

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