gdscript_analyzer.cpp 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760
  1. /*************************************************************************/
  2. /* gdscript_analyzer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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/class_db.h"
  32. #include "core/hash_map.h"
  33. #include "core/io/resource_loader.h"
  34. #include "core/project_settings.h"
  35. #include "core/script_language.h"
  36. #include "gdscript.h"
  37. static GDScriptParser::DataType make_callable_type(const MethodInfo &p_info) {
  38. GDScriptParser::DataType type;
  39. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  40. type.kind = GDScriptParser::DataType::BUILTIN;
  41. type.builtin_type = Variant::CALLABLE;
  42. type.is_constant = true;
  43. type.method_info = p_info;
  44. return type;
  45. }
  46. static GDScriptParser::DataType make_signal_type(const MethodInfo &p_info) {
  47. GDScriptParser::DataType type;
  48. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  49. type.kind = GDScriptParser::DataType::BUILTIN;
  50. type.builtin_type = Variant::SIGNAL;
  51. type.is_constant = true;
  52. type.method_info = p_info;
  53. return type;
  54. }
  55. static GDScriptParser::DataType make_native_meta_type(const StringName &p_class_name) {
  56. GDScriptParser::DataType type;
  57. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  58. type.kind = GDScriptParser::DataType::NATIVE;
  59. type.builtin_type = Variant::OBJECT;
  60. type.is_constant = true;
  61. type.native_type = p_class_name;
  62. type.is_meta_type = true;
  63. return type;
  64. }
  65. static GDScriptParser::DataType make_builtin_meta_type(Variant::Type p_type) {
  66. GDScriptParser::DataType type;
  67. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  68. type.kind = GDScriptParser::DataType::BUILTIN;
  69. type.builtin_type = p_type;
  70. type.is_constant = true;
  71. type.is_meta_type = true;
  72. return type;
  73. }
  74. // TODO: Move this to a central location (maybe core?).
  75. static HashMap<StringName, StringName> underscore_map;
  76. static const char *underscore_classes[] = {
  77. "ClassDB",
  78. "Directory",
  79. "Engine",
  80. "File",
  81. "Geometry",
  82. "GodotSharp",
  83. "JSON",
  84. "Marshalls",
  85. "Mutex",
  86. "OS",
  87. "ResourceLoader",
  88. "ResourceSaver",
  89. "Semaphore",
  90. "Thread",
  91. "VisualScriptEditor",
  92. nullptr,
  93. };
  94. static StringName get_real_class_name(const StringName &p_source) {
  95. if (underscore_map.empty()) {
  96. const char **class_name = underscore_classes;
  97. while (*class_name != nullptr) {
  98. underscore_map[*class_name] = String("_") + *class_name;
  99. class_name++;
  100. }
  101. }
  102. if (underscore_map.has(p_source)) {
  103. return underscore_map[p_source];
  104. }
  105. return p_source;
  106. }
  107. Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  108. if (p_class->base_type.is_set()) {
  109. // Already resolved
  110. return OK;
  111. }
  112. GDScriptParser::DataType result;
  113. // Set datatype for class.
  114. GDScriptParser::DataType class_type;
  115. class_type.is_constant = true;
  116. class_type.is_meta_type = true;
  117. class_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  118. class_type.kind = GDScriptParser::DataType::CLASS;
  119. class_type.class_type = p_class;
  120. p_class->set_datatype(class_type);
  121. if (!p_class->extends_used) {
  122. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  123. result.kind = GDScriptParser::DataType::NATIVE;
  124. result.native_type = "Reference";
  125. } else {
  126. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  127. GDScriptParser::DataType base;
  128. int extends_index = 0;
  129. if (!p_class->extends_path.empty()) {
  130. Ref<GDScriptParserRef> parser = get_parser_for(p_class->extends_path);
  131. if (parser.is_null()) {
  132. push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class);
  133. return ERR_PARSE_ERROR;
  134. }
  135. Error err = parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  136. if (err != OK) {
  137. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", p_class->extends_path), p_class);
  138. return err;
  139. }
  140. base = parser->get_parser()->head->get_datatype();
  141. } else {
  142. const StringName &name = p_class->extends[extends_index++];
  143. base.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  144. if (ScriptServer::is_global_class(name)) {
  145. String base_path = ScriptServer::get_global_class_path(name);
  146. Ref<GDScriptParserRef> parser = get_parser_for(base_path);
  147. if (parser.is_null()) {
  148. push_error(vformat(R"(Could not resolve super class "%s".)", name), p_class);
  149. return ERR_PARSE_ERROR;
  150. }
  151. Error err = parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  152. if (err != OK) {
  153. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
  154. return err;
  155. }
  156. } else if (ProjectSettings::get_singleton()->has_autoload(name) && ProjectSettings::get_singleton()->get_autoload(name).is_singleton) {
  157. const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(name);
  158. if (info.path.get_extension().to_lower() != ".gd") {
  159. push_error(vformat(R"(Singleton %s is not a GDScript.)", info.name), p_class);
  160. return ERR_PARSE_ERROR;
  161. }
  162. Ref<GDScriptParserRef> parser = get_parser_for(info.path);
  163. if (parser.is_null()) {
  164. push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), p_class);
  165. return ERR_PARSE_ERROR;
  166. }
  167. Error err = parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  168. if (err != OK) {
  169. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
  170. return err;
  171. }
  172. } else if (class_exists(name) && ClassDB::can_instance(get_real_class_name(name))) {
  173. base.kind = GDScriptParser::DataType::NATIVE;
  174. base.native_type = name;
  175. } else {
  176. // Look for other classes in script.
  177. const GDScriptParser::ClassNode *look_class = p_class;
  178. bool found = false;
  179. while (look_class != nullptr) {
  180. if (p_class->members_indices.has(name) && p_class->get_member(name).type == GDScriptParser::ClassNode::Member::CLASS) {
  181. GDScriptParser::ClassNode::Member member = p_class->get_member(name);
  182. base.kind = GDScriptParser::DataType::CLASS;
  183. base.class_type = member.m_class;
  184. found = true;
  185. break;
  186. }
  187. look_class = look_class->outer;
  188. }
  189. if (!found) {
  190. push_error(vformat(R"(Could not find base class "%s".)", name), p_class);
  191. return ERR_PARSE_ERROR;
  192. }
  193. }
  194. }
  195. for (int index = extends_index; index < p_class->extends.size(); index++) {
  196. if (base.kind != GDScriptParser::DataType::CLASS) {
  197. push_error(R"(Super type "%s" is not a GDScript. Cannot get nested types.)", p_class);
  198. return ERR_PARSE_ERROR;
  199. }
  200. // TODO: Extends could use identifier nodes. That way errors can be pointed out properly and it can be used here.
  201. GDScriptParser::IdentifierNode *id = parser->alloc_node<GDScriptParser::IdentifierNode>();
  202. id->name = p_class->extends[index];
  203. reduce_identifier_from_base(id, &base);
  204. GDScriptParser::DataType id_type = id->get_datatype();
  205. if (!id_type.is_set()) {
  206. push_error(vformat(R"(Could not find type "%s" under base "%s".)", id->name, base.to_string()), p_class);
  207. }
  208. base = id_type;
  209. }
  210. result = base;
  211. }
  212. if (!result.is_set()) {
  213. // TODO: More specific error messages.
  214. push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->identifier == nullptr ? "<main>" : p_class->identifier->name), p_class);
  215. return ERR_PARSE_ERROR;
  216. }
  217. p_class->base_type = result;
  218. class_type.native_type = result.native_type;
  219. p_class->set_datatype(class_type);
  220. if (p_recursive) {
  221. for (int i = 0; i < p_class->members.size(); i++) {
  222. if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {
  223. resolve_inheritance(p_class->members[i].m_class, true);
  224. }
  225. }
  226. }
  227. return OK;
  228. }
  229. GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::TypeNode *p_type) {
  230. GDScriptParser::DataType result;
  231. if (p_type == nullptr) {
  232. result.kind = GDScriptParser::DataType::VARIANT;
  233. return result;
  234. }
  235. result.type_source = result.ANNOTATED_EXPLICIT;
  236. result.builtin_type = Variant::OBJECT;
  237. if (p_type->type_chain.empty()) {
  238. // void.
  239. result.kind = GDScriptParser::DataType::BUILTIN;
  240. result.builtin_type = Variant::NIL;
  241. p_type->set_datatype(result);
  242. return result;
  243. }
  244. StringName first = p_type->type_chain[0]->name;
  245. if (first == "Variant") {
  246. result.kind = GDScriptParser::DataType::VARIANT;
  247. if (p_type->type_chain.size() > 1) {
  248. push_error(R"("Variant" type don't contain nested types.)", p_type->type_chain[1]);
  249. return GDScriptParser::DataType();
  250. }
  251. return result;
  252. }
  253. if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) {
  254. // Built-in types.
  255. if (p_type->type_chain.size() > 1) {
  256. push_error(R"(Built-in types don't contain nested types.)", p_type->type_chain[1]);
  257. return GDScriptParser::DataType();
  258. }
  259. result.kind = GDScriptParser::DataType::BUILTIN;
  260. result.builtin_type = GDScriptParser::get_builtin_type(first);
  261. } else if (class_exists(first)) {
  262. // Native engine classes.
  263. if (p_type->type_chain.size() > 1) {
  264. push_error(R"(Engine classes don't contain nested types.)", p_type->type_chain[1]);
  265. return GDScriptParser::DataType();
  266. }
  267. result.kind = GDScriptParser::DataType::NATIVE;
  268. result.native_type = first;
  269. } else if (ScriptServer::is_global_class(first)) {
  270. Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(first));
  271. if (ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) {
  272. push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type);
  273. return GDScriptParser::DataType();
  274. }
  275. result = ref->get_parser()->head->get_datatype();
  276. } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) {
  277. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first);
  278. Ref<GDScriptParserRef> ref = get_parser_for(autoload.path);
  279. if (ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) {
  280. push_error(vformat(R"(Could not parse singleton "%s" from "%s".)", first, autoload.path), p_type);
  281. return GDScriptParser::DataType();
  282. }
  283. result = ref->get_parser()->head->get_datatype();
  284. } else {
  285. // Classes in current scope.
  286. GDScriptParser::ClassNode *script_class = parser->current_class;
  287. bool found = false;
  288. while (!found && script_class != nullptr) {
  289. if (script_class->members_indices.has(first)) {
  290. GDScriptParser::ClassNode::Member member = script_class->members[script_class->members_indices[first]];
  291. switch (member.type) {
  292. case GDScriptParser::ClassNode::Member::CLASS:
  293. result.kind = GDScriptParser::DataType::CLASS;
  294. result.class_type = member.m_class;
  295. found = true;
  296. break;
  297. case GDScriptParser::ClassNode::Member::CONSTANT:
  298. if (member.constant->get_datatype().is_meta_type) {
  299. result = member.constant->get_datatype();
  300. break;
  301. }
  302. [[fallthrough]];
  303. default:
  304. // TODO: Get constants as types, disallow others explicitly.
  305. push_error(vformat(R"("%s" is a %s but does not contain a type.)", first, member.get_type_name()), p_type);
  306. return GDScriptParser::DataType();
  307. }
  308. }
  309. script_class = script_class->outer;
  310. }
  311. push_error(vformat(R"("%s" is not a valid type.)", first), p_type);
  312. return GDScriptParser::DataType();
  313. }
  314. if (p_type->type_chain.size() > 1) {
  315. // TODO: Allow enums too.
  316. if (result.kind != GDScriptParser::DataType::CLASS) {
  317. push_error(R"(Only GDScript classes can have subtypes.)", p_type->type_chain[1]);
  318. return GDScriptParser::DataType();
  319. } else {
  320. for (int i = 1; i < p_type->type_chain.size(); i++) {
  321. GDScriptParser::DataType base = result;
  322. reduce_identifier_from_base(p_type->type_chain[i], &base);
  323. result = p_type->type_chain[i]->get_datatype();
  324. if (!result.is_set()) {
  325. 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]);
  326. return GDScriptParser::DataType();
  327. } else if (!result.is_meta_type) {
  328. 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]);
  329. return GDScriptParser::DataType();
  330. }
  331. }
  332. }
  333. }
  334. p_type->set_datatype(result);
  335. return result;
  336. }
  337. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class) {
  338. if (p_class->resolved_interface) {
  339. return;
  340. }
  341. p_class->resolved_interface = true;
  342. GDScriptParser::ClassNode *previous_class = parser->current_class;
  343. parser->current_class = p_class;
  344. for (int i = 0; i < p_class->members.size(); i++) {
  345. GDScriptParser::ClassNode::Member member = p_class->members[i];
  346. switch (member.type) {
  347. case GDScriptParser::ClassNode::Member::VARIABLE: {
  348. GDScriptParser::DataType datatype;
  349. datatype.kind = GDScriptParser::DataType::VARIANT;
  350. datatype.type_source = GDScriptParser::DataType::UNDETECTED;
  351. if (member.variable->initializer != nullptr) {
  352. member.variable->set_datatype(datatype); // Allow recursive usage.
  353. reduce_expression(member.variable->initializer);
  354. datatype = member.variable->initializer->get_datatype();
  355. }
  356. if (member.variable->datatype_specifier != nullptr) {
  357. datatype = resolve_datatype(member.variable->datatype_specifier);
  358. if (member.variable->initializer != nullptr) {
  359. if (!is_type_compatible(datatype, member.variable->initializer->get_datatype(), true)) {
  360. push_error(vformat(R"(Value of type "%s" cannot be assigned to variable of type "%s".)", member.variable->initializer->get_datatype().to_string(), datatype.to_string()), member.variable->initializer);
  361. } else if (datatype.builtin_type == Variant::INT && member.variable->initializer->get_datatype().builtin_type == Variant::FLOAT) {
  362. parser->push_warning(member.variable->initializer, GDScriptWarning::NARROWING_CONVERSION);
  363. }
  364. if (member.variable->initializer->get_datatype().is_variant()) {
  365. // TODO: Warn unsafe assign.
  366. mark_node_unsafe(member.variable->initializer);
  367. }
  368. }
  369. } else if (member.variable->infer_datatype) {
  370. if (member.variable->initializer == nullptr) {
  371. push_error(vformat(R"(Cannot infer the type of "%s" variable because there's no default value.)", member.variable->identifier->name), member.variable->identifier);
  372. } else if (!datatype.is_set() || datatype.has_no_type()) {
  373. 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);
  374. } else if (datatype.is_variant()) {
  375. 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);
  376. } else if (datatype.builtin_type == Variant::NIL) {
  377. push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value is "null".)", member.variable->identifier->name), member.variable->initializer);
  378. }
  379. }
  380. datatype.is_constant = false;
  381. member.variable->set_datatype(datatype);
  382. if (!datatype.has_no_type()) {
  383. // TODO: Move this out into a routine specific to validate annotations.
  384. if (member.variable->export_info.hint == PROPERTY_HINT_TYPE_STRING) {
  385. // @export annotation.
  386. switch (datatype.kind) {
  387. case GDScriptParser::DataType::BUILTIN:
  388. member.variable->export_info.hint_string = Variant::get_type_name(datatype.builtin_type);
  389. break;
  390. case GDScriptParser::DataType::NATIVE:
  391. if (ClassDB::is_parent_class(get_real_class_name(datatype.native_type), "Resource")) {
  392. member.variable->export_info.hint_string = get_real_class_name(datatype.native_type);
  393. } else {
  394. push_error(R"(Export type can only be built-in or a resource.)", member.variable);
  395. }
  396. break;
  397. default:
  398. // TODO: Allow custom user resources.
  399. push_error(R"(Export type can only be built-in or a resource.)", member.variable);
  400. break;
  401. }
  402. }
  403. }
  404. } break;
  405. case GDScriptParser::ClassNode::Member::CONSTANT: {
  406. reduce_expression(member.constant->initializer);
  407. if (!member.constant->initializer->is_constant) {
  408. push_error(R"(Initializer for a constant must be a constant expression.)", member.constant->initializer);
  409. }
  410. GDScriptParser::DataType datatype = member.constant->get_datatype();
  411. if (member.constant->datatype_specifier != nullptr) {
  412. datatype = resolve_datatype(member.constant->datatype_specifier);
  413. if (!is_type_compatible(datatype, member.constant->initializer->get_datatype(), true)) {
  414. 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);
  415. } else if (datatype.builtin_type == Variant::INT && member.constant->initializer->get_datatype().builtin_type == Variant::FLOAT) {
  416. parser->push_warning(member.constant->initializer, GDScriptWarning::NARROWING_CONVERSION);
  417. }
  418. }
  419. datatype.is_constant = true;
  420. member.constant->set_datatype(datatype);
  421. } break;
  422. case GDScriptParser::ClassNode::Member::SIGNAL: {
  423. for (int j = 0; j < member.signal->parameters.size(); j++) {
  424. member.signal->parameters[j]->set_datatype(resolve_datatype(member.signal->parameters[j]->datatype_specifier));
  425. }
  426. // TODO: Make MethodInfo from signal.
  427. GDScriptParser::DataType signal_type;
  428. signal_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  429. signal_type.kind = GDScriptParser::DataType::BUILTIN;
  430. signal_type.builtin_type = Variant::SIGNAL;
  431. member.signal->set_datatype(signal_type);
  432. } break;
  433. case GDScriptParser::ClassNode::Member::ENUM: {
  434. GDScriptParser::DataType enum_type;
  435. enum_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  436. enum_type.kind = GDScriptParser::DataType::BUILTIN;
  437. enum_type.builtin_type = Variant::DICTIONARY;
  438. member.m_enum->set_datatype(enum_type);
  439. } break;
  440. case GDScriptParser::ClassNode::Member::FUNCTION:
  441. resolve_function_signature(member.function);
  442. break;
  443. case GDScriptParser::ClassNode::Member::ENUM_VALUE:
  444. break; // Nothing to do, type and value set in parser.
  445. case GDScriptParser::ClassNode::Member::CLASS:
  446. break; // Done later.
  447. case GDScriptParser::ClassNode::Member::UNDEFINED:
  448. ERR_PRINT("Trying to resolve undefined member.");
  449. break;
  450. }
  451. }
  452. // Recurse nested classes.
  453. for (int i = 0; i < p_class->members.size(); i++) {
  454. GDScriptParser::ClassNode::Member member = p_class->members[i];
  455. if (member.type != GDScriptParser::ClassNode::Member::CLASS) {
  456. continue;
  457. }
  458. resolve_class_interface(member.m_class);
  459. }
  460. parser->current_class = previous_class;
  461. }
  462. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class) {
  463. if (p_class->resolved_body) {
  464. return;
  465. }
  466. p_class->resolved_body = true;
  467. GDScriptParser::ClassNode *previous_class = parser->current_class;
  468. parser->current_class = p_class;
  469. // Do functions now.
  470. for (int i = 0; i < p_class->members.size(); i++) {
  471. GDScriptParser::ClassNode::Member member = p_class->members[i];
  472. if (member.type != GDScriptParser::ClassNode::Member::FUNCTION) {
  473. continue;
  474. }
  475. resolve_function_body(member.function);
  476. }
  477. parser->current_class = previous_class;
  478. // Recurse nested classes.
  479. for (int i = 0; i < p_class->members.size(); i++) {
  480. GDScriptParser::ClassNode::Member member = p_class->members[i];
  481. if (member.type != GDScriptParser::ClassNode::Member::CLASS) {
  482. continue;
  483. }
  484. resolve_class_body(member.m_class);
  485. }
  486. // Check unused variables.
  487. for (int i = 0; i < p_class->members.size(); i++) {
  488. GDScriptParser::ClassNode::Member member = p_class->members[i];
  489. if (member.type != GDScriptParser::ClassNode::Member::VARIABLE) {
  490. continue;
  491. }
  492. if (member.variable->usages == 0 && String(member.variable->identifier->name).begins_with("_")) {
  493. parser->push_warning(member.variable->identifier, GDScriptWarning::UNUSED_PRIVATE_CLASS_VARIABLE, member.variable->identifier->name);
  494. }
  495. }
  496. }
  497. void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) {
  498. ERR_FAIL_COND_MSG(p_node == nullptr, "Trying to resolve type of a null node.");
  499. switch (p_node->type) {
  500. case GDScriptParser::Node::NONE:
  501. break; // Unreachable.
  502. case GDScriptParser::Node::CLASS:
  503. resolve_class_interface(static_cast<GDScriptParser::ClassNode *>(p_node));
  504. resolve_class_body(static_cast<GDScriptParser::ClassNode *>(p_node));
  505. break;
  506. case GDScriptParser::Node::CONSTANT:
  507. resolve_constant(static_cast<GDScriptParser::ConstantNode *>(p_node));
  508. break;
  509. case GDScriptParser::Node::FOR:
  510. resolve_for(static_cast<GDScriptParser::ForNode *>(p_node));
  511. break;
  512. case GDScriptParser::Node::FUNCTION:
  513. resolve_function_signature(static_cast<GDScriptParser::FunctionNode *>(p_node));
  514. resolve_function_body(static_cast<GDScriptParser::FunctionNode *>(p_node));
  515. break;
  516. case GDScriptParser::Node::IF:
  517. resolve_if(static_cast<GDScriptParser::IfNode *>(p_node));
  518. break;
  519. case GDScriptParser::Node::SUITE:
  520. resolve_suite(static_cast<GDScriptParser::SuiteNode *>(p_node));
  521. break;
  522. case GDScriptParser::Node::VARIABLE:
  523. resolve_variable(static_cast<GDScriptParser::VariableNode *>(p_node));
  524. break;
  525. case GDScriptParser::Node::WHILE:
  526. resolve_while(static_cast<GDScriptParser::WhileNode *>(p_node));
  527. break;
  528. case GDScriptParser::Node::ANNOTATION:
  529. resolve_annotation(static_cast<GDScriptParser::AnnotationNode *>(p_node));
  530. break;
  531. case GDScriptParser::Node::ASSERT:
  532. resolve_assert(static_cast<GDScriptParser::AssertNode *>(p_node));
  533. break;
  534. case GDScriptParser::Node::MATCH:
  535. resolve_match(static_cast<GDScriptParser::MatchNode *>(p_node));
  536. break;
  537. case GDScriptParser::Node::MATCH_BRANCH:
  538. resolve_match_branch(static_cast<GDScriptParser::MatchBranchNode *>(p_node), nullptr);
  539. break;
  540. case GDScriptParser::Node::PARAMETER:
  541. resolve_pararameter(static_cast<GDScriptParser::ParameterNode *>(p_node));
  542. break;
  543. case GDScriptParser::Node::PATTERN:
  544. resolve_match_pattern(static_cast<GDScriptParser::PatternNode *>(p_node), nullptr);
  545. break;
  546. case GDScriptParser::Node::RETURN:
  547. resolve_return(static_cast<GDScriptParser::ReturnNode *>(p_node));
  548. break;
  549. case GDScriptParser::Node::TYPE:
  550. resolve_datatype(static_cast<GDScriptParser::TypeNode *>(p_node));
  551. break;
  552. // Resolving expression is the same as reducing them.
  553. case GDScriptParser::Node::ARRAY:
  554. case GDScriptParser::Node::ASSIGNMENT:
  555. case GDScriptParser::Node::AWAIT:
  556. case GDScriptParser::Node::BINARY_OPERATOR:
  557. case GDScriptParser::Node::CALL:
  558. case GDScriptParser::Node::CAST:
  559. case GDScriptParser::Node::DICTIONARY:
  560. case GDScriptParser::Node::GET_NODE:
  561. case GDScriptParser::Node::IDENTIFIER:
  562. case GDScriptParser::Node::LITERAL:
  563. case GDScriptParser::Node::PRELOAD:
  564. case GDScriptParser::Node::SELF:
  565. case GDScriptParser::Node::SUBSCRIPT:
  566. case GDScriptParser::Node::TERNARY_OPERATOR:
  567. case GDScriptParser::Node::UNARY_OPERATOR:
  568. reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node));
  569. break;
  570. case GDScriptParser::Node::BREAK:
  571. case GDScriptParser::Node::BREAKPOINT:
  572. case GDScriptParser::Node::CONTINUE:
  573. case GDScriptParser::Node::ENUM:
  574. case GDScriptParser::Node::PASS:
  575. case GDScriptParser::Node::SIGNAL:
  576. // Nothing to do.
  577. break;
  578. }
  579. }
  580. void GDScriptAnalyzer::resolve_annotation(GDScriptParser::AnnotationNode *p_annotation) {
  581. // TODO: Add second validation function for annotations, so they can use checked types.
  582. }
  583. void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode *p_function) {
  584. if (p_function->resolved_signature) {
  585. return;
  586. }
  587. p_function->resolved_signature = true;
  588. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  589. parser->current_function = p_function;
  590. for (int i = 0; i < p_function->parameters.size(); i++) {
  591. resolve_pararameter(p_function->parameters[i]);
  592. if (p_function->parameters[i]->usages == 0 && !String(p_function->parameters[i]->identifier->name).begins_with("_")) {
  593. parser->push_warning(p_function->parameters[i]->identifier, GDScriptWarning::UNUSED_PARAMETER, p_function->identifier->name, p_function->parameters[i]->identifier->name);
  594. }
  595. is_shadowing(p_function->parameters[i]->identifier, "function parameter");
  596. }
  597. p_function->set_datatype(resolve_datatype(p_function->return_type));
  598. parser->current_function = previous_function;
  599. }
  600. void GDScriptAnalyzer::resolve_function_body(GDScriptParser::FunctionNode *p_function) {
  601. if (p_function->resolved_body) {
  602. return;
  603. }
  604. p_function->resolved_body = true;
  605. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  606. parser->current_function = p_function;
  607. resolve_suite(p_function->body);
  608. GDScriptParser::DataType return_type = p_function->body->get_datatype();
  609. if (p_function->get_datatype().has_no_type() && return_type.is_set()) {
  610. // Use the suite inferred type if return isn't explicitly set.
  611. return_type.type_source = GDScriptParser::DataType::INFERRED;
  612. p_function->set_datatype(p_function->body->get_datatype());
  613. } 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)) {
  614. if (!p_function->body->has_return) {
  615. push_error(R"(Not all code paths return a value.)", p_function);
  616. }
  617. }
  618. parser->current_function = previous_function;
  619. }
  620. void GDScriptAnalyzer::decide_suite_type(GDScriptParser::Node *p_suite, GDScriptParser::Node *p_statement) {
  621. switch (p_statement->type) {
  622. case GDScriptParser::Node::IF:
  623. case GDScriptParser::Node::FOR:
  624. case GDScriptParser::Node::MATCH:
  625. case GDScriptParser::Node::PATTERN:
  626. case GDScriptParser::Node::RETURN:
  627. case GDScriptParser::Node::WHILE:
  628. // Use return or nested suite type as this suite type.
  629. if (p_suite->get_datatype().is_set() && (p_suite->get_datatype() != p_statement->get_datatype())) {
  630. // Mixed types.
  631. // TODO: This could use the common supertype instead.
  632. p_suite->datatype.kind = GDScriptParser::DataType::VARIANT;
  633. p_suite->datatype.type_source = GDScriptParser::DataType::UNDETECTED;
  634. } else {
  635. p_suite->set_datatype(p_statement->get_datatype());
  636. }
  637. break;
  638. default:
  639. break;
  640. }
  641. }
  642. void GDScriptAnalyzer::resolve_suite(GDScriptParser::SuiteNode *p_suite) {
  643. for (int i = 0; i < p_suite->statements.size(); i++) {
  644. GDScriptParser::Node *stmt = p_suite->statements[i];
  645. resolve_node(stmt);
  646. decide_suite_type(p_suite, stmt);
  647. }
  648. }
  649. void GDScriptAnalyzer::resolve_if(GDScriptParser::IfNode *p_if) {
  650. reduce_expression(p_if->condition);
  651. resolve_suite(p_if->true_block);
  652. p_if->set_datatype(p_if->true_block->get_datatype());
  653. if (p_if->false_block != nullptr) {
  654. resolve_suite(p_if->false_block);
  655. decide_suite_type(p_if, p_if->false_block);
  656. }
  657. }
  658. void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {
  659. bool list_resolved = false;
  660. // Optimize constant range() call to not allocate an array.
  661. // Use int, Vector2, Vector3 instead, which also can be used as range iterators.
  662. if (p_for->list->type == GDScriptParser::Node::CALL) {
  663. GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(p_for->list);
  664. if (call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  665. GDScriptParser::IdentifierNode *callee = static_cast<GDScriptParser::IdentifierNode *>(call->callee);
  666. if (callee->name == "range") {
  667. list_resolved = true;
  668. if (call->arguments.size() < 1) {
  669. push_error(R"*(Invalid call for "range()" function. Expected at least 1 argument, none given.)*", call->callee);
  670. } else if (call->arguments.size() > 3) {
  671. push_error(vformat(R"*(Invalid call for "range()" function. Expected at most 3 arguments, %d given.)*", call->arguments.size()), call->callee);
  672. } else {
  673. // Now we can optimize it.
  674. bool all_is_constant = true;
  675. Vector<Variant> args;
  676. args.resize(call->arguments.size());
  677. for (int i = 0; i < call->arguments.size(); i++) {
  678. reduce_expression(call->arguments[i]);
  679. if (!call->arguments[i]->is_constant) {
  680. all_is_constant = false;
  681. } else {
  682. args.write[i] = call->arguments[i]->reduced_value;
  683. }
  684. GDScriptParser::DataType arg_type = call->arguments[i]->get_datatype();
  685. if (arg_type.kind != GDScriptParser::DataType::BUILTIN) {
  686. all_is_constant = false;
  687. 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]);
  688. } else if (arg_type.builtin_type != Variant::INT && arg_type.builtin_type != Variant::FLOAT) {
  689. all_is_constant = false;
  690. 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]);
  691. }
  692. }
  693. Variant reduced;
  694. if (all_is_constant) {
  695. switch (args.size()) {
  696. case 1:
  697. reduced = args[0];
  698. break;
  699. case 2:
  700. reduced = Vector2i(args[0], args[1]);
  701. break;
  702. case 3:
  703. reduced = Vector3i(args[0], args[1], args[2]);
  704. break;
  705. }
  706. p_for->list->is_constant = true;
  707. p_for->list->reduced_value = reduced;
  708. }
  709. }
  710. GDScriptParser::DataType list_type;
  711. list_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  712. list_type.kind = GDScriptParser::DataType::BUILTIN;
  713. list_type.builtin_type = Variant::ARRAY;
  714. p_for->list->set_datatype(list_type);
  715. }
  716. }
  717. }
  718. if (!list_resolved) {
  719. resolve_node(p_for->list);
  720. }
  721. // TODO: If list is a typed array, the variable should be an element.
  722. // Also applicable for constant range() (so variable is int or float).
  723. resolve_suite(p_for->loop);
  724. p_for->set_datatype(p_for->loop->get_datatype());
  725. is_shadowing(p_for->variable, R"("for" iterator variable)");
  726. }
  727. void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) {
  728. resolve_node(p_while->condition);
  729. resolve_suite(p_while->loop);
  730. p_while->set_datatype(p_while->loop->get_datatype());
  731. }
  732. void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable) {
  733. GDScriptParser::DataType type;
  734. type.kind = GDScriptParser::DataType::VARIANT; // By default.
  735. if (p_variable->initializer != nullptr) {
  736. reduce_expression(p_variable->initializer);
  737. type = p_variable->initializer->get_datatype();
  738. if (p_variable->infer_datatype) {
  739. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  740. if (type.has_no_type()) {
  741. 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);
  742. } else if (type.is_variant()) {
  743. 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);
  744. } else if (type.builtin_type == Variant::NIL) {
  745. 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);
  746. }
  747. } else {
  748. type.type_source = GDScriptParser::DataType::INFERRED;
  749. }
  750. if (p_variable->initializer->type == GDScriptParser::Node::CALL && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
  751. parser->push_warning(p_variable->initializer, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_variable->initializer)->function_name);
  752. }
  753. }
  754. if (p_variable->datatype_specifier != nullptr) {
  755. type = resolve_datatype(p_variable->datatype_specifier);
  756. if (p_variable->initializer != nullptr) {
  757. if (!is_type_compatible(type, p_variable->initializer->get_datatype(), true)) {
  758. push_error(vformat(R"(Value of type "%s" cannot be assigned to variable of type "%s".)", p_variable->initializer->get_datatype().to_string(), type.to_string()), p_variable->initializer);
  759. } else if (type.builtin_type == Variant::INT && p_variable->initializer->get_datatype().builtin_type == Variant::FLOAT) {
  760. parser->push_warning(p_variable->initializer, GDScriptWarning::NARROWING_CONVERSION);
  761. }
  762. if (p_variable->initializer->get_datatype().is_variant()) {
  763. // TODO: Warn unsafe assign.
  764. mark_node_unsafe(p_variable->initializer);
  765. }
  766. }
  767. } else if (p_variable->infer_datatype) {
  768. if (type.has_no_type()) {
  769. 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);
  770. }
  771. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  772. }
  773. type.is_constant = false;
  774. p_variable->set_datatype(type);
  775. if (p_variable->usages == 0 && !String(p_variable->identifier->name).begins_with("_")) {
  776. parser->push_warning(p_variable, GDScriptWarning::UNUSED_VARIABLE, p_variable->identifier->name);
  777. } else if (p_variable->assignments == 0) {
  778. parser->push_warning(p_variable, GDScriptWarning::UNASSIGNED_VARIABLE, p_variable->identifier->name);
  779. }
  780. is_shadowing(p_variable->identifier, "variable");
  781. }
  782. void GDScriptAnalyzer::resolve_constant(GDScriptParser::ConstantNode *p_constant) {
  783. GDScriptParser::DataType type;
  784. reduce_expression(p_constant->initializer);
  785. if (!p_constant->initializer->is_constant) {
  786. push_error(vformat(R"(Assigned value for constant "%s" isn't a constant expression.)", p_constant->identifier->name), p_constant->initializer);
  787. }
  788. type = p_constant->initializer->get_datatype();
  789. if (p_constant->initializer->type == GDScriptParser::Node::CALL && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
  790. parser->push_warning(p_constant->initializer, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_constant->initializer)->function_name);
  791. }
  792. if (p_constant->datatype_specifier != nullptr) {
  793. GDScriptParser::DataType explicit_type = resolve_datatype(p_constant->datatype_specifier);
  794. if (!is_type_compatible(explicit_type, type)) {
  795. 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);
  796. } else if (explicit_type.builtin_type == Variant::INT && type.builtin_type == Variant::FLOAT) {
  797. parser->push_warning(p_constant->initializer, GDScriptWarning::NARROWING_CONVERSION);
  798. }
  799. type = explicit_type;
  800. } else if (p_constant->infer_datatype) {
  801. if (type.has_no_type()) {
  802. 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);
  803. }
  804. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  805. }
  806. type.is_constant = true;
  807. p_constant->set_datatype(type);
  808. if (p_constant->usages == 0) {
  809. parser->push_warning(p_constant, GDScriptWarning::UNUSED_LOCAL_CONSTANT, p_constant->identifier->name);
  810. }
  811. is_shadowing(p_constant->identifier, "constant");
  812. }
  813. void GDScriptAnalyzer::resolve_assert(GDScriptParser::AssertNode *p_assert) {
  814. reduce_expression(p_assert->condition);
  815. if (p_assert->message != nullptr) {
  816. reduce_literal(p_assert->message);
  817. }
  818. p_assert->set_datatype(p_assert->condition->get_datatype());
  819. if (p_assert->condition->is_constant) {
  820. if (p_assert->condition->reduced_value.booleanize()) {
  821. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_TRUE);
  822. } else {
  823. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_FALSE);
  824. }
  825. }
  826. }
  827. void GDScriptAnalyzer::resolve_match(GDScriptParser::MatchNode *p_match) {
  828. reduce_expression(p_match->test);
  829. for (int i = 0; i < p_match->branches.size(); i++) {
  830. resolve_match_branch(p_match->branches[i], p_match->test);
  831. decide_suite_type(p_match, p_match->branches[i]);
  832. }
  833. }
  834. void GDScriptAnalyzer::resolve_match_branch(GDScriptParser::MatchBranchNode *p_match_branch, GDScriptParser::ExpressionNode *p_match_test) {
  835. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  836. resolve_match_pattern(p_match_branch->patterns[i], p_match_test);
  837. }
  838. resolve_suite(p_match_branch->block);
  839. decide_suite_type(p_match_branch, p_match_branch->block);
  840. }
  841. void GDScriptAnalyzer::resolve_match_pattern(GDScriptParser::PatternNode *p_match_pattern, GDScriptParser::ExpressionNode *p_match_test) {
  842. GDScriptParser::DataType result;
  843. switch (p_match_pattern->pattern_type) {
  844. case GDScriptParser::PatternNode::PT_LITERAL:
  845. reduce_literal(p_match_pattern->literal);
  846. result = p_match_pattern->literal->get_datatype();
  847. break;
  848. case GDScriptParser::PatternNode::PT_EXPRESSION:
  849. reduce_expression(p_match_pattern->expression);
  850. if (!p_match_pattern->expression->is_constant) {
  851. push_error(R"(Expression in match pattern must be a constant.)", p_match_pattern->expression);
  852. }
  853. result = p_match_pattern->expression->get_datatype();
  854. break;
  855. case GDScriptParser::PatternNode::PT_BIND:
  856. if (p_match_test != nullptr) {
  857. result = p_match_test->get_datatype();
  858. } else {
  859. result.kind = GDScriptParser::DataType::VARIANT;
  860. }
  861. p_match_pattern->bind->set_datatype(result);
  862. is_shadowing(p_match_pattern->bind, "pattern bind");
  863. if (p_match_pattern->bind->usages == 0) {
  864. parser->push_warning(p_match_pattern->bind, GDScriptWarning::UNASSIGNED_VARIABLE, p_match_pattern->bind->name);
  865. }
  866. break;
  867. case GDScriptParser::PatternNode::PT_ARRAY:
  868. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  869. resolve_match_pattern(p_match_pattern->array[i], nullptr);
  870. decide_suite_type(p_match_pattern, p_match_pattern->array[i]);
  871. }
  872. result = p_match_pattern->get_datatype();
  873. break;
  874. case GDScriptParser::PatternNode::PT_DICTIONARY:
  875. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  876. reduce_expression(p_match_pattern->dictionary[i].key);
  877. if (!p_match_pattern->dictionary[i].key->is_constant) {
  878. push_error(R"(Expression in dictionary pattern key must be a constant.)", p_match_pattern->expression);
  879. }
  880. resolve_match_pattern(p_match_pattern->dictionary[i].value_pattern, nullptr);
  881. decide_suite_type(p_match_pattern, p_match_pattern->dictionary[i].value_pattern);
  882. }
  883. result = p_match_pattern->get_datatype();
  884. break;
  885. case GDScriptParser::PatternNode::PT_WILDCARD:
  886. case GDScriptParser::PatternNode::PT_REST:
  887. result.kind = GDScriptParser::DataType::VARIANT;
  888. break;
  889. }
  890. p_match_pattern->set_datatype(result);
  891. }
  892. void GDScriptAnalyzer::resolve_pararameter(GDScriptParser::ParameterNode *p_parameter) {
  893. GDScriptParser::DataType result;
  894. result.kind = GDScriptParser::DataType::VARIANT;
  895. if (p_parameter->default_value != nullptr) {
  896. reduce_expression(p_parameter->default_value);
  897. result = p_parameter->default_value->get_datatype();
  898. result.type_source = GDScriptParser::DataType::INFERRED;
  899. }
  900. if (p_parameter->datatype_specifier != nullptr) {
  901. resolve_datatype(p_parameter->datatype_specifier);
  902. if (p_parameter->default_value != nullptr) {
  903. if (!is_type_compatible(p_parameter->datatype_specifier->get_datatype(), p_parameter->default_value->get_datatype())) {
  904. push_error(vformat(R"(Type of default value for parameter "%s" (%s) is not compatible with paremeter 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);
  905. }
  906. }
  907. result = p_parameter->datatype_specifier->get_datatype();
  908. }
  909. p_parameter->set_datatype(result);
  910. }
  911. void GDScriptAnalyzer::resolve_return(GDScriptParser::ReturnNode *p_return) {
  912. GDScriptParser::DataType result;
  913. if (p_return->return_value != nullptr) {
  914. reduce_expression(p_return->return_value);
  915. result = p_return->return_value->get_datatype();
  916. } else {
  917. // Return type is null by default.
  918. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  919. result.kind = GDScriptParser::DataType::BUILTIN;
  920. result.builtin_type = Variant::NIL;
  921. result.is_constant = true;
  922. }
  923. GDScriptParser::DataType function_type = parser->current_function->get_datatype();
  924. if (function_type.is_hard_type()) {
  925. if (!is_type_compatible(function_type, result)) {
  926. // Try other way. Okay but not safe.
  927. if (!is_type_compatible(result, function_type)) {
  928. 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);
  929. } else {
  930. // TODO: Add warning.
  931. mark_node_unsafe(p_return);
  932. }
  933. } else if (function_type.builtin_type == Variant::INT && result.builtin_type == Variant::FLOAT) {
  934. parser->push_warning(p_return, GDScriptWarning::NARROWING_CONVERSION);
  935. } else if (result.is_variant()) {
  936. mark_node_unsafe(p_return);
  937. }
  938. }
  939. p_return->set_datatype(result);
  940. }
  941. void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expression) {
  942. // This one makes some magic happen.
  943. if (p_expression->reduced) {
  944. // Don't do this more than once.
  945. return;
  946. }
  947. p_expression->reduced = true;
  948. switch (p_expression->type) {
  949. case GDScriptParser::Node::ARRAY:
  950. reduce_array(static_cast<GDScriptParser::ArrayNode *>(p_expression));
  951. break;
  952. case GDScriptParser::Node::ASSIGNMENT:
  953. reduce_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
  954. break;
  955. case GDScriptParser::Node::AWAIT:
  956. reduce_await(static_cast<GDScriptParser::AwaitNode *>(p_expression));
  957. break;
  958. case GDScriptParser::Node::BINARY_OPERATOR:
  959. reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));
  960. break;
  961. case GDScriptParser::Node::CALL:
  962. reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression));
  963. break;
  964. case GDScriptParser::Node::CAST:
  965. reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));
  966. break;
  967. case GDScriptParser::Node::DICTIONARY:
  968. reduce_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_expression));
  969. break;
  970. case GDScriptParser::Node::GET_NODE:
  971. reduce_get_node(static_cast<GDScriptParser::GetNodeNode *>(p_expression));
  972. break;
  973. case GDScriptParser::Node::IDENTIFIER:
  974. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression));
  975. break;
  976. case GDScriptParser::Node::LITERAL:
  977. reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression));
  978. break;
  979. case GDScriptParser::Node::PRELOAD:
  980. reduce_preload(static_cast<GDScriptParser::PreloadNode *>(p_expression));
  981. break;
  982. case GDScriptParser::Node::SELF:
  983. reduce_self(static_cast<GDScriptParser::SelfNode *>(p_expression));
  984. break;
  985. case GDScriptParser::Node::SUBSCRIPT:
  986. reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_expression));
  987. break;
  988. case GDScriptParser::Node::TERNARY_OPERATOR:
  989. reduce_ternary_op(static_cast<GDScriptParser::TernaryOpNode *>(p_expression));
  990. break;
  991. case GDScriptParser::Node::UNARY_OPERATOR:
  992. reduce_unary_op(static_cast<GDScriptParser::UnaryOpNode *>(p_expression));
  993. break;
  994. // Non-expressions. Here only to make sure new nodes aren't forgotten.
  995. case GDScriptParser::Node::NONE:
  996. case GDScriptParser::Node::ANNOTATION:
  997. case GDScriptParser::Node::ASSERT:
  998. case GDScriptParser::Node::BREAK:
  999. case GDScriptParser::Node::BREAKPOINT:
  1000. case GDScriptParser::Node::CLASS:
  1001. case GDScriptParser::Node::CONSTANT:
  1002. case GDScriptParser::Node::CONTINUE:
  1003. case GDScriptParser::Node::ENUM:
  1004. case GDScriptParser::Node::FOR:
  1005. case GDScriptParser::Node::FUNCTION:
  1006. case GDScriptParser::Node::IF:
  1007. case GDScriptParser::Node::MATCH:
  1008. case GDScriptParser::Node::MATCH_BRANCH:
  1009. case GDScriptParser::Node::PARAMETER:
  1010. case GDScriptParser::Node::PASS:
  1011. case GDScriptParser::Node::PATTERN:
  1012. case GDScriptParser::Node::RETURN:
  1013. case GDScriptParser::Node::SIGNAL:
  1014. case GDScriptParser::Node::SUITE:
  1015. case GDScriptParser::Node::TYPE:
  1016. case GDScriptParser::Node::VARIABLE:
  1017. case GDScriptParser::Node::WHILE:
  1018. ERR_FAIL_MSG("Reaching unreachable case");
  1019. }
  1020. }
  1021. void GDScriptAnalyzer::reduce_array(GDScriptParser::ArrayNode *p_array) {
  1022. bool all_is_constant = true;
  1023. for (int i = 0; i < p_array->elements.size(); i++) {
  1024. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  1025. reduce_expression(element);
  1026. all_is_constant = all_is_constant && element->is_constant;
  1027. }
  1028. if (all_is_constant) {
  1029. Array array;
  1030. array.resize(p_array->elements.size());
  1031. for (int i = 0; i < p_array->elements.size(); i++) {
  1032. array[i] = p_array->elements[i]->reduced_value;
  1033. }
  1034. p_array->is_constant = true;
  1035. p_array->reduced_value = array;
  1036. }
  1037. // It's array in any case.
  1038. GDScriptParser::DataType arr_type;
  1039. arr_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1040. arr_type.kind = GDScriptParser::DataType::BUILTIN;
  1041. arr_type.builtin_type = Variant::ARRAY;
  1042. arr_type.is_constant = true;
  1043. p_array->set_datatype(arr_type);
  1044. }
  1045. void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assignment) {
  1046. reduce_expression(p_assignment->assignee);
  1047. reduce_expression(p_assignment->assigned_value);
  1048. if (p_assignment->assignee->get_datatype().is_constant) {
  1049. push_error("Cannot assign a new value to a constant.", p_assignment->assignee);
  1050. }
  1051. if (!is_type_compatible(p_assignment->assignee->get_datatype(), p_assignment->assigned_value->get_datatype())) {
  1052. if (p_assignment->assignee->get_datatype().is_hard_type()) {
  1053. 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);
  1054. } else {
  1055. // TODO: Warning in this case.
  1056. }
  1057. }
  1058. if (p_assignment->assignee->get_datatype().has_no_type() || p_assignment->assigned_value->get_datatype().is_variant()) {
  1059. mark_node_unsafe(p_assignment);
  1060. }
  1061. if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
  1062. // Change source type so it's not wrongly detected later.
  1063. GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee);
  1064. switch (identifier->source) {
  1065. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {
  1066. GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
  1067. if (!id_type.is_hard_type()) {
  1068. id_type.kind = GDScriptParser::DataType::VARIANT;
  1069. id_type.type_source = GDScriptParser::DataType::UNDETECTED;
  1070. identifier->variable_source->set_datatype(id_type);
  1071. }
  1072. } break;
  1073. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {
  1074. GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
  1075. if (!id_type.is_hard_type()) {
  1076. id_type = p_assignment->assigned_value->get_datatype();
  1077. id_type.type_source = GDScriptParser::DataType::INFERRED;
  1078. id_type.is_constant = false;
  1079. identifier->variable_source->set_datatype(id_type);
  1080. }
  1081. } break;
  1082. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {
  1083. GDScriptParser::DataType id_type = identifier->bind_source->get_datatype();
  1084. if (!id_type.is_hard_type()) {
  1085. id_type = p_assignment->assigned_value->get_datatype();
  1086. id_type.type_source = GDScriptParser::DataType::INFERRED;
  1087. id_type.is_constant = false;
  1088. identifier->variable_source->set_datatype(id_type);
  1089. }
  1090. } break;
  1091. default:
  1092. // Nothing to do.
  1093. break;
  1094. }
  1095. }
  1096. GDScriptParser::DataType assignee_type = p_assignment->assignee->get_datatype();
  1097. GDScriptParser::DataType assigned_type = p_assignment->assigned_value->get_datatype();
  1098. if (p_assignment->assigned_value->type == GDScriptParser::Node::CALL && assigned_type.kind == GDScriptParser::DataType::BUILTIN && assigned_type.builtin_type == Variant::NIL) {
  1099. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_assignment->assigned_value)->function_name);
  1100. } else if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_type.builtin_type == Variant::FLOAT) {
  1101. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION);
  1102. }
  1103. }
  1104. void GDScriptAnalyzer::reduce_await(GDScriptParser::AwaitNode *p_await) {
  1105. if (p_await->to_await->type == GDScriptParser::Node::CALL) {
  1106. reduce_call(static_cast<GDScriptParser::CallNode *>(p_await->to_await), true);
  1107. } else {
  1108. reduce_expression(p_await->to_await);
  1109. }
  1110. p_await->is_constant = p_await->to_await->is_constant;
  1111. p_await->reduced_value = p_await->to_await->reduced_value;
  1112. GDScriptParser::DataType awaiting_type = p_await->to_await->get_datatype();
  1113. p_await->set_datatype(awaiting_type);
  1114. if (!awaiting_type.is_coroutine && awaiting_type.builtin_type != Variant::SIGNAL) {
  1115. parser->push_warning(p_await, GDScriptWarning::REDUNDANT_AWAIT);
  1116. }
  1117. }
  1118. void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op) {
  1119. reduce_expression(p_binary_op->left_operand);
  1120. reduce_expression(p_binary_op->right_operand);
  1121. // TODO: Right operand must be a valid type with the `is` operator. Need to check here.
  1122. GDScriptParser::DataType left_type = p_binary_op->left_operand->get_datatype();
  1123. GDScriptParser::DataType right_type = p_binary_op->right_operand->get_datatype();
  1124. if (p_binary_op->variant_op == Variant::OP_DIVIDE && left_type.builtin_type == Variant::INT && right_type.builtin_type == Variant::INT) {
  1125. parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);
  1126. }
  1127. if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {
  1128. p_binary_op->is_constant = true;
  1129. if (p_binary_op->variant_op < Variant::OP_MAX) {
  1130. p_binary_op->reduced_value = Variant::evaluate(p_binary_op->variant_op, p_binary_op->left_operand->reduced_value, p_binary_op->right_operand->reduced_value);
  1131. } else {
  1132. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  1133. GDScriptParser::DataType test_type = right_type;
  1134. test_type.is_meta_type = false;
  1135. if (!is_type_compatible(test_type, p_binary_op->left_operand->get_datatype(), false)) {
  1136. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)"), p_binary_op->left_operand);
  1137. p_binary_op->reduced_value = false;
  1138. } else {
  1139. p_binary_op->reduced_value = true;
  1140. }
  1141. } else {
  1142. ERR_PRINT("Parser bug: unknown binary operation.");
  1143. }
  1144. }
  1145. p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value));
  1146. return;
  1147. }
  1148. GDScriptParser::DataType result;
  1149. if (left_type.is_variant() || right_type.is_variant()) {
  1150. // Cannot infer type because one operand can be anything.
  1151. result.kind = GDScriptParser::DataType::VARIANT;
  1152. mark_node_unsafe(p_binary_op);
  1153. } else {
  1154. if (p_binary_op->variant_op < Variant::OP_MAX) {
  1155. bool valid = false;
  1156. result = get_operation_type(p_binary_op->variant_op, p_binary_op->left_operand->get_datatype(), right_type, valid);
  1157. if (!valid) {
  1158. 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);
  1159. }
  1160. } else {
  1161. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  1162. GDScriptParser::DataType test_type = right_type;
  1163. test_type.is_meta_type = false;
  1164. if (!is_type_compatible(test_type, p_binary_op->left_operand->get_datatype(), false)) {
  1165. if (p_binary_op->left_operand->get_datatype().is_hard_type()) {
  1166. 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);
  1167. } else {
  1168. // TODO: Warning.
  1169. mark_node_unsafe(p_binary_op);
  1170. }
  1171. }
  1172. // "is" operator is always a boolean anyway.
  1173. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1174. result.kind = GDScriptParser::DataType::BUILTIN;
  1175. result.builtin_type = Variant::BOOL;
  1176. } else {
  1177. ERR_PRINT("Parser bug: unknown binary operation.");
  1178. }
  1179. }
  1180. }
  1181. p_binary_op->set_datatype(result);
  1182. }
  1183. void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool is_await) {
  1184. bool all_is_constant = true;
  1185. for (int i = 0; i < p_call->arguments.size(); i++) {
  1186. reduce_expression(p_call->arguments[i]);
  1187. all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;
  1188. }
  1189. GDScriptParser::DataType call_type;
  1190. if (!p_call->is_super && p_call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  1191. // Call to name directly.
  1192. StringName function_name = p_call->function_name;
  1193. Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);
  1194. GDScriptFunctions::Function builtin_function = GDScriptParser::get_builtin_function(function_name);
  1195. if (builtin_type < Variant::VARIANT_MAX) {
  1196. // Is a builtin constructor.
  1197. call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1198. call_type.kind = GDScriptParser::DataType::BUILTIN;
  1199. call_type.builtin_type = builtin_type;
  1200. if (builtin_type == Variant::OBJECT) {
  1201. call_type.kind = GDScriptParser::DataType::NATIVE;
  1202. call_type.native_type = function_name; // "Object".
  1203. }
  1204. if (all_is_constant) {
  1205. // Construct here.
  1206. Vector<const Variant *> args;
  1207. for (int i = 0; i < p_call->arguments.size(); i++) {
  1208. args.push_back(&(p_call->arguments[i]->reduced_value));
  1209. }
  1210. Callable::CallError err;
  1211. Variant value = Variant::construct(builtin_type, (const Variant **)args.ptr(), args.size(), err);
  1212. switch (err.error) {
  1213. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  1214. 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,
  1215. Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),
  1216. p_call->arguments[err.argument]);
  1217. break;
  1218. case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
  1219. String signature = Variant::get_type_name(builtin_type) + "(";
  1220. for (int i = 0; i < p_call->arguments.size(); i++) {
  1221. if (i > 0) {
  1222. signature += ", ";
  1223. }
  1224. signature += p_call->arguments[i]->get_datatype().to_string();
  1225. }
  1226. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);
  1227. } break;
  1228. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  1229. 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);
  1230. break;
  1231. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  1232. 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);
  1233. break;
  1234. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  1235. break; // Can't happen in a builtin constructor.
  1236. case Callable::CallError::CALL_OK:
  1237. p_call->is_constant = true;
  1238. p_call->reduced_value = value;
  1239. break;
  1240. }
  1241. } else {
  1242. // TODO: Check constructors without constants.
  1243. // If there's one argument, try to use copy constructor (those aren't explicitly defined).
  1244. if (p_call->arguments.size() == 1) {
  1245. GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();
  1246. if (arg_type.is_variant()) {
  1247. mark_node_unsafe(p_call->arguments[0]);
  1248. } else {
  1249. if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {
  1250. // Okay.
  1251. p_call->set_datatype(call_type);
  1252. return;
  1253. }
  1254. }
  1255. }
  1256. List<MethodInfo> constructors;
  1257. Variant::get_constructor_list(builtin_type, &constructors);
  1258. bool match = false;
  1259. for (const List<MethodInfo>::Element *E = constructors.front(); E != nullptr; E = E->next()) {
  1260. const MethodInfo &info = E->get();
  1261. if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  1262. continue;
  1263. }
  1264. if (p_call->arguments.size() > info.arguments.size()) {
  1265. continue;
  1266. }
  1267. bool types_match = true;
  1268. for (int i = 0; i < p_call->arguments.size(); i++) {
  1269. GDScriptParser::DataType par_type = type_from_property(info.arguments[i]);
  1270. if (!is_type_compatible(par_type, p_call->arguments[i]->get_datatype())) {
  1271. types_match = false;
  1272. break;
  1273. } else {
  1274. if (par_type.builtin_type == Variant::INT && p_call->arguments[i]->get_datatype().builtin_type == Variant::FLOAT) {
  1275. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  1276. }
  1277. }
  1278. }
  1279. if (types_match) {
  1280. match = true;
  1281. call_type = type_from_property(info.return_val);
  1282. break;
  1283. }
  1284. }
  1285. if (!match) {
  1286. String signature = Variant::get_type_name(builtin_type) + "(";
  1287. for (int i = 0; i < p_call->arguments.size(); i++) {
  1288. if (i > 0) {
  1289. signature += ", ";
  1290. }
  1291. signature += p_call->arguments[i]->get_datatype().to_string();
  1292. }
  1293. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);
  1294. }
  1295. }
  1296. p_call->set_datatype(call_type);
  1297. return;
  1298. } else if (builtin_function < GDScriptFunctions::FUNC_MAX) {
  1299. MethodInfo function_info = GDScriptFunctions::get_info(builtin_function);
  1300. if (all_is_constant && GDScriptFunctions::is_deterministic(builtin_function)) {
  1301. // Can call on compilation.
  1302. Vector<const Variant *> args;
  1303. for (int i = 0; i < p_call->arguments.size(); i++) {
  1304. args.push_back(&(p_call->arguments[i]->reduced_value));
  1305. }
  1306. Variant value;
  1307. Callable::CallError err;
  1308. GDScriptFunctions::call(builtin_function, (const Variant **)args.ptr(), args.size(), value, err);
  1309. switch (err.error) {
  1310. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  1311. PropertyInfo wrong_arg = function_info.arguments[err.argument];
  1312. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*", GDScriptFunctions::get_func_name(builtin_function), err.argument + 1,
  1313. type_from_property(wrong_arg).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()),
  1314. p_call->arguments[err.argument]);
  1315. } break;
  1316. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  1317. push_error(vformat(R"(Invalid call for function "%s".)", GDScriptFunctions::get_func_name(builtin_function)), p_call);
  1318. break;
  1319. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  1320. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", GDScriptFunctions::get_func_name(builtin_function), err.expected, p_call->arguments.size()), p_call);
  1321. break;
  1322. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  1323. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", GDScriptFunctions::get_func_name(builtin_function), err.expected, p_call->arguments.size()), p_call);
  1324. break;
  1325. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  1326. break; // Can't happen in a builtin constructor.
  1327. case Callable::CallError::CALL_OK:
  1328. p_call->is_constant = true;
  1329. p_call->reduced_value = value;
  1330. break;
  1331. }
  1332. } else {
  1333. validate_call_arg(function_info, p_call);
  1334. }
  1335. p_call->set_datatype(type_from_property(function_info.return_val));
  1336. return;
  1337. }
  1338. }
  1339. GDScriptParser::DataType base_type;
  1340. call_type.kind = GDScriptParser::DataType::VARIANT;
  1341. bool is_self = false;
  1342. if (p_call->is_super) {
  1343. base_type = parser->current_class->base_type;
  1344. is_self = true;
  1345. } else if (p_call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  1346. base_type = parser->current_class->get_datatype();
  1347. is_self = true;
  1348. } else if (p_call->callee->type == GDScriptParser::Node::SUBSCRIPT) {
  1349. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);
  1350. if (!subscript->is_attribute) {
  1351. // Invalid call. Error already sent in parser.
  1352. // TODO: Could check if Callable here.
  1353. p_call->set_datatype(call_type);
  1354. mark_node_unsafe(p_call);
  1355. return;
  1356. }
  1357. reduce_expression(subscript->base);
  1358. base_type = subscript->base->get_datatype();
  1359. } else {
  1360. // Invalid call. Error already sent in parser.
  1361. // TODO: Could check if Callable here too.
  1362. p_call->set_datatype(call_type);
  1363. mark_node_unsafe(p_call);
  1364. return;
  1365. }
  1366. bool is_static = false;
  1367. bool is_vararg = false;
  1368. int default_arg_count = 0;
  1369. GDScriptParser::DataType return_type;
  1370. List<GDScriptParser::DataType> par_types;
  1371. if (get_function_signature(p_call, base_type, p_call->function_name, return_type, par_types, default_arg_count, is_static, is_vararg)) {
  1372. validate_call_arg(par_types, default_arg_count, is_vararg, p_call);
  1373. if (is_self && parser->current_function != nullptr && parser->current_function->is_static && !is_static) {
  1374. 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);
  1375. }
  1376. call_type = return_type;
  1377. } else {
  1378. // Check if the name exists as something else.
  1379. bool found = false;
  1380. if (!p_call->is_super) {
  1381. GDScriptParser::IdentifierNode *callee_id;
  1382. if (p_call->callee->type == GDScriptParser::Node::IDENTIFIER) {
  1383. callee_id = static_cast<GDScriptParser::IdentifierNode *>(p_call->callee);
  1384. } else {
  1385. // Can only be attribute.
  1386. callee_id = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee)->attribute;
  1387. }
  1388. reduce_identifier_from_base(callee_id, &base_type);
  1389. GDScriptParser::DataType callee_type = callee_id->get_datatype();
  1390. if (callee_type.is_set() && !callee_type.is_variant()) {
  1391. found = true;
  1392. if (callee_type.builtin_type == Variant::CALLABLE) {
  1393. 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);
  1394. } else {
  1395. push_error(vformat(R"*(Name "%s" called as a function but is a "%s".)*", p_call->function_name, callee_type.to_string()), p_call->callee);
  1396. }
  1397. } else if (!is_self) {
  1398. parser->push_warning(p_call, GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->function_name, base_type.to_string());
  1399. mark_node_unsafe(p_call);
  1400. }
  1401. }
  1402. if (!found && is_self) {
  1403. String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string();
  1404. 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);
  1405. }
  1406. }
  1407. if (call_type.is_coroutine && !is_await) {
  1408. push_error(vformat(R"*(Function "%s()" is a coroutine, so it must be called with "await".)*", p_call->function_name), p_call->callee);
  1409. }
  1410. p_call->set_datatype(call_type);
  1411. }
  1412. void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) {
  1413. reduce_expression(p_cast->operand);
  1414. GDScriptParser::DataType cast_type = resolve_datatype(p_cast->cast_type);
  1415. if (!cast_type.is_set()) {
  1416. return;
  1417. }
  1418. p_cast->set_datatype(cast_type);
  1419. if (!cast_type.is_variant()) {
  1420. if (!cast_type.is_meta_type) {
  1421. push_error(vformat(R"(Cast type "%s" isn't a valid type.)", cast_type.to_string()), p_cast->cast_type);
  1422. } else {
  1423. cast_type.is_meta_type = false; // For compatibility check purpose.
  1424. GDScriptParser::DataType op_type = p_cast->operand->get_datatype();
  1425. if (!op_type.is_variant()) {
  1426. bool valid = false;
  1427. if (op_type.kind == GDScriptParser::DataType::BUILTIN && cast_type.kind == GDScriptParser::DataType::BUILTIN) {
  1428. valid = Variant::can_convert(op_type.builtin_type, cast_type.builtin_type);
  1429. } else if (op_type.kind != GDScriptParser::DataType::BUILTIN && cast_type.kind != GDScriptParser::DataType::BUILTIN) {
  1430. valid = is_type_compatible(cast_type, op_type) || is_type_compatible(op_type, cast_type);
  1431. }
  1432. if (!valid) {
  1433. push_error(vformat(R"(Invalid cast. Cannot convert from "%s" to "%s".)", op_type.to_string(), cast_type.to_string()), p_cast->cast_type);
  1434. }
  1435. }
  1436. }
  1437. }
  1438. if (p_cast->operand->get_datatype().is_variant()) {
  1439. parser->push_warning(p_cast, GDScriptWarning::UNSAFE_CAST, cast_type.to_string());
  1440. mark_node_unsafe(p_cast);
  1441. }
  1442. // TODO: Perform cast on constants.
  1443. }
  1444. void GDScriptAnalyzer::reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
  1445. bool all_is_constant = true;
  1446. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  1447. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  1448. reduce_expression(element.key);
  1449. reduce_expression(element.value);
  1450. all_is_constant = all_is_constant && element.key->is_constant && element.value->is_constant;
  1451. }
  1452. if (all_is_constant) {
  1453. Dictionary dict;
  1454. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  1455. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  1456. dict[element.key->reduced_value] = element.value->reduced_value;
  1457. }
  1458. p_dictionary->is_constant = true;
  1459. p_dictionary->reduced_value = dict;
  1460. }
  1461. // It's dictionary in any case.
  1462. GDScriptParser::DataType dict_type;
  1463. dict_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1464. dict_type.kind = GDScriptParser::DataType::BUILTIN;
  1465. dict_type.builtin_type = Variant::DICTIONARY;
  1466. dict_type.is_constant = true;
  1467. p_dictionary->set_datatype(dict_type);
  1468. }
  1469. void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) {
  1470. GDScriptParser::DataType result;
  1471. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1472. result.kind = GDScriptParser::DataType::NATIVE;
  1473. result.native_type = "Node";
  1474. result.builtin_type = Variant::OBJECT;
  1475. if (!ClassDB::is_parent_class(get_real_class_name(parser->current_class->base_type.native_type), result.native_type)) {
  1476. push_error(R"*(Cannot use shorthand "get_node()" notation ("$") on a class that isn't a node.)*", p_get_node);
  1477. }
  1478. p_get_node->set_datatype(result);
  1479. }
  1480. GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name) {
  1481. Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(p_class_name));
  1482. ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  1483. GDScriptParser::DataType type;
  1484. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1485. type.kind = GDScriptParser::DataType::CLASS;
  1486. type.builtin_type = Variant::OBJECT;
  1487. type.native_type = ScriptServer::get_global_class_native_base(p_class_name);
  1488. type.class_type = ref->get_parser()->head;
  1489. type.is_constant = true;
  1490. return type;
  1491. }
  1492. void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) {
  1493. GDScriptParser::DataType base;
  1494. if (p_base == nullptr) {
  1495. base = type_from_metatype(parser->current_class->get_datatype());
  1496. } else {
  1497. base = *p_base;
  1498. }
  1499. if (base.kind == GDScriptParser::DataType::BUILTIN && base.is_meta_type) {
  1500. bool valid = true;
  1501. Variant result = Variant::get_constant_value(base.builtin_type, p_identifier->name, &valid);
  1502. if (valid) {
  1503. p_identifier->is_constant = true;
  1504. p_identifier->reduced_value = result;
  1505. p_identifier->set_datatype(type_from_variant(result));
  1506. } else {
  1507. push_error(vformat(R"(Cannot find constant "%s" on base "%s".)", p_identifier->name, base.to_string()), p_identifier);
  1508. }
  1509. return;
  1510. }
  1511. const StringName &name = p_identifier->name;
  1512. GDScriptParser::ClassNode *base_class = base.class_type;
  1513. // TODO: Switch current class/function/suite here to avoid misrepresenting identifiers (in recursive reduce calls).
  1514. while (base_class != nullptr) {
  1515. if (base_class->has_member(name)) {
  1516. const GDScriptParser::ClassNode::Member &member = base_class->get_member(name);
  1517. p_identifier->set_datatype(member.get_datatype());
  1518. if (member.type == GDScriptParser::ClassNode::Member::CONSTANT) {
  1519. // For out-of-order resolution:
  1520. reduce_expression(member.constant->initializer);
  1521. p_identifier->is_constant = true;
  1522. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  1523. p_identifier->set_datatype(member.constant->initializer->get_datatype());
  1524. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  1525. p_identifier->constant_source = member.constant;
  1526. } else if (member.type == GDScriptParser::ClassNode::Member::ENUM_VALUE) {
  1527. p_identifier->is_constant = true;
  1528. p_identifier->reduced_value = member.enum_value.value;
  1529. } else if (member.type == GDScriptParser::ClassNode::Member::VARIABLE) {
  1530. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;
  1531. p_identifier->variable_source = member.variable;
  1532. } else if (member.type == GDScriptParser::ClassNode::Member::FUNCTION) {
  1533. p_identifier->set_datatype(make_callable_type(member.function->info));
  1534. }
  1535. return;
  1536. }
  1537. // Check outer constants.
  1538. // TODO: Allow outer static functions.
  1539. GDScriptParser::ClassNode *outer = base_class->outer;
  1540. while (outer != nullptr) {
  1541. if (outer->has_member(name)) {
  1542. const GDScriptParser::ClassNode::Member &member = base_class->get_member(name);
  1543. if (member.type == GDScriptParser::ClassNode::Member::CONSTANT) {
  1544. // TODO: Make sure loops won't cause problem. And make special error message for those.
  1545. // For out-of-order resolution:
  1546. reduce_expression(member.constant->initializer);
  1547. p_identifier->set_datatype(member.get_datatype());
  1548. p_identifier->is_constant = true;
  1549. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  1550. return;
  1551. }
  1552. }
  1553. outer = outer->outer;
  1554. }
  1555. base_class = base_class->base_type.class_type;
  1556. }
  1557. // Check native members.
  1558. const StringName &native = get_real_class_name(base.native_type);
  1559. if (class_exists(native)) {
  1560. PropertyInfo prop_info;
  1561. MethodInfo method_info;
  1562. if (ClassDB::get_property_info(native, name, &prop_info)) {
  1563. p_identifier->set_datatype(type_from_property(prop_info));
  1564. return;
  1565. }
  1566. if (ClassDB::get_method_info(native, name, &method_info)) {
  1567. // Method is callable.
  1568. p_identifier->set_datatype(make_callable_type(method_info));
  1569. return;
  1570. }
  1571. if (ClassDB::get_signal(native, name, &method_info)) {
  1572. // Signal is a type too.
  1573. p_identifier->set_datatype(make_signal_type(method_info));
  1574. return;
  1575. }
  1576. bool valid = false;
  1577. int int_constant = ClassDB::get_integer_constant(native, name, &valid);
  1578. if (valid) {
  1579. p_identifier->is_constant = true;
  1580. p_identifier->reduced_value = int_constant;
  1581. p_identifier->set_datatype(type_from_variant(int_constant));
  1582. return;
  1583. }
  1584. }
  1585. }
  1586. void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier) {
  1587. // TODO: This is opportunity to further infer types.
  1588. // Check if identifier is local.
  1589. // If that's the case, the declaration already was solved before.
  1590. switch (p_identifier->source) {
  1591. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:
  1592. p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());
  1593. return;
  1594. case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:
  1595. case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:
  1596. p_identifier->set_datatype(p_identifier->constant_source->get_datatype());
  1597. p_identifier->is_constant = true;
  1598. // TODO: Constant should have a value on the node itself.
  1599. p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;
  1600. return;
  1601. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
  1602. p_identifier->variable_source->usages++;
  1603. [[fallthrough]];
  1604. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
  1605. p_identifier->set_datatype(p_identifier->variable_source->get_datatype());
  1606. return;
  1607. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:
  1608. p_identifier->set_datatype(p_identifier->bind_source->get_datatype());
  1609. return;
  1610. case GDScriptParser::IdentifierNode::LOCAL_BIND: {
  1611. GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();
  1612. result.is_constant = true;
  1613. p_identifier->set_datatype(result);
  1614. return;
  1615. }
  1616. case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:
  1617. break;
  1618. }
  1619. // Not a local, so check members.
  1620. reduce_identifier_from_base(p_identifier);
  1621. if (p_identifier->get_datatype().is_set()) {
  1622. // Found.
  1623. return;
  1624. }
  1625. StringName name = p_identifier->name;
  1626. p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;
  1627. // Check globals.
  1628. if (GDScriptParser::get_builtin_type(name) < Variant::VARIANT_MAX) {
  1629. p_identifier->set_datatype(make_builtin_meta_type(GDScriptParser::get_builtin_type(name)));
  1630. return;
  1631. }
  1632. if (class_exists(name)) {
  1633. p_identifier->set_datatype(make_native_meta_type(name));
  1634. return;
  1635. }
  1636. if (ScriptServer::is_global_class(name)) {
  1637. p_identifier->set_datatype(make_global_class_meta_type(name));
  1638. return;
  1639. }
  1640. if (GDScriptLanguage::get_singleton()->get_global_map().has(name)) {
  1641. int idx = GDScriptLanguage::get_singleton()->get_global_map()[name];
  1642. Variant constant = GDScriptLanguage::get_singleton()->get_global_array()[idx];
  1643. p_identifier->set_datatype(type_from_variant(constant));
  1644. p_identifier->is_constant = true;
  1645. p_identifier->reduced_value = constant;
  1646. return;
  1647. }
  1648. if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(name)) {
  1649. Variant constant = GDScriptLanguage::get_singleton()->get_named_globals_map()[name];
  1650. p_identifier->set_datatype(type_from_variant(constant));
  1651. p_identifier->is_constant = true;
  1652. p_identifier->reduced_value = constant;
  1653. return;
  1654. }
  1655. // Not found.
  1656. // Check if it's a builtin function.
  1657. if (parser->get_builtin_function(name) < GDScriptFunctions::FUNC_MAX) {
  1658. push_error(vformat(R"(Built-in function "%s" cannot be used as an identifier.)", name), p_identifier);
  1659. } else {
  1660. push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);
  1661. }
  1662. GDScriptParser::DataType dummy;
  1663. dummy.kind = GDScriptParser::DataType::VARIANT;
  1664. p_identifier->set_datatype(dummy); // Just so type is set to something.
  1665. }
  1666. void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {
  1667. p_literal->reduced_value = p_literal->value;
  1668. p_literal->is_constant = true;
  1669. p_literal->set_datatype(type_from_variant(p_literal->reduced_value));
  1670. }
  1671. void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
  1672. p_preload->is_constant = true;
  1673. p_preload->reduced_value = p_preload->resource;
  1674. p_preload->set_datatype(type_from_variant(p_preload->reduced_value));
  1675. }
  1676. void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
  1677. p_self->is_constant = false;
  1678. p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));
  1679. }
  1680. void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript) {
  1681. reduce_expression(p_subscript->base);
  1682. GDScriptParser::DataType result_type;
  1683. // Reduce index first. If it's a constant StringName, use attribute instead.
  1684. if (!p_subscript->is_attribute) {
  1685. reduce_expression(p_subscript->index);
  1686. if (p_subscript->index->is_constant && p_subscript->index->reduced_value.get_type() == Variant::STRING_NAME) {
  1687. GDScriptParser::IdentifierNode *attribute = parser->alloc_node<GDScriptParser::IdentifierNode>();
  1688. // Copy location for better error message.
  1689. attribute->start_line = p_subscript->index->start_line;
  1690. attribute->end_line = p_subscript->index->end_line;
  1691. attribute->leftmost_column = p_subscript->index->leftmost_column;
  1692. attribute->rightmost_column = p_subscript->index->rightmost_column;
  1693. p_subscript->is_attribute = true;
  1694. p_subscript->attribute = attribute;
  1695. }
  1696. }
  1697. if (p_subscript->is_attribute) {
  1698. if (p_subscript->base->is_constant) {
  1699. // Just try to get it.
  1700. bool valid = false;
  1701. Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, &valid);
  1702. if (!valid) {
  1703. push_error(vformat(R"(Cannot get member "%s" from "%s".)", p_subscript->attribute->name, p_subscript->base->reduced_value), p_subscript->index);
  1704. } else {
  1705. p_subscript->is_constant = true;
  1706. p_subscript->reduced_value = value;
  1707. result_type = type_from_variant(value);
  1708. }
  1709. result_type.kind = GDScriptParser::DataType::VARIANT;
  1710. } else {
  1711. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  1712. if (base_type.is_variant()) {
  1713. result_type.kind = GDScriptParser::DataType::VARIANT;
  1714. mark_node_unsafe(p_subscript);
  1715. } else {
  1716. reduce_identifier_from_base(p_subscript->attribute, &base_type);
  1717. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  1718. if (attr_type.is_set()) {
  1719. result_type = attr_type;
  1720. p_subscript->is_constant = p_subscript->attribute->is_constant;
  1721. p_subscript->reduced_value = p_subscript->attribute->reduced_value;
  1722. } else {
  1723. if (base_type.kind == GDScriptParser::DataType::BUILTIN) {
  1724. push_error(vformat(R"(Cannot find member "%s" in base "%s".)", p_subscript->attribute->name, base_type.to_string()), p_subscript->attribute);
  1725. } else {
  1726. parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());
  1727. }
  1728. result_type.kind = GDScriptParser::DataType::VARIANT;
  1729. }
  1730. }
  1731. }
  1732. } else {
  1733. // Index was already reduced before.
  1734. if (p_subscript->base->is_constant && p_subscript->index->is_constant) {
  1735. // Just try to get it.
  1736. bool valid = false;
  1737. Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);
  1738. if (!valid) {
  1739. push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);
  1740. } else {
  1741. p_subscript->is_constant = true;
  1742. p_subscript->reduced_value = value;
  1743. result_type = type_from_variant(value);
  1744. }
  1745. result_type.kind = GDScriptParser::DataType::VARIANT;
  1746. } else {
  1747. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  1748. GDScriptParser::DataType index_type = p_subscript->index->get_datatype();
  1749. if (base_type.is_variant()) {
  1750. result_type.kind = GDScriptParser::DataType::VARIANT;
  1751. mark_node_unsafe(p_subscript);
  1752. } else {
  1753. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  1754. // Check if indexing is valid.
  1755. bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;
  1756. if (!error) {
  1757. switch (base_type.builtin_type) {
  1758. // Expect int or real as index.
  1759. case Variant::PACKED_BYTE_ARRAY:
  1760. case Variant::PACKED_COLOR_ARRAY:
  1761. case Variant::PACKED_FLOAT32_ARRAY:
  1762. case Variant::PACKED_FLOAT64_ARRAY:
  1763. case Variant::PACKED_INT32_ARRAY:
  1764. case Variant::PACKED_INT64_ARRAY:
  1765. case Variant::PACKED_STRING_ARRAY:
  1766. case Variant::PACKED_VECTOR2_ARRAY:
  1767. case Variant::PACKED_VECTOR3_ARRAY:
  1768. case Variant::ARRAY:
  1769. case Variant::STRING:
  1770. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;
  1771. break;
  1772. // Expect String only.
  1773. case Variant::RECT2:
  1774. case Variant::RECT2I:
  1775. case Variant::PLANE:
  1776. case Variant::QUAT:
  1777. case Variant::AABB:
  1778. case Variant::OBJECT:
  1779. error = index_type.builtin_type != Variant::STRING;
  1780. break;
  1781. // Expect String or number.
  1782. case Variant::BASIS:
  1783. case Variant::VECTOR2:
  1784. case Variant::VECTOR2I:
  1785. case Variant::VECTOR3:
  1786. case Variant::VECTOR3I:
  1787. case Variant::TRANSFORM:
  1788. case Variant::TRANSFORM2D:
  1789. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&
  1790. index_type.builtin_type != Variant::STRING;
  1791. break;
  1792. // Expect String or int.
  1793. case Variant::COLOR:
  1794. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING;
  1795. break;
  1796. // Don't support indexing, but we will check it later.
  1797. case Variant::_RID:
  1798. case Variant::BOOL:
  1799. case Variant::CALLABLE:
  1800. case Variant::FLOAT:
  1801. case Variant::INT:
  1802. case Variant::NIL:
  1803. case Variant::NODE_PATH:
  1804. case Variant::SIGNAL:
  1805. case Variant::STRING_NAME:
  1806. break;
  1807. // Here for completeness.
  1808. case Variant::DICTIONARY:
  1809. case Variant::VARIANT_MAX:
  1810. break;
  1811. }
  1812. if (error) {
  1813. 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);
  1814. }
  1815. }
  1816. } else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  1817. if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {
  1818. 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);
  1819. }
  1820. }
  1821. // Check resulting type if possible.
  1822. result_type.builtin_type = Variant::NIL;
  1823. result_type.kind = GDScriptParser::DataType::BUILTIN;
  1824. result_type.type_source = GDScriptParser::DataType::INFERRED;
  1825. switch (base_type.builtin_type) {
  1826. // Can't index at all.
  1827. case Variant::_RID:
  1828. case Variant::BOOL:
  1829. case Variant::CALLABLE:
  1830. case Variant::FLOAT:
  1831. case Variant::INT:
  1832. case Variant::NIL:
  1833. case Variant::NODE_PATH:
  1834. case Variant::SIGNAL:
  1835. case Variant::STRING_NAME:
  1836. result_type.kind = GDScriptParser::DataType::VARIANT;
  1837. push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);
  1838. break;
  1839. // Return int.
  1840. case Variant::PACKED_BYTE_ARRAY:
  1841. case Variant::PACKED_INT32_ARRAY:
  1842. case Variant::PACKED_INT64_ARRAY:
  1843. case Variant::VECTOR2I:
  1844. case Variant::VECTOR3I:
  1845. result_type.builtin_type = Variant::INT;
  1846. break;
  1847. // Return float.
  1848. case Variant::PACKED_FLOAT32_ARRAY:
  1849. case Variant::PACKED_FLOAT64_ARRAY:
  1850. case Variant::VECTOR2:
  1851. case Variant::VECTOR3:
  1852. case Variant::QUAT:
  1853. result_type.builtin_type = Variant::FLOAT;
  1854. break;
  1855. // Return Color.
  1856. case Variant::PACKED_COLOR_ARRAY:
  1857. result_type.builtin_type = Variant::COLOR;
  1858. break;
  1859. // Return String.
  1860. case Variant::PACKED_STRING_ARRAY:
  1861. case Variant::STRING:
  1862. result_type.builtin_type = Variant::STRING;
  1863. break;
  1864. // Return Vector2.
  1865. case Variant::PACKED_VECTOR2_ARRAY:
  1866. case Variant::TRANSFORM2D:
  1867. case Variant::RECT2:
  1868. result_type.builtin_type = Variant::VECTOR2;
  1869. break;
  1870. // Return Vector2I.
  1871. case Variant::RECT2I:
  1872. result_type.builtin_type = Variant::VECTOR2I;
  1873. break;
  1874. // Return Vector3.
  1875. case Variant::PACKED_VECTOR3_ARRAY:
  1876. case Variant::AABB:
  1877. case Variant::BASIS:
  1878. result_type.builtin_type = Variant::VECTOR3;
  1879. break;
  1880. // Depends on the index.
  1881. case Variant::TRANSFORM:
  1882. case Variant::PLANE:
  1883. case Variant::COLOR:
  1884. case Variant::ARRAY:
  1885. case Variant::DICTIONARY:
  1886. result_type.kind = GDScriptParser::DataType::VARIANT;
  1887. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  1888. break;
  1889. // Here for completeness.
  1890. case Variant::OBJECT:
  1891. case Variant::VARIANT_MAX:
  1892. break;
  1893. }
  1894. }
  1895. }
  1896. }
  1897. p_subscript->set_datatype(result_type);
  1898. }
  1899. void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op) {
  1900. reduce_expression(p_ternary_op->condition);
  1901. reduce_expression(p_ternary_op->true_expr);
  1902. reduce_expression(p_ternary_op->false_expr);
  1903. GDScriptParser::DataType result;
  1904. if (p_ternary_op->condition->is_constant && p_ternary_op->true_expr->is_constant && p_ternary_op->false_expr->is_constant) {
  1905. p_ternary_op->is_constant = true;
  1906. if (p_ternary_op->condition->reduced_value.booleanize()) {
  1907. p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;
  1908. } else {
  1909. p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;
  1910. }
  1911. }
  1912. GDScriptParser::DataType true_type = p_ternary_op->true_expr->get_datatype();
  1913. GDScriptParser::DataType false_type = p_ternary_op->false_expr->get_datatype();
  1914. if (true_type.is_variant() || false_type.is_variant()) {
  1915. result.kind = GDScriptParser::DataType::VARIANT;
  1916. } else {
  1917. result = true_type;
  1918. if (!is_type_compatible(true_type, false_type)) {
  1919. result = false_type;
  1920. if (!is_type_compatible(false_type, true_type)) {
  1921. result.type_source = GDScriptParser::DataType::UNDETECTED;
  1922. result.kind = GDScriptParser::DataType::VARIANT;
  1923. parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);
  1924. }
  1925. }
  1926. }
  1927. p_ternary_op->set_datatype(result);
  1928. }
  1929. void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {
  1930. reduce_expression(p_unary_op->operand);
  1931. GDScriptParser::DataType result;
  1932. if (p_unary_op->operand->is_constant) {
  1933. p_unary_op->is_constant = true;
  1934. p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());
  1935. result = type_from_variant(p_unary_op->reduced_value);
  1936. } else if (p_unary_op->operand->get_datatype().is_variant()) {
  1937. result.kind = GDScriptParser::DataType::VARIANT;
  1938. mark_node_unsafe(p_unary_op);
  1939. } else {
  1940. bool valid = false;
  1941. result = get_operation_type(p_unary_op->variant_op, p_unary_op->operand->get_datatype(), p_unary_op->operand->get_datatype(), valid);
  1942. if (!valid) {
  1943. 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);
  1944. }
  1945. }
  1946. p_unary_op->set_datatype(result);
  1947. }
  1948. GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value) {
  1949. GDScriptParser::DataType result;
  1950. result.is_constant = true;
  1951. result.kind = GDScriptParser::DataType::BUILTIN;
  1952. result.builtin_type = p_value.get_type();
  1953. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.
  1954. if (p_value.get_type() == Variant::OBJECT) {
  1955. Object *obj = p_value;
  1956. if (!obj) {
  1957. return GDScriptParser::DataType();
  1958. }
  1959. result.native_type = obj->get_class_name();
  1960. Ref<Script> scr = p_value; // Check if value is a script itself.
  1961. if (scr.is_valid()) {
  1962. result.is_meta_type = true;
  1963. } else {
  1964. result.is_meta_type = false;
  1965. scr = obj->get_script();
  1966. }
  1967. if (scr.is_valid()) {
  1968. result.script_type = scr;
  1969. Ref<GDScript> gds = scr;
  1970. if (gds.is_valid()) {
  1971. result.kind = GDScriptParser::DataType::CLASS;
  1972. Ref<GDScriptParserRef> ref = get_parser_for(gds->get_path());
  1973. ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  1974. result.class_type = ref->get_parser()->head;
  1975. } else {
  1976. result.kind = GDScriptParser::DataType::SCRIPT;
  1977. }
  1978. result.native_type = scr->get_instance_base_type();
  1979. } else {
  1980. result.kind = GDScriptParser::DataType::NATIVE;
  1981. if (result.native_type == GDScriptNativeClass::get_class_static()) {
  1982. result.is_meta_type = true;
  1983. }
  1984. }
  1985. }
  1986. return result;
  1987. }
  1988. GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) const {
  1989. GDScriptParser::DataType result = p_meta_type;
  1990. result.is_meta_type = false;
  1991. result.is_constant = false;
  1992. return result;
  1993. }
  1994. GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property) const {
  1995. GDScriptParser::DataType result;
  1996. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1997. if (p_property.type == Variant::NIL && (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) {
  1998. // Variant
  1999. result.kind = GDScriptParser::DataType::VARIANT;
  2000. return result;
  2001. }
  2002. result.builtin_type = p_property.type;
  2003. if (p_property.type == Variant::OBJECT) {
  2004. result.kind = GDScriptParser::DataType::NATIVE;
  2005. result.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;
  2006. } else {
  2007. result.kind = GDScriptParser::DataType::BUILTIN;
  2008. }
  2009. return result;
  2010. }
  2011. 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) {
  2012. r_static = false;
  2013. r_vararg = false;
  2014. r_default_arg_count = 0;
  2015. if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {
  2016. // Construct a base type to get methods.
  2017. Callable::CallError err;
  2018. Variant dummy = Variant::construct(p_base_type.builtin_type, nullptr, 0, err);
  2019. if (err.error != Callable::CallError::CALL_OK) {
  2020. ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");
  2021. }
  2022. List<MethodInfo> methods;
  2023. dummy.get_method_list(&methods);
  2024. for (const List<MethodInfo>::Element *E = methods.front(); E != nullptr; E = E->next()) {
  2025. if (E->get().name == p_function) {
  2026. return function_signature_from_info(E->get(), r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2027. }
  2028. }
  2029. return false;
  2030. }
  2031. GDScriptParser::ClassNode *base_class = p_base_type.class_type;
  2032. GDScriptParser::FunctionNode *found_function = nullptr;
  2033. while (found_function == nullptr && base_class != nullptr) {
  2034. if (base_class->has_member(p_function)) {
  2035. if (base_class->get_member(p_function).type != GDScriptParser::ClassNode::Member::FUNCTION) {
  2036. // TODO: If this is Callable it can have a better error message.
  2037. push_error(vformat(R"(Member "%s" is not a function.)", p_function), p_source);
  2038. return false;
  2039. }
  2040. found_function = base_class->get_member(p_function).function;
  2041. }
  2042. base_class = base_class->base_type.class_type;
  2043. }
  2044. if (found_function != nullptr) {
  2045. r_static = found_function->is_static;
  2046. for (int i = 0; i < found_function->parameters.size(); i++) {
  2047. r_par_types.push_back(found_function->parameters[i]->get_datatype());
  2048. if (found_function->parameters[i]->default_value != nullptr) {
  2049. r_default_arg_count++;
  2050. }
  2051. }
  2052. r_return_type = found_function->get_datatype();
  2053. r_return_type.is_coroutine = found_function->is_coroutine;
  2054. return true;
  2055. }
  2056. // TODO: Check here the "new" function in GDScript class when metatype, as it needs to look the constructor.
  2057. Ref<Script> base_script = p_base_type.script_type;
  2058. while (base_script.is_valid() && base_script->is_valid()) {
  2059. MethodInfo info = base_script->get_method_info(p_function);
  2060. if (!(info == MethodInfo())) {
  2061. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2062. }
  2063. base_script = base_script->get_base_script();
  2064. }
  2065. // If the base is a script, it might be trying to access members of the Script class itself.
  2066. if (p_base_type.is_meta_type && !(p_function == "new") && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {
  2067. MethodInfo info;
  2068. StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());
  2069. if (ClassDB::get_method_info(script_class, p_function, &info)) {
  2070. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2071. }
  2072. }
  2073. StringName base_native = p_base_type.native_type;
  2074. if (base_native == StringName()) {
  2075. // Empty native class, might happen in some Script implementations.
  2076. // Just ignore it.
  2077. return false;
  2078. }
  2079. #ifdef DEBUG_ENABLED
  2080. if (!class_exists(base_native)) {
  2081. ERR_FAIL_V_MSG(false, vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native));
  2082. }
  2083. #endif
  2084. StringName real_native = get_real_class_name(base_native);
  2085. MethodInfo info;
  2086. if (ClassDB::get_method_info(real_native, p_function, &info)) {
  2087. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  2088. }
  2089. return false;
  2090. }
  2091. 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) {
  2092. r_return_type = type_from_property(p_info.return_val);
  2093. r_default_arg_count = p_info.default_arguments.size();
  2094. r_vararg = (p_info.flags & METHOD_FLAG_VARARG) != 0;
  2095. for (const List<PropertyInfo>::Element *E = p_info.arguments.front(); E != nullptr; E = E->next()) {
  2096. r_par_types.push_back(type_from_property(E->get()));
  2097. }
  2098. return true;
  2099. }
  2100. bool GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {
  2101. List<GDScriptParser::DataType> arg_types;
  2102. for (const List<PropertyInfo>::Element *E = p_method.arguments.front(); E != nullptr; E = E->next()) {
  2103. arg_types.push_back(type_from_property(E->get()));
  2104. }
  2105. return validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);
  2106. }
  2107. 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) {
  2108. bool valid = true;
  2109. if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {
  2110. 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);
  2111. valid = false;
  2112. }
  2113. if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {
  2114. 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()]);
  2115. valid = false;
  2116. }
  2117. for (int i = 0; i < p_call->arguments.size(); i++) {
  2118. if (i >= p_par_types.size()) {
  2119. // Already on vararg place.
  2120. break;
  2121. }
  2122. GDScriptParser::DataType par_type = p_par_types[i];
  2123. GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
  2124. if (arg_type.is_variant()) {
  2125. // Argument can be anything, so this is unsafe.
  2126. mark_node_unsafe(p_call->arguments[i]);
  2127. } else if (!is_type_compatible(par_type, arg_type, true)) {
  2128. // Supertypes are acceptable for dynamic compliance, but it's unsafe.
  2129. mark_node_unsafe(p_call);
  2130. if (!is_type_compatible(arg_type, par_type)) {
  2131. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*",
  2132. p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),
  2133. p_call->arguments[i]);
  2134. valid = false;
  2135. }
  2136. } else {
  2137. 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) {
  2138. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  2139. }
  2140. }
  2141. }
  2142. return valid;
  2143. }
  2144. bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context) {
  2145. const StringName &name = p_local->name;
  2146. GDScriptParser::DataType base = parser->current_class->get_datatype();
  2147. GDScriptParser::ClassNode *base_class = base.class_type;
  2148. while (base_class != nullptr) {
  2149. if (base_class->has_member(name)) {
  2150. 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()));
  2151. return true;
  2152. }
  2153. base_class = base_class->base_type.class_type;
  2154. }
  2155. StringName base_native = base.native_type;
  2156. ERR_FAIL_COND_V_MSG(!class_exists(base_native), false, "Non-existent native base class.");
  2157. StringName parent = base_native;
  2158. while (parent != StringName()) {
  2159. if (ClassDB::has_method(parent, name, true)) {
  2160. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "method", parent);
  2161. return true;
  2162. } else if (ClassDB::has_signal(parent, name, true)) {
  2163. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "signal", parent);
  2164. return true;
  2165. } else if (ClassDB::has_property(parent, name, true)) {
  2166. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "property", parent);
  2167. return true;
  2168. } else if (ClassDB::has_integer_constant(parent, name, true)) {
  2169. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "constant", parent);
  2170. return true;
  2171. } else if (ClassDB::has_enum(parent, name, true)) {
  2172. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "enum", parent);
  2173. return true;
  2174. }
  2175. parent = ClassDB::get_parent_class(parent);
  2176. }
  2177. return false;
  2178. }
  2179. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid) {
  2180. // This function creates dummy variant values and apply the operation to those. Less error-prone than keeping a table of valid operations.
  2181. GDScriptParser::DataType result;
  2182. result.kind = GDScriptParser::DataType::VARIANT;
  2183. Variant::Type a_type = p_a.builtin_type;
  2184. Variant::Type b_type = p_b.builtin_type;
  2185. Variant a;
  2186. REF a_ref;
  2187. if (a_type == Variant::OBJECT) {
  2188. a_ref.instance();
  2189. a = a_ref;
  2190. } else {
  2191. Callable::CallError err;
  2192. a = Variant::construct(a_type, nullptr, 0, err);
  2193. if (err.error != Callable::CallError::CALL_OK) {
  2194. r_valid = false;
  2195. ERR_FAIL_V_MSG(result, vformat("Could not construct value of type %s", Variant::get_type_name(a_type)));
  2196. }
  2197. }
  2198. Variant b;
  2199. REF b_ref;
  2200. if (b_type == Variant::OBJECT) {
  2201. b_ref.instance();
  2202. b = b_ref;
  2203. } else {
  2204. Callable::CallError err;
  2205. b = Variant::construct(b_type, nullptr, 0, err);
  2206. if (err.error != Callable::CallError::CALL_OK) {
  2207. r_valid = false;
  2208. ERR_FAIL_V_MSG(result, vformat("Could not construct value of type %s", Variant::get_type_name(b_type)));
  2209. }
  2210. }
  2211. // Avoid division by zero.
  2212. switch (b_type) {
  2213. case Variant::INT:
  2214. b = 1;
  2215. break;
  2216. case Variant::FLOAT:
  2217. b = 1.0;
  2218. break;
  2219. case Variant::VECTOR2:
  2220. b = Vector2(1.0, 1.0);
  2221. break;
  2222. case Variant::VECTOR2I:
  2223. b = Vector2i(1, 1);
  2224. break;
  2225. case Variant::VECTOR3:
  2226. b = Vector3(1.0, 1.0, 1.0);
  2227. break;
  2228. case Variant::VECTOR3I:
  2229. b = Vector3i(1, 1, 1);
  2230. break;
  2231. case Variant::COLOR:
  2232. b = Color(1.0, 1.0, 1.0, 1.0);
  2233. break;
  2234. default:
  2235. // No change needed.
  2236. break;
  2237. }
  2238. // Avoid error in formatting operator (%) where it doesn't find a placeholder.
  2239. if (a_type == Variant::STRING) {
  2240. a = String("%s");
  2241. }
  2242. Variant ret;
  2243. Variant::evaluate(p_operation, a, b, ret, r_valid);
  2244. if (r_valid) {
  2245. return type_from_variant(ret);
  2246. }
  2247. return result;
  2248. }
  2249. // TODO: Add safe/unsafe return variable (for variant cases)
  2250. bool GDScriptAnalyzer::is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion) const {
  2251. // if (!p_target.is_set()){
  2252. // print_line("target not set");
  2253. // }
  2254. // if (!p_source.is_set()){
  2255. // print_line("source not set");
  2256. // }
  2257. // These return "true" so it doesn't affect users negatively.
  2258. ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");
  2259. ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");
  2260. if (p_target.kind == GDScriptParser::DataType::VARIANT) {
  2261. // Variant can receive anything.
  2262. return true;
  2263. }
  2264. if (p_source.kind == GDScriptParser::DataType::VARIANT) {
  2265. // TODO: This is acceptable but unsafe. Make sure unsafe line is set.
  2266. return true;
  2267. }
  2268. if (p_target.kind == GDScriptParser::DataType::BUILTIN) {
  2269. bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;
  2270. if (!valid && p_allow_implicit_conversion) {
  2271. valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);
  2272. }
  2273. return valid;
  2274. }
  2275. // From here on the target type is an object, so we have to test polymorphism.
  2276. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {
  2277. // null is acceptable in object.
  2278. return true;
  2279. }
  2280. StringName src_native;
  2281. Ref<Script> src_script;
  2282. const GDScriptParser::ClassNode *src_class = nullptr;
  2283. switch (p_source.kind) {
  2284. case GDScriptParser::DataType::NATIVE:
  2285. if (p_target.kind != GDScriptParser::DataType::NATIVE) {
  2286. // Non-native class cannot be supertype of native.
  2287. return false;
  2288. }
  2289. if (p_source.is_meta_type) {
  2290. src_native = GDScriptNativeClass::get_class_static();
  2291. } else {
  2292. src_native = p_source.native_type;
  2293. }
  2294. break;
  2295. case GDScriptParser::DataType::SCRIPT:
  2296. if (p_target.kind == GDScriptParser::DataType::CLASS) {
  2297. // A script type cannot be a subtype of a GDScript class.
  2298. return false;
  2299. }
  2300. if (p_source.is_meta_type) {
  2301. src_native = p_source.script_type->get_class_name();
  2302. } else {
  2303. src_script = p_source.script_type;
  2304. src_native = src_script->get_instance_base_type();
  2305. }
  2306. break;
  2307. case GDScriptParser::DataType::CLASS:
  2308. if (p_source.is_meta_type) {
  2309. src_native = GDScript::get_class_static();
  2310. } else {
  2311. src_class = p_source.class_type;
  2312. const GDScriptParser::ClassNode *base = src_class;
  2313. while (base->base_type.kind == GDScriptParser::DataType::CLASS) {
  2314. base = base->base_type.class_type;
  2315. }
  2316. src_native = base->base_type.native_type;
  2317. src_script = base->base_type.script_type;
  2318. }
  2319. break;
  2320. case GDScriptParser::DataType::VARIANT:
  2321. case GDScriptParser::DataType::BUILTIN:
  2322. case GDScriptParser::DataType::UNRESOLVED:
  2323. break; // Already solved before.
  2324. }
  2325. // Get underscore-prefixed version for some classes.
  2326. src_native = get_real_class_name(src_native);
  2327. switch (p_target.kind) {
  2328. case GDScriptParser::DataType::NATIVE: {
  2329. if (p_target.is_meta_type) {
  2330. return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());
  2331. }
  2332. StringName tgt_native = get_real_class_name(p_target.native_type);
  2333. return ClassDB::is_parent_class(src_native, tgt_native);
  2334. }
  2335. case GDScriptParser::DataType::SCRIPT:
  2336. if (p_target.is_meta_type) {
  2337. return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());
  2338. }
  2339. while (src_script.is_valid()) {
  2340. if (src_script == p_target.script_type) {
  2341. return true;
  2342. }
  2343. src_script = src_script->get_base_script();
  2344. }
  2345. return false;
  2346. case GDScriptParser::DataType::CLASS:
  2347. if (p_target.is_meta_type) {
  2348. return ClassDB::is_parent_class(src_native, GDScript::get_class_static());
  2349. }
  2350. while (src_class != nullptr) {
  2351. if (src_class->fqcn == p_target.class_type->fqcn) {
  2352. return true;
  2353. }
  2354. src_class = src_class->base_type.class_type;
  2355. }
  2356. return false;
  2357. case GDScriptParser::DataType::VARIANT:
  2358. case GDScriptParser::DataType::BUILTIN:
  2359. case GDScriptParser::DataType::UNRESOLVED:
  2360. break; // Already solved before.
  2361. }
  2362. return false;
  2363. }
  2364. void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {
  2365. mark_node_unsafe(p_origin);
  2366. parser->push_error(p_message, p_origin);
  2367. }
  2368. void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {
  2369. for (int i = p_node->start_line; i <= p_node->end_line; i++) {
  2370. parser->unsafe_lines.insert(i);
  2371. }
  2372. }
  2373. bool GDScriptAnalyzer::class_exists(const StringName &p_class) {
  2374. StringName real_name = get_real_class_name(p_class);
  2375. return ClassDB::class_exists(real_name) && ClassDB::is_class_exposed(real_name);
  2376. }
  2377. Ref<GDScriptParserRef> GDScriptAnalyzer::get_parser_for(const String &p_path) {
  2378. Ref<GDScriptParserRef> ref;
  2379. if (depended_parsers.has(p_path)) {
  2380. ref = depended_parsers[p_path];
  2381. } else {
  2382. Error err = OK;
  2383. ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err);
  2384. depended_parsers[p_path] = ref;
  2385. }
  2386. return ref;
  2387. }
  2388. Error GDScriptAnalyzer::resolve_inheritance() {
  2389. return resolve_inheritance(parser->head);
  2390. }
  2391. Error GDScriptAnalyzer::resolve_interface() {
  2392. resolve_class_interface(parser->head);
  2393. return parser->errors.empty() ? OK : ERR_PARSE_ERROR;
  2394. }
  2395. Error GDScriptAnalyzer::resolve_body() {
  2396. resolve_class_body(parser->head);
  2397. return parser->errors.empty() ? OK : ERR_PARSE_ERROR;
  2398. }
  2399. Error GDScriptAnalyzer::resolve_program() {
  2400. resolve_class_interface(parser->head);
  2401. resolve_class_body(parser->head);
  2402. List<String> parser_keys;
  2403. depended_parsers.get_key_list(&parser_keys);
  2404. for (const List<String>::Element *E = parser_keys.front(); E != nullptr; E = E->next()) {
  2405. depended_parsers[E->get()]->raise_status(GDScriptParserRef::FULLY_SOLVED);
  2406. }
  2407. depended_parsers.clear();
  2408. return parser->errors.empty() ? OK : ERR_PARSE_ERROR;
  2409. }
  2410. Error GDScriptAnalyzer::analyze() {
  2411. parser->errors.clear();
  2412. Error err = resolve_inheritance(parser->head);
  2413. if (err) {
  2414. return err;
  2415. }
  2416. return resolve_program();
  2417. }
  2418. GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {
  2419. parser = p_parser;
  2420. }