gdscript_analyzer.cpp 169 KB

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