gdscript_analyzer.cpp 185 KB

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