gdscript_analyzer.cpp 162 KB

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