gdscript_analyzer.cpp 177 KB

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