gdscript_analyzer.cpp 131 KB

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