gdscript_analyzer.cpp 125 KB

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