gdscript_analyzer.cpp 180 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651
  1. /*************************************************************************/
  2. /* gdscript_analyzer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 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. for (int j = 0; j < member.m_enum->values.size(); j++) {
  812. GDScriptParser::EnumNode::Value &element = member.m_enum->values.write[j];
  813. if (element.custom_value) {
  814. reduce_expression(element.custom_value);
  815. if (!element.custom_value->is_constant) {
  816. push_error(R"(Enum values must be constant.)", element.custom_value);
  817. } else if (element.custom_value->reduced_value.get_type() != Variant::INT) {
  818. push_error(R"(Enum values must be integers.)", element.custom_value);
  819. } else {
  820. element.value = element.custom_value->reduced_value;
  821. element.resolved = true;
  822. }
  823. } else {
  824. if (element.index > 0) {
  825. element.value = element.parent_enum->values[element.index - 1].value + 1;
  826. } else {
  827. element.value = 0;
  828. }
  829. element.resolved = true;
  830. }
  831. enum_type.enum_values[element.identifier->name] = element.value;
  832. }
  833. current_enum = prev_enum;
  834. member.m_enum->set_datatype(enum_type);
  835. // Apply annotations.
  836. for (GDScriptParser::AnnotationNode *&E : member.m_enum->annotations) {
  837. E->apply(parser, member.m_enum);
  838. }
  839. } break;
  840. case GDScriptParser::ClassNode::Member::FUNCTION:
  841. resolve_function_signature(member.function, p_source);
  842. break;
  843. case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
  844. if (member.enum_value.custom_value) {
  845. check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.custom_value);
  846. member.enum_value.identifier->set_datatype(resolving_datatype);
  847. const GDScriptParser::EnumNode *prev_enum = current_enum;
  848. current_enum = member.enum_value.parent_enum;
  849. reduce_expression(member.enum_value.custom_value);
  850. current_enum = prev_enum;
  851. if (!member.enum_value.custom_value->is_constant) {
  852. push_error(R"(Enum values must be constant.)", member.enum_value.custom_value);
  853. } else if (member.enum_value.custom_value->reduced_value.get_type() != Variant::INT) {
  854. push_error(R"(Enum values must be integers.)", member.enum_value.custom_value);
  855. } else {
  856. member.enum_value.value = member.enum_value.custom_value->reduced_value;
  857. member.enum_value.resolved = true;
  858. }
  859. } else {
  860. check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.parent_enum);
  861. if (member.enum_value.index > 0) {
  862. const GDScriptParser::EnumNode::Value &prev_value = member.enum_value.parent_enum->values[member.enum_value.index - 1];
  863. resolve_class_member(p_class, prev_value.identifier->name, member.enum_value.identifier);
  864. member.enum_value.value = prev_value.value + 1;
  865. } else {
  866. member.enum_value.value = 0;
  867. }
  868. member.enum_value.resolved = true;
  869. }
  870. // Also update the original references.
  871. member.enum_value.parent_enum->values.set(member.enum_value.index, member.enum_value);
  872. GDScriptParser::DataType datatype;
  873. datatype.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  874. datatype.kind = GDScriptParser::DataType::BUILTIN;
  875. datatype.builtin_type = Variant::INT;
  876. member.enum_value.identifier->set_datatype(datatype);
  877. } break;
  878. case GDScriptParser::ClassNode::Member::CLASS:
  879. check_class_member_name_conflict(p_class, member.m_class->identifier->name, member.m_class);
  880. // If it's already resolving, that's ok.
  881. if (!member.m_class->base_type.is_resolving()) {
  882. resolve_class_inheritance(member.m_class, p_source);
  883. }
  884. break;
  885. case GDScriptParser::ClassNode::Member::GROUP:
  886. // No-op, but needed to silence warnings.
  887. break;
  888. case GDScriptParser::ClassNode::Member::UNDEFINED:
  889. ERR_PRINT("Trying to resolve undefined member.");
  890. break;
  891. }
  892. }
  893. parser->current_class = previous_class;
  894. }
  895. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  896. if (p_source == nullptr && parser->has_class(p_class)) {
  897. p_source = p_class;
  898. }
  899. if (!p_class->resolved_interface) {
  900. if (!parser->has_class(p_class)) {
  901. String script_path = p_class->get_datatype().script_path;
  902. Ref<GDScriptParserRef> parser_ref = get_parser_for(script_path);
  903. if (parser_ref.is_null()) {
  904. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  905. return;
  906. }
  907. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  908. if (err) {
  909. push_error(vformat(R"(Could not resolve script "%s": %s.)", script_path, error_names[err]), p_source);
  910. return;
  911. }
  912. ERR_FAIL_COND_MSG(!parser_ref->get_parser()->has_class(p_class), R"(Parser bug: Mismatched external parser.)");
  913. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  914. GDScriptParser *other_parser = parser_ref->get_parser();
  915. int error_count = other_parser->errors.size();
  916. other_analyzer->resolve_class_interface(p_class);
  917. if (other_parser->errors.size() > error_count) {
  918. push_error(vformat(R"(Could not resolve class "%s".)", p_class->fqcn), p_source);
  919. }
  920. return;
  921. }
  922. p_class->resolved_interface = true;
  923. if (resolve_class_inheritance(p_class) != OK) {
  924. return;
  925. }
  926. GDScriptParser::DataType base_type = p_class->base_type;
  927. if (base_type.kind == GDScriptParser::DataType::CLASS) {
  928. GDScriptParser::ClassNode *base_class = base_type.class_type;
  929. resolve_class_interface(base_class, p_class);
  930. }
  931. for (int i = 0; i < p_class->members.size(); i++) {
  932. resolve_class_member(p_class, i);
  933. }
  934. }
  935. }
  936. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  937. resolve_class_interface(p_class);
  938. if (p_recursive) {
  939. for (int i = 0; i < p_class->members.size(); i++) {
  940. GDScriptParser::ClassNode::Member member = p_class->members[i];
  941. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  942. resolve_class_interface(member.m_class, true);
  943. }
  944. }
  945. }
  946. }
  947. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  948. if (p_source == nullptr && parser->has_class(p_class)) {
  949. p_source = p_class;
  950. }
  951. if (p_class->resolved_body) {
  952. return;
  953. }
  954. if (!parser->has_class(p_class)) {
  955. String script_path = p_class->get_datatype().script_path;
  956. Ref<GDScriptParserRef> parser_ref = get_parser_for(script_path);
  957. if (parser_ref.is_null()) {
  958. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  959. return;
  960. }
  961. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  962. if (err) {
  963. push_error(vformat(R"(Could not resolve script "%s": %s.)", script_path, error_names[err]), p_source);
  964. return;
  965. }
  966. ERR_FAIL_COND_MSG(!parser_ref->get_parser()->has_class(p_class), R"(Parser bug: Mismatched external parser.)");
  967. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  968. GDScriptParser *other_parser = parser_ref->get_parser();
  969. int error_count = other_parser->errors.size();
  970. other_analyzer->resolve_class_body(p_class);
  971. if (other_parser->errors.size() > error_count) {
  972. push_error(vformat(R"(Could not resolve class "%s".)", p_class->fqcn), p_source);
  973. }
  974. return;
  975. }
  976. p_class->resolved_body = true;
  977. GDScriptParser::ClassNode *previous_class = parser->current_class;
  978. parser->current_class = p_class;
  979. resolve_class_interface(p_class, p_source);
  980. GDScriptParser::DataType base_type = p_class->base_type;
  981. if (base_type.kind == GDScriptParser::DataType::CLASS) {
  982. GDScriptParser::ClassNode *base_class = base_type.class_type;
  983. resolve_class_body(base_class, p_class);
  984. }
  985. // Do functions and properties now.
  986. for (int i = 0; i < p_class->members.size(); i++) {
  987. GDScriptParser::ClassNode::Member member = p_class->members[i];
  988. if (member.type == GDScriptParser::ClassNode::Member::FUNCTION) {
  989. // Apply annotations.
  990. for (GDScriptParser::AnnotationNode *&E : member.function->annotations) {
  991. E->apply(parser, member.function);
  992. }
  993. #ifdef DEBUG_ENABLED
  994. HashSet<uint32_t> previously_ignored = parser->ignored_warning_codes;
  995. for (uint32_t ignored_warning : member.function->ignored_warnings) {
  996. parser->ignored_warning_codes.insert(ignored_warning);
  997. }
  998. #endif // DEBUG_ENABLED
  999. resolve_function_body(member.function);
  1000. #ifdef DEBUG_ENABLED
  1001. parser->ignored_warning_codes = previously_ignored;
  1002. #endif // DEBUG_ENABLED
  1003. } else if (member.type == GDScriptParser::ClassNode::Member::VARIABLE && member.variable->property != GDScriptParser::VariableNode::PROP_NONE) {
  1004. if (member.variable->property == GDScriptParser::VariableNode::PROP_INLINE) {
  1005. if (member.variable->getter != nullptr) {
  1006. member.variable->getter->set_datatype(member.variable->datatype);
  1007. resolve_function_body(member.variable->getter);
  1008. }
  1009. if (member.variable->setter != nullptr) {
  1010. resolve_function_signature(member.variable->setter);
  1011. if (member.variable->setter->parameters.size() > 0) {
  1012. member.variable->setter->parameters[0]->datatype_specifier = member.variable->datatype_specifier;
  1013. member.variable->setter->parameters[0]->set_datatype(member.get_datatype());
  1014. }
  1015. resolve_function_body(member.variable->setter);
  1016. }
  1017. }
  1018. }
  1019. }
  1020. // Check unused variables and datatypes of property getters and setters.
  1021. for (int i = 0; i < p_class->members.size(); i++) {
  1022. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1023. if (member.type == GDScriptParser::ClassNode::Member::VARIABLE) {
  1024. #ifdef DEBUG_ENABLED
  1025. HashSet<uint32_t> previously_ignored = parser->ignored_warning_codes;
  1026. for (uint32_t ignored_warning : member.function->ignored_warnings) {
  1027. parser->ignored_warning_codes.insert(ignored_warning);
  1028. }
  1029. if (member.variable->usages == 0 && String(member.variable->identifier->name).begins_with("_")) {
  1030. parser->push_warning(member.variable->identifier, GDScriptWarning::UNUSED_PRIVATE_CLASS_VARIABLE, member.variable->identifier->name);
  1031. }
  1032. #endif
  1033. if (member.variable->property == GDScriptParser::VariableNode::PROP_SETGET) {
  1034. GDScriptParser::FunctionNode *getter_function = nullptr;
  1035. GDScriptParser::FunctionNode *setter_function = nullptr;
  1036. bool has_valid_getter = false;
  1037. bool has_valid_setter = false;
  1038. if (member.variable->getter_pointer != nullptr) {
  1039. if (p_class->has_function(member.variable->getter_pointer->name)) {
  1040. getter_function = p_class->get_member(member.variable->getter_pointer->name).function;
  1041. }
  1042. if (getter_function == nullptr) {
  1043. push_error(vformat(R"(Getter "%s" not found.)", member.variable->getter_pointer->name), member.variable);
  1044. } else {
  1045. GDScriptParser::DataType return_datatype = getter_function->datatype;
  1046. if (getter_function->return_type != nullptr) {
  1047. return_datatype = getter_function->return_type->datatype;
  1048. return_datatype.is_meta_type = false;
  1049. }
  1050. if (getter_function->parameters.size() != 0 || return_datatype.has_no_type()) {
  1051. push_error(vformat(R"(Function "%s" cannot be used as getter because of its signature.)", getter_function->identifier->name), member.variable);
  1052. } else if (!is_type_compatible(member.variable->datatype, return_datatype, true)) {
  1053. 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);
  1054. } else {
  1055. has_valid_getter = true;
  1056. #ifdef DEBUG_ENABLED
  1057. if (member.variable->datatype.builtin_type == Variant::INT && return_datatype.builtin_type == Variant::FLOAT) {
  1058. parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION);
  1059. }
  1060. #endif
  1061. }
  1062. }
  1063. }
  1064. if (member.variable->setter_pointer != nullptr) {
  1065. if (p_class->has_function(member.variable->setter_pointer->name)) {
  1066. setter_function = p_class->get_member(member.variable->setter_pointer->name).function;
  1067. }
  1068. if (setter_function == nullptr) {
  1069. push_error(vformat(R"(Setter "%s" not found.)", member.variable->setter_pointer->name), member.variable);
  1070. } else if (setter_function->parameters.size() != 1) {
  1071. push_error(vformat(R"(Function "%s" cannot be used as setter because of its signature.)", setter_function->identifier->name), member.variable);
  1072. } else if (!is_type_compatible(member.variable->datatype, setter_function->parameters[0]->datatype, true)) {
  1073. 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);
  1074. } else {
  1075. has_valid_setter = true;
  1076. #ifdef DEBUG_ENABLED
  1077. if (member.variable->datatype.builtin_type == Variant::FLOAT && setter_function->parameters[0]->datatype.builtin_type == Variant::INT) {
  1078. parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION);
  1079. }
  1080. #endif
  1081. }
  1082. }
  1083. if (member.variable->datatype.is_variant() && has_valid_getter && has_valid_setter) {
  1084. if (!is_type_compatible(getter_function->datatype, setter_function->parameters[0]->datatype, true)) {
  1085. 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);
  1086. }
  1087. }
  1088. #ifdef DEBUG_ENABLED
  1089. parser->ignored_warning_codes = previously_ignored;
  1090. #endif // DEBUG_ENABLED
  1091. }
  1092. }
  1093. }
  1094. parser->current_class = previous_class;
  1095. }
  1096. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  1097. resolve_class_body(p_class);
  1098. if (p_recursive) {
  1099. for (int i = 0; i < p_class->members.size(); i++) {
  1100. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1101. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  1102. resolve_class_body(member.m_class, true);
  1103. }
  1104. }
  1105. }
  1106. }
  1107. void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node, bool p_is_root) {
  1108. ERR_FAIL_COND_MSG(p_node == nullptr, "Trying to resolve type of a null node.");
  1109. switch (p_node->type) {
  1110. case GDScriptParser::Node::NONE:
  1111. break; // Unreachable.
  1112. case GDScriptParser::Node::CLASS:
  1113. if (OK == resolve_class_inheritance(static_cast<GDScriptParser::ClassNode *>(p_node), true)) {
  1114. resolve_class_interface(static_cast<GDScriptParser::ClassNode *>(p_node), true);
  1115. resolve_class_body(static_cast<GDScriptParser::ClassNode *>(p_node), true);
  1116. }
  1117. break;
  1118. case GDScriptParser::Node::CONSTANT:
  1119. resolve_constant(static_cast<GDScriptParser::ConstantNode *>(p_node));
  1120. break;
  1121. case GDScriptParser::Node::FOR:
  1122. resolve_for(static_cast<GDScriptParser::ForNode *>(p_node));
  1123. break;
  1124. case GDScriptParser::Node::FUNCTION:
  1125. resolve_function_signature(static_cast<GDScriptParser::FunctionNode *>(p_node));
  1126. resolve_function_body(static_cast<GDScriptParser::FunctionNode *>(p_node));
  1127. break;
  1128. case GDScriptParser::Node::IF:
  1129. resolve_if(static_cast<GDScriptParser::IfNode *>(p_node));
  1130. break;
  1131. case GDScriptParser::Node::SUITE:
  1132. resolve_suite(static_cast<GDScriptParser::SuiteNode *>(p_node));
  1133. break;
  1134. case GDScriptParser::Node::VARIABLE:
  1135. resolve_variable(static_cast<GDScriptParser::VariableNode *>(p_node));
  1136. break;
  1137. case GDScriptParser::Node::WHILE:
  1138. resolve_while(static_cast<GDScriptParser::WhileNode *>(p_node));
  1139. break;
  1140. case GDScriptParser::Node::ANNOTATION:
  1141. resolve_annotation(static_cast<GDScriptParser::AnnotationNode *>(p_node));
  1142. break;
  1143. case GDScriptParser::Node::ASSERT:
  1144. resolve_assert(static_cast<GDScriptParser::AssertNode *>(p_node));
  1145. break;
  1146. case GDScriptParser::Node::MATCH:
  1147. resolve_match(static_cast<GDScriptParser::MatchNode *>(p_node));
  1148. break;
  1149. case GDScriptParser::Node::MATCH_BRANCH:
  1150. resolve_match_branch(static_cast<GDScriptParser::MatchBranchNode *>(p_node), nullptr);
  1151. break;
  1152. case GDScriptParser::Node::PARAMETER:
  1153. resolve_parameter(static_cast<GDScriptParser::ParameterNode *>(p_node));
  1154. break;
  1155. case GDScriptParser::Node::PATTERN:
  1156. resolve_match_pattern(static_cast<GDScriptParser::PatternNode *>(p_node), nullptr);
  1157. break;
  1158. case GDScriptParser::Node::RETURN:
  1159. resolve_return(static_cast<GDScriptParser::ReturnNode *>(p_node));
  1160. break;
  1161. case GDScriptParser::Node::TYPE:
  1162. resolve_datatype(static_cast<GDScriptParser::TypeNode *>(p_node));
  1163. break;
  1164. // Resolving expression is the same as reducing them.
  1165. case GDScriptParser::Node::ARRAY:
  1166. case GDScriptParser::Node::ASSIGNMENT:
  1167. case GDScriptParser::Node::AWAIT:
  1168. case GDScriptParser::Node::BINARY_OPERATOR:
  1169. case GDScriptParser::Node::CALL:
  1170. case GDScriptParser::Node::CAST:
  1171. case GDScriptParser::Node::DICTIONARY:
  1172. case GDScriptParser::Node::GET_NODE:
  1173. case GDScriptParser::Node::IDENTIFIER:
  1174. case GDScriptParser::Node::LAMBDA:
  1175. case GDScriptParser::Node::LITERAL:
  1176. case GDScriptParser::Node::PRELOAD:
  1177. case GDScriptParser::Node::SELF:
  1178. case GDScriptParser::Node::SUBSCRIPT:
  1179. case GDScriptParser::Node::TERNARY_OPERATOR:
  1180. case GDScriptParser::Node::UNARY_OPERATOR:
  1181. reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), p_is_root);
  1182. break;
  1183. case GDScriptParser::Node::BREAK:
  1184. case GDScriptParser::Node::BREAKPOINT:
  1185. case GDScriptParser::Node::CONTINUE:
  1186. case GDScriptParser::Node::ENUM:
  1187. case GDScriptParser::Node::PASS:
  1188. case GDScriptParser::Node::SIGNAL:
  1189. // Nothing to do.
  1190. break;
  1191. }
  1192. }
  1193. void GDScriptAnalyzer::resolve_annotation(GDScriptParser::AnnotationNode *p_annotation) {
  1194. // TODO: Add second validation function for annotations, so they can use checked types.
  1195. }
  1196. void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode *p_function, const GDScriptParser::Node *p_source) {
  1197. if (p_source == nullptr) {
  1198. p_source = p_function;
  1199. }
  1200. if (p_function->get_datatype().is_resolving()) {
  1201. push_error(vformat(R"(Could not resolve function "%s": Cyclic reference.)", p_function->identifier->name), p_source);
  1202. return;
  1203. }
  1204. if (p_function->resolved_signature) {
  1205. return;
  1206. }
  1207. p_function->resolved_signature = true;
  1208. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  1209. parser->current_function = p_function;
  1210. GDScriptParser::DataType prev_datatype = p_function->get_datatype();
  1211. GDScriptParser::DataType resolving_datatype;
  1212. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  1213. p_function->set_datatype(resolving_datatype);
  1214. #ifdef TOOLS_ENABLED
  1215. int default_value_count = 0;
  1216. #endif // TOOLS_ENABLED
  1217. for (int i = 0; i < p_function->parameters.size(); i++) {
  1218. resolve_parameter(p_function->parameters[i]);
  1219. #ifdef DEBUG_ENABLED
  1220. if (p_function->parameters[i]->usages == 0 && !String(p_function->parameters[i]->identifier->name).begins_with("_")) {
  1221. parser->push_warning(p_function->parameters[i]->identifier, GDScriptWarning::UNUSED_PARAMETER, p_function->identifier->name, p_function->parameters[i]->identifier->name);
  1222. }
  1223. is_shadowing(p_function->parameters[i]->identifier, "function parameter");
  1224. #endif // DEBUG_ENABLED
  1225. #ifdef TOOLS_ENABLED
  1226. if (p_function->parameters[i]->default_value) {
  1227. default_value_count++;
  1228. if (p_function->parameters[i]->default_value->is_constant) {
  1229. p_function->default_arg_values.push_back(p_function->parameters[i]->default_value->reduced_value);
  1230. } else {
  1231. p_function->default_arg_values.push_back(Variant()); // Prevent shift.
  1232. }
  1233. }
  1234. #endif // TOOLS_ENABLED
  1235. }
  1236. if (p_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init) {
  1237. // Constructor.
  1238. GDScriptParser::DataType return_type = parser->current_class->get_datatype();
  1239. return_type.is_meta_type = false;
  1240. p_function->set_datatype(return_type);
  1241. if (p_function->return_type) {
  1242. GDScriptParser::DataType declared_return = resolve_datatype(p_function->return_type);
  1243. if (declared_return.kind != GDScriptParser::DataType::BUILTIN || declared_return.builtin_type != Variant::NIL) {
  1244. push_error("Constructor cannot have an explicit return type.", p_function->return_type);
  1245. }
  1246. }
  1247. } else {
  1248. if (p_function->return_type != nullptr) {
  1249. p_function->set_datatype(resolve_datatype(p_function->return_type));
  1250. } else {
  1251. // In case the function is not typed, we can safely assume it's a Variant, so it's okay to mark as "inferred" here.
  1252. // It's not "undetected" to not mix up with unknown functions.
  1253. GDScriptParser::DataType return_type;
  1254. return_type.type_source = GDScriptParser::DataType::INFERRED;
  1255. return_type.kind = GDScriptParser::DataType::VARIANT;
  1256. p_function->set_datatype(return_type);
  1257. }
  1258. #ifdef TOOLS_ENABLED
  1259. // Check if the function signature matches the parent. If not it's an error since it breaks polymorphism.
  1260. // Not for the constructor which can vary in signature.
  1261. GDScriptParser::DataType base_type = parser->current_class->base_type;
  1262. GDScriptParser::DataType parent_return_type;
  1263. List<GDScriptParser::DataType> parameters_types;
  1264. int default_par_count = 0;
  1265. bool is_static = false;
  1266. bool is_vararg = false;
  1267. 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)) {
  1268. bool valid = p_function->is_static == is_static;
  1269. valid = valid && parent_return_type == p_function->get_datatype();
  1270. int par_count_diff = p_function->parameters.size() - parameters_types.size();
  1271. valid = valid && par_count_diff >= 0;
  1272. valid = valid && default_value_count >= default_par_count + par_count_diff;
  1273. int i = 0;
  1274. for (const GDScriptParser::DataType &par_type : parameters_types) {
  1275. valid = valid && par_type == p_function->parameters[i++]->get_datatype();
  1276. }
  1277. if (!valid) {
  1278. // Compute parent signature as a string to show in the error message.
  1279. String parent_signature = p_function->identifier->name.operator String() + "(";
  1280. int j = 0;
  1281. for (const GDScriptParser::DataType &par_type : parameters_types) {
  1282. if (j > 0) {
  1283. parent_signature += ", ";
  1284. }
  1285. String parameter = par_type.to_string();
  1286. if (parameter == "null") {
  1287. parameter = "Variant";
  1288. }
  1289. parent_signature += parameter;
  1290. if (j == parameters_types.size() - default_par_count) {
  1291. parent_signature += " = default";
  1292. }
  1293. j++;
  1294. }
  1295. parent_signature += ") -> ";
  1296. const String return_type = parent_return_type.is_hard_type() ? parent_return_type.to_string() : "Variant";
  1297. if (return_type == "null") {
  1298. parent_signature += "void";
  1299. } else {
  1300. parent_signature += return_type;
  1301. }
  1302. push_error(vformat(R"(The function signature doesn't match the parent. Parent signature is "%s".)", parent_signature), p_function);
  1303. }
  1304. }
  1305. #endif // TOOLS_ENABLED
  1306. }
  1307. if (p_function->get_datatype().is_resolving()) {
  1308. p_function->set_datatype(prev_datatype);
  1309. }
  1310. parser->current_function = previous_function;
  1311. }
  1312. void GDScriptAnalyzer::resolve_function_body(GDScriptParser::FunctionNode *p_function) {
  1313. if (p_function->resolved_body) {
  1314. return;
  1315. }
  1316. p_function->resolved_body = true;
  1317. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  1318. parser->current_function = p_function;
  1319. resolve_suite(p_function->body);
  1320. GDScriptParser::DataType return_type = p_function->body->get_datatype();
  1321. if (!p_function->get_datatype().is_hard_type() && return_type.is_set()) {
  1322. // Use the suite inferred type if return isn't explicitly set.
  1323. return_type.type_source = GDScriptParser::DataType::INFERRED;
  1324. p_function->set_datatype(p_function->body->get_datatype());
  1325. } 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)) {
  1326. if (!p_function->body->has_return && p_function->identifier->name != GDScriptLanguage::get_singleton()->strings._init) {
  1327. push_error(R"(Not all code paths return a value.)", p_function);
  1328. }
  1329. }
  1330. parser->current_function = previous_function;
  1331. }
  1332. void GDScriptAnalyzer::decide_suite_type(GDScriptParser::Node *p_suite, GDScriptParser::Node *p_statement) {
  1333. if (p_statement == nullptr) {
  1334. return;
  1335. }
  1336. switch (p_statement->type) {
  1337. case GDScriptParser::Node::IF:
  1338. case GDScriptParser::Node::FOR:
  1339. case GDScriptParser::Node::MATCH:
  1340. case GDScriptParser::Node::PATTERN:
  1341. case GDScriptParser::Node::RETURN:
  1342. case GDScriptParser::Node::WHILE:
  1343. // Use return or nested suite type as this suite type.
  1344. if (p_suite->get_datatype().is_set() && (p_suite->get_datatype() != p_statement->get_datatype())) {
  1345. // Mixed types.
  1346. // TODO: This could use the common supertype instead.
  1347. p_suite->datatype.kind = GDScriptParser::DataType::VARIANT;
  1348. p_suite->datatype.type_source = GDScriptParser::DataType::UNDETECTED;
  1349. } else {
  1350. p_suite->set_datatype(p_statement->get_datatype());
  1351. p_suite->datatype.type_source = GDScriptParser::DataType::INFERRED;
  1352. }
  1353. break;
  1354. default:
  1355. break;
  1356. }
  1357. }
  1358. void GDScriptAnalyzer::resolve_suite(GDScriptParser::SuiteNode *p_suite) {
  1359. for (int i = 0; i < p_suite->statements.size(); i++) {
  1360. GDScriptParser::Node *stmt = p_suite->statements[i];
  1361. for (GDScriptParser::AnnotationNode *&annotation : stmt->annotations) {
  1362. annotation->apply(parser, stmt);
  1363. }
  1364. #ifdef DEBUG_ENABLED
  1365. HashSet<uint32_t> previously_ignored = parser->ignored_warning_codes;
  1366. for (uint32_t ignored_warning : stmt->ignored_warnings) {
  1367. parser->ignored_warning_codes.insert(ignored_warning);
  1368. }
  1369. #endif // DEBUG_ENABLED
  1370. resolve_node(stmt);
  1371. #ifdef DEBUG_ENABLED
  1372. parser->ignored_warning_codes = previously_ignored;
  1373. #endif // DEBUG_ENABLED
  1374. decide_suite_type(p_suite, stmt);
  1375. }
  1376. }
  1377. void GDScriptAnalyzer::resolve_if(GDScriptParser::IfNode *p_if) {
  1378. reduce_expression(p_if->condition);
  1379. resolve_suite(p_if->true_block);
  1380. p_if->set_datatype(p_if->true_block->get_datatype());
  1381. if (p_if->false_block != nullptr) {
  1382. resolve_suite(p_if->false_block);
  1383. decide_suite_type(p_if, p_if->false_block);
  1384. }
  1385. }
  1386. void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {
  1387. bool list_resolved = false;
  1388. // Optimize constant range() call to not allocate an array.
  1389. // Use int, Vector2i, Vector3i instead, which also can be used as range iterators.
  1390. if (p_for->list && p_for->list->type == GDScriptParser::Node::CALL) {
  1391. GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(p_for->list);
  1392. GDScriptParser::Node::Type callee_type = call->get_callee_type();
  1393. if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  1394. GDScriptParser::IdentifierNode *callee = static_cast<GDScriptParser::IdentifierNode *>(call->callee);
  1395. if (callee->name == "range") {
  1396. list_resolved = true;
  1397. if (call->arguments.size() < 1) {
  1398. push_error(R"*(Invalid call for "range()" function. Expected at least 1 argument, none given.)*", call->callee);
  1399. } else if (call->arguments.size() > 3) {
  1400. push_error(vformat(R"*(Invalid call for "range()" function. Expected at most 3 arguments, %d given.)*", call->arguments.size()), call->callee);
  1401. } else {
  1402. // Now we can optimize it.
  1403. bool all_is_constant = true;
  1404. Vector<Variant> args;
  1405. args.resize(call->arguments.size());
  1406. for (int i = 0; i < call->arguments.size(); i++) {
  1407. reduce_expression(call->arguments[i]);
  1408. if (!call->arguments[i]->is_constant) {
  1409. all_is_constant = false;
  1410. } else if (all_is_constant) {
  1411. args.write[i] = call->arguments[i]->reduced_value;
  1412. }
  1413. GDScriptParser::DataType arg_type = call->arguments[i]->get_datatype();
  1414. if (!arg_type.is_variant()) {
  1415. if (arg_type.kind != GDScriptParser::DataType::BUILTIN) {
  1416. all_is_constant = false;
  1417. 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]);
  1418. } else if (arg_type.builtin_type != Variant::INT && arg_type.builtin_type != Variant::FLOAT) {
  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. }
  1422. }
  1423. }
  1424. Variant reduced;
  1425. if (all_is_constant) {
  1426. switch (args.size()) {
  1427. case 1:
  1428. reduced = (int32_t)args[0];
  1429. break;
  1430. case 2:
  1431. reduced = Vector2i(args[0], args[1]);
  1432. break;
  1433. case 3:
  1434. reduced = Vector3i(args[0], args[1], args[2]);
  1435. break;
  1436. }
  1437. p_for->list->is_constant = true;
  1438. p_for->list->reduced_value = reduced;
  1439. }
  1440. }
  1441. if (p_for->list->is_constant) {
  1442. p_for->list->set_datatype(type_from_variant(p_for->list->reduced_value, p_for->list));
  1443. } else {
  1444. GDScriptParser::DataType list_type;
  1445. list_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1446. list_type.kind = GDScriptParser::DataType::BUILTIN;
  1447. list_type.builtin_type = Variant::ARRAY;
  1448. p_for->list->set_datatype(list_type);
  1449. }
  1450. }
  1451. }
  1452. }
  1453. GDScriptParser::DataType variable_type;
  1454. if (list_resolved) {
  1455. variable_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1456. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1457. variable_type.builtin_type = Variant::INT; // Can this ever be a float or something else?
  1458. p_for->variable->set_datatype(variable_type);
  1459. } else if (p_for->list) {
  1460. resolve_node(p_for->list, false);
  1461. if (p_for->list->datatype.has_container_element_type()) {
  1462. variable_type = p_for->list->datatype.get_container_element_type();
  1463. variable_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1464. } else if (p_for->list->datatype.is_typed_container_type()) {
  1465. variable_type = p_for->list->datatype.get_typed_container_type();
  1466. variable_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1467. } else {
  1468. // Last resort
  1469. // TODO: Must other cases be handled? Must we mark as unsafe?
  1470. variable_type.type_source = GDScriptParser::DataType::UNDETECTED;
  1471. variable_type.kind = GDScriptParser::DataType::VARIANT;
  1472. }
  1473. }
  1474. if (p_for->variable) {
  1475. p_for->variable->set_datatype(variable_type);
  1476. }
  1477. resolve_suite(p_for->loop);
  1478. p_for->set_datatype(p_for->loop->get_datatype());
  1479. #ifdef DEBUG_ENABLED
  1480. if (p_for->variable) {
  1481. is_shadowing(p_for->variable, R"("for" iterator variable)");
  1482. }
  1483. #endif
  1484. }
  1485. void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) {
  1486. resolve_node(p_while->condition, false);
  1487. resolve_suite(p_while->loop);
  1488. p_while->set_datatype(p_while->loop->get_datatype());
  1489. }
  1490. void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable) {
  1491. GDScriptParser::DataType type;
  1492. type.kind = GDScriptParser::DataType::VARIANT; // By default.
  1493. GDScriptParser::DataType specified_type;
  1494. if (p_variable->datatype_specifier != nullptr) {
  1495. specified_type = resolve_datatype(p_variable->datatype_specifier);
  1496. specified_type.is_meta_type = false;
  1497. }
  1498. if (p_variable->initializer != nullptr) {
  1499. reduce_expression(p_variable->initializer);
  1500. if ((p_variable->infer_datatype || (p_variable->datatype_specifier != nullptr && specified_type.has_container_element_type())) && p_variable->initializer->type == GDScriptParser::Node::ARRAY) {
  1501. // Typed array.
  1502. GDScriptParser::ArrayNode *array = static_cast<GDScriptParser::ArrayNode *>(p_variable->initializer);
  1503. // Can only infer typed array if it has elements.
  1504. if ((p_variable->infer_datatype && array->elements.size() > 0) || p_variable->datatype_specifier != nullptr) {
  1505. update_array_literal_element_type(specified_type, array);
  1506. }
  1507. }
  1508. type = p_variable->initializer->get_datatype();
  1509. #ifdef DEBUG_ENABLED
  1510. if (p_variable->initializer->type == GDScriptParser::Node::CALL && type.is_hard_type() && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
  1511. parser->push_warning(p_variable->initializer, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_variable->initializer)->function_name);
  1512. }
  1513. #endif
  1514. if (p_variable->infer_datatype) {
  1515. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1516. if (type.has_no_type()) {
  1517. 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);
  1518. } else if (type.is_variant()) {
  1519. 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);
  1520. } else if (type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
  1521. 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);
  1522. }
  1523. } else {
  1524. type.type_source = GDScriptParser::DataType::INFERRED;
  1525. }
  1526. }
  1527. if (p_variable->datatype_specifier != nullptr) {
  1528. type = specified_type;
  1529. type.is_meta_type = false;
  1530. if (p_variable->initializer != nullptr) {
  1531. if (!is_type_compatible(type, p_variable->initializer->get_datatype(), true, p_variable->initializer)) {
  1532. // Try reverse test since it can be a masked subtype.
  1533. if (!is_type_compatible(p_variable->initializer->get_datatype(), type, true, p_variable->initializer)) {
  1534. 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);
  1535. } else {
  1536. // TODO: Add warning.
  1537. mark_node_unsafe(p_variable->initializer);
  1538. p_variable->use_conversion_assign = true;
  1539. }
  1540. #ifdef DEBUG_ENABLED
  1541. } else if (type.builtin_type == Variant::INT && p_variable->initializer->get_datatype().builtin_type == Variant::FLOAT) {
  1542. parser->push_warning(p_variable->initializer, GDScriptWarning::NARROWING_CONVERSION);
  1543. #endif
  1544. }
  1545. if (p_variable->initializer->get_datatype().is_variant() && !type.is_variant()) {
  1546. // TODO: Warn unsafe assign.
  1547. mark_node_unsafe(p_variable->initializer);
  1548. p_variable->use_conversion_assign = true;
  1549. }
  1550. }
  1551. } else if (p_variable->infer_datatype) {
  1552. if (type.has_no_type()) {
  1553. 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);
  1554. }
  1555. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1556. }
  1557. type.is_constant = false;
  1558. p_variable->set_datatype(type);
  1559. #ifdef DEBUG_ENABLED
  1560. if (p_variable->usages == 0 && !String(p_variable->identifier->name).begins_with("_")) {
  1561. parser->push_warning(p_variable, GDScriptWarning::UNUSED_VARIABLE, p_variable->identifier->name);
  1562. } else if (p_variable->assignments == 0) {
  1563. parser->push_warning(p_variable, GDScriptWarning::UNASSIGNED_VARIABLE, p_variable->identifier->name);
  1564. }
  1565. is_shadowing(p_variable->identifier, "variable");
  1566. #endif
  1567. }
  1568. void GDScriptAnalyzer::resolve_constant(GDScriptParser::ConstantNode *p_constant) {
  1569. GDScriptParser::DataType type;
  1570. GDScriptParser::DataType explicit_type;
  1571. if (p_constant->datatype_specifier != nullptr) {
  1572. explicit_type = resolve_datatype(p_constant->datatype_specifier);
  1573. explicit_type.is_meta_type = false;
  1574. }
  1575. if (p_constant->initializer != nullptr) {
  1576. reduce_expression(p_constant->initializer);
  1577. if (p_constant->initializer->type == GDScriptParser::Node::ARRAY) {
  1578. GDScriptParser::ArrayNode *array = static_cast<GDScriptParser::ArrayNode *>(p_constant->initializer);
  1579. const_fold_array(array);
  1580. // Can only infer typed array if it has elements.
  1581. if (array->elements.size() > 0 || (p_constant->datatype_specifier != nullptr && explicit_type.has_container_element_type())) {
  1582. update_array_literal_element_type(explicit_type, array);
  1583. }
  1584. } else if (p_constant->initializer->type == GDScriptParser::Node::DICTIONARY) {
  1585. const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_constant->initializer));
  1586. }
  1587. if (!p_constant->initializer->is_constant) {
  1588. push_error(vformat(R"(Assigned value for constant "%s" isn't a constant expression.)", p_constant->identifier->name), p_constant->initializer);
  1589. }
  1590. type = p_constant->initializer->get_datatype();
  1591. #ifdef DEBUG_ENABLED
  1592. if (p_constant->initializer->type == GDScriptParser::Node::CALL && type.is_hard_type() && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
  1593. parser->push_warning(p_constant->initializer, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_constant->initializer)->function_name);
  1594. }
  1595. #endif
  1596. }
  1597. if (p_constant->datatype_specifier != nullptr) {
  1598. if (!is_type_compatible(explicit_type, type, true)) {
  1599. 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);
  1600. #ifdef DEBUG_ENABLED
  1601. } else if (explicit_type.builtin_type == Variant::INT && type.builtin_type == Variant::FLOAT) {
  1602. parser->push_warning(p_constant->initializer, GDScriptWarning::NARROWING_CONVERSION);
  1603. #endif
  1604. }
  1605. type = explicit_type;
  1606. } else if (p_constant->infer_datatype) {
  1607. if (type.has_no_type()) {
  1608. 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);
  1609. }
  1610. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1611. }
  1612. type.is_constant = true;
  1613. p_constant->set_datatype(type);
  1614. #ifdef DEBUG_ENABLED
  1615. if (p_constant->usages == 0) {
  1616. parser->push_warning(p_constant, GDScriptWarning::UNUSED_LOCAL_CONSTANT, p_constant->identifier->name);
  1617. }
  1618. is_shadowing(p_constant->identifier, "constant");
  1619. #endif
  1620. }
  1621. void GDScriptAnalyzer::resolve_assert(GDScriptParser::AssertNode *p_assert) {
  1622. reduce_expression(p_assert->condition);
  1623. if (p_assert->message != nullptr) {
  1624. reduce_expression(p_assert->message);
  1625. 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)) {
  1626. push_error(R"(Expected string for assert error message.)", p_assert->message);
  1627. }
  1628. }
  1629. p_assert->set_datatype(p_assert->condition->get_datatype());
  1630. #ifdef DEBUG_ENABLED
  1631. if (p_assert->condition->is_constant) {
  1632. if (p_assert->condition->reduced_value.booleanize()) {
  1633. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_TRUE);
  1634. } else {
  1635. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_FALSE);
  1636. }
  1637. }
  1638. #endif
  1639. }
  1640. void GDScriptAnalyzer::resolve_match(GDScriptParser::MatchNode *p_match) {
  1641. reduce_expression(p_match->test);
  1642. for (int i = 0; i < p_match->branches.size(); i++) {
  1643. resolve_match_branch(p_match->branches[i], p_match->test);
  1644. decide_suite_type(p_match, p_match->branches[i]);
  1645. }
  1646. }
  1647. void GDScriptAnalyzer::resolve_match_branch(GDScriptParser::MatchBranchNode *p_match_branch, GDScriptParser::ExpressionNode *p_match_test) {
  1648. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  1649. resolve_match_pattern(p_match_branch->patterns[i], p_match_test);
  1650. }
  1651. resolve_suite(p_match_branch->block);
  1652. decide_suite_type(p_match_branch, p_match_branch->block);
  1653. }
  1654. void GDScriptAnalyzer::resolve_match_pattern(GDScriptParser::PatternNode *p_match_pattern, GDScriptParser::ExpressionNode *p_match_test) {
  1655. if (p_match_pattern == nullptr) {
  1656. return;
  1657. }
  1658. GDScriptParser::DataType result;
  1659. switch (p_match_pattern->pattern_type) {
  1660. case GDScriptParser::PatternNode::PT_LITERAL:
  1661. if (p_match_pattern->literal) {
  1662. reduce_literal(p_match_pattern->literal);
  1663. result = p_match_pattern->literal->get_datatype();
  1664. }
  1665. break;
  1666. case GDScriptParser::PatternNode::PT_EXPRESSION:
  1667. if (p_match_pattern->expression) {
  1668. reduce_expression(p_match_pattern->expression);
  1669. if (!p_match_pattern->expression->is_constant) {
  1670. push_error(R"(Expression in match pattern must be a constant.)", p_match_pattern->expression);
  1671. }
  1672. result = p_match_pattern->expression->get_datatype();
  1673. }
  1674. break;
  1675. case GDScriptParser::PatternNode::PT_BIND:
  1676. if (p_match_test != nullptr) {
  1677. result = p_match_test->get_datatype();
  1678. } else {
  1679. result.kind = GDScriptParser::DataType::VARIANT;
  1680. }
  1681. p_match_pattern->bind->set_datatype(result);
  1682. #ifdef DEBUG_ENABLED
  1683. is_shadowing(p_match_pattern->bind, "pattern bind");
  1684. if (p_match_pattern->bind->usages == 0 && !String(p_match_pattern->bind->name).begins_with("_")) {
  1685. parser->push_warning(p_match_pattern->bind, GDScriptWarning::UNUSED_VARIABLE, p_match_pattern->bind->name);
  1686. }
  1687. #endif
  1688. break;
  1689. case GDScriptParser::PatternNode::PT_ARRAY:
  1690. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  1691. resolve_match_pattern(p_match_pattern->array[i], nullptr);
  1692. decide_suite_type(p_match_pattern, p_match_pattern->array[i]);
  1693. }
  1694. result = p_match_pattern->get_datatype();
  1695. break;
  1696. case GDScriptParser::PatternNode::PT_DICTIONARY:
  1697. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  1698. if (p_match_pattern->dictionary[i].key) {
  1699. reduce_expression(p_match_pattern->dictionary[i].key);
  1700. if (!p_match_pattern->dictionary[i].key->is_constant) {
  1701. push_error(R"(Expression in dictionary pattern key must be a constant.)", p_match_pattern->dictionary[i].key);
  1702. }
  1703. }
  1704. if (p_match_pattern->dictionary[i].value_pattern) {
  1705. resolve_match_pattern(p_match_pattern->dictionary[i].value_pattern, nullptr);
  1706. decide_suite_type(p_match_pattern, p_match_pattern->dictionary[i].value_pattern);
  1707. }
  1708. }
  1709. result = p_match_pattern->get_datatype();
  1710. break;
  1711. case GDScriptParser::PatternNode::PT_WILDCARD:
  1712. case GDScriptParser::PatternNode::PT_REST:
  1713. result.kind = GDScriptParser::DataType::VARIANT;
  1714. break;
  1715. }
  1716. p_match_pattern->set_datatype(result);
  1717. }
  1718. void GDScriptAnalyzer::resolve_parameter(GDScriptParser::ParameterNode *p_parameter) {
  1719. GDScriptParser::DataType result;
  1720. result.kind = GDScriptParser::DataType::VARIANT;
  1721. if (p_parameter->default_value != nullptr) {
  1722. reduce_expression(p_parameter->default_value);
  1723. result = p_parameter->default_value->get_datatype();
  1724. if (p_parameter->infer_datatype) {
  1725. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1726. } else {
  1727. result.type_source = GDScriptParser::DataType::INFERRED;
  1728. }
  1729. }
  1730. if (p_parameter->datatype_specifier != nullptr) {
  1731. result = resolve_datatype(p_parameter->datatype_specifier);
  1732. result.is_meta_type = false;
  1733. if (p_parameter->default_value != nullptr) {
  1734. if (!is_type_compatible(result, p_parameter->default_value->get_datatype())) {
  1735. 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);
  1736. } else if (p_parameter->default_value->get_datatype().is_variant()) {
  1737. mark_node_unsafe(p_parameter);
  1738. }
  1739. }
  1740. }
  1741. if (result.builtin_type == Variant::Type::NIL && result.type_source == GDScriptParser::DataType::ANNOTATED_INFERRED && p_parameter->datatype_specifier == nullptr) {
  1742. 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);
  1743. }
  1744. result.is_constant = false;
  1745. p_parameter->set_datatype(result);
  1746. }
  1747. void GDScriptAnalyzer::resolve_return(GDScriptParser::ReturnNode *p_return) {
  1748. GDScriptParser::DataType result;
  1749. GDScriptParser::DataType expected_type;
  1750. bool has_expected_type = false;
  1751. if (parser->current_function != nullptr) {
  1752. expected_type = parser->current_function->get_datatype();
  1753. has_expected_type = true;
  1754. }
  1755. if (p_return->return_value != nullptr) {
  1756. reduce_expression(p_return->return_value);
  1757. if (p_return->return_value->type == GDScriptParser::Node::ARRAY) {
  1758. // Check if assigned value is an array literal, so we can make it a typed array too if appropriate.
  1759. if (has_expected_type && expected_type.has_container_element_type() && p_return->return_value->type == GDScriptParser::Node::ARRAY) {
  1760. update_array_literal_element_type(expected_type, static_cast<GDScriptParser::ArrayNode *>(p_return->return_value));
  1761. }
  1762. }
  1763. result = p_return->return_value->get_datatype();
  1764. } else {
  1765. // Return type is null by default.
  1766. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1767. result.kind = GDScriptParser::DataType::BUILTIN;
  1768. result.builtin_type = Variant::NIL;
  1769. result.is_constant = true;
  1770. }
  1771. if (has_expected_type) {
  1772. expected_type.is_meta_type = false;
  1773. if (expected_type.is_hard_type()) {
  1774. if (!is_type_compatible(expected_type, result)) {
  1775. // Try other way. Okay but not safe.
  1776. if (!is_type_compatible(result, expected_type)) {
  1777. 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);
  1778. } else {
  1779. // TODO: Add warning.
  1780. mark_node_unsafe(p_return);
  1781. }
  1782. #ifdef DEBUG_ENABLED
  1783. } else if (expected_type.builtin_type == Variant::INT && result.builtin_type == Variant::FLOAT) {
  1784. parser->push_warning(p_return, GDScriptWarning::NARROWING_CONVERSION);
  1785. } else if (result.is_variant()) {
  1786. mark_node_unsafe(p_return);
  1787. #endif
  1788. }
  1789. }
  1790. }
  1791. p_return->set_datatype(result);
  1792. }
  1793. void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expression, bool p_is_root) {
  1794. // This one makes some magic happen.
  1795. if (p_expression == nullptr) {
  1796. return;
  1797. }
  1798. if (p_expression->reduced) {
  1799. // Don't do this more than once.
  1800. return;
  1801. }
  1802. p_expression->reduced = true;
  1803. switch (p_expression->type) {
  1804. case GDScriptParser::Node::ARRAY:
  1805. reduce_array(static_cast<GDScriptParser::ArrayNode *>(p_expression));
  1806. break;
  1807. case GDScriptParser::Node::ASSIGNMENT:
  1808. reduce_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
  1809. break;
  1810. case GDScriptParser::Node::AWAIT:
  1811. reduce_await(static_cast<GDScriptParser::AwaitNode *>(p_expression));
  1812. break;
  1813. case GDScriptParser::Node::BINARY_OPERATOR:
  1814. reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));
  1815. break;
  1816. case GDScriptParser::Node::CALL:
  1817. reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), false, p_is_root);
  1818. break;
  1819. case GDScriptParser::Node::CAST:
  1820. reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));
  1821. break;
  1822. case GDScriptParser::Node::DICTIONARY:
  1823. reduce_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_expression));
  1824. break;
  1825. case GDScriptParser::Node::GET_NODE:
  1826. reduce_get_node(static_cast<GDScriptParser::GetNodeNode *>(p_expression));
  1827. break;
  1828. case GDScriptParser::Node::IDENTIFIER:
  1829. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression));
  1830. break;
  1831. case GDScriptParser::Node::LAMBDA:
  1832. reduce_lambda(static_cast<GDScriptParser::LambdaNode *>(p_expression));
  1833. break;
  1834. case GDScriptParser::Node::LITERAL:
  1835. reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression));
  1836. break;
  1837. case GDScriptParser::Node::PRELOAD:
  1838. reduce_preload(static_cast<GDScriptParser::PreloadNode *>(p_expression));
  1839. break;
  1840. case GDScriptParser::Node::SELF:
  1841. reduce_self(static_cast<GDScriptParser::SelfNode *>(p_expression));
  1842. break;
  1843. case GDScriptParser::Node::SUBSCRIPT:
  1844. reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_expression));
  1845. break;
  1846. case GDScriptParser::Node::TERNARY_OPERATOR:
  1847. reduce_ternary_op(static_cast<GDScriptParser::TernaryOpNode *>(p_expression));
  1848. break;
  1849. case GDScriptParser::Node::UNARY_OPERATOR:
  1850. reduce_unary_op(static_cast<GDScriptParser::UnaryOpNode *>(p_expression));
  1851. break;
  1852. // Non-expressions. Here only to make sure new nodes aren't forgotten.
  1853. case GDScriptParser::Node::NONE:
  1854. case GDScriptParser::Node::ANNOTATION:
  1855. case GDScriptParser::Node::ASSERT:
  1856. case GDScriptParser::Node::BREAK:
  1857. case GDScriptParser::Node::BREAKPOINT:
  1858. case GDScriptParser::Node::CLASS:
  1859. case GDScriptParser::Node::CONSTANT:
  1860. case GDScriptParser::Node::CONTINUE:
  1861. case GDScriptParser::Node::ENUM:
  1862. case GDScriptParser::Node::FOR:
  1863. case GDScriptParser::Node::FUNCTION:
  1864. case GDScriptParser::Node::IF:
  1865. case GDScriptParser::Node::MATCH:
  1866. case GDScriptParser::Node::MATCH_BRANCH:
  1867. case GDScriptParser::Node::PARAMETER:
  1868. case GDScriptParser::Node::PASS:
  1869. case GDScriptParser::Node::PATTERN:
  1870. case GDScriptParser::Node::RETURN:
  1871. case GDScriptParser::Node::SIGNAL:
  1872. case GDScriptParser::Node::SUITE:
  1873. case GDScriptParser::Node::TYPE:
  1874. case GDScriptParser::Node::VARIABLE:
  1875. case GDScriptParser::Node::WHILE:
  1876. ERR_FAIL_MSG("Reaching unreachable case");
  1877. }
  1878. }
  1879. void GDScriptAnalyzer::reduce_array(GDScriptParser::ArrayNode *p_array) {
  1880. for (int i = 0; i < p_array->elements.size(); i++) {
  1881. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  1882. reduce_expression(element);
  1883. }
  1884. // It's array in any case.
  1885. GDScriptParser::DataType arr_type;
  1886. arr_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1887. arr_type.kind = GDScriptParser::DataType::BUILTIN;
  1888. arr_type.builtin_type = Variant::ARRAY;
  1889. arr_type.is_constant = true;
  1890. p_array->set_datatype(arr_type);
  1891. }
  1892. // When an array literal is stored (or passed as function argument) to a typed context, we then assume the array is typed.
  1893. // This function determines which type is that (if any).
  1894. void GDScriptAnalyzer::update_array_literal_element_type(const GDScriptParser::DataType &p_base_type, GDScriptParser::ArrayNode *p_array_literal) {
  1895. GDScriptParser::DataType array_type = p_array_literal->get_datatype();
  1896. if (p_array_literal->elements.size() == 0) {
  1897. // Empty array literal, just make the same type as the storage.
  1898. array_type.set_container_element_type(p_base_type.get_container_element_type());
  1899. } else {
  1900. // Check if elements match.
  1901. bool all_same_type = true;
  1902. bool all_have_type = true;
  1903. GDScriptParser::DataType element_type;
  1904. for (int i = 0; i < p_array_literal->elements.size(); i++) {
  1905. if (i == 0) {
  1906. element_type = p_array_literal->elements[0]->get_datatype();
  1907. } else {
  1908. GDScriptParser::DataType this_element_type = p_array_literal->elements[i]->get_datatype();
  1909. if (this_element_type.has_no_type()) {
  1910. all_same_type = false;
  1911. all_have_type = false;
  1912. break;
  1913. } else if (element_type != this_element_type) {
  1914. if (!is_type_compatible(element_type, this_element_type, false)) {
  1915. if (is_type_compatible(this_element_type, element_type, false)) {
  1916. // This element is a super-type to the previous type, so we use the super-type.
  1917. element_type = this_element_type;
  1918. } else {
  1919. // It's incompatible.
  1920. all_same_type = false;
  1921. break;
  1922. }
  1923. }
  1924. }
  1925. }
  1926. }
  1927. if (all_same_type) {
  1928. element_type.is_constant = false;
  1929. array_type.set_container_element_type(element_type);
  1930. } else if (all_have_type) {
  1931. 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);
  1932. }
  1933. }
  1934. // Update the type on the value itself.
  1935. p_array_literal->set_datatype(array_type);
  1936. }
  1937. void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assignment) {
  1938. reduce_expression(p_assignment->assignee);
  1939. reduce_expression(p_assignment->assigned_value);
  1940. if (p_assignment->assigned_value == nullptr || p_assignment->assignee == nullptr) {
  1941. return;
  1942. }
  1943. GDScriptParser::DataType assignee_type = p_assignment->assignee->get_datatype();
  1944. // Check if assigned value is an array literal, so we can make it a typed array too if appropriate.
  1945. if (assignee_type.has_container_element_type() && p_assignment->assigned_value->type == GDScriptParser::Node::ARRAY) {
  1946. update_array_literal_element_type(assignee_type, static_cast<GDScriptParser::ArrayNode *>(p_assignment->assigned_value));
  1947. }
  1948. GDScriptParser::DataType assigned_value_type = p_assignment->assigned_value->get_datatype();
  1949. if (assignee_type.is_constant) {
  1950. push_error("Cannot assign a new value to a constant.", p_assignment->assignee);
  1951. }
  1952. bool compatible = true;
  1953. GDScriptParser::DataType op_type = assigned_value_type;
  1954. if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) {
  1955. op_type = get_operation_type(p_assignment->variant_op, assignee_type, assigned_value_type, compatible, p_assignment->assigned_value);
  1956. }
  1957. p_assignment->set_datatype(op_type);
  1958. if (!assignee_type.is_variant() && assigned_value_type.is_hard_type()) {
  1959. if (compatible) {
  1960. compatible = is_type_compatible(assignee_type, op_type, true, p_assignment->assigned_value);
  1961. if (!compatible) {
  1962. if (assignee_type.is_hard_type()) {
  1963. // Try reverse test since it can be a masked subtype.
  1964. if (!is_type_compatible(op_type, assignee_type, true, p_assignment->assigned_value)) {
  1965. 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);
  1966. } else {
  1967. // TODO: Add warning.
  1968. mark_node_unsafe(p_assignment);
  1969. p_assignment->use_conversion_assign = true;
  1970. }
  1971. } else {
  1972. // TODO: Warning in this case.
  1973. mark_node_unsafe(p_assignment);
  1974. }
  1975. }
  1976. } else {
  1977. push_error(vformat(R"(Invalid operands "%s" and "%s" for assignment operator.)", assignee_type.to_string(), assigned_value_type.to_string()), p_assignment);
  1978. }
  1979. }
  1980. if (assignee_type.has_no_type() || assigned_value_type.is_variant()) {
  1981. mark_node_unsafe(p_assignment);
  1982. if (assignee_type.is_hard_type() && !assignee_type.is_variant()) {
  1983. p_assignment->use_conversion_assign = true;
  1984. }
  1985. }
  1986. if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
  1987. // Change source type so it's not wrongly detected later.
  1988. GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee);
  1989. switch (identifier->source) {
  1990. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {
  1991. GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
  1992. if (!id_type.is_hard_type()) {
  1993. id_type.kind = GDScriptParser::DataType::VARIANT;
  1994. id_type.type_source = GDScriptParser::DataType::UNDETECTED;
  1995. identifier->variable_source->set_datatype(id_type);
  1996. }
  1997. } break;
  1998. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER: {
  1999. GDScriptParser::DataType id_type = identifier->parameter_source->get_datatype();
  2000. if (!id_type.is_hard_type()) {
  2001. id_type.kind = GDScriptParser::DataType::VARIANT;
  2002. id_type.type_source = GDScriptParser::DataType::UNDETECTED;
  2003. identifier->parameter_source->set_datatype(id_type);
  2004. }
  2005. } break;
  2006. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {
  2007. GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
  2008. if (!id_type.is_hard_type()) {
  2009. id_type.kind = GDScriptParser::DataType::VARIANT;
  2010. id_type.type_source = GDScriptParser::DataType::UNDETECTED;
  2011. identifier->variable_source->set_datatype(id_type);
  2012. }
  2013. } break;
  2014. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {
  2015. GDScriptParser::DataType id_type = identifier->bind_source->get_datatype();
  2016. if (!id_type.is_hard_type()) {
  2017. id_type.kind = GDScriptParser::DataType::VARIANT;
  2018. id_type.type_source = GDScriptParser::DataType::UNDETECTED;
  2019. identifier->variable_source->set_datatype(id_type);
  2020. }
  2021. } break;
  2022. default:
  2023. // Nothing to do.
  2024. break;
  2025. }
  2026. }
  2027. #ifdef DEBUG_ENABLED
  2028. if (p_assignment->assigned_value->type == GDScriptParser::Node::CALL && assigned_value_type.is_hard_type() && assigned_value_type.kind == GDScriptParser::DataType::BUILTIN && assigned_value_type.builtin_type == Variant::NIL) {
  2029. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_assignment->assigned_value)->function_name);
  2030. } else if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_value_type.builtin_type == Variant::FLOAT) {
  2031. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION);
  2032. }
  2033. #endif
  2034. }
  2035. void GDScriptAnalyzer::reduce_await(GDScriptParser::AwaitNode *p_await) {
  2036. if (p_await->to_await == nullptr) {
  2037. GDScriptParser::DataType await_type;
  2038. await_type.kind = GDScriptParser::DataType::VARIANT;
  2039. p_await->set_datatype(await_type);
  2040. return;
  2041. }
  2042. GDScriptParser::DataType awaiting_type;
  2043. if (p_await->to_await->type == GDScriptParser::Node::CALL) {
  2044. reduce_call(static_cast<GDScriptParser::CallNode *>(p_await->to_await), true);
  2045. awaiting_type = p_await->to_await->get_datatype();
  2046. } else {
  2047. reduce_expression(p_await->to_await);
  2048. }
  2049. if (p_await->to_await->is_constant) {
  2050. p_await->is_constant = p_await->to_await->is_constant;
  2051. p_await->reduced_value = p_await->to_await->reduced_value;
  2052. awaiting_type = p_await->to_await->get_datatype();
  2053. } else {
  2054. awaiting_type.kind = GDScriptParser::DataType::VARIANT;
  2055. awaiting_type.type_source = GDScriptParser::DataType::UNDETECTED;
  2056. }
  2057. p_await->set_datatype(awaiting_type);
  2058. #ifdef DEBUG_ENABLED
  2059. awaiting_type = p_await->to_await->get_datatype();
  2060. if (!(awaiting_type.has_no_type() || awaiting_type.is_coroutine || awaiting_type.builtin_type == Variant::SIGNAL)) {
  2061. parser->push_warning(p_await, GDScriptWarning::REDUNDANT_AWAIT);
  2062. }
  2063. #endif
  2064. }
  2065. void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op) {
  2066. reduce_expression(p_binary_op->left_operand);
  2067. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST && p_binary_op->right_operand && p_binary_op->right_operand->type == GDScriptParser::Node::IDENTIFIER) {
  2068. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_binary_op->right_operand), true);
  2069. } else {
  2070. reduce_expression(p_binary_op->right_operand);
  2071. }
  2072. // TODO: Right operand must be a valid type with the `is` operator. Need to check here.
  2073. GDScriptParser::DataType left_type;
  2074. if (p_binary_op->left_operand) {
  2075. left_type = p_binary_op->left_operand->get_datatype();
  2076. }
  2077. GDScriptParser::DataType right_type;
  2078. if (p_binary_op->right_operand) {
  2079. right_type = p_binary_op->right_operand->get_datatype();
  2080. }
  2081. if (!left_type.is_set() || !right_type.is_set()) {
  2082. return;
  2083. }
  2084. #ifdef DEBUG_ENABLED
  2085. if (p_binary_op->variant_op == Variant::OP_DIVIDE && left_type.builtin_type == Variant::INT && right_type.builtin_type == Variant::INT) {
  2086. parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);
  2087. }
  2088. #endif
  2089. if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {
  2090. p_binary_op->is_constant = true;
  2091. if (p_binary_op->variant_op < Variant::OP_MAX) {
  2092. bool valid = false;
  2093. 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);
  2094. if (!valid) {
  2095. if (p_binary_op->reduced_value.get_type() == Variant::STRING) {
  2096. 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);
  2097. } else {
  2098. push_error(vformat(R"(Invalid operands to operator %s, %s and %s.)",
  2099. Variant::get_operator_name(p_binary_op->variant_op),
  2100. Variant::get_type_name(p_binary_op->left_operand->reduced_value.get_type()),
  2101. Variant::get_type_name(p_binary_op->right_operand->reduced_value.get_type())),
  2102. p_binary_op);
  2103. }
  2104. }
  2105. } else {
  2106. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  2107. GDScriptParser::DataType test_type = right_type;
  2108. test_type.is_meta_type = false;
  2109. if (!is_type_compatible(test_type, left_type, false)) {
  2110. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)"), p_binary_op->left_operand);
  2111. p_binary_op->reduced_value = false;
  2112. } else {
  2113. p_binary_op->reduced_value = true;
  2114. }
  2115. } else {
  2116. ERR_PRINT("Parser bug: unknown binary operation.");
  2117. }
  2118. }
  2119. p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value, p_binary_op));
  2120. return;
  2121. }
  2122. GDScriptParser::DataType result;
  2123. if (left_type.is_variant() || right_type.is_variant()) {
  2124. // Cannot infer type because one operand can be anything.
  2125. result.kind = GDScriptParser::DataType::VARIANT;
  2126. mark_node_unsafe(p_binary_op);
  2127. } else {
  2128. if (p_binary_op->variant_op < Variant::OP_MAX) {
  2129. bool valid = false;
  2130. result = get_operation_type(p_binary_op->variant_op, left_type, right_type, valid, p_binary_op);
  2131. if (!valid) {
  2132. 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);
  2133. }
  2134. } else {
  2135. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  2136. GDScriptParser::DataType test_type = right_type;
  2137. test_type.is_meta_type = false;
  2138. if (!is_type_compatible(test_type, left_type, false)) {
  2139. // Test reverse as well to consider for subtypes.
  2140. if (!is_type_compatible(left_type, test_type, false)) {
  2141. if (left_type.is_hard_type()) {
  2142. 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);
  2143. } else {
  2144. // TODO: Warning.
  2145. mark_node_unsafe(p_binary_op);
  2146. }
  2147. }
  2148. }
  2149. // "is" operator is always a boolean anyway.
  2150. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2151. result.kind = GDScriptParser::DataType::BUILTIN;
  2152. result.builtin_type = Variant::BOOL;
  2153. } else {
  2154. ERR_PRINT("Parser bug: unknown binary operation.");
  2155. }
  2156. }
  2157. }
  2158. p_binary_op->set_datatype(result);
  2159. }
  2160. void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_await, bool p_is_root) {
  2161. bool all_is_constant = true;
  2162. HashMap<int, GDScriptParser::ArrayNode *> arrays; // For array literal to potentially type when passing.
  2163. for (int i = 0; i < p_call->arguments.size(); i++) {
  2164. reduce_expression(p_call->arguments[i]);
  2165. if (p_call->arguments[i]->type == GDScriptParser::Node::ARRAY) {
  2166. arrays[i] = static_cast<GDScriptParser::ArrayNode *>(p_call->arguments[i]);
  2167. }
  2168. all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;
  2169. }
  2170. GDScriptParser::Node::Type callee_type = p_call->get_callee_type();
  2171. GDScriptParser::DataType call_type;
  2172. if (!p_call->is_super && callee_type == GDScriptParser::Node::IDENTIFIER) {
  2173. // Call to name directly.
  2174. StringName function_name = p_call->function_name;
  2175. Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);
  2176. if (builtin_type < Variant::VARIANT_MAX) {
  2177. // Is a builtin constructor.
  2178. call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2179. call_type.kind = GDScriptParser::DataType::BUILTIN;
  2180. call_type.builtin_type = builtin_type;
  2181. if (builtin_type == Variant::OBJECT) {
  2182. call_type.kind = GDScriptParser::DataType::NATIVE;
  2183. call_type.native_type = function_name; // "Object".
  2184. }
  2185. bool safe_to_fold = true;
  2186. switch (builtin_type) {
  2187. // Those are stored by reference so not suited for compile-time construction.
  2188. // Because in this case they would be the same reference in all constructed values.
  2189. case Variant::OBJECT:
  2190. case Variant::DICTIONARY:
  2191. case Variant::ARRAY:
  2192. case Variant::PACKED_BYTE_ARRAY:
  2193. case Variant::PACKED_INT32_ARRAY:
  2194. case Variant::PACKED_INT64_ARRAY:
  2195. case Variant::PACKED_FLOAT32_ARRAY:
  2196. case Variant::PACKED_FLOAT64_ARRAY:
  2197. case Variant::PACKED_STRING_ARRAY:
  2198. case Variant::PACKED_VECTOR2_ARRAY:
  2199. case Variant::PACKED_VECTOR3_ARRAY:
  2200. case Variant::PACKED_COLOR_ARRAY:
  2201. safe_to_fold = false;
  2202. break;
  2203. default:
  2204. break;
  2205. }
  2206. if (all_is_constant && safe_to_fold) {
  2207. // Construct here.
  2208. Vector<const Variant *> args;
  2209. for (int i = 0; i < p_call->arguments.size(); i++) {
  2210. args.push_back(&(p_call->arguments[i]->reduced_value));
  2211. }
  2212. Callable::CallError err;
  2213. Variant value;
  2214. Variant::construct(builtin_type, value, (const Variant **)args.ptr(), args.size(), err);
  2215. switch (err.error) {
  2216. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  2217. 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,
  2218. Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),
  2219. p_call->arguments[err.argument]);
  2220. break;
  2221. case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
  2222. String signature = Variant::get_type_name(builtin_type) + "(";
  2223. for (int i = 0; i < p_call->arguments.size(); i++) {
  2224. if (i > 0) {
  2225. signature += ", ";
  2226. }
  2227. signature += p_call->arguments[i]->get_datatype().to_string();
  2228. }
  2229. signature += ")";
  2230. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);
  2231. } break;
  2232. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2233. 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);
  2234. break;
  2235. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2236. 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);
  2237. break;
  2238. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2239. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2240. break; // Can't happen in a builtin constructor.
  2241. case Callable::CallError::CALL_OK:
  2242. p_call->is_constant = true;
  2243. p_call->reduced_value = value;
  2244. break;
  2245. }
  2246. } else {
  2247. // TODO: Check constructors without constants.
  2248. // If there's one argument, try to use copy constructor (those aren't explicitly defined).
  2249. if (p_call->arguments.size() == 1) {
  2250. GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();
  2251. if (arg_type.is_variant()) {
  2252. mark_node_unsafe(p_call->arguments[0]);
  2253. } else {
  2254. if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {
  2255. // Okay.
  2256. p_call->set_datatype(call_type);
  2257. return;
  2258. }
  2259. }
  2260. }
  2261. List<MethodInfo> constructors;
  2262. Variant::get_constructor_list(builtin_type, &constructors);
  2263. bool match = false;
  2264. for (const MethodInfo &info : constructors) {
  2265. if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  2266. continue;
  2267. }
  2268. if (p_call->arguments.size() > info.arguments.size()) {
  2269. continue;
  2270. }
  2271. bool types_match = true;
  2272. for (int i = 0; i < p_call->arguments.size(); i++) {
  2273. GDScriptParser::DataType par_type = type_from_property(info.arguments[i]);
  2274. if (!is_type_compatible(par_type, p_call->arguments[i]->get_datatype(), true)) {
  2275. types_match = false;
  2276. break;
  2277. #ifdef DEBUG_ENABLED
  2278. } else {
  2279. if (par_type.builtin_type == Variant::INT && p_call->arguments[i]->get_datatype().builtin_type == Variant::FLOAT && builtin_type != Variant::INT) {
  2280. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  2281. }
  2282. #endif
  2283. }
  2284. }
  2285. if (types_match) {
  2286. match = true;
  2287. call_type = type_from_property(info.return_val);
  2288. break;
  2289. }
  2290. }
  2291. if (!match) {
  2292. String signature = Variant::get_type_name(builtin_type) + "(";
  2293. for (int i = 0; i < p_call->arguments.size(); i++) {
  2294. if (i > 0) {
  2295. signature += ", ";
  2296. }
  2297. signature += p_call->arguments[i]->get_datatype().to_string();
  2298. }
  2299. signature += ")";
  2300. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);
  2301. }
  2302. }
  2303. p_call->set_datatype(call_type);
  2304. return;
  2305. } else if (GDScriptUtilityFunctions::function_exists(function_name)) {
  2306. MethodInfo function_info = GDScriptUtilityFunctions::get_function_info(function_name);
  2307. if (all_is_constant && GDScriptUtilityFunctions::is_function_constant(function_name)) {
  2308. // Can call on compilation.
  2309. Vector<const Variant *> args;
  2310. for (int i = 0; i < p_call->arguments.size(); i++) {
  2311. args.push_back(&(p_call->arguments[i]->reduced_value));
  2312. }
  2313. Variant value;
  2314. Callable::CallError err;
  2315. GDScriptUtilityFunctions::get_function(function_name)(&value, (const Variant **)args.ptr(), args.size(), err);
  2316. switch (err.error) {
  2317. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  2318. PropertyInfo wrong_arg = function_info.arguments[err.argument];
  2319. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*", function_name, err.argument + 1,
  2320. type_from_property(wrong_arg).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()),
  2321. p_call->arguments[err.argument]);
  2322. } break;
  2323. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  2324. push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
  2325. break;
  2326. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2327. 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);
  2328. break;
  2329. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2330. 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);
  2331. break;
  2332. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2333. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2334. break; // Can't happen in a builtin constructor.
  2335. case Callable::CallError::CALL_OK:
  2336. p_call->is_constant = true;
  2337. p_call->reduced_value = value;
  2338. break;
  2339. }
  2340. } else {
  2341. validate_call_arg(function_info, p_call);
  2342. }
  2343. p_call->set_datatype(type_from_property(function_info.return_val));
  2344. return;
  2345. } else if (Variant::has_utility_function(function_name)) {
  2346. MethodInfo function_info = info_from_utility_func(function_name);
  2347. if (all_is_constant && Variant::get_utility_function_type(function_name) == Variant::UTILITY_FUNC_TYPE_MATH) {
  2348. // Can call on compilation.
  2349. Vector<const Variant *> args;
  2350. for (int i = 0; i < p_call->arguments.size(); i++) {
  2351. args.push_back(&(p_call->arguments[i]->reduced_value));
  2352. }
  2353. Variant value;
  2354. Callable::CallError err;
  2355. Variant::call_utility_function(function_name, &value, (const Variant **)args.ptr(), args.size(), err);
  2356. switch (err.error) {
  2357. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  2358. String expected_type_name;
  2359. if (err.argument < function_info.arguments.size()) {
  2360. expected_type_name = type_from_property(function_info.arguments[err.argument]).to_string();
  2361. } else {
  2362. expected_type_name = Variant::get_type_name((Variant::Type)err.expected);
  2363. }
  2364. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*", function_name, err.argument + 1,
  2365. expected_type_name, p_call->arguments[err.argument]->get_datatype().to_string()),
  2366. p_call->arguments[err.argument]);
  2367. } break;
  2368. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  2369. push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
  2370. break;
  2371. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2372. 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);
  2373. break;
  2374. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2375. 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);
  2376. break;
  2377. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2378. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2379. break; // Can't happen in a builtin constructor.
  2380. case Callable::CallError::CALL_OK:
  2381. p_call->is_constant = true;
  2382. p_call->reduced_value = value;
  2383. break;
  2384. }
  2385. } else {
  2386. validate_call_arg(function_info, p_call);
  2387. }
  2388. p_call->set_datatype(type_from_property(function_info.return_val));
  2389. return;
  2390. }
  2391. }
  2392. GDScriptParser::DataType base_type;
  2393. call_type.kind = GDScriptParser::DataType::VARIANT;
  2394. bool is_self = false;
  2395. if (p_call->is_super) {
  2396. base_type = parser->current_class->base_type;
  2397. base_type.is_meta_type = false;
  2398. is_self = true;
  2399. if (p_call->callee == nullptr && !lambda_stack.is_empty()) {
  2400. push_error("Cannot use `super()` inside a lambda.", p_call);
  2401. }
  2402. } else if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  2403. base_type = parser->current_class->get_datatype();
  2404. base_type.is_meta_type = false;
  2405. is_self = true;
  2406. } else if (callee_type == GDScriptParser::Node::SUBSCRIPT) {
  2407. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);
  2408. if (subscript->base == nullptr) {
  2409. // Invalid syntax, error already set on parser.
  2410. p_call->set_datatype(call_type);
  2411. mark_node_unsafe(p_call);
  2412. return;
  2413. }
  2414. if (!subscript->is_attribute) {
  2415. // Invalid call. Error already sent in parser.
  2416. // TODO: Could check if Callable here.
  2417. p_call->set_datatype(call_type);
  2418. mark_node_unsafe(p_call);
  2419. return;
  2420. }
  2421. if (subscript->attribute == nullptr) {
  2422. // Invalid call. Error already sent in parser.
  2423. p_call->set_datatype(call_type);
  2424. mark_node_unsafe(p_call);
  2425. return;
  2426. }
  2427. GDScriptParser::IdentifierNode *base_id = nullptr;
  2428. if (subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  2429. base_id = static_cast<GDScriptParser::IdentifierNode *>(subscript->base);
  2430. }
  2431. if (base_id && GDScriptParser::get_builtin_type(base_id->name) < Variant::VARIANT_MAX) {
  2432. base_type = make_builtin_meta_type(GDScriptParser::get_builtin_type(base_id->name));
  2433. } else {
  2434. reduce_expression(subscript->base);
  2435. base_type = subscript->base->get_datatype();
  2436. }
  2437. } else {
  2438. // Invalid call. Error already sent in parser.
  2439. // TODO: Could check if Callable here too.
  2440. p_call->set_datatype(call_type);
  2441. mark_node_unsafe(p_call);
  2442. return;
  2443. }
  2444. bool is_static = false;
  2445. bool is_vararg = false;
  2446. int default_arg_count = 0;
  2447. GDScriptParser::DataType return_type;
  2448. List<GDScriptParser::DataType> par_types;
  2449. bool is_constructor = (base_type.is_meta_type || (p_call->callee && p_call->callee->type == GDScriptParser::Node::IDENTIFIER)) && p_call->function_name == SNAME("new");
  2450. 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)) {
  2451. // If the function require typed arrays we must make literals be typed.
  2452. for (const KeyValue<int, GDScriptParser::ArrayNode *> &E : arrays) {
  2453. int index = E.key;
  2454. if (index < par_types.size() && par_types[index].has_container_element_type()) {
  2455. update_array_literal_element_type(par_types[index], E.value);
  2456. }
  2457. }
  2458. validate_call_arg(par_types, default_arg_count, is_vararg, p_call);
  2459. if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {
  2460. // Enum type is treated as a dictionary value for function calls.
  2461. base_type.is_meta_type = false;
  2462. }
  2463. if (is_self && parser->current_function != nullptr && parser->current_function->is_static && !is_static) {
  2464. // Get the parent function above any lambda.
  2465. GDScriptParser::FunctionNode *parent_function = parser->current_function;
  2466. while (parent_function->source_lambda) {
  2467. parent_function = parent_function->source_lambda->parent_function;
  2468. }
  2469. push_error(vformat(R"*(Cannot call non-static function "%s()" from static function "%s()".)*", p_call->function_name, parent_function->identifier->name), p_call);
  2470. } else if (!is_self && base_type.is_meta_type && !is_static) {
  2471. base_type.is_meta_type = false; // For `to_string()`.
  2472. 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);
  2473. } else if (is_self && !is_static) {
  2474. mark_lambda_use_self();
  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::VARIABLE:
  2744. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;
  2745. p_identifier->variable_source = member.variable;
  2746. member.variable->usages += 1;
  2747. break;
  2748. case GDScriptParser::ClassNode::Member::SIGNAL:
  2749. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_SIGNAL;
  2750. break;
  2751. case GDScriptParser::ClassNode::Member::FUNCTION:
  2752. p_identifier->set_datatype(make_callable_type(member.function->info));
  2753. break;
  2754. case GDScriptParser::ClassNode::Member::CLASS:
  2755. if (p_base != nullptr && p_base->is_constant) {
  2756. Error err = OK;
  2757. GDScript *scr = GDScriptCache::get_full_script(base.script_path, err).ptr();
  2758. ERR_FAIL_COND_MSG(err != OK, "Error while getting subscript full script.");
  2759. scr = scr->find_class(p_identifier->get_datatype().class_type->fqcn);
  2760. p_identifier->reduced_value = scr;
  2761. p_identifier->is_constant = true;
  2762. }
  2763. break;
  2764. default:
  2765. break; // Type already set.
  2766. }
  2767. return;
  2768. }
  2769. // Check outer constants.
  2770. // TODO: Allow outer static functions.
  2771. if (base_class->outer != nullptr) {
  2772. List<GDScriptParser::ClassNode *> script_classes;
  2773. get_class_node_current_scope_classes(base_class->outer, &script_classes);
  2774. for (GDScriptParser::ClassNode *script_class : script_classes) {
  2775. if (script_class->has_member(name)) {
  2776. resolve_class_member(script_class, name, p_identifier);
  2777. GDScriptParser::ClassNode::Member member = script_class->get_member(name);
  2778. switch (member.type) {
  2779. case GDScriptParser::ClassNode::Member::CONSTANT:
  2780. // TODO: Make sure loops won't cause problem. And make special error message for those.
  2781. p_identifier->set_datatype(member.get_datatype());
  2782. p_identifier->is_constant = true;
  2783. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  2784. return;
  2785. case GDScriptParser::ClassNode::Member::ENUM_VALUE:
  2786. p_identifier->set_datatype(member.get_datatype());
  2787. p_identifier->is_constant = true;
  2788. p_identifier->reduced_value = member.enum_value.value;
  2789. return;
  2790. case GDScriptParser::ClassNode::Member::ENUM:
  2791. p_identifier->set_datatype(member.get_datatype());
  2792. p_identifier->is_constant = false;
  2793. return;
  2794. case GDScriptParser::ClassNode::Member::CLASS:
  2795. p_identifier->set_datatype(member.get_datatype());
  2796. return;
  2797. default:
  2798. break;
  2799. }
  2800. }
  2801. }
  2802. }
  2803. base_class = base_class->base_type.class_type;
  2804. }
  2805. // Check native members. No need for native class recursion because Node exposes all Object's properties.
  2806. const StringName &native = base.native_type;
  2807. if (class_exists(native)) {
  2808. MethodInfo method_info;
  2809. if (ClassDB::has_property(native, name)) {
  2810. StringName getter_name = ClassDB::get_property_getter(native, name);
  2811. MethodBind *getter = ClassDB::get_method(native, getter_name);
  2812. if (getter != nullptr) {
  2813. p_identifier->set_datatype(type_from_property(getter->get_return_info()));
  2814. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  2815. }
  2816. return;
  2817. }
  2818. if (ClassDB::get_method_info(native, name, &method_info)) {
  2819. // Method is callable.
  2820. p_identifier->set_datatype(make_callable_type(method_info));
  2821. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  2822. return;
  2823. }
  2824. if (ClassDB::get_signal(native, name, &method_info)) {
  2825. // Signal is a type too.
  2826. p_identifier->set_datatype(make_signal_type(method_info));
  2827. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  2828. return;
  2829. }
  2830. if (ClassDB::has_enum(native, name)) {
  2831. p_identifier->set_datatype(make_native_enum_type(native, name));
  2832. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  2833. return;
  2834. }
  2835. bool valid = false;
  2836. int64_t int_constant = ClassDB::get_integer_constant(native, name, &valid);
  2837. if (valid) {
  2838. p_identifier->is_constant = true;
  2839. p_identifier->reduced_value = int_constant;
  2840. p_identifier->set_datatype(type_from_variant(int_constant, p_identifier));
  2841. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  2842. return;
  2843. }
  2844. }
  2845. }
  2846. void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin) {
  2847. // TODO: This is opportunity to further infer types.
  2848. // Check if we are inside and enum. This allows enum values to access other elements of the same enum.
  2849. if (current_enum) {
  2850. for (int i = 0; i < current_enum->values.size(); i++) {
  2851. const GDScriptParser::EnumNode::Value &element = current_enum->values[i];
  2852. if (element.identifier->name == p_identifier->name) {
  2853. GDScriptParser::DataType type;
  2854. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2855. type.kind = element.parent_enum->identifier ? GDScriptParser::DataType::ENUM : GDScriptParser::DataType::BUILTIN;
  2856. type.builtin_type = Variant::INT;
  2857. type.is_constant = true;
  2858. if (element.parent_enum->identifier) {
  2859. type.enum_type = element.parent_enum->identifier->name;
  2860. }
  2861. p_identifier->set_datatype(type);
  2862. if (element.resolved) {
  2863. p_identifier->is_constant = true;
  2864. p_identifier->reduced_value = element.value;
  2865. } else {
  2866. push_error(R"(Cannot use another enum element before it was declared.)", p_identifier);
  2867. }
  2868. return; // Found anyway.
  2869. }
  2870. }
  2871. }
  2872. bool found_source = false;
  2873. // Check if identifier is local.
  2874. // If that's the case, the declaration already was solved before.
  2875. switch (p_identifier->source) {
  2876. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:
  2877. p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());
  2878. found_source = true;
  2879. break;
  2880. case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:
  2881. case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:
  2882. p_identifier->set_datatype(p_identifier->constant_source->get_datatype());
  2883. p_identifier->is_constant = true;
  2884. // TODO: Constant should have a value on the node itself.
  2885. p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;
  2886. found_source = true;
  2887. break;
  2888. case GDScriptParser::IdentifierNode::MEMBER_SIGNAL:
  2889. case GDScriptParser::IdentifierNode::INHERITED_VARIABLE:
  2890. mark_lambda_use_self();
  2891. break;
  2892. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
  2893. mark_lambda_use_self();
  2894. p_identifier->variable_source->usages++;
  2895. [[fallthrough]];
  2896. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
  2897. p_identifier->set_datatype(p_identifier->variable_source->get_datatype());
  2898. found_source = true;
  2899. break;
  2900. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:
  2901. p_identifier->set_datatype(p_identifier->bind_source->get_datatype());
  2902. found_source = true;
  2903. break;
  2904. case GDScriptParser::IdentifierNode::LOCAL_BIND: {
  2905. GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();
  2906. result.is_constant = true;
  2907. p_identifier->set_datatype(result);
  2908. found_source = true;
  2909. } break;
  2910. case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:
  2911. break;
  2912. }
  2913. // Not a local, so check members.
  2914. if (!found_source) {
  2915. reduce_identifier_from_base(p_identifier);
  2916. if (p_identifier->source != GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->get_datatype().is_set()) {
  2917. // Found.
  2918. found_source = true;
  2919. }
  2920. }
  2921. if (found_source) {
  2922. if ((p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_VARIABLE || p_identifier->source == GDScriptParser::IdentifierNode::INHERITED_VARIABLE) && parser->current_function && parser->current_function->is_static) {
  2923. // Get the parent function above any lambda.
  2924. GDScriptParser::FunctionNode *parent_function = parser->current_function;
  2925. while (parent_function->source_lambda) {
  2926. parent_function = parent_function->source_lambda->parent_function;
  2927. }
  2928. push_error(vformat(R"*(Cannot access instance variable "%s" from the static function "%s()".)*", p_identifier->name, parent_function->identifier->name), p_identifier);
  2929. }
  2930. if (!lambda_stack.is_empty()) {
  2931. // 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.
  2932. if (p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_VARIABLE || p_identifier->source == GDScriptParser::IdentifierNode::INHERITED_VARIABLE) {
  2933. mark_lambda_use_self();
  2934. return; // No need to capture.
  2935. }
  2936. // If the identifier is local, check if it's any kind of capture by comparing their source function.
  2937. // Only capture locals and enum values. Constants are still accessible from the lambda using the script reference. If not, this method is done.
  2938. if (p_identifier->source == GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_CONSTANT) {
  2939. return;
  2940. }
  2941. GDScriptParser::FunctionNode *function_test = lambda_stack.back()->get()->function;
  2942. // Make sure we aren't capturing variable in the same lambda.
  2943. // This also add captures for nested lambdas.
  2944. 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)) {
  2945. function_test->source_lambda->captures_indices[p_identifier->name] = function_test->source_lambda->captures.size();
  2946. function_test->source_lambda->captures.push_back(p_identifier);
  2947. function_test = function_test->source_lambda->parent_function;
  2948. }
  2949. }
  2950. return;
  2951. }
  2952. StringName name = p_identifier->name;
  2953. p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;
  2954. // Check globals. We make an exception for Variant::OBJECT because it's the base class for
  2955. // non-builtin types so we allow doing e.g. Object.new()
  2956. Variant::Type builtin_type = GDScriptParser::get_builtin_type(name);
  2957. if (builtin_type != Variant::OBJECT && builtin_type < Variant::VARIANT_MAX) {
  2958. if (can_be_builtin) {
  2959. p_identifier->set_datatype(make_builtin_meta_type(builtin_type));
  2960. return;
  2961. } else {
  2962. push_error(R"(Builtin type cannot be used as a name on its own.)", p_identifier);
  2963. }
  2964. }
  2965. if (class_exists(name)) {
  2966. p_identifier->set_datatype(make_native_meta_type(name));
  2967. return;
  2968. }
  2969. if (ScriptServer::is_global_class(name)) {
  2970. p_identifier->set_datatype(make_global_class_meta_type(name, p_identifier));
  2971. return;
  2972. }
  2973. // Try singletons.
  2974. // Do this before globals because this might be a singleton loading another one before it's compiled.
  2975. if (ProjectSettings::get_singleton()->has_autoload(name)) {
  2976. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(name);
  2977. if (autoload.is_singleton) {
  2978. // Singleton exists, so it's at least a Node.
  2979. GDScriptParser::DataType result;
  2980. result.kind = GDScriptParser::DataType::NATIVE;
  2981. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2982. if (ResourceLoader::get_resource_type(autoload.path) == "GDScript") {
  2983. Ref<GDScriptParserRef> singl_parser = get_parser_for(autoload.path);
  2984. if (singl_parser.is_valid()) {
  2985. Error err = singl_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  2986. if (err == OK) {
  2987. result = type_from_metatype(singl_parser->get_parser()->head->get_datatype());
  2988. }
  2989. }
  2990. } else if (ResourceLoader::get_resource_type(autoload.path) == "PackedScene") {
  2991. if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {
  2992. Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);
  2993. Node *node = Object::cast_to<Node>(constant);
  2994. if (node != nullptr) {
  2995. Ref<GDScript> scr = node->get_script();
  2996. if (scr.is_valid()) {
  2997. Ref<GDScriptParserRef> singl_parser = get_parser_for(scr->get_script_path());
  2998. if (singl_parser.is_valid()) {
  2999. Error err = singl_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3000. if (err == OK) {
  3001. result = type_from_metatype(singl_parser->get_parser()->head->get_datatype());
  3002. }
  3003. }
  3004. }
  3005. }
  3006. }
  3007. }
  3008. result.is_constant = true;
  3009. p_identifier->set_datatype(result);
  3010. return;
  3011. }
  3012. }
  3013. if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {
  3014. Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);
  3015. p_identifier->set_datatype(type_from_variant(constant, p_identifier));
  3016. p_identifier->is_constant = true;
  3017. p_identifier->reduced_value = constant;
  3018. return;
  3019. }
  3020. // Not found.
  3021. // Check if it's a builtin function.
  3022. if (GDScriptUtilityFunctions::function_exists(name)) {
  3023. push_error(vformat(R"(Built-in function "%s" cannot be used as an identifier.)", name), p_identifier);
  3024. } else {
  3025. push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);
  3026. }
  3027. GDScriptParser::DataType dummy;
  3028. dummy.kind = GDScriptParser::DataType::VARIANT;
  3029. p_identifier->set_datatype(dummy); // Just so type is set to something.
  3030. }
  3031. void GDScriptAnalyzer::reduce_lambda(GDScriptParser::LambdaNode *p_lambda) {
  3032. // Lambda is always a Callable.
  3033. GDScriptParser::DataType lambda_type;
  3034. lambda_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  3035. lambda_type.kind = GDScriptParser::DataType::BUILTIN;
  3036. lambda_type.builtin_type = Variant::CALLABLE;
  3037. p_lambda->set_datatype(lambda_type);
  3038. if (p_lambda->function == nullptr) {
  3039. return;
  3040. }
  3041. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  3042. parser->current_function = p_lambda->function;
  3043. lambda_stack.push_back(p_lambda);
  3044. for (int i = 0; i < p_lambda->function->parameters.size(); i++) {
  3045. resolve_parameter(p_lambda->function->parameters[i]);
  3046. }
  3047. resolve_suite(p_lambda->function->body);
  3048. int captures_amount = p_lambda->captures.size();
  3049. if (captures_amount > 0) {
  3050. // Create space for lambda parameters.
  3051. // At the beginning to not mess with optional parameters.
  3052. int param_count = p_lambda->function->parameters.size();
  3053. p_lambda->function->parameters.resize(param_count + captures_amount);
  3054. for (int i = param_count - 1; i >= 0; i--) {
  3055. p_lambda->function->parameters.write[i + captures_amount] = p_lambda->function->parameters[i];
  3056. p_lambda->function->parameters_indices[p_lambda->function->parameters[i]->identifier->name] = i + captures_amount;
  3057. }
  3058. // Add captures as extra parameters at the beginning.
  3059. for (int i = 0; i < p_lambda->captures.size(); i++) {
  3060. GDScriptParser::IdentifierNode *capture = p_lambda->captures[i];
  3061. GDScriptParser::ParameterNode *capture_param = parser->alloc_node<GDScriptParser::ParameterNode>();
  3062. capture_param->identifier = capture;
  3063. capture_param->usages = capture->usages;
  3064. capture_param->set_datatype(capture->get_datatype());
  3065. p_lambda->function->parameters.write[i] = capture_param;
  3066. p_lambda->function->parameters_indices[capture->name] = i;
  3067. }
  3068. }
  3069. lambda_stack.pop_back();
  3070. parser->current_function = previous_function;
  3071. }
  3072. void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {
  3073. p_literal->reduced_value = p_literal->value;
  3074. p_literal->is_constant = true;
  3075. p_literal->set_datatype(type_from_variant(p_literal->reduced_value, p_literal));
  3076. }
  3077. void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
  3078. if (!p_preload->path) {
  3079. return;
  3080. }
  3081. reduce_expression(p_preload->path);
  3082. if (!p_preload->path->is_constant) {
  3083. push_error("Preloaded path must be a constant string.", p_preload->path);
  3084. return;
  3085. }
  3086. if (p_preload->path->reduced_value.get_type() != Variant::STRING) {
  3087. push_error("Preloaded path must be a constant string.", p_preload->path);
  3088. } else {
  3089. p_preload->resolved_path = p_preload->path->reduced_value;
  3090. // TODO: Save this as script dependency.
  3091. if (p_preload->resolved_path.is_relative_path()) {
  3092. p_preload->resolved_path = parser->script_path.get_base_dir().path_join(p_preload->resolved_path);
  3093. }
  3094. p_preload->resolved_path = p_preload->resolved_path.simplify_path();
  3095. if (!ResourceLoader::exists(p_preload->resolved_path)) {
  3096. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  3097. if (file_check->file_exists(p_preload->resolved_path)) {
  3098. push_error(vformat(R"(Preload file "%s" has no resource loaders (unrecognized file extension).)", p_preload->resolved_path), p_preload->path);
  3099. } else {
  3100. push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path);
  3101. }
  3102. } else {
  3103. // TODO: Don't load if validating: use completion cache.
  3104. // Must load GDScript and PackedScenes separately to permit cyclic references
  3105. // as ResourceLoader::load() detect and reject those.
  3106. if (ResourceLoader::get_resource_type(p_preload->resolved_path) == "GDScript") {
  3107. Error err = OK;
  3108. Ref<GDScript> res = GDScriptCache::get_shallow_script(p_preload->resolved_path, err, parser->script_path);
  3109. p_preload->resource = res;
  3110. if (err != OK) {
  3111. push_error(vformat(R"(Could not preload resource script "%s".)", p_preload->resolved_path), p_preload->path);
  3112. }
  3113. } else if (ResourceLoader::get_resource_type(p_preload->resolved_path) == "PackedScene") {
  3114. Error err = OK;
  3115. Ref<PackedScene> res = GDScriptCache::get_packed_scene(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 scene "%s".)", p_preload->resolved_path), p_preload->path);
  3119. }
  3120. } else {
  3121. p_preload->resource = ResourceLoader::load(p_preload->resolved_path);
  3122. if (p_preload->resource.is_null()) {
  3123. push_error(vformat(R"(Could not preload resource file "%s".)", p_preload->resolved_path), p_preload->path);
  3124. }
  3125. }
  3126. }
  3127. }
  3128. p_preload->is_constant = true;
  3129. p_preload->reduced_value = p_preload->resource;
  3130. p_preload->set_datatype(type_from_variant(p_preload->reduced_value, p_preload));
  3131. }
  3132. void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
  3133. p_self->is_constant = false;
  3134. p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));
  3135. mark_lambda_use_self();
  3136. }
  3137. void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript) {
  3138. if (p_subscript->base == nullptr) {
  3139. return;
  3140. }
  3141. if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  3142. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);
  3143. } else {
  3144. reduce_expression(p_subscript->base);
  3145. if (p_subscript->base->type == GDScriptParser::Node::ARRAY) {
  3146. const_fold_array(static_cast<GDScriptParser::ArrayNode *>(p_subscript->base));
  3147. } else if (p_subscript->base->type == GDScriptParser::Node::DICTIONARY) {
  3148. const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_subscript->base));
  3149. }
  3150. }
  3151. GDScriptParser::DataType result_type;
  3152. if (p_subscript->is_attribute) {
  3153. if (p_subscript->attribute == nullptr) {
  3154. return;
  3155. }
  3156. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  3157. bool valid = false;
  3158. // If the base is a metatype, use the analyzer instead.
  3159. if (p_subscript->base->is_constant && !base_type.is_meta_type) {
  3160. // Just try to get it.
  3161. Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, valid);
  3162. if (valid) {
  3163. p_subscript->is_constant = true;
  3164. p_subscript->reduced_value = value;
  3165. result_type = type_from_variant(value, p_subscript);
  3166. }
  3167. } else if (base_type.is_variant() || !base_type.is_hard_type()) {
  3168. valid = true;
  3169. result_type.kind = GDScriptParser::DataType::VARIANT;
  3170. mark_node_unsafe(p_subscript);
  3171. } else {
  3172. reduce_identifier_from_base(p_subscript->attribute, &base_type);
  3173. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  3174. if (attr_type.is_set()) {
  3175. valid = true;
  3176. result_type = attr_type;
  3177. p_subscript->is_constant = p_subscript->attribute->is_constant;
  3178. p_subscript->reduced_value = p_subscript->attribute->reduced_value;
  3179. } else if (!base_type.is_meta_type || !base_type.is_constant) {
  3180. valid = base_type.kind != GDScriptParser::DataType::BUILTIN;
  3181. #ifdef DEBUG_ENABLED
  3182. if (valid) {
  3183. parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());
  3184. }
  3185. #endif
  3186. result_type.kind = GDScriptParser::DataType::VARIANT;
  3187. }
  3188. }
  3189. if (!valid) {
  3190. 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);
  3191. result_type.kind = GDScriptParser::DataType::VARIANT;
  3192. }
  3193. } else {
  3194. if (p_subscript->index == nullptr) {
  3195. return;
  3196. }
  3197. reduce_expression(p_subscript->index);
  3198. if (p_subscript->base->is_constant && p_subscript->index->is_constant) {
  3199. // Just try to get it.
  3200. bool valid = false;
  3201. Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);
  3202. if (!valid) {
  3203. push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);
  3204. } else {
  3205. p_subscript->is_constant = true;
  3206. p_subscript->reduced_value = value;
  3207. result_type = type_from_variant(value, p_subscript);
  3208. }
  3209. result_type.kind = GDScriptParser::DataType::VARIANT;
  3210. } else {
  3211. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  3212. GDScriptParser::DataType index_type = p_subscript->index->get_datatype();
  3213. if (base_type.is_variant()) {
  3214. result_type.kind = GDScriptParser::DataType::VARIANT;
  3215. mark_node_unsafe(p_subscript);
  3216. } else {
  3217. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  3218. // Check if indexing is valid.
  3219. bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;
  3220. if (!error) {
  3221. switch (base_type.builtin_type) {
  3222. // Expect int or real as index.
  3223. case Variant::PACKED_BYTE_ARRAY:
  3224. case Variant::PACKED_COLOR_ARRAY:
  3225. case Variant::PACKED_FLOAT32_ARRAY:
  3226. case Variant::PACKED_FLOAT64_ARRAY:
  3227. case Variant::PACKED_INT32_ARRAY:
  3228. case Variant::PACKED_INT64_ARRAY:
  3229. case Variant::PACKED_STRING_ARRAY:
  3230. case Variant::PACKED_VECTOR2_ARRAY:
  3231. case Variant::PACKED_VECTOR3_ARRAY:
  3232. case Variant::ARRAY:
  3233. case Variant::STRING:
  3234. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;
  3235. break;
  3236. // Expect String only.
  3237. case Variant::RECT2:
  3238. case Variant::RECT2I:
  3239. case Variant::PLANE:
  3240. case Variant::QUATERNION:
  3241. case Variant::AABB:
  3242. case Variant::OBJECT:
  3243. error = index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  3244. break;
  3245. // Expect String or number.
  3246. case Variant::BASIS:
  3247. case Variant::VECTOR2:
  3248. case Variant::VECTOR2I:
  3249. case Variant::VECTOR3:
  3250. case Variant::VECTOR3I:
  3251. case Variant::VECTOR4:
  3252. case Variant::VECTOR4I:
  3253. case Variant::TRANSFORM2D:
  3254. case Variant::TRANSFORM3D:
  3255. case Variant::PROJECTION:
  3256. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&
  3257. index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  3258. break;
  3259. // Expect String or int.
  3260. case Variant::COLOR:
  3261. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  3262. break;
  3263. // Don't support indexing, but we will check it later.
  3264. case Variant::RID:
  3265. case Variant::BOOL:
  3266. case Variant::CALLABLE:
  3267. case Variant::FLOAT:
  3268. case Variant::INT:
  3269. case Variant::NIL:
  3270. case Variant::NODE_PATH:
  3271. case Variant::SIGNAL:
  3272. case Variant::STRING_NAME:
  3273. break;
  3274. // Here for completeness.
  3275. case Variant::DICTIONARY:
  3276. case Variant::VARIANT_MAX:
  3277. break;
  3278. }
  3279. if (error) {
  3280. 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);
  3281. }
  3282. }
  3283. } else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  3284. if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {
  3285. 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);
  3286. }
  3287. }
  3288. // Check resulting type if possible.
  3289. result_type.builtin_type = Variant::NIL;
  3290. result_type.kind = GDScriptParser::DataType::BUILTIN;
  3291. result_type.type_source = base_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  3292. if (base_type.kind != GDScriptParser::DataType::BUILTIN) {
  3293. base_type.builtin_type = Variant::OBJECT;
  3294. }
  3295. switch (base_type.builtin_type) {
  3296. // Can't index at all.
  3297. case Variant::RID:
  3298. case Variant::BOOL:
  3299. case Variant::CALLABLE:
  3300. case Variant::FLOAT:
  3301. case Variant::INT:
  3302. case Variant::NIL:
  3303. case Variant::NODE_PATH:
  3304. case Variant::SIGNAL:
  3305. case Variant::STRING_NAME:
  3306. result_type.kind = GDScriptParser::DataType::VARIANT;
  3307. push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);
  3308. break;
  3309. // Return int.
  3310. case Variant::PACKED_BYTE_ARRAY:
  3311. case Variant::PACKED_INT32_ARRAY:
  3312. case Variant::PACKED_INT64_ARRAY:
  3313. case Variant::VECTOR2I:
  3314. case Variant::VECTOR3I:
  3315. case Variant::VECTOR4I:
  3316. result_type.builtin_type = Variant::INT;
  3317. break;
  3318. // Return float.
  3319. case Variant::PACKED_FLOAT32_ARRAY:
  3320. case Variant::PACKED_FLOAT64_ARRAY:
  3321. case Variant::VECTOR2:
  3322. case Variant::VECTOR3:
  3323. case Variant::VECTOR4:
  3324. case Variant::QUATERNION:
  3325. result_type.builtin_type = Variant::FLOAT;
  3326. break;
  3327. // Return Color.
  3328. case Variant::PACKED_COLOR_ARRAY:
  3329. result_type.builtin_type = Variant::COLOR;
  3330. break;
  3331. // Return String.
  3332. case Variant::PACKED_STRING_ARRAY:
  3333. case Variant::STRING:
  3334. result_type.builtin_type = Variant::STRING;
  3335. break;
  3336. // Return Vector2.
  3337. case Variant::PACKED_VECTOR2_ARRAY:
  3338. case Variant::TRANSFORM2D:
  3339. case Variant::RECT2:
  3340. result_type.builtin_type = Variant::VECTOR2;
  3341. break;
  3342. // Return Vector2I.
  3343. case Variant::RECT2I:
  3344. result_type.builtin_type = Variant::VECTOR2I;
  3345. break;
  3346. // Return Vector3.
  3347. case Variant::PACKED_VECTOR3_ARRAY:
  3348. case Variant::AABB:
  3349. case Variant::BASIS:
  3350. result_type.builtin_type = Variant::VECTOR3;
  3351. break;
  3352. // Depends on the index.
  3353. case Variant::TRANSFORM3D:
  3354. case Variant::PROJECTION:
  3355. case Variant::PLANE:
  3356. case Variant::COLOR:
  3357. case Variant::DICTIONARY:
  3358. case Variant::OBJECT:
  3359. result_type.kind = GDScriptParser::DataType::VARIANT;
  3360. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  3361. break;
  3362. // Can have an element type.
  3363. case Variant::ARRAY:
  3364. if (base_type.has_container_element_type()) {
  3365. result_type = base_type.get_container_element_type();
  3366. result_type.type_source = base_type.type_source;
  3367. } else {
  3368. result_type.kind = GDScriptParser::DataType::VARIANT;
  3369. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  3370. }
  3371. break;
  3372. // Here for completeness.
  3373. case Variant::VARIANT_MAX:
  3374. break;
  3375. }
  3376. }
  3377. }
  3378. }
  3379. p_subscript->set_datatype(result_type);
  3380. }
  3381. void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op) {
  3382. reduce_expression(p_ternary_op->condition);
  3383. reduce_expression(p_ternary_op->true_expr);
  3384. reduce_expression(p_ternary_op->false_expr);
  3385. GDScriptParser::DataType result;
  3386. 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) {
  3387. p_ternary_op->is_constant = true;
  3388. if (p_ternary_op->condition->reduced_value.booleanize()) {
  3389. p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;
  3390. } else {
  3391. p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;
  3392. }
  3393. }
  3394. GDScriptParser::DataType true_type;
  3395. if (p_ternary_op->true_expr) {
  3396. true_type = p_ternary_op->true_expr->get_datatype();
  3397. } else {
  3398. true_type.kind = GDScriptParser::DataType::VARIANT;
  3399. }
  3400. GDScriptParser::DataType false_type;
  3401. if (p_ternary_op->false_expr) {
  3402. false_type = p_ternary_op->false_expr->get_datatype();
  3403. } else {
  3404. false_type.kind = GDScriptParser::DataType::VARIANT;
  3405. }
  3406. if (true_type.is_variant() || false_type.is_variant()) {
  3407. result.kind = GDScriptParser::DataType::VARIANT;
  3408. } else {
  3409. result = true_type;
  3410. if (!is_type_compatible(true_type, false_type)) {
  3411. result = false_type;
  3412. if (!is_type_compatible(false_type, true_type)) {
  3413. result.type_source = GDScriptParser::DataType::UNDETECTED;
  3414. result.kind = GDScriptParser::DataType::VARIANT;
  3415. #ifdef DEBUG_ENABLED
  3416. parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);
  3417. #endif
  3418. }
  3419. }
  3420. }
  3421. p_ternary_op->set_datatype(result);
  3422. }
  3423. void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {
  3424. reduce_expression(p_unary_op->operand);
  3425. GDScriptParser::DataType result;
  3426. if (p_unary_op->operand == nullptr) {
  3427. result.kind = GDScriptParser::DataType::VARIANT;
  3428. p_unary_op->set_datatype(result);
  3429. return;
  3430. }
  3431. GDScriptParser::DataType operand_type = p_unary_op->operand->get_datatype();
  3432. if (p_unary_op->operand->is_constant) {
  3433. p_unary_op->is_constant = true;
  3434. p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());
  3435. result = type_from_variant(p_unary_op->reduced_value, p_unary_op);
  3436. }
  3437. if (operand_type.is_variant()) {
  3438. result.kind = GDScriptParser::DataType::VARIANT;
  3439. mark_node_unsafe(p_unary_op);
  3440. } else {
  3441. bool valid = false;
  3442. result = get_operation_type(p_unary_op->variant_op, operand_type, valid, p_unary_op);
  3443. if (!valid) {
  3444. 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);
  3445. }
  3446. }
  3447. p_unary_op->set_datatype(result);
  3448. }
  3449. void GDScriptAnalyzer::const_fold_array(GDScriptParser::ArrayNode *p_array) {
  3450. bool all_is_constant = true;
  3451. for (int i = 0; i < p_array->elements.size(); i++) {
  3452. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  3453. if (element->type == GDScriptParser::Node::ARRAY) {
  3454. const_fold_array(static_cast<GDScriptParser::ArrayNode *>(element));
  3455. } else if (element->type == GDScriptParser::Node::DICTIONARY) {
  3456. const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(element));
  3457. }
  3458. all_is_constant = all_is_constant && element->is_constant;
  3459. if (!all_is_constant) {
  3460. return;
  3461. }
  3462. }
  3463. Array array;
  3464. array.resize(p_array->elements.size());
  3465. for (int i = 0; i < p_array->elements.size(); i++) {
  3466. array[i] = p_array->elements[i]->reduced_value;
  3467. }
  3468. p_array->is_constant = true;
  3469. p_array->reduced_value = array;
  3470. }
  3471. void GDScriptAnalyzer::const_fold_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
  3472. bool all_is_constant = true;
  3473. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  3474. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  3475. if (element.value->type == GDScriptParser::Node::ARRAY) {
  3476. const_fold_array(static_cast<GDScriptParser::ArrayNode *>(element.value));
  3477. } else if (element.value->type == GDScriptParser::Node::DICTIONARY) {
  3478. const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(element.value));
  3479. }
  3480. all_is_constant = all_is_constant && element.key->is_constant && element.value->is_constant;
  3481. if (!all_is_constant) {
  3482. return;
  3483. }
  3484. }
  3485. Dictionary dict;
  3486. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  3487. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  3488. dict[element.key->reduced_value] = element.value->reduced_value;
  3489. }
  3490. p_dictionary->is_constant = true;
  3491. p_dictionary->reduced_value = dict;
  3492. }
  3493. GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source) {
  3494. GDScriptParser::DataType result;
  3495. result.is_constant = true;
  3496. result.kind = GDScriptParser::DataType::BUILTIN;
  3497. result.builtin_type = p_value.get_type();
  3498. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.
  3499. if (p_value.get_type() == Variant::OBJECT) {
  3500. // Object is treated as a native type, not a builtin type.
  3501. result.kind = GDScriptParser::DataType::NATIVE;
  3502. Object *obj = p_value;
  3503. if (!obj) {
  3504. return GDScriptParser::DataType();
  3505. }
  3506. result.native_type = obj->get_class_name();
  3507. Ref<Script> scr = p_value; // Check if value is a script itself.
  3508. if (scr.is_valid()) {
  3509. result.is_meta_type = true;
  3510. } else {
  3511. result.is_meta_type = false;
  3512. scr = obj->get_script();
  3513. }
  3514. if (scr.is_valid()) {
  3515. result.script_path = scr->get_path();
  3516. Ref<GDScript> gds = scr;
  3517. if (gds.is_valid()) {
  3518. result.kind = GDScriptParser::DataType::CLASS;
  3519. // This might be an inner class, so we want to get the parser for the root.
  3520. // But still get the inner class from that tree.
  3521. String script_path = gds->get_script_path();
  3522. Ref<GDScriptParserRef> ref = get_parser_for(script_path);
  3523. if (ref.is_null()) {
  3524. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  3525. GDScriptParser::DataType error_type;
  3526. error_type.kind = GDScriptParser::DataType::VARIANT;
  3527. return error_type;
  3528. }
  3529. Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3530. GDScriptParser::ClassNode *found = nullptr;
  3531. if (err == OK) {
  3532. found = ref->get_parser()->find_class(gds->fully_qualified_name);
  3533. if (found != nullptr) {
  3534. err = resolve_class_inheritance(found, p_source);
  3535. }
  3536. }
  3537. if (err || found == nullptr) {
  3538. push_error(vformat(R"(Could not resolve script "%s".)", script_path), p_source);
  3539. GDScriptParser::DataType error_type;
  3540. error_type.kind = GDScriptParser::DataType::VARIANT;
  3541. return error_type;
  3542. }
  3543. result.class_type = found;
  3544. result.script_path = ref->get_parser()->script_path;
  3545. } else {
  3546. result.kind = GDScriptParser::DataType::SCRIPT;
  3547. result.native_type = scr->get_instance_base_type();
  3548. }
  3549. result.script_type = scr;
  3550. } else {
  3551. result.kind = GDScriptParser::DataType::NATIVE;
  3552. if (result.native_type == GDScriptNativeClass::get_class_static()) {
  3553. result.is_meta_type = true;
  3554. }
  3555. }
  3556. }
  3557. return result;
  3558. }
  3559. GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) const {
  3560. GDScriptParser::DataType result = p_meta_type;
  3561. result.is_meta_type = false;
  3562. result.is_constant = false;
  3563. if (p_meta_type.kind == GDScriptParser::DataType::ENUM) {
  3564. result.builtin_type = Variant::INT;
  3565. }
  3566. return result;
  3567. }
  3568. GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property) const {
  3569. GDScriptParser::DataType result;
  3570. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3571. if (p_property.type == Variant::NIL && (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) {
  3572. // Variant
  3573. result.kind = GDScriptParser::DataType::VARIANT;
  3574. return result;
  3575. }
  3576. result.builtin_type = p_property.type;
  3577. if (p_property.type == Variant::OBJECT) {
  3578. result.kind = GDScriptParser::DataType::NATIVE;
  3579. result.native_type = p_property.class_name == StringName() ? SNAME("Object") : p_property.class_name;
  3580. } else {
  3581. result.kind = GDScriptParser::DataType::BUILTIN;
  3582. result.builtin_type = p_property.type;
  3583. if (p_property.type == Variant::ARRAY && p_property.hint == PROPERTY_HINT_ARRAY_TYPE) {
  3584. // Check element type.
  3585. StringName elem_type_name = p_property.hint_string;
  3586. GDScriptParser::DataType elem_type;
  3587. elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3588. Variant::Type elem_builtin_type = GDScriptParser::get_builtin_type(elem_type_name);
  3589. if (elem_builtin_type < Variant::VARIANT_MAX) {
  3590. // Builtin type.
  3591. elem_type.kind = GDScriptParser::DataType::BUILTIN;
  3592. elem_type.builtin_type = elem_builtin_type;
  3593. } else if (class_exists(elem_type_name)) {
  3594. elem_type.kind = GDScriptParser::DataType::NATIVE;
  3595. elem_type.builtin_type = Variant::OBJECT;
  3596. elem_type.native_type = p_property.hint_string;
  3597. } else if (ScriptServer::is_global_class(elem_type_name)) {
  3598. // Just load this as it shouldn't be a GDScript.
  3599. Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(elem_type_name));
  3600. elem_type.kind = GDScriptParser::DataType::SCRIPT;
  3601. elem_type.builtin_type = Variant::OBJECT;
  3602. elem_type.native_type = script->get_instance_base_type();
  3603. elem_type.script_type = script;
  3604. } else {
  3605. ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed array.");
  3606. }
  3607. elem_type.is_constant = false;
  3608. result.set_container_element_type(elem_type);
  3609. }
  3610. }
  3611. return result;
  3612. }
  3613. 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) {
  3614. r_static = false;
  3615. r_vararg = false;
  3616. r_default_arg_count = 0;
  3617. StringName function_name = p_function;
  3618. if (p_base_type.kind == GDScriptParser::DataType::ENUM) {
  3619. if (p_base_type.is_meta_type) {
  3620. // Enum type can be treated as a dictionary value.
  3621. p_base_type.kind = GDScriptParser::DataType::BUILTIN;
  3622. p_base_type.builtin_type = Variant::DICTIONARY;
  3623. p_base_type.is_meta_type = false;
  3624. } else {
  3625. push_error("Cannot call function on enum value.", p_source);
  3626. return false;
  3627. }
  3628. }
  3629. if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {
  3630. // Construct a base type to get methods.
  3631. Callable::CallError err;
  3632. Variant dummy;
  3633. Variant::construct(p_base_type.builtin_type, dummy, nullptr, 0, err);
  3634. if (err.error != Callable::CallError::CALL_OK) {
  3635. ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");
  3636. }
  3637. List<MethodInfo> methods;
  3638. dummy.get_method_list(&methods);
  3639. for (const MethodInfo &E : methods) {
  3640. if (E.name == p_function) {
  3641. function_signature_from_info(E, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  3642. r_static = Variant::is_builtin_method_static(p_base_type.builtin_type, function_name);
  3643. return true;
  3644. }
  3645. }
  3646. return false;
  3647. }
  3648. if (p_is_constructor) {
  3649. function_name = "_init";
  3650. r_static = true;
  3651. }
  3652. GDScriptParser::ClassNode *base_class = p_base_type.class_type;
  3653. GDScriptParser::FunctionNode *found_function = nullptr;
  3654. while (found_function == nullptr && base_class != nullptr) {
  3655. if (base_class->has_member(function_name)) {
  3656. if (base_class->get_member(function_name).type != GDScriptParser::ClassNode::Member::FUNCTION) {
  3657. // TODO: If this is Callable it can have a better error message.
  3658. push_error(vformat(R"(Member "%s" is not a function.)", function_name), p_source);
  3659. return false;
  3660. }
  3661. resolve_class_member(base_class, function_name, p_source);
  3662. found_function = base_class->get_member(function_name).function;
  3663. }
  3664. resolve_class_inheritance(base_class, p_source);
  3665. base_class = base_class->base_type.class_type;
  3666. }
  3667. if (found_function != nullptr) {
  3668. r_static = p_is_constructor || found_function->is_static;
  3669. for (int i = 0; i < found_function->parameters.size(); i++) {
  3670. r_par_types.push_back(found_function->parameters[i]->get_datatype());
  3671. if (found_function->parameters[i]->default_value != nullptr) {
  3672. r_default_arg_count++;
  3673. }
  3674. }
  3675. r_return_type = found_function->get_datatype();
  3676. r_return_type.is_meta_type = false;
  3677. r_return_type.is_coroutine = found_function->is_coroutine;
  3678. return true;
  3679. }
  3680. Ref<Script> base_script = p_base_type.script_type;
  3681. while (base_script.is_valid() && base_script->has_method(function_name)) {
  3682. MethodInfo info = base_script->get_method_info(function_name);
  3683. if (!(info == MethodInfo())) {
  3684. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  3685. }
  3686. base_script = base_script->get_base_script();
  3687. }
  3688. // If the base is a script, it might be trying to access members of the Script class itself.
  3689. if (p_base_type.is_meta_type && !p_is_constructor && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {
  3690. MethodInfo info;
  3691. StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());
  3692. if (ClassDB::get_method_info(script_class, function_name, &info)) {
  3693. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  3694. }
  3695. }
  3696. StringName base_native = p_base_type.native_type;
  3697. #ifdef DEBUG_ENABLED
  3698. if (base_native != StringName()) {
  3699. // Empty native class might happen in some Script implementations.
  3700. // Just ignore it.
  3701. if (!class_exists(base_native)) {
  3702. ERR_FAIL_V_MSG(false, vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native));
  3703. }
  3704. }
  3705. #endif
  3706. if (p_is_constructor) {
  3707. // Native types always have a default constructor.
  3708. r_return_type = p_base_type;
  3709. r_return_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3710. r_return_type.is_meta_type = false;
  3711. return true;
  3712. }
  3713. MethodInfo info;
  3714. if (ClassDB::get_method_info(base_native, function_name, &info)) {
  3715. bool valid = function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  3716. if (valid && Engine::get_singleton()->has_singleton(base_native)) {
  3717. r_static = true;
  3718. }
  3719. return valid;
  3720. }
  3721. return false;
  3722. }
  3723. 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) {
  3724. r_return_type = type_from_property(p_info.return_val);
  3725. r_default_arg_count = p_info.default_arguments.size();
  3726. r_vararg = (p_info.flags & METHOD_FLAG_VARARG) != 0;
  3727. r_static = (p_info.flags & METHOD_FLAG_STATIC) != 0;
  3728. for (const PropertyInfo &E : p_info.arguments) {
  3729. r_par_types.push_back(type_from_property(E));
  3730. }
  3731. return true;
  3732. }
  3733. bool GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {
  3734. List<GDScriptParser::DataType> arg_types;
  3735. for (const PropertyInfo &E : p_method.arguments) {
  3736. arg_types.push_back(type_from_property(E));
  3737. }
  3738. return validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);
  3739. }
  3740. 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) {
  3741. bool valid = true;
  3742. if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {
  3743. 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);
  3744. valid = false;
  3745. }
  3746. if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {
  3747. 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()]);
  3748. valid = false;
  3749. }
  3750. for (int i = 0; i < p_call->arguments.size(); i++) {
  3751. if (i >= p_par_types.size()) {
  3752. // Already on vararg place.
  3753. break;
  3754. }
  3755. GDScriptParser::DataType par_type = p_par_types[i];
  3756. GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
  3757. if (arg_type.is_variant()) {
  3758. // Argument can be anything, so this is unsafe.
  3759. mark_node_unsafe(p_call->arguments[i]);
  3760. } else if (par_type.is_hard_type() && !is_type_compatible(par_type, arg_type, true)) {
  3761. // Supertypes are acceptable for dynamic compliance, but it's unsafe.
  3762. mark_node_unsafe(p_call);
  3763. if (!is_type_compatible(arg_type, par_type)) {
  3764. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*",
  3765. p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),
  3766. p_call->arguments[i]);
  3767. valid = false;
  3768. }
  3769. #ifdef DEBUG_ENABLED
  3770. } else {
  3771. 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) {
  3772. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  3773. }
  3774. #endif
  3775. }
  3776. }
  3777. return valid;
  3778. }
  3779. #ifdef DEBUG_ENABLED
  3780. bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context) {
  3781. const StringName &name = p_local->name;
  3782. GDScriptParser::DataType base = parser->current_class->get_datatype();
  3783. GDScriptParser::ClassNode *base_class = base.class_type;
  3784. {
  3785. List<MethodInfo> gdscript_funcs;
  3786. GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);
  3787. for (MethodInfo &info : gdscript_funcs) {
  3788. if (info.name == name) {
  3789. parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");
  3790. return true;
  3791. }
  3792. }
  3793. if (Variant::has_utility_function(name)) {
  3794. parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");
  3795. return true;
  3796. } else if (ClassDB::class_exists(name)) {
  3797. parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "global class");
  3798. return true;
  3799. }
  3800. }
  3801. while (base_class != nullptr) {
  3802. if (base_class->has_member(name)) {
  3803. 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()));
  3804. return true;
  3805. }
  3806. base_class = base_class->base_type.class_type;
  3807. }
  3808. StringName parent = base.native_type;
  3809. while (parent != StringName()) {
  3810. ERR_FAIL_COND_V_MSG(!class_exists(parent), false, "Non-existent native base class.");
  3811. if (ClassDB::has_method(parent, name, true)) {
  3812. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "method", parent);
  3813. return true;
  3814. } else if (ClassDB::has_signal(parent, name, true)) {
  3815. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "signal", parent);
  3816. return true;
  3817. } else if (ClassDB::has_property(parent, name, true)) {
  3818. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "property", parent);
  3819. return true;
  3820. } else if (ClassDB::has_integer_constant(parent, name, true)) {
  3821. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "constant", parent);
  3822. return true;
  3823. } else if (ClassDB::has_enum(parent, name, true)) {
  3824. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "enum", parent);
  3825. return true;
  3826. }
  3827. parent = ClassDB::get_parent_class(parent);
  3828. }
  3829. return false;
  3830. }
  3831. #endif
  3832. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source) {
  3833. // Unary version.
  3834. GDScriptParser::DataType nil_type;
  3835. nil_type.builtin_type = Variant::NIL;
  3836. nil_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  3837. return get_operation_type(p_operation, p_a, nil_type, r_valid, p_source);
  3838. }
  3839. 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) {
  3840. GDScriptParser::DataType result;
  3841. result.kind = GDScriptParser::DataType::VARIANT;
  3842. Variant::Type a_type = p_a.builtin_type;
  3843. Variant::Type b_type = p_b.builtin_type;
  3844. if (p_a.kind == GDScriptParser::DataType::ENUM) {
  3845. if (p_a.is_meta_type) {
  3846. a_type = Variant::DICTIONARY;
  3847. } else {
  3848. a_type = Variant::INT;
  3849. }
  3850. }
  3851. if (p_b.kind == GDScriptParser::DataType::ENUM) {
  3852. if (p_b.is_meta_type) {
  3853. b_type = Variant::DICTIONARY;
  3854. } else {
  3855. b_type = Variant::INT;
  3856. }
  3857. }
  3858. Variant::ValidatedOperatorEvaluator op_eval = Variant::get_validated_operator_evaluator(p_operation, a_type, b_type);
  3859. bool hard_operation = p_a.is_hard_type() && p_b.is_hard_type();
  3860. bool validated = op_eval != nullptr;
  3861. if (hard_operation && !validated) {
  3862. r_valid = false;
  3863. return result;
  3864. } else if (hard_operation && validated) {
  3865. r_valid = true;
  3866. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  3867. result.kind = GDScriptParser::DataType::BUILTIN;
  3868. result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type);
  3869. } else if (!hard_operation && !validated) {
  3870. r_valid = true;
  3871. result.type_source = GDScriptParser::DataType::UNDETECTED;
  3872. result.kind = GDScriptParser::DataType::VARIANT;
  3873. result.builtin_type = Variant::NIL;
  3874. } else if (!hard_operation && validated) {
  3875. r_valid = true;
  3876. result.type_source = GDScriptParser::DataType::INFERRED;
  3877. result.kind = GDScriptParser::DataType::BUILTIN;
  3878. result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type);
  3879. }
  3880. return result;
  3881. }
  3882. // TODO: Add safe/unsafe return variable (for variant cases)
  3883. 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) {
  3884. // These return "true" so it doesn't affect users negatively.
  3885. ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");
  3886. ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");
  3887. if (p_target.kind == GDScriptParser::DataType::VARIANT) {
  3888. // Variant can receive anything.
  3889. return true;
  3890. }
  3891. if (p_source.kind == GDScriptParser::DataType::VARIANT) {
  3892. // TODO: This is acceptable but unsafe. Make sure unsafe line is set.
  3893. return true;
  3894. }
  3895. if (p_target.kind == GDScriptParser::DataType::BUILTIN) {
  3896. bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;
  3897. if (!valid && p_allow_implicit_conversion) {
  3898. valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);
  3899. }
  3900. if (!valid && p_target.builtin_type == Variant::INT && p_source.kind == GDScriptParser::DataType::ENUM && !p_source.is_meta_type) {
  3901. // Enum value is also integer.
  3902. valid = true;
  3903. }
  3904. if (valid && p_target.builtin_type == Variant::ARRAY && p_source.builtin_type == Variant::ARRAY) {
  3905. // Check the element type.
  3906. if (p_target.has_container_element_type()) {
  3907. if (!p_source.has_container_element_type()) {
  3908. // TODO: Maybe this is valid but unsafe?
  3909. // Variant array can't be appended to typed array.
  3910. valid = false;
  3911. } else {
  3912. valid = is_type_compatible(p_target.get_container_element_type(), p_source.get_container_element_type(), p_allow_implicit_conversion);
  3913. }
  3914. }
  3915. }
  3916. return valid;
  3917. }
  3918. if (p_target.kind == GDScriptParser::DataType::ENUM) {
  3919. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {
  3920. #ifdef DEBUG_ENABLED
  3921. if (p_source_node) {
  3922. parser->push_warning(p_source_node, GDScriptWarning::INT_ASSIGNED_TO_ENUM);
  3923. }
  3924. #endif
  3925. return true;
  3926. }
  3927. if (p_source.kind == GDScriptParser::DataType::ENUM) {
  3928. if (p_source.native_type == p_target.native_type) {
  3929. return true;
  3930. }
  3931. }
  3932. return false;
  3933. }
  3934. // From here on the target type is an object, so we have to test polymorphism.
  3935. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {
  3936. // null is acceptable in object.
  3937. return true;
  3938. }
  3939. StringName src_native;
  3940. Ref<Script> src_script;
  3941. const GDScriptParser::ClassNode *src_class = nullptr;
  3942. switch (p_source.kind) {
  3943. case GDScriptParser::DataType::NATIVE:
  3944. if (p_target.kind != GDScriptParser::DataType::NATIVE) {
  3945. // Non-native class cannot be supertype of native.
  3946. return false;
  3947. }
  3948. if (p_source.is_meta_type) {
  3949. src_native = GDScriptNativeClass::get_class_static();
  3950. } else {
  3951. src_native = p_source.native_type;
  3952. }
  3953. break;
  3954. case GDScriptParser::DataType::SCRIPT:
  3955. if (p_target.kind == GDScriptParser::DataType::CLASS) {
  3956. // A script type cannot be a subtype of a GDScript class.
  3957. return false;
  3958. }
  3959. if (p_source.is_meta_type) {
  3960. src_native = p_source.script_type->get_class_name();
  3961. } else {
  3962. src_script = p_source.script_type;
  3963. src_native = src_script->get_instance_base_type();
  3964. }
  3965. break;
  3966. case GDScriptParser::DataType::CLASS:
  3967. if (p_source.is_meta_type) {
  3968. src_native = GDScript::get_class_static();
  3969. } else {
  3970. src_class = p_source.class_type;
  3971. const GDScriptParser::ClassNode *base = src_class;
  3972. while (base->base_type.kind == GDScriptParser::DataType::CLASS) {
  3973. base = base->base_type.class_type;
  3974. }
  3975. src_native = base->base_type.native_type;
  3976. src_script = base->base_type.script_type;
  3977. }
  3978. break;
  3979. case GDScriptParser::DataType::VARIANT:
  3980. case GDScriptParser::DataType::BUILTIN:
  3981. case GDScriptParser::DataType::ENUM:
  3982. case GDScriptParser::DataType::RESOLVING:
  3983. case GDScriptParser::DataType::UNRESOLVED:
  3984. break; // Already solved before.
  3985. }
  3986. switch (p_target.kind) {
  3987. case GDScriptParser::DataType::NATIVE: {
  3988. if (p_target.is_meta_type) {
  3989. return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());
  3990. }
  3991. return ClassDB::is_parent_class(src_native, p_target.native_type);
  3992. }
  3993. case GDScriptParser::DataType::SCRIPT:
  3994. if (p_target.is_meta_type) {
  3995. return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());
  3996. }
  3997. while (src_script.is_valid()) {
  3998. if (src_script == p_target.script_type) {
  3999. return true;
  4000. }
  4001. src_script = src_script->get_base_script();
  4002. }
  4003. return false;
  4004. case GDScriptParser::DataType::CLASS:
  4005. if (p_target.is_meta_type) {
  4006. return ClassDB::is_parent_class(src_native, GDScript::get_class_static());
  4007. }
  4008. while (src_class != nullptr) {
  4009. if (src_class->fqcn == p_target.class_type->fqcn) {
  4010. return true;
  4011. }
  4012. src_class = src_class->base_type.class_type;
  4013. }
  4014. return false;
  4015. case GDScriptParser::DataType::VARIANT:
  4016. case GDScriptParser::DataType::BUILTIN:
  4017. case GDScriptParser::DataType::ENUM:
  4018. case GDScriptParser::DataType::RESOLVING:
  4019. case GDScriptParser::DataType::UNRESOLVED:
  4020. break; // Already solved before.
  4021. }
  4022. return false;
  4023. }
  4024. void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {
  4025. mark_node_unsafe(p_origin);
  4026. parser->push_error(p_message, p_origin);
  4027. }
  4028. void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {
  4029. #ifdef DEBUG_ENABLED
  4030. if (p_node == nullptr) {
  4031. return;
  4032. }
  4033. for (int i = p_node->start_line; i <= p_node->end_line; i++) {
  4034. parser->unsafe_lines.insert(i);
  4035. }
  4036. #endif
  4037. }
  4038. void GDScriptAnalyzer::mark_lambda_use_self() {
  4039. for (GDScriptParser::LambdaNode *lambda : lambda_stack) {
  4040. lambda->use_self = true;
  4041. }
  4042. }
  4043. bool GDScriptAnalyzer::class_exists(const StringName &p_class) const {
  4044. return ClassDB::class_exists(p_class) && ClassDB::is_class_exposed(p_class);
  4045. }
  4046. Ref<GDScriptParserRef> GDScriptAnalyzer::get_parser_for(const String &p_path) {
  4047. Ref<GDScriptParserRef> ref;
  4048. if (depended_parsers.has(p_path)) {
  4049. ref = depended_parsers[p_path];
  4050. } else {
  4051. Error err = OK;
  4052. ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err, parser->script_path);
  4053. if (ref.is_valid()) {
  4054. depended_parsers[p_path] = ref;
  4055. }
  4056. }
  4057. return ref;
  4058. }
  4059. Error GDScriptAnalyzer::resolve_inheritance() {
  4060. return resolve_class_inheritance(parser->head, true);
  4061. }
  4062. Error GDScriptAnalyzer::resolve_interface() {
  4063. resolve_class_interface(parser->head, true);
  4064. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  4065. }
  4066. Error GDScriptAnalyzer::resolve_body() {
  4067. resolve_class_body(parser->head, true);
  4068. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  4069. }
  4070. Error GDScriptAnalyzer::resolve_dependencies() {
  4071. for (KeyValue<String, Ref<GDScriptParserRef>> &K : depended_parsers) {
  4072. if (K.value.is_null()) {
  4073. return ERR_PARSE_ERROR;
  4074. }
  4075. K.value->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  4076. }
  4077. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  4078. }
  4079. Error GDScriptAnalyzer::analyze() {
  4080. parser->errors.clear();
  4081. Error err = OK;
  4082. err = resolve_inheritance();
  4083. if (err) {
  4084. return err;
  4085. }
  4086. resolve_interface();
  4087. resolve_body();
  4088. if (!parser->errors.is_empty()) {
  4089. return ERR_PARSE_ERROR;
  4090. }
  4091. return resolve_dependencies();
  4092. }
  4093. GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {
  4094. parser = p_parser;
  4095. }