gdscript_analyzer.cpp 127 KB

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