gdscript_analyzer.cpp 142 KB

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