gdscript_analyzer.cpp 163 KB

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