gdscript_analyzer.cpp 180 KB

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