gdscript_analyzer.cpp 150 KB

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