gdscript_analyzer.cpp 181 KB

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