gdscript_analyzer.cpp 175 KB

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