gdscript_analyzer.cpp 169 KB

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