gdscript_analyzer.cpp 160 KB

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