gdscript_analyzer.cpp 140 KB

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