gdscript_analyzer.cpp 167 KB

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