gdscript_analyzer.cpp 142 KB

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