gdscript_analyzer.cpp 237 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983
  1. /**************************************************************************/
  2. /* gdscript_analyzer.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gdscript_analyzer.h"
  31. #include "gdscript.h"
  32. #include "gdscript_utility_callable.h"
  33. #include "gdscript_utility_functions.h"
  34. #include "core/config/engine.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/core_constants.h"
  37. #include "core/io/file_access.h"
  38. #include "core/io/resource_loader.h"
  39. #include "core/object/class_db.h"
  40. #include "core/object/script_language.h"
  41. #include "core/templates/hash_map.h"
  42. #include "scene/resources/packed_scene.h"
  43. #if defined(TOOLS_ENABLED) && !defined(DISABLE_DEPRECATED)
  44. #define SUGGEST_GODOT4_RENAMES
  45. #include "editor/renames_map_3_to_4.h"
  46. #endif
  47. #define UNNAMED_ENUM "<anonymous enum>"
  48. #define ENUM_SEPARATOR "."
  49. static MethodInfo info_from_utility_func(const StringName &p_function) {
  50. ERR_FAIL_COND_V(!Variant::has_utility_function(p_function), MethodInfo());
  51. MethodInfo info(p_function);
  52. if (Variant::has_utility_function_return_value(p_function)) {
  53. info.return_val.type = Variant::get_utility_function_return_type(p_function);
  54. if (info.return_val.type == Variant::NIL) {
  55. info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  56. }
  57. }
  58. if (Variant::is_utility_function_vararg(p_function)) {
  59. info.flags |= METHOD_FLAG_VARARG;
  60. } else {
  61. for (int i = 0; i < Variant::get_utility_function_argument_count(p_function); i++) {
  62. PropertyInfo pi;
  63. #ifdef DEBUG_METHODS_ENABLED
  64. pi.name = Variant::get_utility_function_argument_name(p_function, i);
  65. #else
  66. pi.name = "arg" + itos(i + 1);
  67. #endif
  68. pi.type = Variant::get_utility_function_argument_type(p_function, i);
  69. info.arguments.push_back(pi);
  70. }
  71. }
  72. return info;
  73. }
  74. static GDScriptParser::DataType make_callable_type(const MethodInfo &p_info) {
  75. GDScriptParser::DataType type;
  76. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  77. type.kind = GDScriptParser::DataType::BUILTIN;
  78. type.builtin_type = Variant::CALLABLE;
  79. type.is_constant = true;
  80. type.method_info = p_info;
  81. return type;
  82. }
  83. static GDScriptParser::DataType make_signal_type(const MethodInfo &p_info) {
  84. GDScriptParser::DataType type;
  85. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  86. type.kind = GDScriptParser::DataType::BUILTIN;
  87. type.builtin_type = Variant::SIGNAL;
  88. type.is_constant = true;
  89. type.method_info = p_info;
  90. return type;
  91. }
  92. static GDScriptParser::DataType make_native_meta_type(const StringName &p_class_name) {
  93. GDScriptParser::DataType type;
  94. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  95. type.kind = GDScriptParser::DataType::NATIVE;
  96. type.builtin_type = Variant::OBJECT;
  97. type.native_type = p_class_name;
  98. type.is_constant = true;
  99. type.is_meta_type = true;
  100. return type;
  101. }
  102. static GDScriptParser::DataType make_script_meta_type(const Ref<Script> &p_script) {
  103. GDScriptParser::DataType type;
  104. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  105. type.kind = GDScriptParser::DataType::SCRIPT;
  106. type.builtin_type = Variant::OBJECT;
  107. type.native_type = p_script->get_instance_base_type();
  108. type.script_type = p_script;
  109. type.script_path = p_script->get_path();
  110. type.is_constant = true;
  111. type.is_meta_type = true;
  112. return type;
  113. }
  114. // In enum types, native_type is used to store the class (native or otherwise) that the enum belongs to.
  115. // This disambiguates between similarly named enums in base classes or outer classes
  116. static GDScriptParser::DataType make_enum_type(const StringName &p_enum_name, const String &p_base_name, const bool p_meta = false) {
  117. GDScriptParser::DataType type;
  118. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  119. type.kind = GDScriptParser::DataType::ENUM;
  120. type.builtin_type = p_meta ? Variant::DICTIONARY : Variant::INT;
  121. type.enum_type = p_enum_name;
  122. type.is_constant = true;
  123. type.is_meta_type = p_meta;
  124. // For enums, native_type is only used to check compatibility in is_type_compatible()
  125. // We can set anything readable here for error messages, as long as it uniquely identifies the type of the enum
  126. if (p_base_name.is_empty()) {
  127. type.native_type = p_enum_name;
  128. } else {
  129. type.native_type = p_base_name + ENUM_SEPARATOR + p_enum_name;
  130. }
  131. return type;
  132. }
  133. static GDScriptParser::DataType make_native_enum_type(const StringName &p_enum_name, const StringName &p_native_class, bool p_meta = true) {
  134. // Find out which base class declared the enum, so the name is always the same even when coming from other contexts.
  135. StringName native_base = p_native_class;
  136. while (true && native_base != StringName()) {
  137. if (ClassDB::has_enum(native_base, p_enum_name, true)) {
  138. break;
  139. }
  140. native_base = ClassDB::get_parent_class_nocheck(native_base);
  141. }
  142. GDScriptParser::DataType type = make_enum_type(p_enum_name, native_base, p_meta);
  143. if (p_meta) {
  144. type.builtin_type = Variant::NIL; // Native enum types are not Dictionaries.
  145. }
  146. List<StringName> enum_values;
  147. ClassDB::get_enum_constants(native_base, p_enum_name, &enum_values, true);
  148. for (const StringName &E : enum_values) {
  149. type.enum_values[E] = ClassDB::get_integer_constant(native_base, E);
  150. }
  151. return type;
  152. }
  153. static GDScriptParser::DataType make_global_enum_type(const StringName &p_enum_name, const StringName &p_base, bool p_meta = true) {
  154. GDScriptParser::DataType type = make_enum_type(p_enum_name, p_base, p_meta);
  155. if (p_meta) {
  156. type.builtin_type = Variant::NIL; // Native enum types are not Dictionaries.
  157. type.is_pseudo_type = true;
  158. }
  159. HashMap<StringName, int64_t> enum_values;
  160. CoreConstants::get_enum_values(type.native_type, &enum_values);
  161. for (const KeyValue<StringName, int64_t> &element : enum_values) {
  162. type.enum_values[element.key] = element.value;
  163. }
  164. return type;
  165. }
  166. static GDScriptParser::DataType make_builtin_meta_type(Variant::Type p_type) {
  167. GDScriptParser::DataType type;
  168. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  169. type.kind = GDScriptParser::DataType::BUILTIN;
  170. type.builtin_type = p_type;
  171. type.is_constant = true;
  172. type.is_meta_type = true;
  173. return type;
  174. }
  175. bool GDScriptAnalyzer::has_member_name_conflict_in_script_class(const StringName &p_member_name, const GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_member) {
  176. if (p_class->members_indices.has(p_member_name)) {
  177. int index = p_class->members_indices[p_member_name];
  178. const GDScriptParser::ClassNode::Member *member = &p_class->members[index];
  179. if (member->type == GDScriptParser::ClassNode::Member::VARIABLE ||
  180. member->type == GDScriptParser::ClassNode::Member::CONSTANT ||
  181. member->type == GDScriptParser::ClassNode::Member::ENUM ||
  182. member->type == GDScriptParser::ClassNode::Member::ENUM_VALUE ||
  183. member->type == GDScriptParser::ClassNode::Member::CLASS ||
  184. member->type == GDScriptParser::ClassNode::Member::SIGNAL) {
  185. return true;
  186. }
  187. if (p_member->type != GDScriptParser::Node::FUNCTION && member->type == GDScriptParser::ClassNode::Member::FUNCTION) {
  188. return true;
  189. }
  190. }
  191. return false;
  192. }
  193. bool GDScriptAnalyzer::has_member_name_conflict_in_native_type(const StringName &p_member_name, const StringName &p_native_type_string) {
  194. if (ClassDB::has_signal(p_native_type_string, p_member_name)) {
  195. return true;
  196. }
  197. if (ClassDB::has_property(p_native_type_string, p_member_name)) {
  198. return true;
  199. }
  200. if (ClassDB::has_integer_constant(p_native_type_string, p_member_name)) {
  201. return true;
  202. }
  203. if (p_member_name == CoreStringName(script)) {
  204. return true;
  205. }
  206. return false;
  207. }
  208. Error GDScriptAnalyzer::check_native_member_name_conflict(const StringName &p_member_name, const GDScriptParser::Node *p_member_node, const StringName &p_native_type_string) {
  209. if (has_member_name_conflict_in_native_type(p_member_name, p_native_type_string)) {
  210. push_error(vformat(R"(Member "%s" redefined (original in native class '%s'))", p_member_name, p_native_type_string), p_member_node);
  211. return ERR_PARSE_ERROR;
  212. }
  213. if (class_exists(p_member_name)) {
  214. push_error(vformat(R"(The member "%s" shadows a native class.)", p_member_name), p_member_node);
  215. return ERR_PARSE_ERROR;
  216. }
  217. if (GDScriptParser::get_builtin_type(p_member_name) < Variant::VARIANT_MAX) {
  218. push_error(vformat(R"(The member "%s" cannot have the same name as a builtin type.)", p_member_name), p_member_node);
  219. return ERR_PARSE_ERROR;
  220. }
  221. return OK;
  222. }
  223. Error GDScriptAnalyzer::check_class_member_name_conflict(const GDScriptParser::ClassNode *p_class_node, const StringName &p_member_name, const GDScriptParser::Node *p_member_node) {
  224. // TODO check outer classes for static members only
  225. const GDScriptParser::DataType *current_data_type = &p_class_node->base_type;
  226. while (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::CLASS) {
  227. GDScriptParser::ClassNode *current_class_node = current_data_type->class_type;
  228. if (has_member_name_conflict_in_script_class(p_member_name, current_class_node, p_member_node)) {
  229. String parent_class_name = current_class_node->fqcn;
  230. if (current_class_node->identifier != nullptr) {
  231. parent_class_name = current_class_node->identifier->name;
  232. }
  233. push_error(vformat(R"(The member "%s" already exists in parent class %s.)", p_member_name, parent_class_name), p_member_node);
  234. return ERR_PARSE_ERROR;
  235. }
  236. current_data_type = &current_class_node->base_type;
  237. }
  238. // No need for native class recursion because Node exposes all Object's properties.
  239. if (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::NATIVE) {
  240. if (current_data_type->native_type != StringName()) {
  241. return check_native_member_name_conflict(
  242. p_member_name,
  243. p_member_node,
  244. current_data_type->native_type);
  245. }
  246. }
  247. return OK;
  248. }
  249. void GDScriptAnalyzer::get_class_node_current_scope_classes(GDScriptParser::ClassNode *p_node, List<GDScriptParser::ClassNode *> *p_list, GDScriptParser::Node *p_source) {
  250. ERR_FAIL_NULL(p_node);
  251. ERR_FAIL_NULL(p_list);
  252. if (p_list->find(p_node) != nullptr) {
  253. return;
  254. }
  255. p_list->push_back(p_node);
  256. // TODO: Try to solve class inheritance if not yet resolving.
  257. // Prioritize node base type over its outer class
  258. if (p_node->base_type.class_type != nullptr) {
  259. // TODO: 'ensure_cached_external_parser_for_class()' is only necessary because 'resolve_class_inheritance()' is not getting called here.
  260. ensure_cached_external_parser_for_class(p_node->base_type.class_type, p_node, "Trying to fetch classes in the current scope", p_source);
  261. get_class_node_current_scope_classes(p_node->base_type.class_type, p_list, p_source);
  262. }
  263. if (p_node->outer != nullptr) {
  264. // TODO: 'ensure_cached_external_parser_for_class()' is only necessary because 'resolve_class_inheritance()' is not getting called here.
  265. ensure_cached_external_parser_for_class(p_node->outer, p_node, "Trying to fetch classes in the current scope", p_source);
  266. get_class_node_current_scope_classes(p_node->outer, p_list, p_source);
  267. }
  268. }
  269. Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  270. if (p_source == nullptr && parser->has_class(p_class)) {
  271. p_source = p_class;
  272. }
  273. Ref<GDScriptParserRef> parser_ref = ensure_cached_external_parser_for_class(p_class, nullptr, "Trying to resolve class inheritance", p_source);
  274. Finally finally([&]() {
  275. for (GDScriptParser::ClassNode *look_class = p_class; look_class != nullptr; look_class = look_class->base_type.class_type) {
  276. ensure_cached_external_parser_for_class(look_class->base_type.class_type, look_class, "Trying to resolve class inheritance", p_source);
  277. }
  278. });
  279. if (p_class->base_type.is_resolving()) {
  280. push_error(vformat(R"(Could not resolve class "%s": Cyclic reference.)", type_from_metatype(p_class->get_datatype()).to_string()), p_source);
  281. return ERR_PARSE_ERROR;
  282. }
  283. if (!p_class->base_type.has_no_type()) {
  284. // Already resolved.
  285. return OK;
  286. }
  287. if (!parser->has_class(p_class)) {
  288. if (parser_ref.is_null()) {
  289. // Error already pushed.
  290. return ERR_PARSE_ERROR;
  291. }
  292. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  293. if (err) {
  294. push_error(vformat(R"(Could not parse script "%s": %s.)", p_class->get_datatype().script_path, error_names[err]), p_source);
  295. return ERR_PARSE_ERROR;
  296. }
  297. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  298. GDScriptParser *other_parser = parser_ref->get_parser();
  299. int error_count = other_parser->errors.size();
  300. other_analyzer->resolve_class_inheritance(p_class);
  301. if (other_parser->errors.size() > error_count) {
  302. push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->fqcn), p_source);
  303. return ERR_PARSE_ERROR;
  304. }
  305. return OK;
  306. }
  307. GDScriptParser::ClassNode *previous_class = parser->current_class;
  308. parser->current_class = p_class;
  309. if (p_class->identifier) {
  310. StringName class_name = p_class->identifier->name;
  311. if (GDScriptParser::get_builtin_type(class_name) < Variant::VARIANT_MAX) {
  312. push_error(vformat(R"(Class "%s" hides a built-in type.)", class_name), p_class->identifier);
  313. } else if (class_exists(class_name)) {
  314. push_error(vformat(R"(Class "%s" hides a native class.)", class_name), p_class->identifier);
  315. } else if (ScriptServer::is_global_class(class_name) && (!GDScript::is_canonically_equal_paths(ScriptServer::get_global_class_path(class_name), parser->script_path) || p_class != parser->head)) {
  316. push_error(vformat(R"(Class "%s" hides a global script class.)", class_name), p_class->identifier);
  317. } else if (ProjectSettings::get_singleton()->has_autoload(class_name) && ProjectSettings::get_singleton()->get_autoload(class_name).is_singleton) {
  318. push_error(vformat(R"(Class "%s" hides an autoload singleton.)", class_name), p_class->identifier);
  319. }
  320. }
  321. GDScriptParser::DataType resolving_datatype;
  322. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  323. p_class->base_type = resolving_datatype;
  324. // Set datatype for class.
  325. GDScriptParser::DataType class_type;
  326. class_type.is_constant = true;
  327. class_type.is_meta_type = true;
  328. class_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  329. class_type.kind = GDScriptParser::DataType::CLASS;
  330. class_type.class_type = p_class;
  331. class_type.script_path = parser->script_path;
  332. class_type.builtin_type = Variant::OBJECT;
  333. p_class->set_datatype(class_type);
  334. GDScriptParser::DataType result;
  335. if (!p_class->extends_used) {
  336. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  337. result.kind = GDScriptParser::DataType::NATIVE;
  338. result.builtin_type = Variant::OBJECT;
  339. result.native_type = SNAME("RefCounted");
  340. } else {
  341. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  342. GDScriptParser::DataType base;
  343. int extends_index = 0;
  344. if (!p_class->extends_path.is_empty()) {
  345. if (p_class->extends_path.is_relative_path()) {
  346. p_class->extends_path = class_type.script_path.get_base_dir().path_join(p_class->extends_path).simplify_path();
  347. }
  348. Ref<GDScriptParserRef> ext_parser = parser->get_depended_parser_for(p_class->extends_path);
  349. if (ext_parser.is_null()) {
  350. push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class);
  351. return ERR_PARSE_ERROR;
  352. }
  353. Error err = ext_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  354. if (err != OK) {
  355. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", p_class->extends_path), p_class);
  356. return err;
  357. }
  358. #ifdef DEBUG_ENABLED
  359. if (!parser->_is_tool && ext_parser->get_parser()->_is_tool) {
  360. parser->push_warning(p_class, GDScriptWarning::MISSING_TOOL);
  361. }
  362. #endif
  363. base = ext_parser->get_parser()->head->get_datatype();
  364. } else {
  365. if (p_class->extends.is_empty()) {
  366. push_error("Could not resolve an empty super class path.", p_class);
  367. return ERR_PARSE_ERROR;
  368. }
  369. GDScriptParser::IdentifierNode *id = p_class->extends[extends_index++];
  370. const StringName &name = id->name;
  371. base.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  372. if (ScriptServer::is_global_class(name)) {
  373. String base_path = ScriptServer::get_global_class_path(name);
  374. if (GDScript::is_canonically_equal_paths(base_path, parser->script_path)) {
  375. base = parser->head->get_datatype();
  376. } else {
  377. Ref<GDScriptParserRef> base_parser = parser->get_depended_parser_for(base_path);
  378. if (base_parser.is_null()) {
  379. push_error(vformat(R"(Could not resolve super class "%s".)", name), id);
  380. return ERR_PARSE_ERROR;
  381. }
  382. Error err = base_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  383. if (err != OK) {
  384. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), id);
  385. return err;
  386. }
  387. #ifdef DEBUG_ENABLED
  388. if (!parser->_is_tool && base_parser->get_parser()->_is_tool) {
  389. parser->push_warning(p_class, GDScriptWarning::MISSING_TOOL);
  390. }
  391. #endif
  392. base = base_parser->get_parser()->head->get_datatype();
  393. }
  394. } else if (ProjectSettings::get_singleton()->has_autoload(name) && ProjectSettings::get_singleton()->get_autoload(name).is_singleton) {
  395. const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(name);
  396. if (info.path.get_extension().to_lower() != GDScriptLanguage::get_singleton()->get_extension()) {
  397. push_error(vformat(R"(Singleton %s is not a GDScript.)", info.name), id);
  398. return ERR_PARSE_ERROR;
  399. }
  400. Ref<GDScriptParserRef> info_parser = parser->get_depended_parser_for(info.path);
  401. if (info_parser.is_null()) {
  402. push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), id);
  403. return ERR_PARSE_ERROR;
  404. }
  405. Error err = info_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  406. if (err != OK) {
  407. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), id);
  408. return err;
  409. }
  410. #ifdef DEBUG_ENABLED
  411. if (!parser->_is_tool && info_parser->get_parser()->_is_tool) {
  412. parser->push_warning(p_class, GDScriptWarning::MISSING_TOOL);
  413. }
  414. #endif
  415. base = info_parser->get_parser()->head->get_datatype();
  416. } else if (class_exists(name)) {
  417. if (Engine::get_singleton()->has_singleton(name)) {
  418. push_error(vformat(R"(Cannot inherit native class "%s" because it is an engine singleton.)", name), id);
  419. return ERR_PARSE_ERROR;
  420. }
  421. base.kind = GDScriptParser::DataType::NATIVE;
  422. base.builtin_type = Variant::OBJECT;
  423. base.native_type = name;
  424. } else {
  425. // Look for other classes in script.
  426. bool found = false;
  427. List<GDScriptParser::ClassNode *> script_classes;
  428. get_class_node_current_scope_classes(p_class, &script_classes, id);
  429. for (GDScriptParser::ClassNode *look_class : script_classes) {
  430. if (look_class->identifier && look_class->identifier->name == name) {
  431. if (!look_class->get_datatype().is_set()) {
  432. Error err = resolve_class_inheritance(look_class, id);
  433. if (err) {
  434. return err;
  435. }
  436. }
  437. base = look_class->get_datatype();
  438. found = true;
  439. break;
  440. }
  441. if (look_class->has_member(name)) {
  442. resolve_class_member(look_class, name, id);
  443. GDScriptParser::ClassNode::Member member = look_class->get_member(name);
  444. GDScriptParser::DataType member_datatype = member.get_datatype();
  445. switch (member.type) {
  446. case GDScriptParser::ClassNode::Member::CLASS:
  447. break; // OK.
  448. case GDScriptParser::ClassNode::Member::CONSTANT:
  449. if (member_datatype.kind != GDScriptParser::DataType::SCRIPT && member_datatype.kind != GDScriptParser::DataType::CLASS) {
  450. push_error(vformat(R"(Constant "%s" is not a preloaded script or class.)", name), id);
  451. return ERR_PARSE_ERROR;
  452. }
  453. break;
  454. default:
  455. push_error(vformat(R"(Cannot use %s "%s" in extends chain.)", member.get_type_name(), name), id);
  456. return ERR_PARSE_ERROR;
  457. }
  458. base = member_datatype;
  459. found = true;
  460. break;
  461. }
  462. }
  463. if (!found) {
  464. push_error(vformat(R"(Could not find base class "%s".)", name), id);
  465. return ERR_PARSE_ERROR;
  466. }
  467. }
  468. }
  469. for (int index = extends_index; index < p_class->extends.size(); index++) {
  470. GDScriptParser::IdentifierNode *id = p_class->extends[index];
  471. if (base.kind != GDScriptParser::DataType::CLASS) {
  472. push_error(vformat(R"(Cannot get nested types for extension from non-GDScript type "%s".)", base.to_string()), id);
  473. return ERR_PARSE_ERROR;
  474. }
  475. reduce_identifier_from_base(id, &base);
  476. GDScriptParser::DataType id_type = id->get_datatype();
  477. if (!id_type.is_set()) {
  478. push_error(vformat(R"(Could not find nested type "%s".)", id->name), id);
  479. return ERR_PARSE_ERROR;
  480. } else if (id_type.kind != GDScriptParser::DataType::SCRIPT && id_type.kind != GDScriptParser::DataType::CLASS) {
  481. push_error(vformat(R"(Identifier "%s" is not a preloaded script or class.)", id->name), id);
  482. return ERR_PARSE_ERROR;
  483. }
  484. base = id_type;
  485. }
  486. result = base;
  487. }
  488. if (!result.is_set() || result.has_no_type()) {
  489. // TODO: More specific error messages.
  490. push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->identifier == nullptr ? "<main>" : p_class->identifier->name), p_class);
  491. return ERR_PARSE_ERROR;
  492. }
  493. // Check for cyclic inheritance.
  494. const GDScriptParser::ClassNode *base_class = result.class_type;
  495. while (base_class) {
  496. if (base_class->fqcn == p_class->fqcn) {
  497. push_error("Cyclic inheritance.", p_class);
  498. return ERR_PARSE_ERROR;
  499. }
  500. base_class = base_class->base_type.class_type;
  501. }
  502. p_class->base_type = result;
  503. class_type.native_type = result.native_type;
  504. p_class->set_datatype(class_type);
  505. // Apply annotations.
  506. for (GDScriptParser::AnnotationNode *&E : p_class->annotations) {
  507. resolve_annotation(E);
  508. E->apply(parser, p_class, p_class->outer);
  509. }
  510. parser->current_class = previous_class;
  511. return OK;
  512. }
  513. Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  514. Error err = resolve_class_inheritance(p_class);
  515. if (err) {
  516. return err;
  517. }
  518. if (p_recursive) {
  519. for (int i = 0; i < p_class->members.size(); i++) {
  520. if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {
  521. err = resolve_class_inheritance(p_class->members[i].m_class, true);
  522. if (err) {
  523. return err;
  524. }
  525. }
  526. }
  527. }
  528. return OK;
  529. }
  530. GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::TypeNode *p_type) {
  531. GDScriptParser::DataType bad_type;
  532. bad_type.kind = GDScriptParser::DataType::VARIANT;
  533. bad_type.type_source = GDScriptParser::DataType::INFERRED;
  534. if (p_type == nullptr) {
  535. return bad_type;
  536. }
  537. if (p_type->get_datatype().is_resolving()) {
  538. push_error(R"(Could not resolve datatype: Cyclic reference.)", p_type);
  539. return bad_type;
  540. }
  541. if (!p_type->get_datatype().has_no_type()) {
  542. return p_type->get_datatype();
  543. }
  544. GDScriptParser::DataType resolving_datatype;
  545. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  546. p_type->set_datatype(resolving_datatype);
  547. GDScriptParser::DataType result;
  548. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  549. if (p_type->type_chain.is_empty()) {
  550. // void.
  551. result.kind = GDScriptParser::DataType::BUILTIN;
  552. result.builtin_type = Variant::NIL;
  553. p_type->set_datatype(result);
  554. return result;
  555. }
  556. const GDScriptParser::IdentifierNode *first_id = p_type->type_chain[0];
  557. StringName first = first_id->name;
  558. bool type_found = false;
  559. if (first_id->suite && first_id->suite->has_local(first)) {
  560. const GDScriptParser::SuiteNode::Local &local = first_id->suite->get_local(first);
  561. if (local.type == GDScriptParser::SuiteNode::Local::CONSTANT) {
  562. result = local.get_datatype();
  563. if (!result.is_set()) {
  564. // Don't try to resolve it as the constant can be declared below.
  565. push_error(vformat(R"(Local constant "%s" is not resolved at this point.)", first), first_id);
  566. return bad_type;
  567. }
  568. if (result.is_meta_type) {
  569. type_found = true;
  570. } else if (Ref<Script>(local.constant->initializer->reduced_value).is_valid()) {
  571. Ref<GDScript> gdscript = local.constant->initializer->reduced_value;
  572. if (gdscript.is_valid()) {
  573. Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(gdscript->get_script_path());
  574. if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {
  575. push_error(vformat(R"(Could not parse script from "%s".)", gdscript->get_script_path()), first_id);
  576. return bad_type;
  577. }
  578. result = ref->get_parser()->head->get_datatype();
  579. } else {
  580. result = make_script_meta_type(local.constant->initializer->reduced_value);
  581. }
  582. type_found = true;
  583. } else {
  584. push_error(vformat(R"(Local constant "%s" is not a valid type.)", first), first_id);
  585. return bad_type;
  586. }
  587. } else {
  588. push_error(vformat(R"(Local %s "%s" cannot be used as a type.)", local.get_name(), first), first_id);
  589. return bad_type;
  590. }
  591. }
  592. if (!type_found) {
  593. if (first == SNAME("Variant")) {
  594. if (p_type->type_chain.size() == 2) {
  595. // May be nested enum.
  596. StringName enum_name = p_type->type_chain[1]->name;
  597. StringName qualified_name = String(first) + ENUM_SEPARATOR + String(p_type->type_chain[1]->name);
  598. if (CoreConstants::is_global_enum(qualified_name)) {
  599. result = make_global_enum_type(enum_name, first, true);
  600. return result;
  601. } else {
  602. push_error(vformat(R"(Name "%s" is not a nested type of "Variant".)", enum_name), p_type->type_chain[1]);
  603. return bad_type;
  604. }
  605. } else if (p_type->type_chain.size() > 2) {
  606. push_error(R"(Variant only contains enum types, which do not have nested types.)", p_type->type_chain[2]);
  607. return bad_type;
  608. }
  609. result.kind = GDScriptParser::DataType::VARIANT;
  610. } else if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) {
  611. // Built-in types.
  612. if (p_type->type_chain.size() > 1) {
  613. push_error(R"(Built-in types don't contain nested types.)", p_type->type_chain[1]);
  614. return bad_type;
  615. }
  616. result.kind = GDScriptParser::DataType::BUILTIN;
  617. result.builtin_type = GDScriptParser::get_builtin_type(first);
  618. if (result.builtin_type == Variant::ARRAY) {
  619. GDScriptParser::DataType container_type = type_from_metatype(resolve_datatype(p_type->get_container_type_or_null(0)));
  620. if (container_type.kind != GDScriptParser::DataType::VARIANT) {
  621. container_type.is_constant = false;
  622. result.set_container_element_type(0, container_type);
  623. }
  624. }
  625. } else if (class_exists(first)) {
  626. // Native engine classes.
  627. result.kind = GDScriptParser::DataType::NATIVE;
  628. result.builtin_type = Variant::OBJECT;
  629. result.native_type = first;
  630. } else if (ScriptServer::is_global_class(first)) {
  631. if (GDScript::is_canonically_equal_paths(parser->script_path, ScriptServer::get_global_class_path(first))) {
  632. result = parser->head->get_datatype();
  633. } else {
  634. String path = ScriptServer::get_global_class_path(first);
  635. String ext = path.get_extension();
  636. if (ext == GDScriptLanguage::get_singleton()->get_extension()) {
  637. Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(path);
  638. if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {
  639. push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type);
  640. return bad_type;
  641. }
  642. result = ref->get_parser()->head->get_datatype();
  643. } else {
  644. result = make_script_meta_type(ResourceLoader::load(path, "Script"));
  645. }
  646. }
  647. } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) {
  648. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first);
  649. String script_path;
  650. if (ResourceLoader::get_resource_type(autoload.path) == "PackedScene") {
  651. // Try to get script from scene if possible.
  652. if (GDScriptLanguage::get_singleton()->has_any_global_constant(autoload.name)) {
  653. Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(autoload.name);
  654. Node *node = Object::cast_to<Node>(constant);
  655. if (node != nullptr) {
  656. Ref<GDScript> scr = node->get_script();
  657. if (scr.is_valid()) {
  658. script_path = scr->get_script_path();
  659. }
  660. }
  661. }
  662. } else if (ResourceLoader::get_resource_type(autoload.path) == "GDScript") {
  663. script_path = autoload.path;
  664. }
  665. if (script_path.is_empty()) {
  666. return bad_type;
  667. }
  668. Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(script_path);
  669. if (ref.is_null()) {
  670. push_error(vformat(R"(The referenced autoload "%s" (from "%s") could not be loaded.)", first, script_path), p_type);
  671. return bad_type;
  672. }
  673. if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {
  674. push_error(vformat(R"(Could not parse singleton "%s" from "%s".)", first, script_path), p_type);
  675. return bad_type;
  676. }
  677. result = ref->get_parser()->head->get_datatype();
  678. } else if (ClassDB::has_enum(parser->current_class->base_type.native_type, first)) {
  679. // Native enum in current class.
  680. result = make_native_enum_type(first, parser->current_class->base_type.native_type);
  681. } else if (CoreConstants::is_global_enum(first)) {
  682. if (p_type->type_chain.size() > 1) {
  683. push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[1]);
  684. return bad_type;
  685. }
  686. result = make_global_enum_type(first, StringName());
  687. } else {
  688. // Classes in current scope.
  689. List<GDScriptParser::ClassNode *> script_classes;
  690. bool found = false;
  691. get_class_node_current_scope_classes(parser->current_class, &script_classes, p_type);
  692. for (GDScriptParser::ClassNode *script_class : script_classes) {
  693. if (found) {
  694. break;
  695. }
  696. if (script_class->identifier && script_class->identifier->name == first) {
  697. result = script_class->get_datatype();
  698. break;
  699. }
  700. if (script_class->members_indices.has(first)) {
  701. resolve_class_member(script_class, first, p_type);
  702. GDScriptParser::ClassNode::Member member = script_class->get_member(first);
  703. switch (member.type) {
  704. case GDScriptParser::ClassNode::Member::CLASS:
  705. result = member.get_datatype();
  706. found = true;
  707. break;
  708. case GDScriptParser::ClassNode::Member::ENUM:
  709. result = member.get_datatype();
  710. found = true;
  711. break;
  712. case GDScriptParser::ClassNode::Member::CONSTANT:
  713. if (member.get_datatype().is_meta_type) {
  714. result = member.get_datatype();
  715. found = true;
  716. break;
  717. } else if (Ref<Script>(member.constant->initializer->reduced_value).is_valid()) {
  718. Ref<GDScript> gdscript = member.constant->initializer->reduced_value;
  719. if (gdscript.is_valid()) {
  720. Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(gdscript->get_script_path());
  721. if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) {
  722. push_error(vformat(R"(Could not parse script from "%s".)", gdscript->get_script_path()), p_type);
  723. return bad_type;
  724. }
  725. result = ref->get_parser()->head->get_datatype();
  726. } else {
  727. result = make_script_meta_type(member.constant->initializer->reduced_value);
  728. }
  729. found = true;
  730. break;
  731. }
  732. [[fallthrough]];
  733. default:
  734. push_error(vformat(R"("%s" is a %s but does not contain a type.)", first, member.get_type_name()), p_type);
  735. return bad_type;
  736. }
  737. }
  738. }
  739. }
  740. }
  741. if (!result.is_set()) {
  742. push_error(vformat(R"(Could not find type "%s" in the current scope.)", first), p_type);
  743. return bad_type;
  744. }
  745. if (p_type->type_chain.size() > 1) {
  746. if (result.kind == GDScriptParser::DataType::CLASS) {
  747. for (int i = 1; i < p_type->type_chain.size(); i++) {
  748. GDScriptParser::DataType base = result;
  749. reduce_identifier_from_base(p_type->type_chain[i], &base);
  750. result = p_type->type_chain[i]->get_datatype();
  751. if (!result.is_set()) {
  752. 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]);
  753. return bad_type;
  754. } else if (!result.is_meta_type) {
  755. 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]);
  756. return bad_type;
  757. }
  758. }
  759. } else if (result.kind == GDScriptParser::DataType::NATIVE) {
  760. // Only enums allowed for native.
  761. if (ClassDB::has_enum(result.native_type, p_type->type_chain[1]->name)) {
  762. if (p_type->type_chain.size() > 2) {
  763. push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[2]);
  764. return bad_type;
  765. } else {
  766. result = make_native_enum_type(p_type->type_chain[1]->name, result.native_type);
  767. }
  768. } else {
  769. push_error(vformat(R"(Could not find type "%s" in "%s".)", p_type->type_chain[1]->name, first), p_type->type_chain[1]);
  770. return bad_type;
  771. }
  772. } else {
  773. 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]);
  774. return bad_type;
  775. }
  776. }
  777. if (!p_type->container_types.is_empty()) {
  778. if (result.builtin_type == Variant::ARRAY) {
  779. if (p_type->container_types.size() != 1) {
  780. push_error("Arrays require exactly one collection element type.", p_type);
  781. return bad_type;
  782. }
  783. } else {
  784. push_error("Only arrays can specify collection element types.", p_type);
  785. return bad_type;
  786. }
  787. }
  788. p_type->set_datatype(result);
  789. return result;
  790. }
  791. void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, const StringName &p_name, const GDScriptParser::Node *p_source) {
  792. ERR_FAIL_COND(!p_class->has_member(p_name));
  793. resolve_class_member(p_class, p_class->members_indices[p_name], p_source);
  794. }
  795. void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, int p_index, const GDScriptParser::Node *p_source) {
  796. ERR_FAIL_INDEX(p_index, p_class->members.size());
  797. GDScriptParser::ClassNode::Member &member = p_class->members.write[p_index];
  798. if (p_source == nullptr && parser->has_class(p_class)) {
  799. p_source = member.get_source_node();
  800. }
  801. Ref<GDScriptParserRef> parser_ref = ensure_cached_external_parser_for_class(p_class, nullptr, "Trying to resolve class member", p_source);
  802. Finally finally([&]() {
  803. ensure_cached_external_parser_for_class(member.get_datatype().class_type, p_class, "Trying to resolve datatype of class member", p_source);
  804. GDScriptParser::DataType member_type = member.get_datatype();
  805. if (member_type.has_container_element_type(0)) {
  806. ensure_cached_external_parser_for_class(member_type.get_container_element_type(0).class_type, p_class, "Trying to resolve datatype of class member", p_source);
  807. }
  808. });
  809. if (member.get_datatype().is_resolving()) {
  810. push_error(vformat(R"(Could not resolve member "%s": Cyclic reference.)", member.get_name()), p_source);
  811. return;
  812. }
  813. if (member.get_datatype().is_set()) {
  814. return;
  815. }
  816. // If it's already resolving, that's ok.
  817. if (!p_class->base_type.is_resolving()) {
  818. Error err = resolve_class_inheritance(p_class);
  819. if (err) {
  820. return;
  821. }
  822. }
  823. if (!parser->has_class(p_class)) {
  824. if (parser_ref.is_null()) {
  825. // Error already pushed.
  826. return;
  827. }
  828. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  829. if (err) {
  830. push_error(vformat(R"(Could not parse script "%s": %s (While resolving external class member "%s").)", p_class->get_datatype().script_path, error_names[err], member.get_name()), p_source);
  831. return;
  832. }
  833. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  834. GDScriptParser *other_parser = parser_ref->get_parser();
  835. int error_count = other_parser->errors.size();
  836. other_analyzer->resolve_class_member(p_class, p_index);
  837. if (other_parser->errors.size() > error_count) {
  838. push_error(vformat(R"(Could not resolve external class member "%s".)", member.get_name()), p_source);
  839. return;
  840. }
  841. return;
  842. }
  843. GDScriptParser::ClassNode *previous_class = parser->current_class;
  844. parser->current_class = p_class;
  845. GDScriptParser::DataType resolving_datatype;
  846. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  847. {
  848. #ifdef DEBUG_ENABLED
  849. GDScriptParser::Node *member_node = member.get_source_node();
  850. if (member_node && member_node->type != GDScriptParser::Node::ANNOTATION) {
  851. // Apply @warning_ignore annotations before resolving member.
  852. for (GDScriptParser::AnnotationNode *&E : member_node->annotations) {
  853. if (E->name == SNAME("@warning_ignore")) {
  854. resolve_annotation(E);
  855. E->apply(parser, member.variable, p_class);
  856. }
  857. }
  858. }
  859. #endif
  860. switch (member.type) {
  861. case GDScriptParser::ClassNode::Member::VARIABLE: {
  862. bool previous_static_context = static_context;
  863. static_context = member.variable->is_static;
  864. check_class_member_name_conflict(p_class, member.variable->identifier->name, member.variable);
  865. member.variable->set_datatype(resolving_datatype);
  866. resolve_variable(member.variable, false);
  867. resolve_pending_lambda_bodies();
  868. // Apply annotations.
  869. for (GDScriptParser::AnnotationNode *&E : member.variable->annotations) {
  870. if (E->name != SNAME("@warning_ignore")) {
  871. resolve_annotation(E);
  872. E->apply(parser, member.variable, p_class);
  873. }
  874. }
  875. static_context = previous_static_context;
  876. #ifdef DEBUG_ENABLED
  877. if (member.variable->exported && member.variable->onready) {
  878. parser->push_warning(member.variable, GDScriptWarning::ONREADY_WITH_EXPORT);
  879. }
  880. if (member.variable->initializer) {
  881. // Check if it is call to get_node() on self (using shorthand $ or not), so we can check if @onready is needed.
  882. // This could be improved by traversing the expression fully and checking the presence of get_node at any level.
  883. if (!member.variable->is_static && !member.variable->onready && member.variable->initializer && (member.variable->initializer->type == GDScriptParser::Node::GET_NODE || member.variable->initializer->type == GDScriptParser::Node::CALL || member.variable->initializer->type == GDScriptParser::Node::CAST)) {
  884. GDScriptParser::Node *expr = member.variable->initializer;
  885. if (expr->type == GDScriptParser::Node::CAST) {
  886. expr = static_cast<GDScriptParser::CastNode *>(expr)->operand;
  887. }
  888. bool is_get_node = expr->type == GDScriptParser::Node::GET_NODE;
  889. bool is_using_shorthand = is_get_node;
  890. if (!is_get_node && expr->type == GDScriptParser::Node::CALL) {
  891. is_using_shorthand = false;
  892. GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(expr);
  893. if (call->function_name == SNAME("get_node")) {
  894. switch (call->get_callee_type()) {
  895. case GDScriptParser::Node::IDENTIFIER: {
  896. is_get_node = true;
  897. } break;
  898. case GDScriptParser::Node::SUBSCRIPT: {
  899. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(call->callee);
  900. is_get_node = subscript->is_attribute && subscript->base->type == GDScriptParser::Node::SELF;
  901. } break;
  902. default:
  903. break;
  904. }
  905. }
  906. }
  907. if (is_get_node) {
  908. parser->push_warning(member.variable, GDScriptWarning::GET_NODE_DEFAULT_WITHOUT_ONREADY, is_using_shorthand ? "$" : "get_node()");
  909. }
  910. }
  911. }
  912. #endif
  913. } break;
  914. case GDScriptParser::ClassNode::Member::CONSTANT: {
  915. check_class_member_name_conflict(p_class, member.constant->identifier->name, member.constant);
  916. member.constant->set_datatype(resolving_datatype);
  917. resolve_constant(member.constant, false);
  918. // Apply annotations.
  919. for (GDScriptParser::AnnotationNode *&E : member.constant->annotations) {
  920. resolve_annotation(E);
  921. E->apply(parser, member.constant, p_class);
  922. }
  923. } break;
  924. case GDScriptParser::ClassNode::Member::SIGNAL: {
  925. check_class_member_name_conflict(p_class, member.signal->identifier->name, member.signal);
  926. member.signal->set_datatype(resolving_datatype);
  927. // This is the _only_ way to declare a signal. Therefore, we can generate its
  928. // MethodInfo inline so it's a tiny bit more efficient.
  929. MethodInfo mi = MethodInfo(member.signal->identifier->name);
  930. for (int j = 0; j < member.signal->parameters.size(); j++) {
  931. GDScriptParser::ParameterNode *param = member.signal->parameters[j];
  932. GDScriptParser::DataType param_type = type_from_metatype(resolve_datatype(param->datatype_specifier));
  933. param->set_datatype(param_type);
  934. #ifdef DEBUG_ENABLED
  935. if (param->datatype_specifier == nullptr) {
  936. parser->push_warning(param, GDScriptWarning::UNTYPED_DECLARATION, "Parameter", param->identifier->name);
  937. }
  938. #endif
  939. mi.arguments.push_back(param_type.to_property_info(param->identifier->name));
  940. // Signals do not support parameter default values.
  941. }
  942. member.signal->set_datatype(make_signal_type(mi));
  943. member.signal->method_info = mi;
  944. // Apply annotations.
  945. for (GDScriptParser::AnnotationNode *&E : member.signal->annotations) {
  946. resolve_annotation(E);
  947. E->apply(parser, member.signal, p_class);
  948. }
  949. } break;
  950. case GDScriptParser::ClassNode::Member::ENUM: {
  951. check_class_member_name_conflict(p_class, member.m_enum->identifier->name, member.m_enum);
  952. member.m_enum->set_datatype(resolving_datatype);
  953. GDScriptParser::DataType enum_type = make_enum_type(member.m_enum->identifier->name, p_class->fqcn, true);
  954. const GDScriptParser::EnumNode *prev_enum = current_enum;
  955. current_enum = member.m_enum;
  956. Dictionary dictionary;
  957. for (int j = 0; j < member.m_enum->values.size(); j++) {
  958. GDScriptParser::EnumNode::Value &element = member.m_enum->values.write[j];
  959. if (element.custom_value) {
  960. reduce_expression(element.custom_value);
  961. if (!element.custom_value->is_constant) {
  962. push_error(R"(Enum values must be constant.)", element.custom_value);
  963. } else if (element.custom_value->reduced_value.get_type() != Variant::INT) {
  964. push_error(R"(Enum values must be integers.)", element.custom_value);
  965. } else {
  966. element.value = element.custom_value->reduced_value;
  967. element.resolved = true;
  968. }
  969. } else {
  970. if (element.index > 0) {
  971. element.value = element.parent_enum->values[element.index - 1].value + 1;
  972. } else {
  973. element.value = 0;
  974. }
  975. element.resolved = true;
  976. }
  977. enum_type.enum_values[element.identifier->name] = element.value;
  978. dictionary[String(element.identifier->name)] = element.value;
  979. #ifdef DEBUG_ENABLED
  980. // Named enum identifiers do not shadow anything since you can only access them with `NamedEnum.ENUM_VALUE`.
  981. if (member.m_enum->identifier->name == StringName()) {
  982. is_shadowing(element.identifier, "enum member", false);
  983. }
  984. #endif
  985. }
  986. current_enum = prev_enum;
  987. dictionary.make_read_only();
  988. member.m_enum->set_datatype(enum_type);
  989. member.m_enum->dictionary = dictionary;
  990. // Apply annotations.
  991. for (GDScriptParser::AnnotationNode *&E : member.m_enum->annotations) {
  992. resolve_annotation(E);
  993. E->apply(parser, member.m_enum, p_class);
  994. }
  995. } break;
  996. case GDScriptParser::ClassNode::Member::FUNCTION:
  997. for (GDScriptParser::AnnotationNode *&E : member.function->annotations) {
  998. resolve_annotation(E);
  999. E->apply(parser, member.function, p_class);
  1000. }
  1001. resolve_function_signature(member.function, p_source);
  1002. break;
  1003. case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
  1004. member.enum_value.identifier->set_datatype(resolving_datatype);
  1005. if (member.enum_value.custom_value) {
  1006. check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.custom_value);
  1007. const GDScriptParser::EnumNode *prev_enum = current_enum;
  1008. current_enum = member.enum_value.parent_enum;
  1009. reduce_expression(member.enum_value.custom_value);
  1010. current_enum = prev_enum;
  1011. if (!member.enum_value.custom_value->is_constant) {
  1012. push_error(R"(Enum values must be constant.)", member.enum_value.custom_value);
  1013. } else if (member.enum_value.custom_value->reduced_value.get_type() != Variant::INT) {
  1014. push_error(R"(Enum values must be integers.)", member.enum_value.custom_value);
  1015. } else {
  1016. member.enum_value.value = member.enum_value.custom_value->reduced_value;
  1017. member.enum_value.resolved = true;
  1018. }
  1019. } else {
  1020. check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.parent_enum);
  1021. if (member.enum_value.index > 0) {
  1022. const GDScriptParser::EnumNode::Value &prev_value = member.enum_value.parent_enum->values[member.enum_value.index - 1];
  1023. resolve_class_member(p_class, prev_value.identifier->name, member.enum_value.identifier);
  1024. member.enum_value.value = prev_value.value + 1;
  1025. } else {
  1026. member.enum_value.value = 0;
  1027. }
  1028. member.enum_value.resolved = true;
  1029. }
  1030. // Also update the original references.
  1031. member.enum_value.parent_enum->values.set(member.enum_value.index, member.enum_value);
  1032. member.enum_value.identifier->set_datatype(make_enum_type(UNNAMED_ENUM, p_class->fqcn, false));
  1033. } break;
  1034. case GDScriptParser::ClassNode::Member::CLASS:
  1035. check_class_member_name_conflict(p_class, member.m_class->identifier->name, member.m_class);
  1036. // If it's already resolving, that's ok.
  1037. if (!member.m_class->base_type.is_resolving()) {
  1038. resolve_class_inheritance(member.m_class, p_source);
  1039. }
  1040. break;
  1041. case GDScriptParser::ClassNode::Member::GROUP:
  1042. // No-op, but needed to silence warnings.
  1043. break;
  1044. case GDScriptParser::ClassNode::Member::UNDEFINED:
  1045. ERR_PRINT("Trying to resolve undefined member.");
  1046. break;
  1047. }
  1048. }
  1049. parser->current_class = previous_class;
  1050. }
  1051. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  1052. if (p_source == nullptr && parser->has_class(p_class)) {
  1053. p_source = p_class;
  1054. }
  1055. Ref<GDScriptParserRef> parser_ref = ensure_cached_external_parser_for_class(p_class, nullptr, "Trying to resolve class interface", p_source);
  1056. if (!p_class->resolved_interface) {
  1057. #ifdef DEBUG_ENABLED
  1058. bool has_static_data = p_class->has_static_data;
  1059. #endif
  1060. if (!parser->has_class(p_class)) {
  1061. if (parser_ref.is_null()) {
  1062. // Error already pushed.
  1063. return;
  1064. }
  1065. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  1066. if (err) {
  1067. push_error(vformat(R"(Could not parse script "%s": %s.)", p_class->get_datatype().script_path, error_names[err]), p_source);
  1068. return;
  1069. }
  1070. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  1071. GDScriptParser *other_parser = parser_ref->get_parser();
  1072. int error_count = other_parser->errors.size();
  1073. other_analyzer->resolve_class_interface(p_class);
  1074. if (other_parser->errors.size() > error_count) {
  1075. push_error(vformat(R"(Could not resolve class "%s".)", p_class->fqcn), p_source);
  1076. return;
  1077. }
  1078. return;
  1079. }
  1080. p_class->resolved_interface = true;
  1081. if (resolve_class_inheritance(p_class) != OK) {
  1082. return;
  1083. }
  1084. GDScriptParser::DataType base_type = p_class->base_type;
  1085. if (base_type.kind == GDScriptParser::DataType::CLASS) {
  1086. GDScriptParser::ClassNode *base_class = base_type.class_type;
  1087. resolve_class_interface(base_class, p_class);
  1088. }
  1089. for (int i = 0; i < p_class->members.size(); i++) {
  1090. resolve_class_member(p_class, i);
  1091. #ifdef DEBUG_ENABLED
  1092. if (!has_static_data) {
  1093. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1094. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  1095. has_static_data = member.m_class->has_static_data;
  1096. }
  1097. }
  1098. #endif
  1099. }
  1100. #ifdef DEBUG_ENABLED
  1101. if (!has_static_data && p_class->annotated_static_unload) {
  1102. GDScriptParser::Node *static_unload = nullptr;
  1103. for (GDScriptParser::AnnotationNode *node : p_class->annotations) {
  1104. if (node->name == "@static_unload") {
  1105. static_unload = node;
  1106. break;
  1107. }
  1108. }
  1109. parser->push_warning(static_unload ? static_unload : p_class, GDScriptWarning::REDUNDANT_STATIC_UNLOAD);
  1110. }
  1111. #endif
  1112. }
  1113. }
  1114. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  1115. resolve_class_interface(p_class);
  1116. if (p_recursive) {
  1117. for (int i = 0; i < p_class->members.size(); i++) {
  1118. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1119. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  1120. resolve_class_interface(member.m_class, true);
  1121. }
  1122. }
  1123. }
  1124. }
  1125. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, const GDScriptParser::Node *p_source) {
  1126. if (p_source == nullptr && parser->has_class(p_class)) {
  1127. p_source = p_class;
  1128. }
  1129. Ref<GDScriptParserRef> parser_ref = ensure_cached_external_parser_for_class(p_class, nullptr, "Trying to resolve class body", p_source);
  1130. if (p_class->resolved_body) {
  1131. return;
  1132. }
  1133. if (!parser->has_class(p_class)) {
  1134. if (parser_ref.is_null()) {
  1135. // Error already pushed.
  1136. return;
  1137. }
  1138. Error err = parser_ref->raise_status(GDScriptParserRef::PARSED);
  1139. if (err) {
  1140. push_error(vformat(R"(Could not parse script "%s": %s.)", p_class->get_datatype().script_path, error_names[err]), p_source);
  1141. return;
  1142. }
  1143. GDScriptAnalyzer *other_analyzer = parser_ref->get_analyzer();
  1144. GDScriptParser *other_parser = parser_ref->get_parser();
  1145. int error_count = other_parser->errors.size();
  1146. other_analyzer->resolve_class_body(p_class);
  1147. if (other_parser->errors.size() > error_count) {
  1148. push_error(vformat(R"(Could not resolve class "%s".)", p_class->fqcn), p_source);
  1149. return;
  1150. }
  1151. return;
  1152. }
  1153. p_class->resolved_body = true;
  1154. GDScriptParser::ClassNode *previous_class = parser->current_class;
  1155. parser->current_class = p_class;
  1156. resolve_class_interface(p_class, p_source);
  1157. GDScriptParser::DataType base_type = p_class->base_type;
  1158. if (base_type.kind == GDScriptParser::DataType::CLASS) {
  1159. GDScriptParser::ClassNode *base_class = base_type.class_type;
  1160. resolve_class_body(base_class, p_class);
  1161. }
  1162. // Do functions, properties, and groups now.
  1163. for (int i = 0; i < p_class->members.size(); i++) {
  1164. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1165. if (member.type == GDScriptParser::ClassNode::Member::FUNCTION) {
  1166. // Apply annotations.
  1167. for (GDScriptParser::AnnotationNode *&E : member.function->annotations) {
  1168. resolve_annotation(E);
  1169. E->apply(parser, member.function, p_class);
  1170. }
  1171. resolve_function_body(member.function);
  1172. } else if (member.type == GDScriptParser::ClassNode::Member::VARIABLE && member.variable->property != GDScriptParser::VariableNode::PROP_NONE) {
  1173. if (member.variable->property == GDScriptParser::VariableNode::PROP_INLINE) {
  1174. if (member.variable->getter != nullptr) {
  1175. member.variable->getter->return_type = member.variable->datatype_specifier;
  1176. member.variable->getter->set_datatype(member.get_datatype());
  1177. resolve_function_body(member.variable->getter);
  1178. }
  1179. if (member.variable->setter != nullptr) {
  1180. ERR_CONTINUE(member.variable->setter->parameters.is_empty());
  1181. member.variable->setter->parameters[0]->datatype_specifier = member.variable->datatype_specifier;
  1182. member.variable->setter->parameters[0]->set_datatype(member.get_datatype());
  1183. resolve_function_body(member.variable->setter);
  1184. }
  1185. }
  1186. } else if (member.type == GDScriptParser::ClassNode::Member::GROUP) {
  1187. // Apply annotation (`@export_{category,group,subgroup}`).
  1188. resolve_annotation(member.annotation);
  1189. member.annotation->apply(parser, nullptr, p_class);
  1190. }
  1191. }
  1192. // Check unused variables and datatypes of property getters and setters.
  1193. for (int i = 0; i < p_class->members.size(); i++) {
  1194. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1195. if (member.type == GDScriptParser::ClassNode::Member::VARIABLE) {
  1196. #ifdef DEBUG_ENABLED
  1197. if (member.variable->usages == 0 && String(member.variable->identifier->name).begins_with("_")) {
  1198. parser->push_warning(member.variable->identifier, GDScriptWarning::UNUSED_PRIVATE_CLASS_VARIABLE, member.variable->identifier->name);
  1199. }
  1200. #endif
  1201. if (member.variable->property == GDScriptParser::VariableNode::PROP_SETGET) {
  1202. GDScriptParser::FunctionNode *getter_function = nullptr;
  1203. GDScriptParser::FunctionNode *setter_function = nullptr;
  1204. bool has_valid_getter = false;
  1205. bool has_valid_setter = false;
  1206. if (member.variable->getter_pointer != nullptr) {
  1207. if (p_class->has_function(member.variable->getter_pointer->name)) {
  1208. getter_function = p_class->get_member(member.variable->getter_pointer->name).function;
  1209. }
  1210. if (getter_function == nullptr) {
  1211. push_error(vformat(R"(Getter "%s" not found.)", member.variable->getter_pointer->name), member.variable);
  1212. } else {
  1213. GDScriptParser::DataType return_datatype = getter_function->datatype;
  1214. if (getter_function->return_type != nullptr) {
  1215. return_datatype = getter_function->return_type->datatype;
  1216. return_datatype.is_meta_type = false;
  1217. }
  1218. if (getter_function->parameters.size() != 0 || return_datatype.has_no_type()) {
  1219. push_error(vformat(R"(Function "%s" cannot be used as getter because of its signature.)", getter_function->identifier->name), member.variable);
  1220. } else if (!is_type_compatible(member.variable->datatype, return_datatype, true)) {
  1221. 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);
  1222. } else {
  1223. has_valid_getter = true;
  1224. #ifdef DEBUG_ENABLED
  1225. if (member.variable->datatype.builtin_type == Variant::INT && return_datatype.builtin_type == Variant::FLOAT) {
  1226. parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION);
  1227. }
  1228. #endif
  1229. }
  1230. }
  1231. }
  1232. if (member.variable->setter_pointer != nullptr) {
  1233. if (p_class->has_function(member.variable->setter_pointer->name)) {
  1234. setter_function = p_class->get_member(member.variable->setter_pointer->name).function;
  1235. }
  1236. if (setter_function == nullptr) {
  1237. push_error(vformat(R"(Setter "%s" not found.)", member.variable->setter_pointer->name), member.variable);
  1238. } else if (setter_function->parameters.size() != 1) {
  1239. push_error(vformat(R"(Function "%s" cannot be used as setter because of its signature.)", setter_function->identifier->name), member.variable);
  1240. } else if (!is_type_compatible(member.variable->datatype, setter_function->parameters[0]->datatype, true)) {
  1241. 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);
  1242. } else {
  1243. has_valid_setter = true;
  1244. #ifdef DEBUG_ENABLED
  1245. if (member.variable->datatype.builtin_type == Variant::FLOAT && setter_function->parameters[0]->datatype.builtin_type == Variant::INT) {
  1246. parser->push_warning(member.variable, GDScriptWarning::NARROWING_CONVERSION);
  1247. }
  1248. #endif
  1249. }
  1250. }
  1251. if (member.variable->datatype.is_variant() && has_valid_getter && has_valid_setter) {
  1252. if (!is_type_compatible(getter_function->datatype, setter_function->parameters[0]->datatype, true)) {
  1253. 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);
  1254. }
  1255. }
  1256. }
  1257. } else if (member.type == GDScriptParser::ClassNode::Member::SIGNAL) {
  1258. #ifdef DEBUG_ENABLED
  1259. if (member.signal->usages == 0) {
  1260. parser->push_warning(member.signal->identifier, GDScriptWarning::UNUSED_SIGNAL, member.signal->identifier->name);
  1261. }
  1262. #endif
  1263. }
  1264. }
  1265. if (!pending_body_resolution_lambdas.is_empty()) {
  1266. ERR_PRINT("GDScript bug (please report): Not all pending lambda bodies were resolved in time.");
  1267. resolve_pending_lambda_bodies();
  1268. }
  1269. parser->current_class = previous_class;
  1270. }
  1271. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  1272. resolve_class_body(p_class);
  1273. if (p_recursive) {
  1274. for (int i = 0; i < p_class->members.size(); i++) {
  1275. GDScriptParser::ClassNode::Member member = p_class->members[i];
  1276. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  1277. resolve_class_body(member.m_class, true);
  1278. }
  1279. }
  1280. }
  1281. }
  1282. void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node, bool p_is_root) {
  1283. ERR_FAIL_NULL_MSG(p_node, "Trying to resolve type of a null node.");
  1284. switch (p_node->type) {
  1285. case GDScriptParser::Node::NONE:
  1286. break; // Unreachable.
  1287. case GDScriptParser::Node::CLASS:
  1288. // NOTE: Currently this route is never executed, `resolve_class_*()` is called directly.
  1289. if (OK == resolve_class_inheritance(static_cast<GDScriptParser::ClassNode *>(p_node), true)) {
  1290. resolve_class_interface(static_cast<GDScriptParser::ClassNode *>(p_node), true);
  1291. resolve_class_body(static_cast<GDScriptParser::ClassNode *>(p_node), true);
  1292. }
  1293. break;
  1294. case GDScriptParser::Node::CONSTANT:
  1295. resolve_constant(static_cast<GDScriptParser::ConstantNode *>(p_node), true);
  1296. break;
  1297. case GDScriptParser::Node::FOR:
  1298. resolve_for(static_cast<GDScriptParser::ForNode *>(p_node));
  1299. break;
  1300. case GDScriptParser::Node::IF:
  1301. resolve_if(static_cast<GDScriptParser::IfNode *>(p_node));
  1302. break;
  1303. case GDScriptParser::Node::SUITE:
  1304. resolve_suite(static_cast<GDScriptParser::SuiteNode *>(p_node));
  1305. break;
  1306. case GDScriptParser::Node::VARIABLE:
  1307. resolve_variable(static_cast<GDScriptParser::VariableNode *>(p_node), true);
  1308. break;
  1309. case GDScriptParser::Node::WHILE:
  1310. resolve_while(static_cast<GDScriptParser::WhileNode *>(p_node));
  1311. break;
  1312. case GDScriptParser::Node::ANNOTATION:
  1313. resolve_annotation(static_cast<GDScriptParser::AnnotationNode *>(p_node));
  1314. break;
  1315. case GDScriptParser::Node::ASSERT:
  1316. resolve_assert(static_cast<GDScriptParser::AssertNode *>(p_node));
  1317. break;
  1318. case GDScriptParser::Node::MATCH:
  1319. resolve_match(static_cast<GDScriptParser::MatchNode *>(p_node));
  1320. break;
  1321. case GDScriptParser::Node::MATCH_BRANCH:
  1322. resolve_match_branch(static_cast<GDScriptParser::MatchBranchNode *>(p_node), nullptr);
  1323. break;
  1324. case GDScriptParser::Node::PARAMETER:
  1325. resolve_parameter(static_cast<GDScriptParser::ParameterNode *>(p_node));
  1326. break;
  1327. case GDScriptParser::Node::PATTERN:
  1328. resolve_match_pattern(static_cast<GDScriptParser::PatternNode *>(p_node), nullptr);
  1329. break;
  1330. case GDScriptParser::Node::RETURN:
  1331. resolve_return(static_cast<GDScriptParser::ReturnNode *>(p_node));
  1332. break;
  1333. case GDScriptParser::Node::TYPE:
  1334. resolve_datatype(static_cast<GDScriptParser::TypeNode *>(p_node));
  1335. break;
  1336. // Resolving expression is the same as reducing them.
  1337. case GDScriptParser::Node::ARRAY:
  1338. case GDScriptParser::Node::ASSIGNMENT:
  1339. case GDScriptParser::Node::AWAIT:
  1340. case GDScriptParser::Node::BINARY_OPERATOR:
  1341. case GDScriptParser::Node::CALL:
  1342. case GDScriptParser::Node::CAST:
  1343. case GDScriptParser::Node::DICTIONARY:
  1344. case GDScriptParser::Node::GET_NODE:
  1345. case GDScriptParser::Node::IDENTIFIER:
  1346. case GDScriptParser::Node::LAMBDA:
  1347. case GDScriptParser::Node::LITERAL:
  1348. case GDScriptParser::Node::PRELOAD:
  1349. case GDScriptParser::Node::SELF:
  1350. case GDScriptParser::Node::SUBSCRIPT:
  1351. case GDScriptParser::Node::TERNARY_OPERATOR:
  1352. case GDScriptParser::Node::TYPE_TEST:
  1353. case GDScriptParser::Node::UNARY_OPERATOR:
  1354. reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), p_is_root);
  1355. break;
  1356. case GDScriptParser::Node::BREAK:
  1357. case GDScriptParser::Node::BREAKPOINT:
  1358. case GDScriptParser::Node::CONTINUE:
  1359. case GDScriptParser::Node::ENUM:
  1360. case GDScriptParser::Node::FUNCTION:
  1361. case GDScriptParser::Node::PASS:
  1362. case GDScriptParser::Node::SIGNAL:
  1363. // Nothing to do.
  1364. break;
  1365. }
  1366. }
  1367. void GDScriptAnalyzer::resolve_annotation(GDScriptParser::AnnotationNode *p_annotation) {
  1368. ERR_FAIL_COND_MSG(!parser->valid_annotations.has(p_annotation->name), vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  1369. if (p_annotation->is_resolved) {
  1370. return;
  1371. }
  1372. p_annotation->is_resolved = true;
  1373. const MethodInfo &annotation_info = parser->valid_annotations[p_annotation->name].info;
  1374. const List<PropertyInfo>::Element *E = annotation_info.arguments.front();
  1375. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  1376. GDScriptParser::ExpressionNode *argument = p_annotation->arguments[i];
  1377. const PropertyInfo &argument_info = E->get();
  1378. if (E->next() != nullptr) {
  1379. E = E->next();
  1380. }
  1381. reduce_expression(argument);
  1382. if (!argument->is_constant) {
  1383. push_error(vformat(R"(Argument %d of annotation "%s" isn't a constant expression.)", i + 1, p_annotation->name), argument);
  1384. return;
  1385. }
  1386. Variant value = argument->reduced_value;
  1387. if (value.get_type() != argument_info.type) {
  1388. #ifdef DEBUG_ENABLED
  1389. if (argument_info.type == Variant::INT && value.get_type() == Variant::FLOAT) {
  1390. parser->push_warning(argument, GDScriptWarning::NARROWING_CONVERSION);
  1391. }
  1392. #endif
  1393. if (!Variant::can_convert_strict(value.get_type(), argument_info.type)) {
  1394. push_error(vformat(R"(Invalid argument for annotation "%s": argument %d should be "%s" but is "%s".)", p_annotation->name, i + 1, Variant::get_type_name(argument_info.type), argument->get_datatype().to_string()), argument);
  1395. return;
  1396. }
  1397. Variant converted_to;
  1398. const Variant *converted_from = &value;
  1399. Callable::CallError call_error;
  1400. Variant::construct(argument_info.type, converted_to, &converted_from, 1, call_error);
  1401. if (call_error.error != Callable::CallError::CALL_OK) {
  1402. push_error(vformat(R"(Cannot convert argument %d of annotation "%s" from "%s" to "%s".)", i + 1, p_annotation->name, Variant::get_type_name(value.get_type()), Variant::get_type_name(argument_info.type)), argument);
  1403. return;
  1404. }
  1405. value = converted_to;
  1406. }
  1407. p_annotation->resolved_arguments.push_back(value);
  1408. }
  1409. }
  1410. void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode *p_function, const GDScriptParser::Node *p_source, bool p_is_lambda) {
  1411. if (p_source == nullptr) {
  1412. p_source = p_function;
  1413. }
  1414. StringName function_name = p_function->identifier != nullptr ? p_function->identifier->name : StringName();
  1415. if (p_function->get_datatype().is_resolving()) {
  1416. push_error(vformat(R"(Could not resolve function "%s": Cyclic reference.)", function_name), p_source);
  1417. return;
  1418. }
  1419. if (p_function->resolved_signature) {
  1420. return;
  1421. }
  1422. p_function->resolved_signature = true;
  1423. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  1424. parser->current_function = p_function;
  1425. bool previous_static_context = static_context;
  1426. if (p_is_lambda) {
  1427. // For lambdas this is determined from the context, the `static` keyword is not allowed.
  1428. p_function->is_static = static_context;
  1429. } else {
  1430. // For normal functions, this is determined in the parser by the `static` keyword.
  1431. static_context = p_function->is_static;
  1432. }
  1433. GDScriptParser::DataType prev_datatype = p_function->get_datatype();
  1434. GDScriptParser::DataType resolving_datatype;
  1435. resolving_datatype.kind = GDScriptParser::DataType::RESOLVING;
  1436. p_function->set_datatype(resolving_datatype);
  1437. #ifdef TOOLS_ENABLED
  1438. int default_value_count = 0;
  1439. #endif // TOOLS_ENABLED
  1440. #ifdef DEBUG_ENABLED
  1441. String function_visible_name = function_name;
  1442. if (function_name == StringName()) {
  1443. function_visible_name = p_is_lambda ? "<anonymous lambda>" : "<unknown function>";
  1444. }
  1445. #endif
  1446. for (int i = 0; i < p_function->parameters.size(); i++) {
  1447. resolve_parameter(p_function->parameters[i]);
  1448. #ifdef DEBUG_ENABLED
  1449. if (p_function->parameters[i]->usages == 0 && !String(p_function->parameters[i]->identifier->name).begins_with("_")) {
  1450. parser->push_warning(p_function->parameters[i]->identifier, GDScriptWarning::UNUSED_PARAMETER, function_visible_name, p_function->parameters[i]->identifier->name);
  1451. }
  1452. is_shadowing(p_function->parameters[i]->identifier, "function parameter", true);
  1453. #endif // DEBUG_ENABLED
  1454. if (p_function->parameters[i]->initializer) {
  1455. #ifdef TOOLS_ENABLED
  1456. default_value_count++;
  1457. #endif // TOOLS_ENABLED
  1458. if (p_function->parameters[i]->initializer->is_constant) {
  1459. p_function->default_arg_values.push_back(p_function->parameters[i]->initializer->reduced_value);
  1460. } else {
  1461. p_function->default_arg_values.push_back(Variant()); // Prevent shift.
  1462. }
  1463. }
  1464. }
  1465. if (!p_is_lambda && function_name == GDScriptLanguage::get_singleton()->strings._init) {
  1466. // Constructor.
  1467. GDScriptParser::DataType return_type = parser->current_class->get_datatype();
  1468. return_type.is_meta_type = false;
  1469. p_function->set_datatype(return_type);
  1470. if (p_function->return_type) {
  1471. GDScriptParser::DataType declared_return = resolve_datatype(p_function->return_type);
  1472. if (declared_return.kind != GDScriptParser::DataType::BUILTIN || declared_return.builtin_type != Variant::NIL) {
  1473. push_error("Constructor cannot have an explicit return type.", p_function->return_type);
  1474. }
  1475. }
  1476. } else if (!p_is_lambda && function_name == GDScriptLanguage::get_singleton()->strings._static_init) {
  1477. // Static constructor.
  1478. GDScriptParser::DataType return_type;
  1479. return_type.kind = GDScriptParser::DataType::BUILTIN;
  1480. return_type.builtin_type = Variant::NIL;
  1481. p_function->set_datatype(return_type);
  1482. if (p_function->return_type) {
  1483. GDScriptParser::DataType declared_return = resolve_datatype(p_function->return_type);
  1484. if (declared_return.kind != GDScriptParser::DataType::BUILTIN || declared_return.builtin_type != Variant::NIL) {
  1485. push_error("Static constructor cannot have an explicit return type.", p_function->return_type);
  1486. }
  1487. }
  1488. } else {
  1489. if (p_function->return_type != nullptr) {
  1490. p_function->set_datatype(type_from_metatype(resolve_datatype(p_function->return_type)));
  1491. } else {
  1492. // In case the function is not typed, we can safely assume it's a Variant, so it's okay to mark as "inferred" here.
  1493. // It's not "undetected" to not mix up with unknown functions.
  1494. GDScriptParser::DataType return_type;
  1495. return_type.type_source = GDScriptParser::DataType::INFERRED;
  1496. return_type.kind = GDScriptParser::DataType::VARIANT;
  1497. p_function->set_datatype(return_type);
  1498. }
  1499. #ifdef TOOLS_ENABLED
  1500. // Check if the function signature matches the parent. If not it's an error since it breaks polymorphism.
  1501. // Not for the constructor which can vary in signature.
  1502. GDScriptParser::DataType base_type = parser->current_class->base_type;
  1503. base_type.is_meta_type = false;
  1504. GDScriptParser::DataType parent_return_type;
  1505. List<GDScriptParser::DataType> parameters_types;
  1506. int default_par_count = 0;
  1507. BitField<MethodFlags> method_flags;
  1508. StringName native_base;
  1509. if (!p_is_lambda && get_function_signature(p_function, false, base_type, function_name, parent_return_type, parameters_types, default_par_count, method_flags, &native_base)) {
  1510. bool valid = p_function->is_static == method_flags.has_flag(METHOD_FLAG_STATIC);
  1511. if (p_function->return_type != nullptr) {
  1512. // Check return type covariance.
  1513. GDScriptParser::DataType return_type = p_function->get_datatype();
  1514. if (return_type.is_variant()) {
  1515. // `is_type_compatible()` returns `true` if one of the types is `Variant`.
  1516. // Don't allow an explicitly specified `Variant` if the parent return type is narrower.
  1517. valid = valid && parent_return_type.is_variant();
  1518. } else if (return_type.kind == GDScriptParser::DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {
  1519. // `is_type_compatible()` returns `true` if target is an `Object` and source is `null`.
  1520. // Don't allow `void` if the parent return type is a hard non-`void` type.
  1521. if (parent_return_type.is_hard_type() && !(parent_return_type.kind == GDScriptParser::DataType::BUILTIN && parent_return_type.builtin_type == Variant::NIL)) {
  1522. valid = false;
  1523. }
  1524. } else {
  1525. valid = valid && is_type_compatible(parent_return_type, return_type);
  1526. }
  1527. }
  1528. int par_count_diff = p_function->parameters.size() - parameters_types.size();
  1529. valid = valid && par_count_diff >= 0;
  1530. valid = valid && default_value_count >= default_par_count + par_count_diff;
  1531. if (valid) {
  1532. int i = 0;
  1533. for (const GDScriptParser::DataType &parent_par_type : parameters_types) {
  1534. // Check parameter type contravariance.
  1535. GDScriptParser::DataType current_par_type = p_function->parameters[i++]->get_datatype();
  1536. if (parent_par_type.is_variant() && parent_par_type.is_hard_type()) {
  1537. // `is_type_compatible()` returns `true` if one of the types is `Variant`.
  1538. // Don't allow narrowing a hard `Variant`.
  1539. valid = valid && current_par_type.is_variant();
  1540. } else {
  1541. valid = valid && is_type_compatible(current_par_type, parent_par_type);
  1542. }
  1543. }
  1544. }
  1545. if (!valid) {
  1546. // Compute parent signature as a string to show in the error message.
  1547. String parent_signature = String(function_name) + "(";
  1548. int j = 0;
  1549. for (const GDScriptParser::DataType &par_type : parameters_types) {
  1550. if (j > 0) {
  1551. parent_signature += ", ";
  1552. }
  1553. String parameter = par_type.to_string();
  1554. if (parameter == "null") {
  1555. parameter = "Variant";
  1556. }
  1557. parent_signature += parameter;
  1558. if (j >= parameters_types.size() - default_par_count) {
  1559. parent_signature += " = <default>";
  1560. }
  1561. j++;
  1562. }
  1563. parent_signature += ") -> ";
  1564. const String return_type = parent_return_type.to_string_strict();
  1565. if (return_type == "null") {
  1566. parent_signature += "void";
  1567. } else {
  1568. parent_signature += return_type;
  1569. }
  1570. push_error(vformat(R"(The function signature doesn't match the parent. Parent signature is "%s".)", parent_signature), p_function);
  1571. }
  1572. #ifdef DEBUG_ENABLED
  1573. if (native_base != StringName()) {
  1574. parser->push_warning(p_function, GDScriptWarning::NATIVE_METHOD_OVERRIDE, function_name, native_base);
  1575. }
  1576. #endif
  1577. }
  1578. #endif // TOOLS_ENABLED
  1579. }
  1580. #ifdef DEBUG_ENABLED
  1581. if (p_function->return_type == nullptr) {
  1582. parser->push_warning(p_function, GDScriptWarning::UNTYPED_DECLARATION, "Function", function_visible_name);
  1583. }
  1584. #endif
  1585. if (p_function->get_datatype().is_resolving()) {
  1586. p_function->set_datatype(prev_datatype);
  1587. }
  1588. parser->current_function = previous_function;
  1589. static_context = previous_static_context;
  1590. }
  1591. void GDScriptAnalyzer::resolve_function_body(GDScriptParser::FunctionNode *p_function, bool p_is_lambda) {
  1592. if (p_function->resolved_body) {
  1593. return;
  1594. }
  1595. p_function->resolved_body = true;
  1596. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  1597. parser->current_function = p_function;
  1598. bool previous_static_context = static_context;
  1599. static_context = p_function->is_static;
  1600. resolve_suite(p_function->body);
  1601. if (!p_function->get_datatype().is_hard_type() && p_function->body->get_datatype().is_set()) {
  1602. // Use the suite inferred type if return isn't explicitly set.
  1603. p_function->set_datatype(p_function->body->get_datatype());
  1604. } 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)) {
  1605. if (!p_function->body->has_return && (p_is_lambda || p_function->identifier->name != GDScriptLanguage::get_singleton()->strings._init)) {
  1606. push_error(R"(Not all code paths return a value.)", p_function);
  1607. }
  1608. }
  1609. parser->current_function = previous_function;
  1610. static_context = previous_static_context;
  1611. }
  1612. void GDScriptAnalyzer::decide_suite_type(GDScriptParser::Node *p_suite, GDScriptParser::Node *p_statement) {
  1613. if (p_statement == nullptr) {
  1614. return;
  1615. }
  1616. switch (p_statement->type) {
  1617. case GDScriptParser::Node::IF:
  1618. case GDScriptParser::Node::FOR:
  1619. case GDScriptParser::Node::MATCH:
  1620. case GDScriptParser::Node::PATTERN:
  1621. case GDScriptParser::Node::RETURN:
  1622. case GDScriptParser::Node::WHILE:
  1623. // Use return or nested suite type as this suite type.
  1624. if (p_suite->get_datatype().is_set() && (p_suite->get_datatype() != p_statement->get_datatype())) {
  1625. // Mixed types.
  1626. // TODO: This could use the common supertype instead.
  1627. p_suite->datatype.kind = GDScriptParser::DataType::VARIANT;
  1628. p_suite->datatype.type_source = GDScriptParser::DataType::UNDETECTED;
  1629. } else {
  1630. p_suite->set_datatype(p_statement->get_datatype());
  1631. p_suite->datatype.type_source = GDScriptParser::DataType::INFERRED;
  1632. }
  1633. break;
  1634. default:
  1635. break;
  1636. }
  1637. }
  1638. void GDScriptAnalyzer::resolve_suite(GDScriptParser::SuiteNode *p_suite) {
  1639. for (int i = 0; i < p_suite->statements.size(); i++) {
  1640. GDScriptParser::Node *stmt = p_suite->statements[i];
  1641. // Apply annotations.
  1642. for (GDScriptParser::AnnotationNode *&E : stmt->annotations) {
  1643. resolve_annotation(E);
  1644. E->apply(parser, stmt, nullptr); // TODO: Provide `p_class`.
  1645. }
  1646. resolve_node(stmt);
  1647. resolve_pending_lambda_bodies();
  1648. decide_suite_type(p_suite, stmt);
  1649. }
  1650. }
  1651. void GDScriptAnalyzer::resolve_assignable(GDScriptParser::AssignableNode *p_assignable, const char *p_kind) {
  1652. GDScriptParser::DataType type;
  1653. type.kind = GDScriptParser::DataType::VARIANT;
  1654. bool is_constant = p_assignable->type == GDScriptParser::Node::CONSTANT;
  1655. #ifdef DEBUG_ENABLED
  1656. if (p_assignable->identifier != nullptr && p_assignable->identifier->suite != nullptr && p_assignable->identifier->suite->parent_block != nullptr) {
  1657. if (p_assignable->identifier->suite->parent_block->has_local(p_assignable->identifier->name)) {
  1658. const GDScriptParser::SuiteNode::Local &local = p_assignable->identifier->suite->parent_block->get_local(p_assignable->identifier->name);
  1659. parser->push_warning(p_assignable->identifier, GDScriptWarning::CONFUSABLE_LOCAL_DECLARATION, local.get_name(), p_assignable->identifier->name);
  1660. }
  1661. }
  1662. #endif
  1663. GDScriptParser::DataType specified_type;
  1664. bool has_specified_type = p_assignable->datatype_specifier != nullptr;
  1665. if (has_specified_type) {
  1666. specified_type = type_from_metatype(resolve_datatype(p_assignable->datatype_specifier));
  1667. type = specified_type;
  1668. }
  1669. if (p_assignable->initializer != nullptr) {
  1670. reduce_expression(p_assignable->initializer);
  1671. if (p_assignable->initializer->type == GDScriptParser::Node::ARRAY) {
  1672. GDScriptParser::ArrayNode *array = static_cast<GDScriptParser::ArrayNode *>(p_assignable->initializer);
  1673. if (has_specified_type && specified_type.has_container_element_type(0)) {
  1674. update_array_literal_element_type(array, specified_type.get_container_element_type(0));
  1675. }
  1676. }
  1677. if (is_constant && !p_assignable->initializer->is_constant) {
  1678. bool is_initializer_value_reduced = false;
  1679. Variant initializer_value = make_expression_reduced_value(p_assignable->initializer, is_initializer_value_reduced);
  1680. if (is_initializer_value_reduced) {
  1681. p_assignable->initializer->is_constant = true;
  1682. p_assignable->initializer->reduced_value = initializer_value;
  1683. } else {
  1684. push_error(vformat(R"(Assigned value for %s "%s" isn't a constant expression.)", p_kind, p_assignable->identifier->name), p_assignable->initializer);
  1685. }
  1686. }
  1687. if (has_specified_type && p_assignable->initializer->is_constant) {
  1688. update_const_expression_builtin_type(p_assignable->initializer, specified_type, "assign");
  1689. }
  1690. GDScriptParser::DataType initializer_type = p_assignable->initializer->get_datatype();
  1691. if (p_assignable->infer_datatype) {
  1692. if (!initializer_type.is_set() || initializer_type.has_no_type() || !initializer_type.is_hard_type()) {
  1693. push_error(vformat(R"(Cannot infer the type of "%s" %s because the value doesn't have a set type.)", p_assignable->identifier->name, p_kind), p_assignable->initializer);
  1694. } else if (initializer_type.kind == GDScriptParser::DataType::BUILTIN && initializer_type.builtin_type == Variant::NIL && !is_constant) {
  1695. push_error(vformat(R"(Cannot infer the type of "%s" %s because the value is "null".)", p_assignable->identifier->name, p_kind), p_assignable->initializer);
  1696. }
  1697. #ifdef DEBUG_ENABLED
  1698. if (initializer_type.is_hard_type() && initializer_type.is_variant()) {
  1699. parser->push_warning(p_assignable, GDScriptWarning::INFERENCE_ON_VARIANT, p_kind);
  1700. }
  1701. #endif
  1702. } else {
  1703. if (!initializer_type.is_set()) {
  1704. push_error(vformat(R"(Could not resolve type for %s "%s".)", p_kind, p_assignable->identifier->name), p_assignable->initializer);
  1705. }
  1706. }
  1707. if (!has_specified_type) {
  1708. type = initializer_type;
  1709. if (!type.is_set() || (type.is_hard_type() && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL && !is_constant)) {
  1710. type.kind = GDScriptParser::DataType::VARIANT;
  1711. }
  1712. if (p_assignable->infer_datatype || is_constant) {
  1713. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1714. } else {
  1715. type.type_source = GDScriptParser::DataType::INFERRED;
  1716. }
  1717. } else if (!specified_type.is_variant()) {
  1718. if (initializer_type.is_variant() || !initializer_type.is_hard_type()) {
  1719. mark_node_unsafe(p_assignable->initializer);
  1720. p_assignable->use_conversion_assign = true;
  1721. if (!initializer_type.is_variant() && !is_type_compatible(specified_type, initializer_type, true, p_assignable->initializer)) {
  1722. downgrade_node_type_source(p_assignable->initializer);
  1723. }
  1724. } else if (!is_type_compatible(specified_type, initializer_type, true, p_assignable->initializer)) {
  1725. if (!is_constant && is_type_compatible(initializer_type, specified_type)) {
  1726. mark_node_unsafe(p_assignable->initializer);
  1727. p_assignable->use_conversion_assign = true;
  1728. } else {
  1729. push_error(vformat(R"(Cannot assign a value of type %s to %s "%s" with specified type %s.)", initializer_type.to_string(), p_kind, p_assignable->identifier->name, specified_type.to_string()), p_assignable->initializer);
  1730. }
  1731. } else if (specified_type.has_container_element_type(0) && !initializer_type.has_container_element_type(0)) {
  1732. mark_node_unsafe(p_assignable->initializer);
  1733. #ifdef DEBUG_ENABLED
  1734. } else if (specified_type.builtin_type == Variant::INT && initializer_type.builtin_type == Variant::FLOAT) {
  1735. parser->push_warning(p_assignable->initializer, GDScriptWarning::NARROWING_CONVERSION);
  1736. #endif
  1737. }
  1738. }
  1739. }
  1740. #ifdef DEBUG_ENABLED
  1741. const bool is_parameter = p_assignable->type == GDScriptParser::Node::PARAMETER;
  1742. if (!has_specified_type) {
  1743. const String declaration_type = is_constant ? "Constant" : (is_parameter ? "Parameter" : "Variable");
  1744. if (p_assignable->infer_datatype || is_constant) {
  1745. // Do not produce the `INFERRED_DECLARATION` warning on type import because there is no way to specify the true type.
  1746. // And removing the metatype makes it impossible to use the constant as a type hint (especially for enums).
  1747. const bool is_type_import = is_constant && p_assignable->initializer != nullptr && p_assignable->initializer->datatype.is_meta_type;
  1748. if (!is_type_import) {
  1749. parser->push_warning(p_assignable, GDScriptWarning::INFERRED_DECLARATION, declaration_type, p_assignable->identifier->name);
  1750. }
  1751. } else {
  1752. parser->push_warning(p_assignable, GDScriptWarning::UNTYPED_DECLARATION, declaration_type, p_assignable->identifier->name);
  1753. }
  1754. } else if (!is_parameter && specified_type.kind == GDScriptParser::DataType::ENUM && p_assignable->initializer == nullptr) {
  1755. // Warn about enum variables without default value. Unless the enum defines the "0" value, then it's fine.
  1756. bool has_zero_value = false;
  1757. for (const KeyValue<StringName, int64_t> &kv : specified_type.enum_values) {
  1758. if (kv.value == 0) {
  1759. has_zero_value = true;
  1760. break;
  1761. }
  1762. }
  1763. if (!has_zero_value) {
  1764. parser->push_warning(p_assignable, GDScriptWarning::ENUM_VARIABLE_WITHOUT_DEFAULT, p_assignable->identifier->name);
  1765. }
  1766. }
  1767. #endif
  1768. type.is_constant = is_constant;
  1769. type.is_read_only = false;
  1770. p_assignable->set_datatype(type);
  1771. }
  1772. void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable, bool p_is_local) {
  1773. static constexpr const char *kind = "variable";
  1774. resolve_assignable(p_variable, kind);
  1775. #ifdef DEBUG_ENABLED
  1776. if (p_is_local) {
  1777. if (p_variable->usages == 0 && !String(p_variable->identifier->name).begins_with("_")) {
  1778. parser->push_warning(p_variable, GDScriptWarning::UNUSED_VARIABLE, p_variable->identifier->name);
  1779. }
  1780. }
  1781. is_shadowing(p_variable->identifier, kind, p_is_local);
  1782. #endif
  1783. }
  1784. void GDScriptAnalyzer::resolve_constant(GDScriptParser::ConstantNode *p_constant, bool p_is_local) {
  1785. static constexpr const char *kind = "constant";
  1786. resolve_assignable(p_constant, kind);
  1787. #ifdef DEBUG_ENABLED
  1788. if (p_is_local) {
  1789. if (p_constant->usages == 0 && !String(p_constant->identifier->name).begins_with("_")) {
  1790. parser->push_warning(p_constant, GDScriptWarning::UNUSED_LOCAL_CONSTANT, p_constant->identifier->name);
  1791. }
  1792. }
  1793. is_shadowing(p_constant->identifier, kind, p_is_local);
  1794. #endif
  1795. }
  1796. void GDScriptAnalyzer::resolve_parameter(GDScriptParser::ParameterNode *p_parameter) {
  1797. static constexpr const char *kind = "parameter";
  1798. resolve_assignable(p_parameter, kind);
  1799. }
  1800. void GDScriptAnalyzer::resolve_if(GDScriptParser::IfNode *p_if) {
  1801. reduce_expression(p_if->condition);
  1802. resolve_suite(p_if->true_block);
  1803. p_if->set_datatype(p_if->true_block->get_datatype());
  1804. if (p_if->false_block != nullptr) {
  1805. resolve_suite(p_if->false_block);
  1806. decide_suite_type(p_if, p_if->false_block);
  1807. }
  1808. }
  1809. void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {
  1810. bool list_resolved = false;
  1811. // Optimize constant range() call to not allocate an array.
  1812. // Use int, Vector2i, Vector3i instead, which also can be used as range iterators.
  1813. if (p_for->list && p_for->list->type == GDScriptParser::Node::CALL) {
  1814. GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(p_for->list);
  1815. GDScriptParser::Node::Type callee_type = call->get_callee_type();
  1816. if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  1817. GDScriptParser::IdentifierNode *callee = static_cast<GDScriptParser::IdentifierNode *>(call->callee);
  1818. if (callee->name == "range") {
  1819. list_resolved = true;
  1820. if (call->arguments.size() < 1) {
  1821. push_error(R"*(Invalid call for "range()" function. Expected at least 1 argument, none given.)*", call->callee);
  1822. } else if (call->arguments.size() > 3) {
  1823. push_error(vformat(R"*(Invalid call for "range()" function. Expected at most 3 arguments, %d given.)*", call->arguments.size()), call->callee);
  1824. } else {
  1825. // Now we can optimize it.
  1826. bool can_reduce = true;
  1827. Vector<Variant> args;
  1828. args.resize(call->arguments.size());
  1829. for (int i = 0; i < call->arguments.size(); i++) {
  1830. GDScriptParser::ExpressionNode *argument = call->arguments[i];
  1831. reduce_expression(argument);
  1832. if (argument->is_constant) {
  1833. if (argument->reduced_value.get_type() != Variant::INT && argument->reduced_value.get_type() != Variant::FLOAT) {
  1834. can_reduce = false;
  1835. push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, Variant::get_type_name(argument->reduced_value.get_type())), argument);
  1836. }
  1837. if (can_reduce) {
  1838. args.write[i] = argument->reduced_value;
  1839. }
  1840. } else {
  1841. can_reduce = false;
  1842. GDScriptParser::DataType argument_type = argument->get_datatype();
  1843. if (argument_type.is_variant() || !argument_type.is_hard_type()) {
  1844. mark_node_unsafe(argument);
  1845. }
  1846. if (!argument_type.is_variant() && (argument_type.builtin_type != Variant::INT && argument_type.builtin_type != Variant::FLOAT)) {
  1847. if (!argument_type.is_hard_type()) {
  1848. downgrade_node_type_source(argument);
  1849. } else {
  1850. push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, argument_type.to_string()), argument);
  1851. }
  1852. }
  1853. }
  1854. }
  1855. Variant reduced;
  1856. if (can_reduce) {
  1857. switch (args.size()) {
  1858. case 1:
  1859. reduced = (int32_t)args[0];
  1860. break;
  1861. case 2:
  1862. reduced = Vector2i(args[0], args[1]);
  1863. break;
  1864. case 3:
  1865. reduced = Vector3i(args[0], args[1], args[2]);
  1866. break;
  1867. }
  1868. p_for->list->is_constant = true;
  1869. p_for->list->reduced_value = reduced;
  1870. }
  1871. }
  1872. if (p_for->list->is_constant) {
  1873. p_for->list->set_datatype(type_from_variant(p_for->list->reduced_value, p_for->list));
  1874. } else {
  1875. GDScriptParser::DataType list_type;
  1876. list_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1877. list_type.kind = GDScriptParser::DataType::BUILTIN;
  1878. list_type.builtin_type = Variant::ARRAY;
  1879. p_for->list->set_datatype(list_type);
  1880. }
  1881. }
  1882. }
  1883. }
  1884. GDScriptParser::DataType variable_type;
  1885. String list_visible_type = "<unresolved type>";
  1886. if (list_resolved) {
  1887. variable_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1888. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1889. variable_type.builtin_type = Variant::INT;
  1890. list_visible_type = "Array[int]"; // NOTE: `range()` has `Array` return type.
  1891. } else if (p_for->list) {
  1892. resolve_node(p_for->list, false);
  1893. GDScriptParser::DataType list_type = p_for->list->get_datatype();
  1894. list_visible_type = list_type.to_string();
  1895. if (!list_type.is_hard_type()) {
  1896. mark_node_unsafe(p_for->list);
  1897. }
  1898. if (list_type.is_variant()) {
  1899. variable_type.kind = GDScriptParser::DataType::VARIANT;
  1900. mark_node_unsafe(p_for->list);
  1901. } else if (list_type.has_container_element_type(0)) {
  1902. variable_type = list_type.get_container_element_type(0);
  1903. variable_type.type_source = list_type.type_source;
  1904. } else if (list_type.is_typed_container_type()) {
  1905. variable_type = list_type.get_typed_container_type();
  1906. variable_type.type_source = list_type.type_source;
  1907. } else if (list_type.builtin_type == Variant::INT || list_type.builtin_type == Variant::FLOAT || list_type.builtin_type == Variant::STRING) {
  1908. variable_type.type_source = list_type.type_source;
  1909. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1910. variable_type.builtin_type = list_type.builtin_type;
  1911. } else if (list_type.builtin_type == Variant::VECTOR2I || list_type.builtin_type == Variant::VECTOR3I) {
  1912. variable_type.type_source = list_type.type_source;
  1913. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1914. variable_type.builtin_type = Variant::INT;
  1915. } else if (list_type.builtin_type == Variant::VECTOR2 || list_type.builtin_type == Variant::VECTOR3) {
  1916. variable_type.type_source = list_type.type_source;
  1917. variable_type.kind = GDScriptParser::DataType::BUILTIN;
  1918. variable_type.builtin_type = Variant::FLOAT;
  1919. } else if (list_type.builtin_type == Variant::OBJECT) {
  1920. GDScriptParser::DataType return_type;
  1921. List<GDScriptParser::DataType> par_types;
  1922. int default_arg_count = 0;
  1923. BitField<MethodFlags> method_flags;
  1924. if (get_function_signature(p_for->list, false, list_type, CoreStringName(_iter_get), return_type, par_types, default_arg_count, method_flags)) {
  1925. variable_type = return_type;
  1926. variable_type.type_source = list_type.type_source;
  1927. } else if (!list_type.is_hard_type()) {
  1928. variable_type.kind = GDScriptParser::DataType::VARIANT;
  1929. } else {
  1930. push_error(vformat(R"(Unable to iterate on object of type "%s".)", list_type.to_string()), p_for->list);
  1931. }
  1932. } else if (list_type.builtin_type == Variant::ARRAY || list_type.builtin_type == Variant::DICTIONARY || !list_type.is_hard_type()) {
  1933. variable_type.kind = GDScriptParser::DataType::VARIANT;
  1934. } else {
  1935. push_error(vformat(R"(Unable to iterate on value of type "%s".)", list_type.to_string()), p_for->list);
  1936. }
  1937. }
  1938. if (p_for->variable) {
  1939. if (p_for->datatype_specifier) {
  1940. GDScriptParser::DataType specified_type = type_from_metatype(resolve_datatype(p_for->datatype_specifier));
  1941. if (!specified_type.is_variant()) {
  1942. if (variable_type.is_variant() || !variable_type.is_hard_type()) {
  1943. mark_node_unsafe(p_for->variable);
  1944. p_for->use_conversion_assign = true;
  1945. } else if (!is_type_compatible(specified_type, variable_type, true, p_for->variable)) {
  1946. if (is_type_compatible(variable_type, specified_type)) {
  1947. mark_node_unsafe(p_for->variable);
  1948. p_for->use_conversion_assign = true;
  1949. } else {
  1950. push_error(vformat(R"(Unable to iterate on value of type "%s" with variable of type "%s".)", list_visible_type, specified_type.to_string()), p_for->datatype_specifier);
  1951. }
  1952. } else if (!is_type_compatible(specified_type, variable_type)) {
  1953. p_for->use_conversion_assign = true;
  1954. }
  1955. if (p_for->list && p_for->list->type == GDScriptParser::Node::ARRAY) {
  1956. update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_for->list), specified_type);
  1957. }
  1958. }
  1959. p_for->variable->set_datatype(specified_type);
  1960. } else {
  1961. p_for->variable->set_datatype(variable_type);
  1962. #ifdef DEBUG_ENABLED
  1963. if (variable_type.is_hard_type()) {
  1964. parser->push_warning(p_for->variable, GDScriptWarning::INFERRED_DECLARATION, R"("for" iterator variable)", p_for->variable->name);
  1965. } else {
  1966. parser->push_warning(p_for->variable, GDScriptWarning::UNTYPED_DECLARATION, R"("for" iterator variable)", p_for->variable->name);
  1967. }
  1968. #endif
  1969. }
  1970. }
  1971. resolve_suite(p_for->loop);
  1972. p_for->set_datatype(p_for->loop->get_datatype());
  1973. #ifdef DEBUG_ENABLED
  1974. if (p_for->variable) {
  1975. is_shadowing(p_for->variable, R"("for" iterator variable)", true);
  1976. }
  1977. #endif
  1978. }
  1979. void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) {
  1980. resolve_node(p_while->condition, false);
  1981. resolve_suite(p_while->loop);
  1982. p_while->set_datatype(p_while->loop->get_datatype());
  1983. }
  1984. void GDScriptAnalyzer::resolve_assert(GDScriptParser::AssertNode *p_assert) {
  1985. reduce_expression(p_assert->condition);
  1986. if (p_assert->message != nullptr) {
  1987. reduce_expression(p_assert->message);
  1988. 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)) {
  1989. push_error(R"(Expected string for assert error message.)", p_assert->message);
  1990. }
  1991. }
  1992. p_assert->set_datatype(p_assert->condition->get_datatype());
  1993. #ifdef DEBUG_ENABLED
  1994. if (p_assert->condition->is_constant) {
  1995. if (p_assert->condition->reduced_value.booleanize()) {
  1996. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_TRUE);
  1997. } else if (!(p_assert->condition->type == GDScriptParser::Node::LITERAL && static_cast<GDScriptParser::LiteralNode *>(p_assert->condition)->value.get_type() == Variant::BOOL)) {
  1998. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_FALSE);
  1999. }
  2000. }
  2001. #endif
  2002. }
  2003. void GDScriptAnalyzer::resolve_match(GDScriptParser::MatchNode *p_match) {
  2004. reduce_expression(p_match->test);
  2005. for (int i = 0; i < p_match->branches.size(); i++) {
  2006. resolve_match_branch(p_match->branches[i], p_match->test);
  2007. decide_suite_type(p_match, p_match->branches[i]);
  2008. }
  2009. }
  2010. void GDScriptAnalyzer::resolve_match_branch(GDScriptParser::MatchBranchNode *p_match_branch, GDScriptParser::ExpressionNode *p_match_test) {
  2011. // Apply annotations.
  2012. for (GDScriptParser::AnnotationNode *&E : p_match_branch->annotations) {
  2013. resolve_annotation(E);
  2014. E->apply(parser, p_match_branch, nullptr); // TODO: Provide `p_class`.
  2015. }
  2016. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  2017. resolve_match_pattern(p_match_branch->patterns[i], p_match_test);
  2018. }
  2019. if (p_match_branch->guard_body) {
  2020. resolve_suite(p_match_branch->guard_body);
  2021. }
  2022. resolve_suite(p_match_branch->block);
  2023. decide_suite_type(p_match_branch, p_match_branch->block);
  2024. }
  2025. void GDScriptAnalyzer::resolve_match_pattern(GDScriptParser::PatternNode *p_match_pattern, GDScriptParser::ExpressionNode *p_match_test) {
  2026. if (p_match_pattern == nullptr) {
  2027. return;
  2028. }
  2029. GDScriptParser::DataType result;
  2030. switch (p_match_pattern->pattern_type) {
  2031. case GDScriptParser::PatternNode::PT_LITERAL:
  2032. if (p_match_pattern->literal) {
  2033. reduce_literal(p_match_pattern->literal);
  2034. result = p_match_pattern->literal->get_datatype();
  2035. }
  2036. break;
  2037. case GDScriptParser::PatternNode::PT_EXPRESSION:
  2038. if (p_match_pattern->expression) {
  2039. GDScriptParser::ExpressionNode *expr = p_match_pattern->expression;
  2040. reduce_expression(expr);
  2041. result = expr->get_datatype();
  2042. if (!expr->is_constant) {
  2043. while (expr && expr->type == GDScriptParser::Node::SUBSCRIPT) {
  2044. GDScriptParser::SubscriptNode *sub = static_cast<GDScriptParser::SubscriptNode *>(expr);
  2045. if (!sub->is_attribute) {
  2046. expr = nullptr;
  2047. } else {
  2048. expr = sub->base;
  2049. }
  2050. }
  2051. if (!expr || expr->type != GDScriptParser::Node::IDENTIFIER) {
  2052. push_error(R"(Expression in match pattern must be a constant expression, an identifier, or an attribute access ("A.B").)", expr);
  2053. }
  2054. }
  2055. }
  2056. break;
  2057. case GDScriptParser::PatternNode::PT_BIND:
  2058. if (p_match_test != nullptr) {
  2059. result = p_match_test->get_datatype();
  2060. } else {
  2061. result.kind = GDScriptParser::DataType::VARIANT;
  2062. }
  2063. p_match_pattern->bind->set_datatype(result);
  2064. #ifdef DEBUG_ENABLED
  2065. is_shadowing(p_match_pattern->bind, "pattern bind", true);
  2066. if (p_match_pattern->bind->usages == 0 && !String(p_match_pattern->bind->name).begins_with("_")) {
  2067. parser->push_warning(p_match_pattern->bind, GDScriptWarning::UNUSED_VARIABLE, p_match_pattern->bind->name);
  2068. }
  2069. #endif
  2070. break;
  2071. case GDScriptParser::PatternNode::PT_ARRAY:
  2072. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  2073. resolve_match_pattern(p_match_pattern->array[i], nullptr);
  2074. decide_suite_type(p_match_pattern, p_match_pattern->array[i]);
  2075. }
  2076. result = p_match_pattern->get_datatype();
  2077. break;
  2078. case GDScriptParser::PatternNode::PT_DICTIONARY:
  2079. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  2080. if (p_match_pattern->dictionary[i].key) {
  2081. reduce_expression(p_match_pattern->dictionary[i].key);
  2082. if (!p_match_pattern->dictionary[i].key->is_constant) {
  2083. push_error(R"(Expression in dictionary pattern key must be a constant.)", p_match_pattern->dictionary[i].key);
  2084. }
  2085. }
  2086. if (p_match_pattern->dictionary[i].value_pattern) {
  2087. resolve_match_pattern(p_match_pattern->dictionary[i].value_pattern, nullptr);
  2088. decide_suite_type(p_match_pattern, p_match_pattern->dictionary[i].value_pattern);
  2089. }
  2090. }
  2091. result = p_match_pattern->get_datatype();
  2092. break;
  2093. case GDScriptParser::PatternNode::PT_WILDCARD:
  2094. case GDScriptParser::PatternNode::PT_REST:
  2095. result.kind = GDScriptParser::DataType::VARIANT;
  2096. break;
  2097. }
  2098. p_match_pattern->set_datatype(result);
  2099. }
  2100. void GDScriptAnalyzer::resolve_return(GDScriptParser::ReturnNode *p_return) {
  2101. GDScriptParser::DataType result;
  2102. GDScriptParser::DataType expected_type;
  2103. bool has_expected_type = parser->current_function != nullptr;
  2104. if (has_expected_type) {
  2105. expected_type = parser->current_function->get_datatype();
  2106. }
  2107. if (p_return->return_value != nullptr) {
  2108. bool is_void_function = has_expected_type && expected_type.is_hard_type() && expected_type.kind == GDScriptParser::DataType::BUILTIN && expected_type.builtin_type == Variant::NIL;
  2109. bool is_call = p_return->return_value->type == GDScriptParser::Node::CALL;
  2110. if (is_void_function && is_call) {
  2111. // Pretend the call is a root expression to allow those that are "void".
  2112. reduce_call(static_cast<GDScriptParser::CallNode *>(p_return->return_value), false, true);
  2113. } else {
  2114. reduce_expression(p_return->return_value);
  2115. }
  2116. if (is_void_function) {
  2117. p_return->void_return = true;
  2118. const GDScriptParser::DataType &return_type = p_return->return_value->datatype;
  2119. if (is_call && !return_type.is_hard_type()) {
  2120. String function_name = parser->current_function->identifier ? parser->current_function->identifier->name.operator String() : String("<anonymous function>");
  2121. String called_function_name = static_cast<GDScriptParser::CallNode *>(p_return->return_value)->function_name.operator String();
  2122. #ifdef DEBUG_ENABLED
  2123. parser->push_warning(p_return, GDScriptWarning::UNSAFE_VOID_RETURN, function_name, called_function_name);
  2124. #endif
  2125. mark_node_unsafe(p_return);
  2126. } else if (!is_call) {
  2127. push_error("A void function cannot return a value.", p_return);
  2128. }
  2129. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2130. result.kind = GDScriptParser::DataType::BUILTIN;
  2131. result.builtin_type = Variant::NIL;
  2132. result.is_constant = true;
  2133. } else {
  2134. if (p_return->return_value->type == GDScriptParser::Node::ARRAY && has_expected_type && expected_type.has_container_element_type(0)) {
  2135. update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_return->return_value), expected_type.get_container_element_type(0));
  2136. }
  2137. if (has_expected_type && expected_type.is_hard_type() && p_return->return_value->is_constant) {
  2138. update_const_expression_builtin_type(p_return->return_value, expected_type, "return");
  2139. }
  2140. result = p_return->return_value->get_datatype();
  2141. }
  2142. } else {
  2143. // Return type is null by default.
  2144. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2145. result.kind = GDScriptParser::DataType::BUILTIN;
  2146. result.builtin_type = Variant::NIL;
  2147. result.is_constant = true;
  2148. }
  2149. if (has_expected_type && !expected_type.is_variant()) {
  2150. if (result.is_variant() || !result.is_hard_type()) {
  2151. mark_node_unsafe(p_return);
  2152. if (!is_type_compatible(expected_type, result, true, p_return)) {
  2153. downgrade_node_type_source(p_return);
  2154. }
  2155. } else if (!is_type_compatible(expected_type, result, true, p_return)) {
  2156. mark_node_unsafe(p_return);
  2157. if (!is_type_compatible(result, expected_type)) {
  2158. 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);
  2159. }
  2160. #ifdef DEBUG_ENABLED
  2161. } else if (expected_type.builtin_type == Variant::INT && result.builtin_type == Variant::FLOAT) {
  2162. parser->push_warning(p_return, GDScriptWarning::NARROWING_CONVERSION);
  2163. #endif
  2164. }
  2165. }
  2166. p_return->set_datatype(result);
  2167. }
  2168. void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expression, bool p_is_root) {
  2169. // This one makes some magic happen.
  2170. if (p_expression == nullptr) {
  2171. return;
  2172. }
  2173. if (p_expression->reduced) {
  2174. // Don't do this more than once.
  2175. return;
  2176. }
  2177. p_expression->reduced = true;
  2178. switch (p_expression->type) {
  2179. case GDScriptParser::Node::ARRAY:
  2180. reduce_array(static_cast<GDScriptParser::ArrayNode *>(p_expression));
  2181. break;
  2182. case GDScriptParser::Node::ASSIGNMENT:
  2183. reduce_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
  2184. break;
  2185. case GDScriptParser::Node::AWAIT:
  2186. reduce_await(static_cast<GDScriptParser::AwaitNode *>(p_expression));
  2187. break;
  2188. case GDScriptParser::Node::BINARY_OPERATOR:
  2189. reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));
  2190. break;
  2191. case GDScriptParser::Node::CALL:
  2192. reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), false, p_is_root);
  2193. break;
  2194. case GDScriptParser::Node::CAST:
  2195. reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));
  2196. break;
  2197. case GDScriptParser::Node::DICTIONARY:
  2198. reduce_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_expression));
  2199. break;
  2200. case GDScriptParser::Node::GET_NODE:
  2201. reduce_get_node(static_cast<GDScriptParser::GetNodeNode *>(p_expression));
  2202. break;
  2203. case GDScriptParser::Node::IDENTIFIER:
  2204. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression));
  2205. break;
  2206. case GDScriptParser::Node::LAMBDA:
  2207. reduce_lambda(static_cast<GDScriptParser::LambdaNode *>(p_expression));
  2208. break;
  2209. case GDScriptParser::Node::LITERAL:
  2210. reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression));
  2211. break;
  2212. case GDScriptParser::Node::PRELOAD:
  2213. reduce_preload(static_cast<GDScriptParser::PreloadNode *>(p_expression));
  2214. break;
  2215. case GDScriptParser::Node::SELF:
  2216. reduce_self(static_cast<GDScriptParser::SelfNode *>(p_expression));
  2217. break;
  2218. case GDScriptParser::Node::SUBSCRIPT:
  2219. reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_expression));
  2220. break;
  2221. case GDScriptParser::Node::TERNARY_OPERATOR:
  2222. reduce_ternary_op(static_cast<GDScriptParser::TernaryOpNode *>(p_expression), p_is_root);
  2223. break;
  2224. case GDScriptParser::Node::TYPE_TEST:
  2225. reduce_type_test(static_cast<GDScriptParser::TypeTestNode *>(p_expression));
  2226. break;
  2227. case GDScriptParser::Node::UNARY_OPERATOR:
  2228. reduce_unary_op(static_cast<GDScriptParser::UnaryOpNode *>(p_expression));
  2229. break;
  2230. // Non-expressions. Here only to make sure new nodes aren't forgotten.
  2231. case GDScriptParser::Node::NONE:
  2232. case GDScriptParser::Node::ANNOTATION:
  2233. case GDScriptParser::Node::ASSERT:
  2234. case GDScriptParser::Node::BREAK:
  2235. case GDScriptParser::Node::BREAKPOINT:
  2236. case GDScriptParser::Node::CLASS:
  2237. case GDScriptParser::Node::CONSTANT:
  2238. case GDScriptParser::Node::CONTINUE:
  2239. case GDScriptParser::Node::ENUM:
  2240. case GDScriptParser::Node::FOR:
  2241. case GDScriptParser::Node::FUNCTION:
  2242. case GDScriptParser::Node::IF:
  2243. case GDScriptParser::Node::MATCH:
  2244. case GDScriptParser::Node::MATCH_BRANCH:
  2245. case GDScriptParser::Node::PARAMETER:
  2246. case GDScriptParser::Node::PASS:
  2247. case GDScriptParser::Node::PATTERN:
  2248. case GDScriptParser::Node::RETURN:
  2249. case GDScriptParser::Node::SIGNAL:
  2250. case GDScriptParser::Node::SUITE:
  2251. case GDScriptParser::Node::TYPE:
  2252. case GDScriptParser::Node::VARIABLE:
  2253. case GDScriptParser::Node::WHILE:
  2254. ERR_FAIL_MSG("Reaching unreachable case");
  2255. }
  2256. if (p_expression->get_datatype().kind == GDScriptParser::DataType::UNRESOLVED) {
  2257. // Prevent `is_type_compatible()` errors for incomplete expressions.
  2258. // The error can still occur if `reduce_*()` is called directly.
  2259. GDScriptParser::DataType dummy;
  2260. dummy.kind = GDScriptParser::DataType::VARIANT;
  2261. p_expression->set_datatype(dummy);
  2262. }
  2263. }
  2264. void GDScriptAnalyzer::reduce_array(GDScriptParser::ArrayNode *p_array) {
  2265. for (int i = 0; i < p_array->elements.size(); i++) {
  2266. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  2267. reduce_expression(element);
  2268. }
  2269. // It's array in any case.
  2270. GDScriptParser::DataType arr_type;
  2271. arr_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2272. arr_type.kind = GDScriptParser::DataType::BUILTIN;
  2273. arr_type.builtin_type = Variant::ARRAY;
  2274. arr_type.is_constant = true;
  2275. p_array->set_datatype(arr_type);
  2276. }
  2277. #ifdef DEBUG_ENABLED
  2278. static bool enum_has_value(const GDScriptParser::DataType p_type, int64_t p_value) {
  2279. for (const KeyValue<StringName, int64_t> &E : p_type.enum_values) {
  2280. if (E.value == p_value) {
  2281. return true;
  2282. }
  2283. }
  2284. return false;
  2285. }
  2286. #endif
  2287. void GDScriptAnalyzer::update_const_expression_builtin_type(GDScriptParser::ExpressionNode *p_expression, const GDScriptParser::DataType &p_type, const char *p_usage, bool p_is_cast) {
  2288. if (p_expression->get_datatype() == p_type) {
  2289. return;
  2290. }
  2291. if (p_type.kind != GDScriptParser::DataType::BUILTIN && p_type.kind != GDScriptParser::DataType::ENUM) {
  2292. return;
  2293. }
  2294. GDScriptParser::DataType expression_type = p_expression->get_datatype();
  2295. bool is_enum_cast = p_is_cast && p_type.kind == GDScriptParser::DataType::ENUM && p_type.is_meta_type == false && expression_type.builtin_type == Variant::INT;
  2296. if (!is_enum_cast && !is_type_compatible(p_type, expression_type, true, p_expression)) {
  2297. push_error(vformat(R"(Cannot %s a value of type "%s" as "%s".)", p_usage, expression_type.to_string(), p_type.to_string()), p_expression);
  2298. return;
  2299. }
  2300. GDScriptParser::DataType value_type = type_from_variant(p_expression->reduced_value, p_expression);
  2301. if (expression_type.is_variant() && !is_enum_cast && !is_type_compatible(p_type, value_type, true, p_expression)) {
  2302. push_error(vformat(R"(Cannot %s a value of type "%s" as "%s".)", p_usage, value_type.to_string(), p_type.to_string()), p_expression);
  2303. return;
  2304. }
  2305. #ifdef DEBUG_ENABLED
  2306. if (p_type.kind == GDScriptParser::DataType::ENUM && value_type.builtin_type == Variant::INT && !enum_has_value(p_type, p_expression->reduced_value)) {
  2307. parser->push_warning(p_expression, GDScriptWarning::INT_AS_ENUM_WITHOUT_MATCH, p_usage, p_expression->reduced_value.stringify(), p_type.to_string());
  2308. }
  2309. #endif
  2310. if (value_type.builtin_type == p_type.builtin_type) {
  2311. p_expression->set_datatype(p_type);
  2312. return;
  2313. }
  2314. Variant converted_to;
  2315. const Variant *converted_from = &p_expression->reduced_value;
  2316. Callable::CallError call_error;
  2317. Variant::construct(p_type.builtin_type, converted_to, &converted_from, 1, call_error);
  2318. if (call_error.error) {
  2319. push_error(vformat(R"(Failed to convert a value of type "%s" to "%s".)", value_type.to_string(), p_type.to_string()), p_expression);
  2320. return;
  2321. }
  2322. #ifdef DEBUG_ENABLED
  2323. if (p_type.builtin_type == Variant::INT && value_type.builtin_type == Variant::FLOAT) {
  2324. parser->push_warning(p_expression, GDScriptWarning::NARROWING_CONVERSION);
  2325. }
  2326. #endif
  2327. p_expression->reduced_value = converted_to;
  2328. p_expression->set_datatype(p_type);
  2329. }
  2330. // When an array literal is stored (or passed as function argument) to a typed context, we then assume the array is typed.
  2331. // This function determines which type is that (if any).
  2332. void GDScriptAnalyzer::update_array_literal_element_type(GDScriptParser::ArrayNode *p_array, const GDScriptParser::DataType &p_element_type) {
  2333. GDScriptParser::DataType expected_type = p_element_type;
  2334. expected_type.container_element_types.clear(); // Nested types (like `Array[Array[int]]`) are not currently supported.
  2335. for (int i = 0; i < p_array->elements.size(); i++) {
  2336. GDScriptParser::ExpressionNode *element_node = p_array->elements[i];
  2337. if (element_node->is_constant) {
  2338. update_const_expression_builtin_type(element_node, expected_type, "include");
  2339. }
  2340. const GDScriptParser::DataType &actual_type = element_node->get_datatype();
  2341. if (actual_type.has_no_type() || actual_type.is_variant() || !actual_type.is_hard_type()) {
  2342. mark_node_unsafe(element_node);
  2343. continue;
  2344. }
  2345. if (!is_type_compatible(expected_type, actual_type, true, p_array)) {
  2346. if (is_type_compatible(actual_type, expected_type)) {
  2347. mark_node_unsafe(element_node);
  2348. continue;
  2349. }
  2350. push_error(vformat(R"(Cannot have an element of type "%s" in an array of type "Array[%s]".)", actual_type.to_string(), expected_type.to_string()), element_node);
  2351. return;
  2352. }
  2353. }
  2354. GDScriptParser::DataType array_type = p_array->get_datatype();
  2355. array_type.set_container_element_type(0, expected_type);
  2356. p_array->set_datatype(array_type);
  2357. }
  2358. void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assignment) {
  2359. reduce_expression(p_assignment->assigned_value);
  2360. #ifdef DEBUG_ENABLED
  2361. // Increment assignment count for local variables.
  2362. // Before we reduce the assignee because we don't want to warn about not being assigned when performing the assignment.
  2363. if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
  2364. GDScriptParser::IdentifierNode *id = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee);
  2365. if (id->source == GDScriptParser::IdentifierNode::LOCAL_VARIABLE && id->variable_source) {
  2366. id->variable_source->assignments++;
  2367. }
  2368. }
  2369. #endif
  2370. reduce_expression(p_assignment->assignee);
  2371. #ifdef DEBUG_ENABLED
  2372. {
  2373. bool is_subscript = false;
  2374. GDScriptParser::ExpressionNode *base = p_assignment->assignee;
  2375. while (base && base->type == GDScriptParser::Node::SUBSCRIPT) {
  2376. is_subscript = true;
  2377. base = static_cast<GDScriptParser::SubscriptNode *>(base)->base;
  2378. }
  2379. if (base && base->type == GDScriptParser::Node::IDENTIFIER) {
  2380. GDScriptParser::IdentifierNode *id = static_cast<GDScriptParser::IdentifierNode *>(base);
  2381. if (current_lambda && current_lambda->captures_indices.has(id->name)) {
  2382. bool need_warn = false;
  2383. if (is_subscript) {
  2384. const GDScriptParser::DataType &id_type = id->datatype;
  2385. if (id_type.is_hard_type()) {
  2386. switch (id_type.kind) {
  2387. case GDScriptParser::DataType::BUILTIN:
  2388. // TODO: Change `Variant::is_type_shared()` to include packed arrays?
  2389. need_warn = !Variant::is_type_shared(id_type.builtin_type) && id_type.builtin_type < Variant::PACKED_BYTE_ARRAY;
  2390. break;
  2391. case GDScriptParser::DataType::ENUM:
  2392. need_warn = true;
  2393. break;
  2394. default:
  2395. break;
  2396. }
  2397. }
  2398. } else {
  2399. need_warn = true;
  2400. }
  2401. if (need_warn) {
  2402. parser->push_warning(p_assignment, GDScriptWarning::CONFUSABLE_CAPTURE_REASSIGNMENT, id->name);
  2403. }
  2404. }
  2405. }
  2406. }
  2407. #endif
  2408. if (p_assignment->assigned_value == nullptr || p_assignment->assignee == nullptr) {
  2409. return;
  2410. }
  2411. GDScriptParser::DataType assignee_type = p_assignment->assignee->get_datatype();
  2412. if (assignee_type.is_constant) {
  2413. push_error("Cannot assign a new value to a constant.", p_assignment->assignee);
  2414. return;
  2415. } else if (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT && static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee)->base->is_constant) {
  2416. const GDScriptParser::DataType &base_type = static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee)->base->datatype;
  2417. if (base_type.kind != GDScriptParser::DataType::SCRIPT && base_type.kind != GDScriptParser::DataType::CLASS) { // Static variables.
  2418. push_error("Cannot assign a new value to a constant.", p_assignment->assignee);
  2419. return;
  2420. }
  2421. } else if (assignee_type.is_read_only) {
  2422. push_error("Cannot assign a new value to a read-only property.", p_assignment->assignee);
  2423. return;
  2424. } else if (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {
  2425. GDScriptParser::SubscriptNode *sub = static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee);
  2426. while (sub) {
  2427. const GDScriptParser::DataType &base_type = sub->base->datatype;
  2428. if (base_type.is_hard_type() && base_type.is_read_only) {
  2429. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !Variant::is_type_shared(base_type.builtin_type)) {
  2430. push_error("Cannot assign a new value to a read-only property.", p_assignment->assignee);
  2431. return;
  2432. }
  2433. } else {
  2434. break;
  2435. }
  2436. if (sub->base->type == GDScriptParser::Node::SUBSCRIPT) {
  2437. sub = static_cast<GDScriptParser::SubscriptNode *>(sub->base);
  2438. } else {
  2439. sub = nullptr;
  2440. }
  2441. }
  2442. }
  2443. // Check if assigned value is an array literal, so we can make it a typed array too if appropriate.
  2444. if (p_assignment->assigned_value->type == GDScriptParser::Node::ARRAY && assignee_type.is_hard_type() && assignee_type.has_container_element_type(0)) {
  2445. update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_assignment->assigned_value), assignee_type.get_container_element_type(0));
  2446. }
  2447. if (p_assignment->operation == GDScriptParser::AssignmentNode::OP_NONE && assignee_type.is_hard_type() && p_assignment->assigned_value->is_constant) {
  2448. update_const_expression_builtin_type(p_assignment->assigned_value, assignee_type, "assign");
  2449. }
  2450. GDScriptParser::DataType assigned_value_type = p_assignment->assigned_value->get_datatype();
  2451. bool assignee_is_variant = assignee_type.is_variant();
  2452. bool assignee_is_hard = assignee_type.is_hard_type();
  2453. bool assigned_is_variant = assigned_value_type.is_variant();
  2454. bool assigned_is_hard = assigned_value_type.is_hard_type();
  2455. bool compatible = true;
  2456. bool downgrades_assignee = false;
  2457. bool downgrades_assigned = false;
  2458. GDScriptParser::DataType op_type = assigned_value_type;
  2459. if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE && !op_type.is_variant()) {
  2460. op_type = get_operation_type(p_assignment->variant_op, assignee_type, assigned_value_type, compatible, p_assignment->assigned_value);
  2461. if (assignee_is_variant) {
  2462. // variant assignee
  2463. mark_node_unsafe(p_assignment);
  2464. } else if (!compatible) {
  2465. // incompatible hard types and non-variant assignee
  2466. mark_node_unsafe(p_assignment);
  2467. if (assigned_is_variant) {
  2468. // incompatible hard non-variant assignee and hard variant assigned
  2469. p_assignment->use_conversion_assign = true;
  2470. } else {
  2471. // incompatible hard non-variant types
  2472. push_error(vformat(R"(Invalid operands "%s" and "%s" for assignment operator.)", assignee_type.to_string(), assigned_value_type.to_string()), p_assignment);
  2473. }
  2474. } else if (op_type.type_source == GDScriptParser::DataType::UNDETECTED && !assigned_is_variant) {
  2475. // incompatible non-variant types (at least one weak)
  2476. downgrades_assignee = !assignee_is_hard;
  2477. downgrades_assigned = !assigned_is_hard;
  2478. }
  2479. }
  2480. p_assignment->set_datatype(op_type);
  2481. if (assignee_is_variant) {
  2482. if (!assignee_is_hard) {
  2483. // weak variant assignee
  2484. mark_node_unsafe(p_assignment);
  2485. }
  2486. } else {
  2487. if (assignee_is_hard && !assigned_is_hard) {
  2488. // hard non-variant assignee and weak assigned
  2489. mark_node_unsafe(p_assignment);
  2490. p_assignment->use_conversion_assign = true;
  2491. downgrades_assigned = downgrades_assigned || (!assigned_is_variant && !is_type_compatible(assignee_type, op_type, true, p_assignment->assigned_value));
  2492. } else if (compatible) {
  2493. if (op_type.is_variant()) {
  2494. // non-variant assignee and variant result
  2495. mark_node_unsafe(p_assignment);
  2496. if (assignee_is_hard) {
  2497. // hard non-variant assignee and variant result
  2498. p_assignment->use_conversion_assign = true;
  2499. } else {
  2500. // weak non-variant assignee and variant result
  2501. downgrades_assignee = true;
  2502. }
  2503. } else if (!is_type_compatible(assignee_type, op_type, assignee_is_hard, p_assignment->assigned_value)) {
  2504. // non-variant assignee and incompatible result
  2505. mark_node_unsafe(p_assignment);
  2506. if (assignee_is_hard) {
  2507. if (is_type_compatible(op_type, assignee_type)) {
  2508. // hard non-variant assignee and maybe compatible result
  2509. p_assignment->use_conversion_assign = true;
  2510. } else {
  2511. // hard non-variant assignee and incompatible result
  2512. push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", assigned_value_type.to_string(), assignee_type.to_string()), p_assignment->assigned_value);
  2513. }
  2514. } else {
  2515. // weak non-variant assignee and incompatible result
  2516. downgrades_assignee = true;
  2517. }
  2518. } else if (assignee_type.has_container_element_type(0) && !op_type.has_container_element_type(0)) {
  2519. // typed array assignee and untyped array result
  2520. mark_node_unsafe(p_assignment);
  2521. }
  2522. }
  2523. }
  2524. if (downgrades_assignee) {
  2525. downgrade_node_type_source(p_assignment->assignee);
  2526. }
  2527. if (downgrades_assigned) {
  2528. downgrade_node_type_source(p_assignment->assigned_value);
  2529. }
  2530. #ifdef DEBUG_ENABLED
  2531. if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_value_type.builtin_type == Variant::FLOAT) {
  2532. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION);
  2533. }
  2534. // Check for assignment with operation before assignment.
  2535. if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE && p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
  2536. GDScriptParser::IdentifierNode *id = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee);
  2537. // Use == 1 here because this assignment was already counted in the beginning of the function.
  2538. if (id->source == GDScriptParser::IdentifierNode::LOCAL_VARIABLE && id->variable_source && id->variable_source->assignments == 1) {
  2539. parser->push_warning(p_assignment, GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, id->name);
  2540. }
  2541. }
  2542. #endif
  2543. }
  2544. void GDScriptAnalyzer::reduce_await(GDScriptParser::AwaitNode *p_await) {
  2545. if (p_await->to_await == nullptr) {
  2546. GDScriptParser::DataType await_type;
  2547. await_type.kind = GDScriptParser::DataType::VARIANT;
  2548. p_await->set_datatype(await_type);
  2549. return;
  2550. }
  2551. if (p_await->to_await->type == GDScriptParser::Node::CALL) {
  2552. reduce_call(static_cast<GDScriptParser::CallNode *>(p_await->to_await), true);
  2553. } else {
  2554. reduce_expression(p_await->to_await);
  2555. }
  2556. GDScriptParser::DataType await_type = p_await->to_await->get_datatype();
  2557. // We cannot infer the type of the result of waiting for a signal.
  2558. if (await_type.is_hard_type() && await_type.kind == GDScriptParser::DataType::BUILTIN && await_type.builtin_type == Variant::SIGNAL) {
  2559. await_type.kind = GDScriptParser::DataType::VARIANT;
  2560. await_type.type_source = GDScriptParser::DataType::UNDETECTED;
  2561. } else if (p_await->to_await->is_constant) {
  2562. p_await->is_constant = p_await->to_await->is_constant;
  2563. p_await->reduced_value = p_await->to_await->reduced_value;
  2564. }
  2565. await_type.is_coroutine = false;
  2566. p_await->set_datatype(await_type);
  2567. #ifdef DEBUG_ENABLED
  2568. GDScriptParser::DataType to_await_type = p_await->to_await->get_datatype();
  2569. if (!to_await_type.is_coroutine && !to_await_type.is_variant() && to_await_type.builtin_type != Variant::SIGNAL) {
  2570. parser->push_warning(p_await, GDScriptWarning::REDUNDANT_AWAIT);
  2571. }
  2572. #endif
  2573. }
  2574. void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op) {
  2575. reduce_expression(p_binary_op->left_operand);
  2576. reduce_expression(p_binary_op->right_operand);
  2577. GDScriptParser::DataType left_type;
  2578. if (p_binary_op->left_operand) {
  2579. left_type = p_binary_op->left_operand->get_datatype();
  2580. }
  2581. GDScriptParser::DataType right_type;
  2582. if (p_binary_op->right_operand) {
  2583. right_type = p_binary_op->right_operand->get_datatype();
  2584. }
  2585. if (!left_type.is_set() || !right_type.is_set()) {
  2586. return;
  2587. }
  2588. #ifdef DEBUG_ENABLED
  2589. if (p_binary_op->variant_op == Variant::OP_DIVIDE && left_type.builtin_type == Variant::INT && right_type.builtin_type == Variant::INT) {
  2590. parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);
  2591. }
  2592. #endif
  2593. if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {
  2594. p_binary_op->is_constant = true;
  2595. if (p_binary_op->variant_op < Variant::OP_MAX) {
  2596. bool valid = false;
  2597. 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);
  2598. if (!valid) {
  2599. if (p_binary_op->reduced_value.get_type() == Variant::STRING) {
  2600. 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);
  2601. } else {
  2602. push_error(vformat(R"(Invalid operands to operator %s, %s and %s.)",
  2603. Variant::get_operator_name(p_binary_op->variant_op),
  2604. Variant::get_type_name(p_binary_op->left_operand->reduced_value.get_type()),
  2605. Variant::get_type_name(p_binary_op->right_operand->reduced_value.get_type())),
  2606. p_binary_op);
  2607. }
  2608. }
  2609. } else {
  2610. ERR_PRINT("Parser bug: unknown binary operation.");
  2611. }
  2612. p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value, p_binary_op));
  2613. return;
  2614. }
  2615. GDScriptParser::DataType result;
  2616. if ((p_binary_op->variant_op == Variant::OP_EQUAL || p_binary_op->variant_op == Variant::OP_NOT_EQUAL) &&
  2617. ((left_type.kind == GDScriptParser::DataType::BUILTIN && left_type.builtin_type == Variant::NIL) || (right_type.kind == GDScriptParser::DataType::BUILTIN && right_type.builtin_type == Variant::NIL))) {
  2618. // "==" and "!=" operators always return a boolean when comparing to null.
  2619. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2620. result.kind = GDScriptParser::DataType::BUILTIN;
  2621. result.builtin_type = Variant::BOOL;
  2622. } else if (p_binary_op->variant_op == Variant::OP_MODULE && left_type.builtin_type == Variant::STRING) {
  2623. // The modulo operator (%) on string acts as formatting and will always return a string.
  2624. result.type_source = left_type.type_source;
  2625. result.kind = GDScriptParser::DataType::BUILTIN;
  2626. result.builtin_type = Variant::STRING;
  2627. } else if (left_type.is_variant() || right_type.is_variant()) {
  2628. // Cannot infer type because one operand can be anything.
  2629. result.kind = GDScriptParser::DataType::VARIANT;
  2630. mark_node_unsafe(p_binary_op);
  2631. } else if (p_binary_op->variant_op < Variant::OP_MAX) {
  2632. bool valid = false;
  2633. result = get_operation_type(p_binary_op->variant_op, left_type, right_type, valid, p_binary_op);
  2634. if (!valid) {
  2635. 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);
  2636. } else if (!result.is_hard_type()) {
  2637. mark_node_unsafe(p_binary_op);
  2638. }
  2639. } else {
  2640. ERR_PRINT("Parser bug: unknown binary operation.");
  2641. }
  2642. p_binary_op->set_datatype(result);
  2643. }
  2644. #ifdef SUGGEST_GODOT4_RENAMES
  2645. const char *get_rename_from_map(const char *map[][2], String key) {
  2646. for (int index = 0; map[index][0]; index++) {
  2647. if (map[index][0] == key) {
  2648. return map[index][1];
  2649. }
  2650. }
  2651. return nullptr;
  2652. }
  2653. // Checks if an identifier/function name has been renamed in Godot 4, uses ProjectConverter3To4 for rename map.
  2654. // Returns the new name if found, nullptr otherwise.
  2655. const char *check_for_renamed_identifier(String identifier, GDScriptParser::Node::Type type) {
  2656. switch (type) {
  2657. case GDScriptParser::Node::IDENTIFIER: {
  2658. // Check properties
  2659. const char *result = get_rename_from_map(RenamesMap3To4::gdscript_properties_renames, identifier);
  2660. if (result) {
  2661. return result;
  2662. }
  2663. // Check enum values
  2664. result = get_rename_from_map(RenamesMap3To4::enum_renames, identifier);
  2665. if (result) {
  2666. return result;
  2667. }
  2668. // Check color constants
  2669. result = get_rename_from_map(RenamesMap3To4::color_renames, identifier);
  2670. if (result) {
  2671. return result;
  2672. }
  2673. // Check type names
  2674. result = get_rename_from_map(RenamesMap3To4::class_renames, identifier);
  2675. if (result) {
  2676. return result;
  2677. }
  2678. return get_rename_from_map(RenamesMap3To4::builtin_types_renames, identifier);
  2679. }
  2680. case GDScriptParser::Node::CALL: {
  2681. const char *result = get_rename_from_map(RenamesMap3To4::gdscript_function_renames, identifier);
  2682. if (result) {
  2683. return result;
  2684. }
  2685. // Built-in Types are mistaken for function calls when the built-in type is not found.
  2686. // Check built-in types if function rename not found
  2687. return get_rename_from_map(RenamesMap3To4::builtin_types_renames, identifier);
  2688. }
  2689. // Signal references don't get parsed through the GDScriptAnalyzer. No support for signal rename hints.
  2690. default:
  2691. // No rename found, return null
  2692. return nullptr;
  2693. }
  2694. }
  2695. #endif // SUGGEST_GODOT4_RENAMES
  2696. void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_await, bool p_is_root) {
  2697. bool all_is_constant = true;
  2698. HashMap<int, GDScriptParser::ArrayNode *> arrays; // For array literal to potentially type when passing.
  2699. for (int i = 0; i < p_call->arguments.size(); i++) {
  2700. reduce_expression(p_call->arguments[i]);
  2701. if (p_call->arguments[i]->type == GDScriptParser::Node::ARRAY) {
  2702. arrays[i] = static_cast<GDScriptParser::ArrayNode *>(p_call->arguments[i]);
  2703. }
  2704. all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;
  2705. }
  2706. GDScriptParser::Node::Type callee_type = p_call->get_callee_type();
  2707. GDScriptParser::DataType call_type;
  2708. if (!p_call->is_super && callee_type == GDScriptParser::Node::IDENTIFIER) {
  2709. // Call to name directly.
  2710. StringName function_name = p_call->function_name;
  2711. if (function_name == SNAME("Object")) {
  2712. push_error(R"*(Invalid constructor "Object()", use "Object.new()" instead.)*", p_call);
  2713. p_call->set_datatype(call_type);
  2714. return;
  2715. }
  2716. Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);
  2717. if (builtin_type < Variant::VARIANT_MAX) {
  2718. // Is a builtin constructor.
  2719. call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2720. call_type.kind = GDScriptParser::DataType::BUILTIN;
  2721. call_type.builtin_type = builtin_type;
  2722. bool safe_to_fold = true;
  2723. switch (builtin_type) {
  2724. // Those are stored by reference so not suited for compile-time construction.
  2725. // Because in this case they would be the same reference in all constructed values.
  2726. case Variant::OBJECT:
  2727. case Variant::DICTIONARY:
  2728. case Variant::ARRAY:
  2729. case Variant::PACKED_BYTE_ARRAY:
  2730. case Variant::PACKED_INT32_ARRAY:
  2731. case Variant::PACKED_INT64_ARRAY:
  2732. case Variant::PACKED_FLOAT32_ARRAY:
  2733. case Variant::PACKED_FLOAT64_ARRAY:
  2734. case Variant::PACKED_STRING_ARRAY:
  2735. case Variant::PACKED_VECTOR2_ARRAY:
  2736. case Variant::PACKED_VECTOR3_ARRAY:
  2737. case Variant::PACKED_COLOR_ARRAY:
  2738. case Variant::PACKED_VECTOR4_ARRAY:
  2739. safe_to_fold = false;
  2740. break;
  2741. default:
  2742. break;
  2743. }
  2744. if (all_is_constant && safe_to_fold) {
  2745. // Construct here.
  2746. Vector<const Variant *> args;
  2747. for (int i = 0; i < p_call->arguments.size(); i++) {
  2748. args.push_back(&(p_call->arguments[i]->reduced_value));
  2749. }
  2750. Callable::CallError err;
  2751. Variant value;
  2752. Variant::construct(builtin_type, value, (const Variant **)args.ptr(), args.size(), err);
  2753. switch (err.error) {
  2754. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  2755. 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,
  2756. Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),
  2757. p_call->arguments[err.argument]);
  2758. break;
  2759. case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
  2760. String signature = Variant::get_type_name(builtin_type) + "(";
  2761. for (int i = 0; i < p_call->arguments.size(); i++) {
  2762. if (i > 0) {
  2763. signature += ", ";
  2764. }
  2765. signature += p_call->arguments[i]->get_datatype().to_string();
  2766. }
  2767. signature += ")";
  2768. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);
  2769. } break;
  2770. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2771. 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);
  2772. break;
  2773. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2774. 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);
  2775. break;
  2776. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2777. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2778. break; // Can't happen in a builtin constructor.
  2779. case Callable::CallError::CALL_OK:
  2780. p_call->is_constant = true;
  2781. p_call->reduced_value = value;
  2782. break;
  2783. }
  2784. } else {
  2785. // If there's one argument, try to use copy constructor (those aren't explicitly defined).
  2786. if (p_call->arguments.size() == 1) {
  2787. GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();
  2788. if (arg_type.is_hard_type() && !arg_type.is_variant()) {
  2789. if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {
  2790. // Okay.
  2791. p_call->set_datatype(call_type);
  2792. return;
  2793. }
  2794. } else {
  2795. #ifdef DEBUG_ENABLED
  2796. mark_node_unsafe(p_call);
  2797. // Constructors support overloads.
  2798. Vector<String> types;
  2799. for (int i = 0; i < Variant::VARIANT_MAX; i++) {
  2800. if (i != builtin_type && Variant::can_convert_strict((Variant::Type)i, builtin_type)) {
  2801. types.push_back(Variant::get_type_name((Variant::Type)i));
  2802. }
  2803. }
  2804. String expected_types = function_name;
  2805. if (types.size() == 1) {
  2806. expected_types += "\" or \"" + types[0];
  2807. } else if (types.size() >= 2) {
  2808. for (int i = 0; i < types.size() - 1; i++) {
  2809. expected_types += "\", \"" + types[i];
  2810. }
  2811. expected_types += "\", or \"" + types[types.size() - 1];
  2812. }
  2813. parser->push_warning(p_call->arguments[0], GDScriptWarning::UNSAFE_CALL_ARGUMENT, "1", "constructor", function_name, expected_types, "Variant");
  2814. #endif
  2815. p_call->set_datatype(call_type);
  2816. return;
  2817. }
  2818. }
  2819. List<MethodInfo> constructors;
  2820. Variant::get_constructor_list(builtin_type, &constructors);
  2821. bool match = false;
  2822. for (const MethodInfo &info : constructors) {
  2823. if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  2824. continue;
  2825. }
  2826. if (p_call->arguments.size() > info.arguments.size()) {
  2827. continue;
  2828. }
  2829. bool types_match = true;
  2830. {
  2831. List<PropertyInfo>::ConstIterator arg_itr = info.arguments.begin();
  2832. for (int i = 0; i < p_call->arguments.size(); ++arg_itr, ++i) {
  2833. GDScriptParser::DataType par_type = type_from_property(*arg_itr, true);
  2834. GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
  2835. if (!is_type_compatible(par_type, arg_type, true)) {
  2836. types_match = false;
  2837. break;
  2838. #ifdef DEBUG_ENABLED
  2839. } else {
  2840. if (par_type.builtin_type == Variant::INT && arg_type.builtin_type == Variant::FLOAT && builtin_type != Variant::INT) {
  2841. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, function_name);
  2842. }
  2843. #endif
  2844. }
  2845. }
  2846. }
  2847. if (types_match) {
  2848. List<PropertyInfo>::ConstIterator arg_itr = info.arguments.begin();
  2849. for (int i = 0; i < p_call->arguments.size(); ++arg_itr, ++i) {
  2850. GDScriptParser::DataType par_type = type_from_property(*arg_itr, true);
  2851. if (p_call->arguments[i]->is_constant) {
  2852. update_const_expression_builtin_type(p_call->arguments[i], par_type, "pass");
  2853. }
  2854. #ifdef DEBUG_ENABLED
  2855. if (!(par_type.is_variant() && par_type.is_hard_type())) {
  2856. GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
  2857. if (arg_type.is_variant() || !arg_type.is_hard_type()) {
  2858. mark_node_unsafe(p_call);
  2859. parser->push_warning(p_call->arguments[i], GDScriptWarning::UNSAFE_CALL_ARGUMENT, itos(i + 1), "constructor", function_name, par_type.to_string(), arg_type.to_string_strict());
  2860. }
  2861. }
  2862. #endif
  2863. }
  2864. match = true;
  2865. call_type = type_from_property(info.return_val);
  2866. break;
  2867. }
  2868. }
  2869. if (!match) {
  2870. String signature = Variant::get_type_name(builtin_type) + "(";
  2871. for (int i = 0; i < p_call->arguments.size(); i++) {
  2872. if (i > 0) {
  2873. signature += ", ";
  2874. }
  2875. signature += p_call->arguments[i]->get_datatype().to_string();
  2876. }
  2877. signature += ")";
  2878. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);
  2879. }
  2880. }
  2881. #ifdef DEBUG_ENABLED
  2882. // Consider `Signal(self, "my_signal")` as an implicit use of the signal.
  2883. if (builtin_type == Variant::SIGNAL && p_call->arguments.size() >= 2) {
  2884. const GDScriptParser::ExpressionNode *object_arg = p_call->arguments[0];
  2885. if (object_arg && object_arg->type == GDScriptParser::Node::SELF) {
  2886. const GDScriptParser::ExpressionNode *signal_arg = p_call->arguments[1];
  2887. if (signal_arg && signal_arg->is_constant) {
  2888. const StringName &signal_name = signal_arg->reduced_value;
  2889. if (parser->current_class->has_member(signal_name)) {
  2890. const GDScriptParser::ClassNode::Member &member = parser->current_class->get_member(signal_name);
  2891. if (member.type == GDScriptParser::ClassNode::Member::SIGNAL) {
  2892. member.signal->usages++;
  2893. }
  2894. }
  2895. }
  2896. }
  2897. }
  2898. #endif
  2899. p_call->set_datatype(call_type);
  2900. return;
  2901. } else if (GDScriptUtilityFunctions::function_exists(function_name)) {
  2902. MethodInfo function_info = GDScriptUtilityFunctions::get_function_info(function_name);
  2903. if (!p_is_root && !p_is_await && function_info.return_val.type == Variant::NIL && ((function_info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) == 0)) {
  2904. push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", function_name), p_call);
  2905. }
  2906. if (all_is_constant && GDScriptUtilityFunctions::is_function_constant(function_name)) {
  2907. // Can call on compilation.
  2908. Vector<const Variant *> args;
  2909. for (int i = 0; i < p_call->arguments.size(); i++) {
  2910. args.push_back(&(p_call->arguments[i]->reduced_value));
  2911. }
  2912. Variant value;
  2913. Callable::CallError err;
  2914. GDScriptUtilityFunctions::get_function(function_name)(&value, (const Variant **)args.ptr(), args.size(), err);
  2915. switch (err.error) {
  2916. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  2917. if (value.get_type() == Variant::STRING && !value.operator String().is_empty()) {
  2918. push_error(vformat(R"*(Invalid argument for "%s()" function: %s)*", function_name, value), p_call->arguments[err.argument]);
  2919. } else {
  2920. // Do not use `type_from_property()` for expected type, since utility functions use their own checks.
  2921. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1,
  2922. Variant::get_type_name((Variant::Type)err.expected), p_call->arguments[err.argument]->get_datatype().to_string()),
  2923. p_call->arguments[err.argument]);
  2924. }
  2925. break;
  2926. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  2927. push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
  2928. break;
  2929. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2930. 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);
  2931. break;
  2932. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2933. 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);
  2934. break;
  2935. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2936. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2937. break; // Can't happen in a builtin constructor.
  2938. case Callable::CallError::CALL_OK:
  2939. p_call->is_constant = true;
  2940. p_call->reduced_value = value;
  2941. break;
  2942. }
  2943. } else {
  2944. validate_call_arg(function_info, p_call);
  2945. }
  2946. p_call->set_datatype(type_from_property(function_info.return_val));
  2947. return;
  2948. } else if (Variant::has_utility_function(function_name)) {
  2949. MethodInfo function_info = info_from_utility_func(function_name);
  2950. if (!p_is_root && !p_is_await && function_info.return_val.type == Variant::NIL && ((function_info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) == 0)) {
  2951. push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", function_name), p_call);
  2952. }
  2953. if (all_is_constant && Variant::get_utility_function_type(function_name) == Variant::UTILITY_FUNC_TYPE_MATH) {
  2954. // Can call on compilation.
  2955. Vector<const Variant *> args;
  2956. for (int i = 0; i < p_call->arguments.size(); i++) {
  2957. args.push_back(&(p_call->arguments[i]->reduced_value));
  2958. }
  2959. Variant value;
  2960. Callable::CallError err;
  2961. Variant::call_utility_function(function_name, &value, (const Variant **)args.ptr(), args.size(), err);
  2962. switch (err.error) {
  2963. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  2964. if (value.get_type() == Variant::STRING && !value.operator String().is_empty()) {
  2965. push_error(vformat(R"*(Invalid argument for "%s()" function: %s)*", function_name, value), p_call->arguments[err.argument]);
  2966. } else {
  2967. // Do not use `type_from_property()` for expected type, since utility functions use their own checks.
  2968. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*", function_name, err.argument + 1,
  2969. Variant::get_type_name((Variant::Type)err.expected), p_call->arguments[err.argument]->get_datatype().to_string()),
  2970. p_call->arguments[err.argument]);
  2971. }
  2972. break;
  2973. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  2974. push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
  2975. break;
  2976. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  2977. 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);
  2978. break;
  2979. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  2980. 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);
  2981. break;
  2982. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  2983. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  2984. break; // Can't happen in a builtin constructor.
  2985. case Callable::CallError::CALL_OK:
  2986. p_call->is_constant = true;
  2987. p_call->reduced_value = value;
  2988. break;
  2989. }
  2990. } else {
  2991. validate_call_arg(function_info, p_call);
  2992. }
  2993. p_call->set_datatype(type_from_property(function_info.return_val));
  2994. return;
  2995. }
  2996. }
  2997. GDScriptParser::DataType base_type;
  2998. call_type.kind = GDScriptParser::DataType::VARIANT;
  2999. bool is_self = false;
  3000. if (p_call->is_super) {
  3001. base_type = parser->current_class->base_type;
  3002. base_type.is_meta_type = false;
  3003. is_self = true;
  3004. if (p_call->callee == nullptr && current_lambda != nullptr) {
  3005. push_error("Cannot use `super()` inside a lambda.", p_call);
  3006. }
  3007. } else if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  3008. base_type = parser->current_class->get_datatype();
  3009. base_type.is_meta_type = false;
  3010. is_self = true;
  3011. } else if (callee_type == GDScriptParser::Node::SUBSCRIPT) {
  3012. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);
  3013. if (subscript->base == nullptr) {
  3014. // Invalid syntax, error already set on parser.
  3015. p_call->set_datatype(call_type);
  3016. mark_node_unsafe(p_call);
  3017. return;
  3018. }
  3019. if (!subscript->is_attribute) {
  3020. // Invalid call. Error already sent in parser.
  3021. // TODO: Could check if Callable here.
  3022. p_call->set_datatype(call_type);
  3023. mark_node_unsafe(p_call);
  3024. return;
  3025. }
  3026. if (subscript->attribute == nullptr) {
  3027. // Invalid call. Error already sent in parser.
  3028. p_call->set_datatype(call_type);
  3029. mark_node_unsafe(p_call);
  3030. return;
  3031. }
  3032. GDScriptParser::IdentifierNode *base_id = nullptr;
  3033. if (subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  3034. base_id = static_cast<GDScriptParser::IdentifierNode *>(subscript->base);
  3035. }
  3036. if (base_id && GDScriptParser::get_builtin_type(base_id->name) < Variant::VARIANT_MAX) {
  3037. base_type = make_builtin_meta_type(GDScriptParser::get_builtin_type(base_id->name));
  3038. } else {
  3039. reduce_expression(subscript->base);
  3040. base_type = subscript->base->get_datatype();
  3041. is_self = subscript->base->type == GDScriptParser::Node::SELF;
  3042. }
  3043. } else {
  3044. // Invalid call. Error already sent in parser.
  3045. // TODO: Could check if Callable here too.
  3046. p_call->set_datatype(call_type);
  3047. mark_node_unsafe(p_call);
  3048. return;
  3049. }
  3050. int default_arg_count = 0;
  3051. BitField<MethodFlags> method_flags;
  3052. GDScriptParser::DataType return_type;
  3053. List<GDScriptParser::DataType> par_types;
  3054. bool is_constructor = (base_type.is_meta_type || (p_call->callee && p_call->callee->type == GDScriptParser::Node::IDENTIFIER)) && p_call->function_name == SNAME("new");
  3055. if (is_constructor && Engine::get_singleton()->has_singleton(base_type.native_type)) {
  3056. push_error(vformat(R"(Cannot construct native class "%s" because it is an engine singleton.)", base_type.native_type), p_call);
  3057. p_call->set_datatype(call_type);
  3058. return;
  3059. }
  3060. if (get_function_signature(p_call, is_constructor, base_type, p_call->function_name, return_type, par_types, default_arg_count, method_flags)) {
  3061. // If the method is implemented in the class hierarchy, the virtual flag will not be set for that MethodInfo and the search stops there.
  3062. // Virtual check only possible for super() calls because class hierarchy is known. Node/Objects may have scripts attached we don't know of at compile-time.
  3063. p_call->is_static = method_flags.has_flag(METHOD_FLAG_STATIC);
  3064. if (p_call->is_super && method_flags.has_flag(METHOD_FLAG_VIRTUAL)) {
  3065. push_error(vformat(R"*(Cannot call the parent class' virtual function "%s()" because it hasn't been defined.)*", p_call->function_name), p_call);
  3066. }
  3067. // If the function requires typed arrays we must make literals be typed.
  3068. for (const KeyValue<int, GDScriptParser::ArrayNode *> &E : arrays) {
  3069. int index = E.key;
  3070. if (index < par_types.size() && par_types.get(index).is_hard_type() && par_types.get(index).has_container_element_type(0)) {
  3071. update_array_literal_element_type(E.value, par_types.get(index).get_container_element_type(0));
  3072. }
  3073. }
  3074. validate_call_arg(par_types, default_arg_count, method_flags.has_flag(METHOD_FLAG_VARARG), p_call);
  3075. if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {
  3076. // Enum type is treated as a dictionary value for function calls.
  3077. base_type.is_meta_type = false;
  3078. }
  3079. if (is_self && static_context && !p_call->is_static) {
  3080. // Get the parent function above any lambda.
  3081. GDScriptParser::FunctionNode *parent_function = parser->current_function;
  3082. while (parent_function && parent_function->source_lambda) {
  3083. parent_function = parent_function->source_lambda->parent_function;
  3084. }
  3085. if (parent_function) {
  3086. push_error(vformat(R"*(Cannot call non-static function "%s()" from the static function "%s()".)*", p_call->function_name, parent_function->identifier->name), p_call);
  3087. } else {
  3088. push_error(vformat(R"*(Cannot call non-static function "%s()" from a static variable initializer.)*", p_call->function_name), p_call);
  3089. }
  3090. } else if (!is_self && base_type.is_meta_type && !p_call->is_static) {
  3091. base_type.is_meta_type = false; // For `to_string()`.
  3092. 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);
  3093. } else if (is_self && !p_call->is_static) {
  3094. mark_lambda_use_self();
  3095. }
  3096. if (!p_is_root && !p_is_await && return_type.is_hard_type() && return_type.kind == GDScriptParser::DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {
  3097. push_error(vformat(R"*(Cannot get return value of call to "%s()" because it returns "void".)*", p_call->function_name), p_call);
  3098. }
  3099. #ifdef DEBUG_ENABLED
  3100. // FIXME: No warning for built-in constructors and utilities due to early return.
  3101. if (p_is_root && return_type.kind != GDScriptParser::DataType::UNRESOLVED && return_type.builtin_type != Variant::NIL &&
  3102. !(p_call->is_super && p_call->function_name == GDScriptLanguage::get_singleton()->strings._init)) {
  3103. parser->push_warning(p_call, GDScriptWarning::RETURN_VALUE_DISCARDED, p_call->function_name);
  3104. }
  3105. if (method_flags.has_flag(METHOD_FLAG_STATIC) && !is_constructor && !base_type.is_meta_type && !is_self) {
  3106. String caller_type = base_type.to_string();
  3107. parser->push_warning(p_call, GDScriptWarning::STATIC_CALLED_ON_INSTANCE, p_call->function_name, caller_type);
  3108. }
  3109. // Consider `emit_signal()`, `connect()`, and `disconnect()` as implicit uses of the signal.
  3110. if (is_self && (p_call->function_name == SNAME("emit_signal") || p_call->function_name == SNAME("connect") || p_call->function_name == SNAME("disconnect")) && !p_call->arguments.is_empty()) {
  3111. const GDScriptParser::ExpressionNode *signal_arg = p_call->arguments[0];
  3112. if (signal_arg && signal_arg->is_constant) {
  3113. const StringName &signal_name = signal_arg->reduced_value;
  3114. if (parser->current_class->has_member(signal_name)) {
  3115. const GDScriptParser::ClassNode::Member &member = parser->current_class->get_member(signal_name);
  3116. if (member.type == GDScriptParser::ClassNode::Member::SIGNAL) {
  3117. member.signal->usages++;
  3118. }
  3119. }
  3120. }
  3121. }
  3122. #endif // DEBUG_ENABLED
  3123. call_type = return_type;
  3124. } else {
  3125. bool found = false;
  3126. // Enums do not have functions other than the built-in dictionary ones.
  3127. if (base_type.kind == GDScriptParser::DataType::ENUM && base_type.is_meta_type) {
  3128. if (base_type.builtin_type == Variant::DICTIONARY) {
  3129. push_error(vformat(R"*(Enums only have Dictionary built-in methods. Function "%s()" does not exist for enum "%s".)*", p_call->function_name, base_type.enum_type), p_call->callee);
  3130. } else {
  3131. push_error(vformat(R"*(The native enum "%s" does not behave like Dictionary and does not have methods of its own.)*", base_type.enum_type), p_call->callee);
  3132. }
  3133. } else if (!p_call->is_super && callee_type != GDScriptParser::Node::NONE) { // Check if the name exists as something else.
  3134. GDScriptParser::IdentifierNode *callee_id;
  3135. if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  3136. callee_id = static_cast<GDScriptParser::IdentifierNode *>(p_call->callee);
  3137. } else {
  3138. // Can only be attribute.
  3139. callee_id = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee)->attribute;
  3140. }
  3141. if (callee_id) {
  3142. reduce_identifier_from_base(callee_id, &base_type);
  3143. GDScriptParser::DataType callee_datatype = callee_id->get_datatype();
  3144. if (callee_datatype.is_set() && !callee_datatype.is_variant()) {
  3145. found = true;
  3146. if (callee_datatype.builtin_type == Variant::CALLABLE) {
  3147. 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);
  3148. } else {
  3149. 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);
  3150. }
  3151. #ifdef DEBUG_ENABLED
  3152. } else if (!is_self && !(base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN)) {
  3153. parser->push_warning(p_call, GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->function_name, base_type.to_string());
  3154. mark_node_unsafe(p_call);
  3155. #endif
  3156. }
  3157. }
  3158. }
  3159. if (!found && (is_self || (base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN))) {
  3160. String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string();
  3161. #ifdef SUGGEST_GODOT4_RENAMES
  3162. String rename_hint;
  3163. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::RENAMED_IN_GODOT_4_HINT)).booleanize()) {
  3164. const char *renamed_function_name = check_for_renamed_identifier(p_call->function_name, p_call->type);
  3165. if (renamed_function_name) {
  3166. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", String(renamed_function_name) + "()");
  3167. }
  3168. }
  3169. push_error(vformat(R"*(Function "%s()" not found in base %s.%s)*", p_call->function_name, base_name, rename_hint), p_call->is_super ? p_call : p_call->callee);
  3170. #else
  3171. 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);
  3172. #endif // SUGGEST_GODOT4_RENAMES
  3173. } else if (!found && (!p_call->is_super && base_type.is_hard_type() && base_type.is_meta_type)) {
  3174. push_error(vformat(R"*(Static function "%s()" not found in base "%s".)*", p_call->function_name, base_type.to_string()), p_call);
  3175. }
  3176. }
  3177. if (call_type.is_coroutine && !p_is_await && !p_is_root) {
  3178. push_error(vformat(R"*(Function "%s()" is a coroutine, so it must be called with "await".)*", p_call->function_name), p_call);
  3179. }
  3180. p_call->set_datatype(call_type);
  3181. }
  3182. void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) {
  3183. reduce_expression(p_cast->operand);
  3184. GDScriptParser::DataType cast_type = type_from_metatype(resolve_datatype(p_cast->cast_type));
  3185. if (!cast_type.is_set()) {
  3186. mark_node_unsafe(p_cast);
  3187. return;
  3188. }
  3189. p_cast->set_datatype(cast_type);
  3190. if (p_cast->operand->is_constant) {
  3191. update_const_expression_builtin_type(p_cast->operand, cast_type, "cast", true);
  3192. if (cast_type.is_variant() || p_cast->operand->get_datatype() == cast_type) {
  3193. p_cast->is_constant = true;
  3194. p_cast->reduced_value = p_cast->operand->reduced_value;
  3195. }
  3196. }
  3197. if (p_cast->operand->type == GDScriptParser::Node::ARRAY && cast_type.has_container_element_type(0)) {
  3198. update_array_literal_element_type(static_cast<GDScriptParser::ArrayNode *>(p_cast->operand), cast_type.get_container_element_type(0));
  3199. }
  3200. if (!cast_type.is_variant()) {
  3201. GDScriptParser::DataType op_type = p_cast->operand->get_datatype();
  3202. if (op_type.is_variant() || !op_type.is_hard_type()) {
  3203. mark_node_unsafe(p_cast);
  3204. #ifdef DEBUG_ENABLED
  3205. parser->push_warning(p_cast, GDScriptWarning::UNSAFE_CAST, cast_type.to_string());
  3206. #endif
  3207. } else {
  3208. bool valid = false;
  3209. if (op_type.builtin_type == Variant::INT && cast_type.kind == GDScriptParser::DataType::ENUM) {
  3210. mark_node_unsafe(p_cast);
  3211. valid = true;
  3212. } else if (op_type.kind == GDScriptParser::DataType::ENUM && cast_type.builtin_type == Variant::INT) {
  3213. valid = true;
  3214. } else if (op_type.kind == GDScriptParser::DataType::BUILTIN && cast_type.kind == GDScriptParser::DataType::BUILTIN) {
  3215. valid = Variant::can_convert(op_type.builtin_type, cast_type.builtin_type);
  3216. } else if (op_type.kind != GDScriptParser::DataType::BUILTIN && cast_type.kind != GDScriptParser::DataType::BUILTIN) {
  3217. valid = is_type_compatible(cast_type, op_type) || is_type_compatible(op_type, cast_type);
  3218. }
  3219. if (!valid) {
  3220. push_error(vformat(R"(Invalid cast. Cannot convert from "%s" to "%s".)", op_type.to_string(), cast_type.to_string()), p_cast->cast_type);
  3221. }
  3222. }
  3223. }
  3224. }
  3225. void GDScriptAnalyzer::reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
  3226. HashMap<Variant, GDScriptParser::ExpressionNode *, VariantHasher, StringLikeVariantComparator> elements;
  3227. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  3228. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  3229. if (p_dictionary->style == GDScriptParser::DictionaryNode::PYTHON_DICT) {
  3230. reduce_expression(element.key);
  3231. }
  3232. reduce_expression(element.value);
  3233. if (element.key->is_constant) {
  3234. if (elements.has(element.key->reduced_value)) {
  3235. 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);
  3236. } else {
  3237. elements[element.key->reduced_value] = element.value;
  3238. }
  3239. }
  3240. }
  3241. // It's dictionary in any case.
  3242. GDScriptParser::DataType dict_type;
  3243. dict_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3244. dict_type.kind = GDScriptParser::DataType::BUILTIN;
  3245. dict_type.builtin_type = Variant::DICTIONARY;
  3246. dict_type.is_constant = true;
  3247. p_dictionary->set_datatype(dict_type);
  3248. }
  3249. void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) {
  3250. GDScriptParser::DataType result;
  3251. result.kind = GDScriptParser::DataType::VARIANT;
  3252. if (!ClassDB::is_parent_class(parser->current_class->base_type.native_type, SNAME("Node"))) {
  3253. push_error(vformat(R"*(Cannot use shorthand "get_node()" notation ("%c") on a class that isn't a node.)*", p_get_node->use_dollar ? '$' : '%'), p_get_node);
  3254. p_get_node->set_datatype(result);
  3255. return;
  3256. }
  3257. if (static_context) {
  3258. push_error(vformat(R"*(Cannot use shorthand "get_node()" notation ("%c") in a static function.)*", p_get_node->use_dollar ? '$' : '%'), p_get_node);
  3259. p_get_node->set_datatype(result);
  3260. return;
  3261. }
  3262. mark_lambda_use_self();
  3263. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3264. result.kind = GDScriptParser::DataType::NATIVE;
  3265. result.builtin_type = Variant::OBJECT;
  3266. result.native_type = SNAME("Node");
  3267. p_get_node->set_datatype(result);
  3268. }
  3269. GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) {
  3270. GDScriptParser::DataType type;
  3271. String path = ScriptServer::get_global_class_path(p_class_name);
  3272. String ext = path.get_extension();
  3273. if (ext == GDScriptLanguage::get_singleton()->get_extension()) {
  3274. Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(path);
  3275. if (ref.is_null()) {
  3276. push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source);
  3277. type.type_source = GDScriptParser::DataType::UNDETECTED;
  3278. type.kind = GDScriptParser::DataType::VARIANT;
  3279. return type;
  3280. }
  3281. Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3282. if (err) {
  3283. push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source);
  3284. type.type_source = GDScriptParser::DataType::UNDETECTED;
  3285. type.kind = GDScriptParser::DataType::VARIANT;
  3286. return type;
  3287. }
  3288. return ref->get_parser()->head->get_datatype();
  3289. } else {
  3290. return make_script_meta_type(ResourceLoader::load(path, "Script"));
  3291. }
  3292. }
  3293. Ref<GDScriptParserRef> GDScriptAnalyzer::ensure_cached_external_parser_for_class(const GDScriptParser::ClassNode *p_class, const GDScriptParser::ClassNode *p_from_class, const char *p_context, const GDScriptParser::Node *p_source) {
  3294. if (p_class == nullptr) {
  3295. return nullptr;
  3296. }
  3297. if (HashMap<const GDScriptParser::ClassNode *, Ref<GDScriptParserRef>>::Iterator E = external_class_parser_cache.find(p_class)) {
  3298. return E->value;
  3299. }
  3300. if (parser->has_class(p_class)) {
  3301. return nullptr;
  3302. }
  3303. if (p_from_class == nullptr) {
  3304. p_from_class = parser->head;
  3305. }
  3306. String script_path = p_class->get_datatype().script_path;
  3307. Ref<GDScriptParserRef> parser_ref;
  3308. for (const GDScriptParser::ClassNode *look_class = p_from_class; look_class != nullptr; look_class = look_class->base_type.class_type) {
  3309. if (parser->has_class(look_class)) {
  3310. parser_ref = find_cached_external_parser_for_class(p_class, parser);
  3311. if (parser_ref.is_valid()) {
  3312. break;
  3313. }
  3314. }
  3315. if (HashMap<const GDScriptParser::ClassNode *, Ref<GDScriptParserRef>>::Iterator E = external_class_parser_cache.find(look_class)) {
  3316. parser_ref = find_cached_external_parser_for_class(p_class, E->value);
  3317. if (parser_ref.is_valid()) {
  3318. break;
  3319. }
  3320. }
  3321. String look_class_script_path = look_class->get_datatype().script_path;
  3322. if (HashMap<String, Ref<GDScriptParserRef>>::Iterator E = parser->depended_parsers.find(look_class_script_path)) {
  3323. parser_ref = find_cached_external_parser_for_class(p_class, E->value);
  3324. if (parser_ref.is_valid()) {
  3325. break;
  3326. }
  3327. }
  3328. }
  3329. if (parser_ref.is_null()) {
  3330. push_error(vformat(R"(Parser bug (please report): Could not find external parser for class "%s". (%s))", p_class->fqcn, p_context), p_source);
  3331. // A null parser will be inserted into the cache, so this error won't spam for the same class.
  3332. // This is ok, the values of external_class_parser_cache are not assumed to be valid references.
  3333. }
  3334. external_class_parser_cache.insert(p_class, parser_ref);
  3335. return parser_ref;
  3336. }
  3337. Ref<GDScriptParserRef> GDScriptAnalyzer::find_cached_external_parser_for_class(const GDScriptParser::ClassNode *p_class, const Ref<GDScriptParserRef> &p_dependant_parser) {
  3338. if (p_dependant_parser.is_null()) {
  3339. return nullptr;
  3340. }
  3341. if (HashMap<const GDScriptParser::ClassNode *, Ref<GDScriptParserRef>>::Iterator E = p_dependant_parser->get_analyzer()->external_class_parser_cache.find(p_class)) {
  3342. if (E->value.is_valid()) {
  3343. // Silently ensure it's parsed.
  3344. E->value->raise_status(GDScriptParserRef::PARSED);
  3345. if (E->value->get_parser()->has_class(p_class)) {
  3346. return E->value;
  3347. }
  3348. }
  3349. }
  3350. if (p_dependant_parser->get_parser()->has_class(p_class)) {
  3351. return p_dependant_parser;
  3352. }
  3353. // Silently ensure it's parsed.
  3354. p_dependant_parser->raise_status(GDScriptParserRef::PARSED);
  3355. return find_cached_external_parser_for_class(p_class, p_dependant_parser->get_parser());
  3356. }
  3357. Ref<GDScriptParserRef> GDScriptAnalyzer::find_cached_external_parser_for_class(const GDScriptParser::ClassNode *p_class, GDScriptParser *p_dependant_parser) {
  3358. if (p_dependant_parser == nullptr) {
  3359. return nullptr;
  3360. }
  3361. String script_path = p_class->get_datatype().script_path;
  3362. if (HashMap<String, Ref<GDScriptParserRef>>::Iterator E = p_dependant_parser->depended_parsers.find(script_path)) {
  3363. if (E->value.is_valid()) {
  3364. // Silently ensure it's parsed.
  3365. E->value->raise_status(GDScriptParserRef::PARSED);
  3366. if (E->value->get_parser()->has_class(p_class)) {
  3367. return E->value;
  3368. }
  3369. }
  3370. }
  3371. return nullptr;
  3372. }
  3373. Ref<GDScript> GDScriptAnalyzer::get_depended_shallow_script(const String &p_path, Error &r_error) {
  3374. // To keep a local cache of the parser for resolving external nodes later.
  3375. parser->get_depended_parser_for(p_path);
  3376. Ref<GDScript> scr = GDScriptCache::get_shallow_script(p_path, r_error, parser->script_path);
  3377. return scr;
  3378. }
  3379. void GDScriptAnalyzer::reduce_identifier_from_base_set_class(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType p_identifier_datatype) {
  3380. ERR_FAIL_NULL(p_identifier);
  3381. p_identifier->set_datatype(p_identifier_datatype);
  3382. Error err = OK;
  3383. Ref<GDScript> scr = get_depended_shallow_script(p_identifier_datatype.script_path, err);
  3384. if (err) {
  3385. push_error(vformat(R"(Error while getting cache for script "%s".)", p_identifier_datatype.script_path), p_identifier);
  3386. return;
  3387. }
  3388. p_identifier->reduced_value = scr->find_class(p_identifier_datatype.class_type->fqcn);
  3389. p_identifier->is_constant = true;
  3390. }
  3391. void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) {
  3392. if (!p_identifier->get_datatype().has_no_type()) {
  3393. return;
  3394. }
  3395. GDScriptParser::DataType base;
  3396. if (p_base == nullptr) {
  3397. base = type_from_metatype(parser->current_class->get_datatype());
  3398. } else {
  3399. base = *p_base;
  3400. }
  3401. StringName name = p_identifier->name;
  3402. if (base.kind == GDScriptParser::DataType::ENUM) {
  3403. if (base.is_meta_type) {
  3404. if (base.enum_values.has(name)) {
  3405. p_identifier->set_datatype(type_from_metatype(base));
  3406. p_identifier->is_constant = true;
  3407. p_identifier->reduced_value = base.enum_values[name];
  3408. return;
  3409. }
  3410. // Enum does not have this value, return.
  3411. return;
  3412. } else {
  3413. push_error(R"(Cannot get property from enum value.)", p_identifier);
  3414. return;
  3415. }
  3416. }
  3417. if (base.kind == GDScriptParser::DataType::BUILTIN) {
  3418. if (base.is_meta_type) {
  3419. bool valid = true;
  3420. Variant result = Variant::get_constant_value(base.builtin_type, name, &valid);
  3421. if (valid) {
  3422. p_identifier->is_constant = true;
  3423. p_identifier->reduced_value = result;
  3424. p_identifier->set_datatype(type_from_variant(result, p_identifier));
  3425. } else if (base.is_hard_type()) {
  3426. #ifdef SUGGEST_GODOT4_RENAMES
  3427. String rename_hint;
  3428. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::RENAMED_IN_GODOT_4_HINT)).booleanize()) {
  3429. const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);
  3430. if (renamed_identifier_name) {
  3431. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);
  3432. }
  3433. }
  3434. push_error(vformat(R"(Cannot find constant "%s" on base "%s".%s)", name, base.to_string(), rename_hint), p_identifier);
  3435. #else
  3436. push_error(vformat(R"(Cannot find constant "%s" on base "%s".)", name, base.to_string()), p_identifier);
  3437. #endif // SUGGEST_GODOT4_RENAMES
  3438. }
  3439. } else {
  3440. switch (base.builtin_type) {
  3441. case Variant::NIL: {
  3442. if (base.is_hard_type()) {
  3443. push_error(vformat(R"(Cannot get property "%s" on a null object.)", name), p_identifier);
  3444. }
  3445. return;
  3446. }
  3447. case Variant::DICTIONARY: {
  3448. GDScriptParser::DataType dummy;
  3449. dummy.kind = GDScriptParser::DataType::VARIANT;
  3450. p_identifier->set_datatype(dummy);
  3451. return;
  3452. }
  3453. default: {
  3454. Callable::CallError temp;
  3455. Variant dummy;
  3456. Variant::construct(base.builtin_type, dummy, nullptr, 0, temp);
  3457. List<PropertyInfo> properties;
  3458. dummy.get_property_list(&properties);
  3459. for (const PropertyInfo &prop : properties) {
  3460. if (prop.name == name) {
  3461. p_identifier->set_datatype(type_from_property(prop));
  3462. return;
  3463. }
  3464. }
  3465. if (Variant::has_builtin_method(base.builtin_type, name)) {
  3466. p_identifier->set_datatype(make_callable_type(Variant::get_builtin_method_info(base.builtin_type, name)));
  3467. return;
  3468. }
  3469. if (base.is_hard_type()) {
  3470. #ifdef SUGGEST_GODOT4_RENAMES
  3471. String rename_hint;
  3472. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::RENAMED_IN_GODOT_4_HINT)).booleanize()) {
  3473. const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);
  3474. if (renamed_identifier_name) {
  3475. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);
  3476. }
  3477. }
  3478. push_error(vformat(R"(Cannot find property "%s" on base "%s".%s)", name, base.to_string(), rename_hint), p_identifier);
  3479. #else
  3480. push_error(vformat(R"(Cannot find property "%s" on base "%s".)", name, base.to_string()), p_identifier);
  3481. #endif // SUGGEST_GODOT4_RENAMES
  3482. }
  3483. }
  3484. }
  3485. }
  3486. return;
  3487. }
  3488. GDScriptParser::ClassNode *base_class = base.class_type;
  3489. List<GDScriptParser::ClassNode *> script_classes;
  3490. bool is_base = true;
  3491. if (base_class != nullptr) {
  3492. get_class_node_current_scope_classes(base_class, &script_classes, p_identifier);
  3493. }
  3494. bool is_constructor = base.is_meta_type && p_identifier->name == SNAME("new");
  3495. for (GDScriptParser::ClassNode *script_class : script_classes) {
  3496. if (p_base == nullptr && script_class->identifier && script_class->identifier->name == name) {
  3497. reduce_identifier_from_base_set_class(p_identifier, script_class->get_datatype());
  3498. if (script_class->outer != nullptr) {
  3499. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CLASS;
  3500. }
  3501. return;
  3502. }
  3503. if (is_constructor) {
  3504. name = "_init";
  3505. }
  3506. if (script_class->has_member(name)) {
  3507. resolve_class_member(script_class, name, p_identifier);
  3508. GDScriptParser::ClassNode::Member member = script_class->get_member(name);
  3509. switch (member.type) {
  3510. case GDScriptParser::ClassNode::Member::CONSTANT: {
  3511. p_identifier->set_datatype(member.get_datatype());
  3512. p_identifier->is_constant = true;
  3513. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  3514. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3515. p_identifier->constant_source = member.constant;
  3516. return;
  3517. }
  3518. case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
  3519. p_identifier->set_datatype(member.get_datatype());
  3520. p_identifier->is_constant = true;
  3521. p_identifier->reduced_value = member.enum_value.value;
  3522. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3523. return;
  3524. }
  3525. case GDScriptParser::ClassNode::Member::ENUM: {
  3526. p_identifier->set_datatype(member.get_datatype());
  3527. p_identifier->is_constant = true;
  3528. p_identifier->reduced_value = member.m_enum->dictionary;
  3529. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3530. return;
  3531. }
  3532. case GDScriptParser::ClassNode::Member::VARIABLE: {
  3533. if (is_base && (!base.is_meta_type || member.variable->is_static)) {
  3534. p_identifier->set_datatype(member.get_datatype());
  3535. p_identifier->source = member.variable->is_static ? GDScriptParser::IdentifierNode::STATIC_VARIABLE : GDScriptParser::IdentifierNode::MEMBER_VARIABLE;
  3536. p_identifier->variable_source = member.variable;
  3537. member.variable->usages += 1;
  3538. return;
  3539. }
  3540. } break;
  3541. case GDScriptParser::ClassNode::Member::SIGNAL: {
  3542. if (is_base && !base.is_meta_type) {
  3543. p_identifier->set_datatype(member.get_datatype());
  3544. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_SIGNAL;
  3545. p_identifier->signal_source = member.signal;
  3546. member.signal->usages += 1;
  3547. return;
  3548. }
  3549. } break;
  3550. case GDScriptParser::ClassNode::Member::FUNCTION: {
  3551. if (is_base && (!base.is_meta_type || member.function->is_static || is_constructor)) {
  3552. p_identifier->set_datatype(make_callable_type(member.function->info));
  3553. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_FUNCTION;
  3554. p_identifier->function_source = member.function;
  3555. p_identifier->function_source_is_static = member.function->is_static;
  3556. return;
  3557. }
  3558. } break;
  3559. case GDScriptParser::ClassNode::Member::CLASS: {
  3560. reduce_identifier_from_base_set_class(p_identifier, member.get_datatype());
  3561. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CLASS;
  3562. return;
  3563. }
  3564. default: {
  3565. // Do nothing
  3566. }
  3567. }
  3568. }
  3569. if (is_base) {
  3570. is_base = script_class->base_type.class_type != nullptr;
  3571. if (!is_base && p_base != nullptr) {
  3572. break;
  3573. }
  3574. }
  3575. }
  3576. // Check non-GDScript scripts.
  3577. Ref<Script> script_type = base.script_type;
  3578. if (base_class == nullptr && script_type.is_valid()) {
  3579. List<PropertyInfo> property_list;
  3580. script_type->get_script_property_list(&property_list);
  3581. for (const PropertyInfo &property_info : property_list) {
  3582. if (property_info.name != p_identifier->name) {
  3583. continue;
  3584. }
  3585. const GDScriptParser::DataType property_type = GDScriptAnalyzer::type_from_property(property_info, false, false);
  3586. p_identifier->set_datatype(property_type);
  3587. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;
  3588. return;
  3589. }
  3590. MethodInfo method_info = script_type->get_method_info(p_identifier->name);
  3591. if (method_info.name == p_identifier->name) {
  3592. p_identifier->set_datatype(make_callable_type(method_info));
  3593. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_FUNCTION;
  3594. p_identifier->function_source_is_static = method_info.flags & METHOD_FLAG_STATIC;
  3595. return;
  3596. }
  3597. List<MethodInfo> signal_list;
  3598. script_type->get_script_signal_list(&signal_list);
  3599. for (const MethodInfo &signal_info : signal_list) {
  3600. if (signal_info.name != p_identifier->name) {
  3601. continue;
  3602. }
  3603. const GDScriptParser::DataType signal_type = make_signal_type(signal_info);
  3604. p_identifier->set_datatype(signal_type);
  3605. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_SIGNAL;
  3606. return;
  3607. }
  3608. HashMap<StringName, Variant> constant_map;
  3609. script_type->get_constants(&constant_map);
  3610. if (constant_map.has(p_identifier->name)) {
  3611. Variant constant = constant_map.get(p_identifier->name);
  3612. p_identifier->set_datatype(make_builtin_meta_type(constant.get_type()));
  3613. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3614. return;
  3615. }
  3616. }
  3617. // Check native members. No need for native class recursion because Node exposes all Object's properties.
  3618. const StringName &native = base.native_type;
  3619. if (class_exists(native)) {
  3620. if (is_constructor) {
  3621. name = "_init";
  3622. }
  3623. MethodInfo method_info;
  3624. if (ClassDB::has_property(native, name)) {
  3625. StringName getter_name = ClassDB::get_property_getter(native, name);
  3626. MethodBind *getter = ClassDB::get_method(native, getter_name);
  3627. if (getter != nullptr) {
  3628. bool has_setter = ClassDB::get_property_setter(native, name) != StringName();
  3629. p_identifier->set_datatype(type_from_property(getter->get_return_info(), false, !has_setter));
  3630. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3631. }
  3632. return;
  3633. }
  3634. if (ClassDB::get_method_info(native, name, &method_info)) {
  3635. // Method is callable.
  3636. p_identifier->set_datatype(make_callable_type(method_info));
  3637. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3638. return;
  3639. }
  3640. if (ClassDB::get_signal(native, name, &method_info)) {
  3641. // Signal is a type too.
  3642. p_identifier->set_datatype(make_signal_type(method_info));
  3643. p_identifier->source = GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3644. return;
  3645. }
  3646. if (ClassDB::has_enum(native, name)) {
  3647. p_identifier->set_datatype(make_native_enum_type(name, native));
  3648. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3649. return;
  3650. }
  3651. bool valid = false;
  3652. int64_t int_constant = ClassDB::get_integer_constant(native, name, &valid);
  3653. if (valid) {
  3654. p_identifier->is_constant = true;
  3655. p_identifier->reduced_value = int_constant;
  3656. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  3657. // Check whether this constant, which exists, belongs to an enum
  3658. StringName enum_name = ClassDB::get_integer_constant_enum(native, name);
  3659. if (enum_name != StringName()) {
  3660. p_identifier->set_datatype(make_native_enum_type(enum_name, native, false));
  3661. } else {
  3662. p_identifier->set_datatype(type_from_variant(int_constant, p_identifier));
  3663. }
  3664. }
  3665. }
  3666. }
  3667. void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin) {
  3668. // TODO: This is an opportunity to further infer types.
  3669. // Check if we are inside an enum. This allows enum values to access other elements of the same enum.
  3670. if (current_enum) {
  3671. for (int i = 0; i < current_enum->values.size(); i++) {
  3672. const GDScriptParser::EnumNode::Value &element = current_enum->values[i];
  3673. if (element.identifier->name == p_identifier->name) {
  3674. StringName enum_name = current_enum->identifier ? current_enum->identifier->name : UNNAMED_ENUM;
  3675. GDScriptParser::DataType type = make_enum_type(enum_name, parser->current_class->fqcn, false);
  3676. if (element.parent_enum->identifier) {
  3677. type.enum_type = element.parent_enum->identifier->name;
  3678. }
  3679. p_identifier->set_datatype(type);
  3680. if (element.resolved) {
  3681. p_identifier->is_constant = true;
  3682. p_identifier->reduced_value = element.value;
  3683. } else {
  3684. push_error(R"(Cannot use another enum element before it was declared.)", p_identifier);
  3685. }
  3686. return; // Found anyway.
  3687. }
  3688. }
  3689. }
  3690. bool found_source = false;
  3691. // Check if identifier is local.
  3692. // If that's the case, the declaration already was solved before.
  3693. switch (p_identifier->source) {
  3694. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:
  3695. p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());
  3696. found_source = true;
  3697. break;
  3698. case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:
  3699. case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:
  3700. p_identifier->set_datatype(p_identifier->constant_source->get_datatype());
  3701. p_identifier->is_constant = true;
  3702. // TODO: Constant should have a value on the node itself.
  3703. p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;
  3704. found_source = true;
  3705. break;
  3706. case GDScriptParser::IdentifierNode::MEMBER_SIGNAL:
  3707. p_identifier->signal_source->usages++;
  3708. [[fallthrough]];
  3709. case GDScriptParser::IdentifierNode::INHERITED_VARIABLE:
  3710. mark_lambda_use_self();
  3711. break;
  3712. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
  3713. mark_lambda_use_self();
  3714. p_identifier->variable_source->usages++;
  3715. [[fallthrough]];
  3716. case GDScriptParser::IdentifierNode::STATIC_VARIABLE:
  3717. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
  3718. p_identifier->set_datatype(p_identifier->variable_source->get_datatype());
  3719. found_source = true;
  3720. #ifdef DEBUG_ENABLED
  3721. if (p_identifier->variable_source && p_identifier->variable_source->assignments == 0 && !(p_identifier->get_datatype().is_hard_type() && p_identifier->get_datatype().kind == GDScriptParser::DataType::BUILTIN)) {
  3722. parser->push_warning(p_identifier, GDScriptWarning::UNASSIGNED_VARIABLE, p_identifier->name);
  3723. }
  3724. #endif
  3725. break;
  3726. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:
  3727. p_identifier->set_datatype(p_identifier->bind_source->get_datatype());
  3728. found_source = true;
  3729. break;
  3730. case GDScriptParser::IdentifierNode::LOCAL_BIND: {
  3731. GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();
  3732. result.is_constant = true;
  3733. p_identifier->set_datatype(result);
  3734. found_source = true;
  3735. } break;
  3736. case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:
  3737. case GDScriptParser::IdentifierNode::MEMBER_FUNCTION:
  3738. case GDScriptParser::IdentifierNode::MEMBER_CLASS:
  3739. break;
  3740. }
  3741. #ifdef DEBUG_ENABLED
  3742. if (!found_source && p_identifier->suite != nullptr && p_identifier->suite->has_local(p_identifier->name)) {
  3743. parser->push_warning(p_identifier, GDScriptWarning::CONFUSABLE_LOCAL_USAGE, p_identifier->name);
  3744. }
  3745. #endif
  3746. // Not a local, so check members.
  3747. if (!found_source) {
  3748. reduce_identifier_from_base(p_identifier);
  3749. if (p_identifier->source != GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->get_datatype().is_set()) {
  3750. // Found.
  3751. found_source = true;
  3752. }
  3753. }
  3754. if (found_source) {
  3755. const bool source_is_instance_variable = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_VARIABLE || p_identifier->source == GDScriptParser::IdentifierNode::INHERITED_VARIABLE;
  3756. const bool source_is_instance_function = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_FUNCTION && !p_identifier->function_source_is_static;
  3757. const bool source_is_signal = p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_SIGNAL;
  3758. if (static_context && (source_is_instance_variable || source_is_instance_function || source_is_signal)) {
  3759. // Get the parent function above any lambda.
  3760. GDScriptParser::FunctionNode *parent_function = parser->current_function;
  3761. while (parent_function && parent_function->source_lambda) {
  3762. parent_function = parent_function->source_lambda->parent_function;
  3763. }
  3764. String source_type;
  3765. if (source_is_instance_variable) {
  3766. source_type = "non-static variable";
  3767. } else if (source_is_instance_function) {
  3768. source_type = "non-static function";
  3769. } else { // source_is_signal
  3770. source_type = "signal";
  3771. }
  3772. if (parent_function) {
  3773. push_error(vformat(R"*(Cannot access %s "%s" from the static function "%s()".)*", source_type, p_identifier->name, parent_function->identifier->name), p_identifier);
  3774. } else {
  3775. push_error(vformat(R"*(Cannot access %s "%s" from a static variable initializer.)*", source_type, p_identifier->name), p_identifier);
  3776. }
  3777. }
  3778. if (current_lambda != nullptr) {
  3779. // If the identifier is a member variable (including the native class properties), member function, or a signal,
  3780. // we consider the lambda to be using `self`, so we keep a reference to the current instance.
  3781. if (source_is_instance_variable || source_is_instance_function || source_is_signal) {
  3782. mark_lambda_use_self();
  3783. return; // No need to capture.
  3784. }
  3785. switch (p_identifier->source) {
  3786. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:
  3787. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
  3788. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:
  3789. case GDScriptParser::IdentifierNode::LOCAL_BIND:
  3790. break; // Need to capture.
  3791. case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE: // A global.
  3792. case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:
  3793. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
  3794. case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:
  3795. case GDScriptParser::IdentifierNode::MEMBER_FUNCTION:
  3796. case GDScriptParser::IdentifierNode::MEMBER_SIGNAL:
  3797. case GDScriptParser::IdentifierNode::MEMBER_CLASS:
  3798. case GDScriptParser::IdentifierNode::INHERITED_VARIABLE:
  3799. case GDScriptParser::IdentifierNode::STATIC_VARIABLE:
  3800. return; // No need to capture.
  3801. }
  3802. GDScriptParser::FunctionNode *function_test = current_lambda->function;
  3803. // Make sure we aren't capturing variable in the same lambda.
  3804. // This also add captures for nested lambdas.
  3805. 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)) {
  3806. function_test->source_lambda->captures_indices[p_identifier->name] = function_test->source_lambda->captures.size();
  3807. function_test->source_lambda->captures.push_back(p_identifier);
  3808. function_test = function_test->source_lambda->parent_function;
  3809. }
  3810. }
  3811. return;
  3812. }
  3813. StringName name = p_identifier->name;
  3814. p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;
  3815. // Not a local or a member, so check globals.
  3816. Variant::Type builtin_type = GDScriptParser::get_builtin_type(name);
  3817. if (builtin_type < Variant::VARIANT_MAX) {
  3818. if (can_be_builtin) {
  3819. p_identifier->set_datatype(make_builtin_meta_type(builtin_type));
  3820. return;
  3821. } else {
  3822. push_error(R"(Builtin type cannot be used as a name on its own.)", p_identifier);
  3823. }
  3824. }
  3825. if (class_exists(name)) {
  3826. p_identifier->set_datatype(make_native_meta_type(name));
  3827. return;
  3828. }
  3829. if (ScriptServer::is_global_class(name)) {
  3830. p_identifier->set_datatype(make_global_class_meta_type(name, p_identifier));
  3831. return;
  3832. }
  3833. // Try singletons.
  3834. // Do this before globals because this might be a singleton loading another one before it's compiled.
  3835. if (ProjectSettings::get_singleton()->has_autoload(name)) {
  3836. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(name);
  3837. if (autoload.is_singleton) {
  3838. // Singleton exists, so it's at least a Node.
  3839. GDScriptParser::DataType result;
  3840. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3841. result.kind = GDScriptParser::DataType::NATIVE;
  3842. result.builtin_type = Variant::OBJECT;
  3843. result.native_type = SNAME("Node");
  3844. if (ResourceLoader::get_resource_type(autoload.path) == "GDScript") {
  3845. Ref<GDScriptParserRef> singl_parser = parser->get_depended_parser_for(autoload.path);
  3846. if (singl_parser.is_valid()) {
  3847. Error err = singl_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3848. if (err == OK) {
  3849. result = type_from_metatype(singl_parser->get_parser()->head->get_datatype());
  3850. }
  3851. }
  3852. } else if (ResourceLoader::get_resource_type(autoload.path) == "PackedScene") {
  3853. if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {
  3854. Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);
  3855. Node *node = Object::cast_to<Node>(constant);
  3856. if (node != nullptr) {
  3857. Ref<GDScript> scr = node->get_script();
  3858. if (scr.is_valid()) {
  3859. Ref<GDScriptParserRef> singl_parser = parser->get_depended_parser_for(scr->get_script_path());
  3860. if (singl_parser.is_valid()) {
  3861. Error err = singl_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  3862. if (err == OK) {
  3863. result = type_from_metatype(singl_parser->get_parser()->head->get_datatype());
  3864. }
  3865. }
  3866. }
  3867. }
  3868. }
  3869. }
  3870. result.is_constant = true;
  3871. p_identifier->set_datatype(result);
  3872. return;
  3873. }
  3874. }
  3875. if (CoreConstants::is_global_constant(name)) {
  3876. int index = CoreConstants::get_global_constant_index(name);
  3877. StringName enum_name = CoreConstants::get_global_constant_enum(index);
  3878. int64_t value = CoreConstants::get_global_constant_value(index);
  3879. if (enum_name != StringName()) {
  3880. p_identifier->set_datatype(make_global_enum_type(enum_name, StringName(), false));
  3881. } else {
  3882. p_identifier->set_datatype(type_from_variant(value, p_identifier));
  3883. }
  3884. p_identifier->is_constant = true;
  3885. p_identifier->reduced_value = value;
  3886. return;
  3887. }
  3888. if (GDScriptLanguage::get_singleton()->has_any_global_constant(name)) {
  3889. Variant constant = GDScriptLanguage::get_singleton()->get_any_global_constant(name);
  3890. p_identifier->set_datatype(type_from_variant(constant, p_identifier));
  3891. p_identifier->is_constant = true;
  3892. p_identifier->reduced_value = constant;
  3893. return;
  3894. }
  3895. if (CoreConstants::is_global_enum(name)) {
  3896. p_identifier->set_datatype(make_global_enum_type(name, StringName(), true));
  3897. if (!can_be_builtin) {
  3898. push_error(vformat(R"(Global enum "%s" cannot be used on its own.)", name), p_identifier);
  3899. }
  3900. return;
  3901. }
  3902. if (Variant::has_utility_function(name) || GDScriptUtilityFunctions::function_exists(name)) {
  3903. p_identifier->is_constant = true;
  3904. p_identifier->reduced_value = Callable(memnew(GDScriptUtilityCallable(name)));
  3905. MethodInfo method_info;
  3906. if (GDScriptUtilityFunctions::function_exists(name)) {
  3907. method_info = GDScriptUtilityFunctions::get_function_info(name);
  3908. } else {
  3909. method_info = Variant::get_utility_function_info(name);
  3910. }
  3911. p_identifier->set_datatype(make_callable_type(method_info));
  3912. return;
  3913. }
  3914. // Allow "Variant" here since it might be used for nested enums.
  3915. if (can_be_builtin && name == SNAME("Variant")) {
  3916. GDScriptParser::DataType variant;
  3917. variant.kind = GDScriptParser::DataType::VARIANT;
  3918. variant.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3919. variant.is_meta_type = true;
  3920. variant.is_pseudo_type = true;
  3921. p_identifier->set_datatype(variant);
  3922. return;
  3923. }
  3924. // Not found.
  3925. #ifdef SUGGEST_GODOT4_RENAMES
  3926. String rename_hint;
  3927. if (GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(GDScriptWarning::RENAMED_IN_GODOT_4_HINT)).booleanize()) {
  3928. const char *renamed_identifier_name = check_for_renamed_identifier(name, p_identifier->type);
  3929. if (renamed_identifier_name) {
  3930. rename_hint = " " + vformat(R"(Did you mean to use "%s"?)", renamed_identifier_name);
  3931. }
  3932. }
  3933. push_error(vformat(R"(Identifier "%s" not declared in the current scope.%s)", name, rename_hint), p_identifier);
  3934. #else
  3935. push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);
  3936. #endif // SUGGEST_GODOT4_RENAMES
  3937. GDScriptParser::DataType dummy;
  3938. dummy.kind = GDScriptParser::DataType::VARIANT;
  3939. p_identifier->set_datatype(dummy); // Just so type is set to something.
  3940. }
  3941. void GDScriptAnalyzer::reduce_lambda(GDScriptParser::LambdaNode *p_lambda) {
  3942. // Lambda is always a Callable.
  3943. GDScriptParser::DataType lambda_type;
  3944. lambda_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  3945. lambda_type.kind = GDScriptParser::DataType::BUILTIN;
  3946. lambda_type.builtin_type = Variant::CALLABLE;
  3947. p_lambda->set_datatype(lambda_type);
  3948. if (p_lambda->function == nullptr) {
  3949. return;
  3950. }
  3951. GDScriptParser::LambdaNode *previous_lambda = current_lambda;
  3952. current_lambda = p_lambda;
  3953. resolve_function_signature(p_lambda->function, p_lambda, true);
  3954. current_lambda = previous_lambda;
  3955. pending_body_resolution_lambdas.push_back(p_lambda);
  3956. }
  3957. void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {
  3958. p_literal->reduced_value = p_literal->value;
  3959. p_literal->is_constant = true;
  3960. p_literal->set_datatype(type_from_variant(p_literal->reduced_value, p_literal));
  3961. }
  3962. void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
  3963. if (!p_preload->path) {
  3964. return;
  3965. }
  3966. reduce_expression(p_preload->path);
  3967. if (!p_preload->path->is_constant) {
  3968. push_error("Preloaded path must be a constant string.", p_preload->path);
  3969. return;
  3970. }
  3971. if (p_preload->path->reduced_value.get_type() != Variant::STRING) {
  3972. push_error("Preloaded path must be a constant string.", p_preload->path);
  3973. } else {
  3974. p_preload->resolved_path = p_preload->path->reduced_value;
  3975. // TODO: Save this as script dependency.
  3976. if (p_preload->resolved_path.is_relative_path()) {
  3977. p_preload->resolved_path = parser->script_path.get_base_dir().path_join(p_preload->resolved_path);
  3978. }
  3979. p_preload->resolved_path = p_preload->resolved_path.simplify_path();
  3980. if (!ResourceLoader::exists(p_preload->resolved_path)) {
  3981. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  3982. if (file_check->file_exists(p_preload->resolved_path)) {
  3983. push_error(vformat(R"(Preload file "%s" has no resource loaders (unrecognized file extension).)", p_preload->resolved_path), p_preload->path);
  3984. } else {
  3985. push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path);
  3986. }
  3987. } else {
  3988. // TODO: Don't load if validating: use completion cache.
  3989. // Must load GDScript separately to permit cyclic references
  3990. // as ResourceLoader::load() detects and rejects those.
  3991. const String &res_type = ResourceLoader::get_resource_type(p_preload->resolved_path);
  3992. if (res_type == "GDScript") {
  3993. Error err = OK;
  3994. Ref<GDScript> res = get_depended_shallow_script(p_preload->resolved_path, err);
  3995. p_preload->resource = res;
  3996. if (err != OK) {
  3997. push_error(vformat(R"(Could not preload resource script "%s".)", p_preload->resolved_path), p_preload->path);
  3998. }
  3999. } else {
  4000. Error err = OK;
  4001. p_preload->resource = ResourceLoader::load(p_preload->resolved_path, res_type, ResourceFormatLoader::CACHE_MODE_REUSE, &err);
  4002. if (err == ERR_BUSY) {
  4003. p_preload->resource = ResourceLoader::ensure_resource_ref_override_for_outer_load(p_preload->resolved_path, res_type);
  4004. }
  4005. if (p_preload->resource.is_null()) {
  4006. push_error(vformat(R"(Could not preload resource file "%s".)", p_preload->resolved_path), p_preload->path);
  4007. }
  4008. }
  4009. }
  4010. }
  4011. p_preload->is_constant = true;
  4012. p_preload->reduced_value = p_preload->resource;
  4013. p_preload->set_datatype(type_from_variant(p_preload->reduced_value, p_preload));
  4014. // TODO: Not sure if this is necessary anymore.
  4015. // 'type_from_variant()' should call 'resolve_class_inheritance()' which would call 'ensure_cached_external_parser_for_class()'
  4016. // Better safe than sorry.
  4017. ensure_cached_external_parser_for_class(p_preload->get_datatype().class_type, nullptr, "Trying to resolve preload", p_preload);
  4018. }
  4019. void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
  4020. p_self->is_constant = false;
  4021. p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));
  4022. mark_lambda_use_self();
  4023. }
  4024. void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript, bool p_can_be_pseudo_type) {
  4025. if (p_subscript->base == nullptr) {
  4026. return;
  4027. }
  4028. if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  4029. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);
  4030. } else if (p_subscript->base->type == GDScriptParser::Node::SUBSCRIPT) {
  4031. reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_subscript->base), true);
  4032. } else {
  4033. reduce_expression(p_subscript->base);
  4034. }
  4035. GDScriptParser::DataType result_type;
  4036. if (p_subscript->is_attribute) {
  4037. if (p_subscript->attribute == nullptr) {
  4038. return;
  4039. }
  4040. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  4041. bool valid = false;
  4042. // If the base is a metatype, use the analyzer instead.
  4043. if (p_subscript->base->is_constant && !base_type.is_meta_type) {
  4044. // GH-92534. If the base is a GDScript, use the analyzer instead.
  4045. bool base_is_gdscript = false;
  4046. if (p_subscript->base->reduced_value.get_type() == Variant::OBJECT) {
  4047. Ref<GDScript> gdscript = Object::cast_to<GDScript>(p_subscript->base->reduced_value.get_validated_object());
  4048. if (gdscript.is_valid()) {
  4049. base_is_gdscript = true;
  4050. // Makes a metatype from a constant GDScript, since `base_type` is not a metatype.
  4051. GDScriptParser::DataType base_type_meta = type_from_variant(gdscript, p_subscript);
  4052. // First try to reduce the attribute from the metatype.
  4053. reduce_identifier_from_base(p_subscript->attribute, &base_type_meta);
  4054. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  4055. if (attr_type.is_set()) {
  4056. valid = !attr_type.is_pseudo_type || p_can_be_pseudo_type;
  4057. result_type = attr_type;
  4058. p_subscript->is_constant = p_subscript->attribute->is_constant;
  4059. p_subscript->reduced_value = p_subscript->attribute->reduced_value;
  4060. }
  4061. if (!valid) {
  4062. // If unsuccessful, reset and return to the normal route.
  4063. p_subscript->attribute->set_datatype(GDScriptParser::DataType());
  4064. }
  4065. }
  4066. }
  4067. if (!base_is_gdscript) {
  4068. // Just try to get it.
  4069. Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, valid);
  4070. if (valid) {
  4071. p_subscript->is_constant = true;
  4072. p_subscript->reduced_value = value;
  4073. result_type = type_from_variant(value, p_subscript);
  4074. }
  4075. }
  4076. }
  4077. if (valid) {
  4078. // Do nothing.
  4079. } else if (base_type.is_variant() || !base_type.is_hard_type()) {
  4080. valid = !base_type.is_pseudo_type || p_can_be_pseudo_type;
  4081. result_type.kind = GDScriptParser::DataType::VARIANT;
  4082. if (base_type.is_variant() && base_type.is_hard_type() && base_type.is_meta_type && base_type.is_pseudo_type) {
  4083. // Special case: it may be a global enum with pseudo base (e.g. Variant.Type).
  4084. String enum_name;
  4085. if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  4086. enum_name = String(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base)->name) + ENUM_SEPARATOR + String(p_subscript->attribute->name);
  4087. }
  4088. if (CoreConstants::is_global_enum(enum_name)) {
  4089. result_type = make_global_enum_type(enum_name, StringName());
  4090. } else {
  4091. valid = false;
  4092. mark_node_unsafe(p_subscript);
  4093. }
  4094. } else {
  4095. mark_node_unsafe(p_subscript);
  4096. }
  4097. } else {
  4098. reduce_identifier_from_base(p_subscript->attribute, &base_type);
  4099. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  4100. if (attr_type.is_set()) {
  4101. valid = !attr_type.is_pseudo_type || p_can_be_pseudo_type;
  4102. result_type = attr_type;
  4103. p_subscript->is_constant = p_subscript->attribute->is_constant;
  4104. p_subscript->reduced_value = p_subscript->attribute->reduced_value;
  4105. } else if (!base_type.is_meta_type || !base_type.is_constant) {
  4106. valid = base_type.kind != GDScriptParser::DataType::BUILTIN;
  4107. #ifdef DEBUG_ENABLED
  4108. if (valid) {
  4109. parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());
  4110. }
  4111. #endif
  4112. result_type.kind = GDScriptParser::DataType::VARIANT;
  4113. mark_node_unsafe(p_subscript);
  4114. }
  4115. }
  4116. if (!valid) {
  4117. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  4118. if (!p_can_be_pseudo_type && (attr_type.is_pseudo_type || result_type.is_pseudo_type)) {
  4119. push_error(vformat(R"(Type "%s" in base "%s" cannot be used on its own.)", p_subscript->attribute->name, type_from_metatype(base_type).to_string()), p_subscript->attribute);
  4120. } else {
  4121. 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);
  4122. }
  4123. result_type.kind = GDScriptParser::DataType::VARIANT;
  4124. }
  4125. } else {
  4126. if (p_subscript->index == nullptr) {
  4127. return;
  4128. }
  4129. reduce_expression(p_subscript->index);
  4130. if (p_subscript->base->is_constant && p_subscript->index->is_constant) {
  4131. // Just try to get it.
  4132. bool valid = false;
  4133. // TODO: Check if `p_subscript->base->reduced_value` is GDScript.
  4134. Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);
  4135. if (!valid) {
  4136. push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);
  4137. result_type.kind = GDScriptParser::DataType::VARIANT;
  4138. } else {
  4139. p_subscript->is_constant = true;
  4140. p_subscript->reduced_value = value;
  4141. result_type = type_from_variant(value, p_subscript);
  4142. }
  4143. } else {
  4144. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  4145. GDScriptParser::DataType index_type = p_subscript->index->get_datatype();
  4146. if (base_type.is_variant()) {
  4147. result_type.kind = GDScriptParser::DataType::VARIANT;
  4148. mark_node_unsafe(p_subscript);
  4149. } else {
  4150. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  4151. // Check if indexing is valid.
  4152. bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;
  4153. if (!error) {
  4154. switch (base_type.builtin_type) {
  4155. // Expect int or real as index.
  4156. case Variant::PACKED_BYTE_ARRAY:
  4157. case Variant::PACKED_FLOAT32_ARRAY:
  4158. case Variant::PACKED_FLOAT64_ARRAY:
  4159. case Variant::PACKED_INT32_ARRAY:
  4160. case Variant::PACKED_INT64_ARRAY:
  4161. case Variant::PACKED_STRING_ARRAY:
  4162. case Variant::PACKED_VECTOR2_ARRAY:
  4163. case Variant::PACKED_VECTOR3_ARRAY:
  4164. case Variant::PACKED_COLOR_ARRAY:
  4165. case Variant::PACKED_VECTOR4_ARRAY:
  4166. case Variant::ARRAY:
  4167. case Variant::STRING:
  4168. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;
  4169. break;
  4170. // Expect String only.
  4171. case Variant::RECT2:
  4172. case Variant::RECT2I:
  4173. case Variant::PLANE:
  4174. case Variant::QUATERNION:
  4175. case Variant::AABB:
  4176. case Variant::OBJECT:
  4177. error = index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  4178. break;
  4179. // Expect String or number.
  4180. case Variant::BASIS:
  4181. case Variant::VECTOR2:
  4182. case Variant::VECTOR2I:
  4183. case Variant::VECTOR3:
  4184. case Variant::VECTOR3I:
  4185. case Variant::VECTOR4:
  4186. case Variant::VECTOR4I:
  4187. case Variant::TRANSFORM2D:
  4188. case Variant::TRANSFORM3D:
  4189. case Variant::PROJECTION:
  4190. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&
  4191. index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  4192. break;
  4193. // Expect String or int.
  4194. case Variant::COLOR:
  4195. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME;
  4196. break;
  4197. // Don't support indexing, but we will check it later.
  4198. case Variant::RID:
  4199. case Variant::BOOL:
  4200. case Variant::CALLABLE:
  4201. case Variant::FLOAT:
  4202. case Variant::INT:
  4203. case Variant::NIL:
  4204. case Variant::NODE_PATH:
  4205. case Variant::SIGNAL:
  4206. case Variant::STRING_NAME:
  4207. break;
  4208. // Here for completeness.
  4209. case Variant::DICTIONARY:
  4210. case Variant::VARIANT_MAX:
  4211. break;
  4212. }
  4213. if (error) {
  4214. 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);
  4215. }
  4216. }
  4217. } else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  4218. if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {
  4219. push_error(vformat(R"(Only "String" or "StringName" can be used as index for type "%s", but received "%s".)", base_type.to_string(), index_type.to_string()), p_subscript->index);
  4220. }
  4221. }
  4222. // Check resulting type if possible.
  4223. result_type.builtin_type = Variant::NIL;
  4224. result_type.kind = GDScriptParser::DataType::BUILTIN;
  4225. result_type.type_source = base_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  4226. if (base_type.kind != GDScriptParser::DataType::BUILTIN) {
  4227. base_type.builtin_type = Variant::OBJECT;
  4228. }
  4229. switch (base_type.builtin_type) {
  4230. // Can't index at all.
  4231. case Variant::RID:
  4232. case Variant::BOOL:
  4233. case Variant::CALLABLE:
  4234. case Variant::FLOAT:
  4235. case Variant::INT:
  4236. case Variant::NIL:
  4237. case Variant::NODE_PATH:
  4238. case Variant::SIGNAL:
  4239. case Variant::STRING_NAME:
  4240. result_type.kind = GDScriptParser::DataType::VARIANT;
  4241. push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);
  4242. break;
  4243. // Return int.
  4244. case Variant::PACKED_BYTE_ARRAY:
  4245. case Variant::PACKED_INT32_ARRAY:
  4246. case Variant::PACKED_INT64_ARRAY:
  4247. case Variant::VECTOR2I:
  4248. case Variant::VECTOR3I:
  4249. case Variant::VECTOR4I:
  4250. result_type.builtin_type = Variant::INT;
  4251. break;
  4252. // Return float.
  4253. case Variant::PACKED_FLOAT32_ARRAY:
  4254. case Variant::PACKED_FLOAT64_ARRAY:
  4255. case Variant::VECTOR2:
  4256. case Variant::VECTOR3:
  4257. case Variant::VECTOR4:
  4258. case Variant::QUATERNION:
  4259. result_type.builtin_type = Variant::FLOAT;
  4260. break;
  4261. // Return String.
  4262. case Variant::PACKED_STRING_ARRAY:
  4263. case Variant::STRING:
  4264. result_type.builtin_type = Variant::STRING;
  4265. break;
  4266. // Return Vector2.
  4267. case Variant::PACKED_VECTOR2_ARRAY:
  4268. case Variant::TRANSFORM2D:
  4269. case Variant::RECT2:
  4270. result_type.builtin_type = Variant::VECTOR2;
  4271. break;
  4272. // Return Vector2I.
  4273. case Variant::RECT2I:
  4274. result_type.builtin_type = Variant::VECTOR2I;
  4275. break;
  4276. // Return Vector3.
  4277. case Variant::PACKED_VECTOR3_ARRAY:
  4278. case Variant::AABB:
  4279. case Variant::BASIS:
  4280. result_type.builtin_type = Variant::VECTOR3;
  4281. break;
  4282. // Return Color.
  4283. case Variant::PACKED_COLOR_ARRAY:
  4284. result_type.builtin_type = Variant::COLOR;
  4285. break;
  4286. // Return Vector4.
  4287. case Variant::PACKED_VECTOR4_ARRAY:
  4288. result_type.builtin_type = Variant::VECTOR4;
  4289. break;
  4290. // Depends on the index.
  4291. case Variant::TRANSFORM3D:
  4292. case Variant::PROJECTION:
  4293. case Variant::PLANE:
  4294. case Variant::COLOR:
  4295. case Variant::DICTIONARY:
  4296. case Variant::OBJECT:
  4297. result_type.kind = GDScriptParser::DataType::VARIANT;
  4298. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  4299. break;
  4300. // Can have an element type.
  4301. case Variant::ARRAY:
  4302. if (base_type.has_container_element_type(0)) {
  4303. result_type = base_type.get_container_element_type(0);
  4304. result_type.type_source = base_type.type_source;
  4305. } else {
  4306. result_type.kind = GDScriptParser::DataType::VARIANT;
  4307. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  4308. }
  4309. break;
  4310. // Here for completeness.
  4311. case Variant::VARIANT_MAX:
  4312. break;
  4313. }
  4314. }
  4315. }
  4316. }
  4317. p_subscript->set_datatype(result_type);
  4318. }
  4319. void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op, bool p_is_root) {
  4320. reduce_expression(p_ternary_op->condition);
  4321. reduce_expression(p_ternary_op->true_expr, p_is_root);
  4322. reduce_expression(p_ternary_op->false_expr, p_is_root);
  4323. GDScriptParser::DataType result;
  4324. 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) {
  4325. p_ternary_op->is_constant = true;
  4326. if (p_ternary_op->condition->reduced_value.booleanize()) {
  4327. p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;
  4328. } else {
  4329. p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;
  4330. }
  4331. }
  4332. GDScriptParser::DataType true_type;
  4333. if (p_ternary_op->true_expr) {
  4334. true_type = p_ternary_op->true_expr->get_datatype();
  4335. } else {
  4336. true_type.kind = GDScriptParser::DataType::VARIANT;
  4337. }
  4338. GDScriptParser::DataType false_type;
  4339. if (p_ternary_op->false_expr) {
  4340. false_type = p_ternary_op->false_expr->get_datatype();
  4341. } else {
  4342. false_type.kind = GDScriptParser::DataType::VARIANT;
  4343. }
  4344. if (true_type.is_variant() || false_type.is_variant()) {
  4345. result.kind = GDScriptParser::DataType::VARIANT;
  4346. } else {
  4347. result = true_type;
  4348. if (!is_type_compatible(true_type, false_type)) {
  4349. result = false_type;
  4350. if (!is_type_compatible(false_type, true_type)) {
  4351. result.kind = GDScriptParser::DataType::VARIANT;
  4352. #ifdef DEBUG_ENABLED
  4353. parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);
  4354. #endif
  4355. }
  4356. }
  4357. }
  4358. result.type_source = true_type.is_hard_type() && false_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  4359. p_ternary_op->set_datatype(result);
  4360. }
  4361. void GDScriptAnalyzer::reduce_type_test(GDScriptParser::TypeTestNode *p_type_test) {
  4362. GDScriptParser::DataType result;
  4363. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  4364. result.kind = GDScriptParser::DataType::BUILTIN;
  4365. result.builtin_type = Variant::BOOL;
  4366. p_type_test->set_datatype(result);
  4367. if (!p_type_test->operand || !p_type_test->test_type) {
  4368. return;
  4369. }
  4370. reduce_expression(p_type_test->operand);
  4371. GDScriptParser::DataType operand_type = p_type_test->operand->get_datatype();
  4372. GDScriptParser::DataType test_type = type_from_metatype(resolve_datatype(p_type_test->test_type));
  4373. p_type_test->test_datatype = test_type;
  4374. if (!operand_type.is_set() || !test_type.is_set()) {
  4375. return;
  4376. }
  4377. if (p_type_test->operand->is_constant) {
  4378. p_type_test->is_constant = true;
  4379. p_type_test->reduced_value = false;
  4380. if (!is_type_compatible(test_type, operand_type)) {
  4381. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)", operand_type.to_string(), test_type.to_string()), p_type_test->operand);
  4382. } else if (is_type_compatible(test_type, type_from_variant(p_type_test->operand->reduced_value, p_type_test->operand))) {
  4383. p_type_test->reduced_value = test_type.builtin_type != Variant::OBJECT || !p_type_test->operand->reduced_value.is_null();
  4384. }
  4385. return;
  4386. }
  4387. if (!is_type_compatible(test_type, operand_type) && !is_type_compatible(operand_type, test_type)) {
  4388. if (operand_type.is_hard_type()) {
  4389. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)", operand_type.to_string(), test_type.to_string()), p_type_test->operand);
  4390. } else {
  4391. downgrade_node_type_source(p_type_test->operand);
  4392. }
  4393. }
  4394. }
  4395. void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {
  4396. reduce_expression(p_unary_op->operand);
  4397. GDScriptParser::DataType result;
  4398. if (p_unary_op->operand == nullptr) {
  4399. result.kind = GDScriptParser::DataType::VARIANT;
  4400. p_unary_op->set_datatype(result);
  4401. return;
  4402. }
  4403. GDScriptParser::DataType operand_type = p_unary_op->operand->get_datatype();
  4404. if (p_unary_op->operand->is_constant) {
  4405. p_unary_op->is_constant = true;
  4406. p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());
  4407. result = type_from_variant(p_unary_op->reduced_value, p_unary_op);
  4408. }
  4409. if (operand_type.is_variant()) {
  4410. result.kind = GDScriptParser::DataType::VARIANT;
  4411. mark_node_unsafe(p_unary_op);
  4412. } else {
  4413. bool valid = false;
  4414. result = get_operation_type(p_unary_op->variant_op, operand_type, valid, p_unary_op);
  4415. if (!valid) {
  4416. 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);
  4417. }
  4418. }
  4419. p_unary_op->set_datatype(result);
  4420. }
  4421. Variant GDScriptAnalyzer::make_expression_reduced_value(GDScriptParser::ExpressionNode *p_expression, bool &is_reduced) {
  4422. Variant value;
  4423. if (p_expression == nullptr) {
  4424. return value;
  4425. }
  4426. if (p_expression->is_constant) {
  4427. is_reduced = true;
  4428. value = p_expression->reduced_value;
  4429. } else if (p_expression->type == GDScriptParser::Node::ARRAY) {
  4430. value = make_array_reduced_value(static_cast<GDScriptParser::ArrayNode *>(p_expression), is_reduced);
  4431. } else if (p_expression->type == GDScriptParser::Node::DICTIONARY) {
  4432. value = make_dictionary_reduced_value(static_cast<GDScriptParser::DictionaryNode *>(p_expression), is_reduced);
  4433. } else if (p_expression->type == GDScriptParser::Node::SUBSCRIPT) {
  4434. value = make_subscript_reduced_value(static_cast<GDScriptParser::SubscriptNode *>(p_expression), is_reduced);
  4435. }
  4436. return value;
  4437. }
  4438. Variant GDScriptAnalyzer::make_array_reduced_value(GDScriptParser::ArrayNode *p_array, bool &is_reduced) {
  4439. Array array = p_array->get_datatype().has_container_element_type(0) ? make_array_from_element_datatype(p_array->get_datatype().get_container_element_type(0)) : Array();
  4440. array.resize(p_array->elements.size());
  4441. for (int i = 0; i < p_array->elements.size(); i++) {
  4442. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  4443. bool is_element_value_reduced = false;
  4444. Variant element_value = make_expression_reduced_value(element, is_element_value_reduced);
  4445. if (!is_element_value_reduced) {
  4446. return Variant();
  4447. }
  4448. array[i] = element_value;
  4449. }
  4450. array.make_read_only();
  4451. is_reduced = true;
  4452. return array;
  4453. }
  4454. Variant GDScriptAnalyzer::make_dictionary_reduced_value(GDScriptParser::DictionaryNode *p_dictionary, bool &is_reduced) {
  4455. Dictionary dictionary;
  4456. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  4457. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  4458. bool is_element_key_reduced = false;
  4459. Variant element_key = make_expression_reduced_value(element.key, is_element_key_reduced);
  4460. if (!is_element_key_reduced) {
  4461. return Variant();
  4462. }
  4463. bool is_element_value_reduced = false;
  4464. Variant element_value = make_expression_reduced_value(element.value, is_element_value_reduced);
  4465. if (!is_element_value_reduced) {
  4466. return Variant();
  4467. }
  4468. dictionary[element_key] = element_value;
  4469. }
  4470. dictionary.make_read_only();
  4471. is_reduced = true;
  4472. return dictionary;
  4473. }
  4474. Variant GDScriptAnalyzer::make_subscript_reduced_value(GDScriptParser::SubscriptNode *p_subscript, bool &is_reduced) {
  4475. if (p_subscript->base == nullptr || p_subscript->index == nullptr) {
  4476. return Variant();
  4477. }
  4478. bool is_base_value_reduced = false;
  4479. Variant base_value = make_expression_reduced_value(p_subscript->base, is_base_value_reduced);
  4480. if (!is_base_value_reduced) {
  4481. return Variant();
  4482. }
  4483. if (p_subscript->is_attribute) {
  4484. bool is_valid = false;
  4485. Variant value = base_value.get_named(p_subscript->attribute->name, is_valid);
  4486. if (is_valid) {
  4487. is_reduced = true;
  4488. return value;
  4489. } else {
  4490. return Variant();
  4491. }
  4492. } else {
  4493. bool is_index_value_reduced = false;
  4494. Variant index_value = make_expression_reduced_value(p_subscript->index, is_index_value_reduced);
  4495. if (!is_index_value_reduced) {
  4496. return Variant();
  4497. }
  4498. bool is_valid = false;
  4499. Variant value = base_value.get(index_value, &is_valid);
  4500. if (is_valid) {
  4501. is_reduced = true;
  4502. return value;
  4503. } else {
  4504. return Variant();
  4505. }
  4506. }
  4507. }
  4508. Array GDScriptAnalyzer::make_array_from_element_datatype(const GDScriptParser::DataType &p_element_datatype, const GDScriptParser::Node *p_source_node) {
  4509. Array array;
  4510. if (p_element_datatype.builtin_type == Variant::OBJECT) {
  4511. Ref<Script> script_type = p_element_datatype.script_type;
  4512. if (p_element_datatype.kind == GDScriptParser::DataType::CLASS && script_type.is_null()) {
  4513. Error err = OK;
  4514. Ref<GDScript> scr = get_depended_shallow_script(p_element_datatype.script_path, err);
  4515. if (err) {
  4516. push_error(vformat(R"(Error while getting cache for script "%s".)", p_element_datatype.script_path), p_source_node);
  4517. return array;
  4518. }
  4519. script_type.reference_ptr(scr->find_class(p_element_datatype.class_type->fqcn));
  4520. }
  4521. array.set_typed(p_element_datatype.builtin_type, p_element_datatype.native_type, script_type);
  4522. } else {
  4523. array.set_typed(p_element_datatype.builtin_type, StringName(), Variant());
  4524. }
  4525. return array;
  4526. }
  4527. Variant GDScriptAnalyzer::make_variable_default_value(GDScriptParser::VariableNode *p_variable) {
  4528. Variant result = Variant();
  4529. if (p_variable->initializer) {
  4530. bool is_initializer_value_reduced = false;
  4531. Variant initializer_value = make_expression_reduced_value(p_variable->initializer, is_initializer_value_reduced);
  4532. if (is_initializer_value_reduced) {
  4533. result = initializer_value;
  4534. }
  4535. } else {
  4536. GDScriptParser::DataType datatype = p_variable->get_datatype();
  4537. if (datatype.is_hard_type()) {
  4538. if (datatype.kind == GDScriptParser::DataType::BUILTIN && datatype.builtin_type != Variant::OBJECT) {
  4539. if (datatype.builtin_type == Variant::ARRAY && datatype.has_container_element_type(0)) {
  4540. result = make_array_from_element_datatype(datatype.get_container_element_type(0));
  4541. } else {
  4542. VariantInternal::initialize(&result, datatype.builtin_type);
  4543. }
  4544. } else if (datatype.kind == GDScriptParser::DataType::ENUM) {
  4545. result = 0;
  4546. }
  4547. }
  4548. }
  4549. return result;
  4550. }
  4551. GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source) {
  4552. GDScriptParser::DataType result;
  4553. result.is_constant = true;
  4554. result.kind = GDScriptParser::DataType::BUILTIN;
  4555. result.builtin_type = p_value.get_type();
  4556. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.
  4557. if (p_value.get_type() == Variant::ARRAY) {
  4558. const Array &array = p_value;
  4559. if (array.get_typed_script()) {
  4560. result.set_container_element_type(0, type_from_metatype(make_script_meta_type(array.get_typed_script())));
  4561. } else if (array.get_typed_class_name()) {
  4562. result.set_container_element_type(0, type_from_metatype(make_native_meta_type(array.get_typed_class_name())));
  4563. } else if (array.get_typed_builtin() != Variant::NIL) {
  4564. result.set_container_element_type(0, type_from_metatype(make_builtin_meta_type((Variant::Type)array.get_typed_builtin())));
  4565. }
  4566. } else if (p_value.get_type() == Variant::OBJECT) {
  4567. // Object is treated as a native type, not a builtin type.
  4568. result.kind = GDScriptParser::DataType::NATIVE;
  4569. Object *obj = p_value;
  4570. if (!obj) {
  4571. return GDScriptParser::DataType();
  4572. }
  4573. result.native_type = obj->get_class_name();
  4574. Ref<Script> scr = p_value; // Check if value is a script itself.
  4575. if (scr.is_valid()) {
  4576. result.is_meta_type = true;
  4577. } else {
  4578. result.is_meta_type = false;
  4579. scr = obj->get_script();
  4580. }
  4581. if (scr.is_valid()) {
  4582. Ref<GDScript> gds = scr;
  4583. if (gds.is_valid()) {
  4584. // This might be an inner class, so we want to get the parser for the root.
  4585. // But still get the inner class from that tree.
  4586. String script_path = gds->get_script_path();
  4587. Ref<GDScriptParserRef> ref = parser->get_depended_parser_for(script_path);
  4588. if (ref.is_null()) {
  4589. push_error(vformat(R"(Could not find script "%s".)", script_path), p_source);
  4590. GDScriptParser::DataType error_type;
  4591. error_type.kind = GDScriptParser::DataType::VARIANT;
  4592. return error_type;
  4593. }
  4594. Error err = ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  4595. GDScriptParser::ClassNode *found = nullptr;
  4596. if (err == OK) {
  4597. found = ref->get_parser()->find_class(gds->fully_qualified_name);
  4598. if (found != nullptr) {
  4599. err = resolve_class_inheritance(found, p_source);
  4600. }
  4601. }
  4602. if (err || found == nullptr) {
  4603. push_error(vformat(R"(Could not resolve script "%s".)", script_path), p_source);
  4604. GDScriptParser::DataType error_type;
  4605. error_type.kind = GDScriptParser::DataType::VARIANT;
  4606. return error_type;
  4607. }
  4608. result.kind = GDScriptParser::DataType::CLASS;
  4609. result.native_type = found->get_datatype().native_type;
  4610. result.class_type = found;
  4611. result.script_path = ref->get_parser()->script_path;
  4612. } else {
  4613. result.kind = GDScriptParser::DataType::SCRIPT;
  4614. result.native_type = scr->get_instance_base_type();
  4615. result.script_path = scr->get_path();
  4616. }
  4617. result.script_type = scr;
  4618. } else {
  4619. result.kind = GDScriptParser::DataType::NATIVE;
  4620. if (result.native_type == GDScriptNativeClass::get_class_static()) {
  4621. result.is_meta_type = true;
  4622. }
  4623. }
  4624. }
  4625. return result;
  4626. }
  4627. GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) {
  4628. GDScriptParser::DataType result = p_meta_type;
  4629. result.is_meta_type = false;
  4630. result.is_pseudo_type = false;
  4631. if (p_meta_type.kind == GDScriptParser::DataType::ENUM) {
  4632. result.builtin_type = Variant::INT;
  4633. } else {
  4634. result.is_constant = false;
  4635. }
  4636. return result;
  4637. }
  4638. GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property, bool p_is_arg, bool p_is_readonly) const {
  4639. GDScriptParser::DataType result;
  4640. result.is_read_only = p_is_readonly;
  4641. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  4642. if (p_property.type == Variant::NIL && (p_is_arg || (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) {
  4643. // Variant
  4644. result.kind = GDScriptParser::DataType::VARIANT;
  4645. return result;
  4646. }
  4647. result.builtin_type = p_property.type;
  4648. if (p_property.type == Variant::OBJECT) {
  4649. if (ScriptServer::is_global_class(p_property.class_name)) {
  4650. result.kind = GDScriptParser::DataType::SCRIPT;
  4651. result.script_path = ScriptServer::get_global_class_path(p_property.class_name);
  4652. result.native_type = ScriptServer::get_global_class_native_base(p_property.class_name);
  4653. Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(p_property.class_name));
  4654. if (scr.is_valid()) {
  4655. result.script_type = scr;
  4656. }
  4657. } else {
  4658. result.kind = GDScriptParser::DataType::NATIVE;
  4659. result.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;
  4660. }
  4661. } else {
  4662. result.kind = GDScriptParser::DataType::BUILTIN;
  4663. result.builtin_type = p_property.type;
  4664. if (p_property.type == Variant::ARRAY && p_property.hint == PROPERTY_HINT_ARRAY_TYPE) {
  4665. // Check element type.
  4666. StringName elem_type_name = p_property.hint_string;
  4667. GDScriptParser::DataType elem_type;
  4668. elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  4669. Variant::Type elem_builtin_type = GDScriptParser::get_builtin_type(elem_type_name);
  4670. if (elem_builtin_type < Variant::VARIANT_MAX) {
  4671. // Builtin type.
  4672. elem_type.kind = GDScriptParser::DataType::BUILTIN;
  4673. elem_type.builtin_type = elem_builtin_type;
  4674. } else if (class_exists(elem_type_name)) {
  4675. elem_type.kind = GDScriptParser::DataType::NATIVE;
  4676. elem_type.builtin_type = Variant::OBJECT;
  4677. elem_type.native_type = elem_type_name;
  4678. } else if (ScriptServer::is_global_class(elem_type_name)) {
  4679. // Just load this as it shouldn't be a GDScript.
  4680. Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(elem_type_name));
  4681. elem_type.kind = GDScriptParser::DataType::SCRIPT;
  4682. elem_type.builtin_type = Variant::OBJECT;
  4683. elem_type.native_type = script->get_instance_base_type();
  4684. elem_type.script_type = script;
  4685. } else {
  4686. ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed array.");
  4687. }
  4688. elem_type.is_constant = false;
  4689. result.set_container_element_type(0, elem_type);
  4690. } else if (p_property.type == Variant::INT) {
  4691. // Check if it's enum.
  4692. if ((p_property.usage & PROPERTY_USAGE_CLASS_IS_ENUM) && p_property.class_name != StringName()) {
  4693. if (CoreConstants::is_global_enum(p_property.class_name)) {
  4694. result = make_global_enum_type(p_property.class_name, StringName(), false);
  4695. result.is_constant = false;
  4696. } else {
  4697. Vector<String> names = String(p_property.class_name).split(ENUM_SEPARATOR);
  4698. if (names.size() == 2) {
  4699. result = make_native_enum_type(names[1], names[0], false);
  4700. result.is_constant = false;
  4701. }
  4702. }
  4703. }
  4704. // PROPERTY_USAGE_CLASS_IS_BITFIELD: BitField[T] isn't supported (yet?), use plain int.
  4705. }
  4706. }
  4707. return result;
  4708. }
  4709. 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, BitField<MethodFlags> &r_method_flags, StringName *r_native_class) {
  4710. r_method_flags = METHOD_FLAGS_DEFAULT;
  4711. r_default_arg_count = 0;
  4712. if (r_native_class) {
  4713. *r_native_class = StringName();
  4714. }
  4715. StringName function_name = p_function;
  4716. bool was_enum = false;
  4717. if (p_base_type.kind == GDScriptParser::DataType::ENUM) {
  4718. was_enum = true;
  4719. if (p_base_type.is_meta_type) {
  4720. // Enum type can be treated as a dictionary value.
  4721. p_base_type.kind = GDScriptParser::DataType::BUILTIN;
  4722. p_base_type.is_meta_type = false;
  4723. } else {
  4724. push_error("Cannot call function on enum value.", p_source);
  4725. return false;
  4726. }
  4727. }
  4728. if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {
  4729. // Construct a base type to get methods.
  4730. Callable::CallError err;
  4731. Variant dummy;
  4732. Variant::construct(p_base_type.builtin_type, dummy, nullptr, 0, err);
  4733. if (err.error != Callable::CallError::CALL_OK) {
  4734. ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");
  4735. }
  4736. List<MethodInfo> methods;
  4737. dummy.get_method_list(&methods);
  4738. for (const MethodInfo &E : methods) {
  4739. if (E.name == p_function) {
  4740. function_signature_from_info(E, r_return_type, r_par_types, r_default_arg_count, r_method_flags);
  4741. // Cannot use non-const methods on enums.
  4742. if (!r_method_flags.has_flag(METHOD_FLAG_STATIC) && was_enum && !(E.flags & METHOD_FLAG_CONST)) {
  4743. push_error(vformat(R"*(Cannot call non-const Dictionary function "%s()" on enum "%s".)*", p_function, p_base_type.enum_type), p_source);
  4744. }
  4745. return true;
  4746. }
  4747. }
  4748. return false;
  4749. }
  4750. StringName base_native = p_base_type.native_type;
  4751. if (base_native != StringName()) {
  4752. // Empty native class might happen in some Script implementations.
  4753. // Just ignore it.
  4754. if (!class_exists(base_native)) {
  4755. push_error(vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native), p_source);
  4756. return false;
  4757. } else if (p_is_constructor && ClassDB::is_abstract(base_native)) {
  4758. if (p_base_type.kind == GDScriptParser::DataType::CLASS) {
  4759. push_error(vformat(R"(Class "%s" cannot be constructed as it is based on abstract native class "%s".)", p_base_type.class_type->fqcn.get_file(), base_native), p_source);
  4760. } else if (p_base_type.kind == GDScriptParser::DataType::SCRIPT) {
  4761. push_error(vformat(R"(Script "%s" cannot be constructed as it is based on abstract native class "%s".)", p_base_type.script_path.get_file(), base_native), p_source);
  4762. } else {
  4763. push_error(vformat(R"(Native class "%s" cannot be constructed as it is abstract.)", base_native), p_source);
  4764. }
  4765. return false;
  4766. }
  4767. }
  4768. if (p_is_constructor) {
  4769. function_name = GDScriptLanguage::get_singleton()->strings._init;
  4770. r_method_flags.set_flag(METHOD_FLAG_STATIC);
  4771. }
  4772. GDScriptParser::ClassNode *base_class = p_base_type.class_type;
  4773. GDScriptParser::FunctionNode *found_function = nullptr;
  4774. while (found_function == nullptr && base_class != nullptr) {
  4775. if (base_class->has_member(function_name)) {
  4776. if (base_class->get_member(function_name).type != GDScriptParser::ClassNode::Member::FUNCTION) {
  4777. // TODO: If this is Callable it can have a better error message.
  4778. push_error(vformat(R"(Member "%s" is not a function.)", function_name), p_source);
  4779. return false;
  4780. }
  4781. resolve_class_member(base_class, function_name, p_source);
  4782. found_function = base_class->get_member(function_name).function;
  4783. }
  4784. resolve_class_inheritance(base_class, p_source);
  4785. base_class = base_class->base_type.class_type;
  4786. }
  4787. if (found_function != nullptr) {
  4788. if (p_is_constructor || found_function->is_static) {
  4789. r_method_flags.set_flag(METHOD_FLAG_STATIC);
  4790. }
  4791. for (int i = 0; i < found_function->parameters.size(); i++) {
  4792. r_par_types.push_back(found_function->parameters[i]->get_datatype());
  4793. if (found_function->parameters[i]->initializer != nullptr) {
  4794. r_default_arg_count++;
  4795. }
  4796. }
  4797. r_return_type = p_is_constructor ? p_base_type : found_function->get_datatype();
  4798. r_return_type.is_meta_type = false;
  4799. r_return_type.is_coroutine = found_function->is_coroutine;
  4800. return true;
  4801. }
  4802. Ref<Script> base_script = p_base_type.script_type;
  4803. while (base_script.is_valid() && base_script->has_method(function_name)) {
  4804. MethodInfo info = base_script->get_method_info(function_name);
  4805. if (!(info == MethodInfo())) {
  4806. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_method_flags);
  4807. }
  4808. base_script = base_script->get_base_script();
  4809. }
  4810. // If the base is a script, it might be trying to access members of the Script class itself.
  4811. if (p_base_type.is_meta_type && !p_is_constructor && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {
  4812. MethodInfo info;
  4813. StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());
  4814. if (ClassDB::get_method_info(script_class, function_name, &info)) {
  4815. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_method_flags);
  4816. }
  4817. }
  4818. if (p_is_constructor) {
  4819. // Native types always have a default constructor.
  4820. r_return_type = p_base_type;
  4821. r_return_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  4822. r_return_type.is_meta_type = false;
  4823. return true;
  4824. }
  4825. MethodInfo info;
  4826. if (ClassDB::get_method_info(base_native, function_name, &info)) {
  4827. bool valid = function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_method_flags);
  4828. if (valid && Engine::get_singleton()->has_singleton(base_native)) {
  4829. r_method_flags.set_flag(METHOD_FLAG_STATIC);
  4830. }
  4831. #ifdef DEBUG_ENABLED
  4832. MethodBind *native_method = ClassDB::get_method(base_native, function_name);
  4833. if (native_method && r_native_class) {
  4834. *r_native_class = native_method->get_instance_class();
  4835. }
  4836. #endif
  4837. return valid;
  4838. }
  4839. return false;
  4840. }
  4841. 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, BitField<MethodFlags> &r_method_flags) {
  4842. r_return_type = type_from_property(p_info.return_val);
  4843. r_default_arg_count = p_info.default_arguments.size();
  4844. r_method_flags = p_info.flags;
  4845. for (const PropertyInfo &E : p_info.arguments) {
  4846. r_par_types.push_back(type_from_property(E, true));
  4847. }
  4848. return true;
  4849. }
  4850. void GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {
  4851. List<GDScriptParser::DataType> arg_types;
  4852. for (const PropertyInfo &E : p_method.arguments) {
  4853. arg_types.push_back(type_from_property(E, true));
  4854. }
  4855. validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);
  4856. }
  4857. void GDScriptAnalyzer::validate_call_arg(const List<GDScriptParser::DataType> &p_par_types, int p_default_args_count, bool p_is_vararg, const GDScriptParser::CallNode *p_call) {
  4858. if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {
  4859. 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);
  4860. }
  4861. if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {
  4862. 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()]);
  4863. }
  4864. List<GDScriptParser::DataType>::ConstIterator par_itr = p_par_types.begin();
  4865. for (int i = 0; i < p_call->arguments.size(); ++par_itr, ++i) {
  4866. if (i >= p_par_types.size()) {
  4867. // Already on vararg place.
  4868. break;
  4869. }
  4870. GDScriptParser::DataType par_type = *par_itr;
  4871. if (par_type.is_hard_type() && p_call->arguments[i]->is_constant) {
  4872. update_const_expression_builtin_type(p_call->arguments[i], par_type, "pass");
  4873. }
  4874. GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
  4875. if (arg_type.is_variant() || !arg_type.is_hard_type()) {
  4876. #ifdef DEBUG_ENABLED
  4877. // Argument can be anything, so this is unsafe (unless the parameter is a hard variant).
  4878. if (!(par_type.is_hard_type() && par_type.is_variant())) {
  4879. mark_node_unsafe(p_call->arguments[i]);
  4880. parser->push_warning(p_call->arguments[i], GDScriptWarning::UNSAFE_CALL_ARGUMENT, itos(i + 1), "function", p_call->function_name, par_type.to_string(), arg_type.to_string_strict());
  4881. }
  4882. #endif
  4883. } else if (par_type.is_hard_type() && !is_type_compatible(par_type, arg_type, true)) {
  4884. if (!is_type_compatible(arg_type, par_type)) {
  4885. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be "%s" but is "%s".)*",
  4886. p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),
  4887. p_call->arguments[i]);
  4888. #ifdef DEBUG_ENABLED
  4889. } else {
  4890. // Supertypes are acceptable for dynamic compliance, but it's unsafe.
  4891. mark_node_unsafe(p_call);
  4892. parser->push_warning(p_call->arguments[i], GDScriptWarning::UNSAFE_CALL_ARGUMENT, itos(i + 1), "function", p_call->function_name, par_type.to_string(), arg_type.to_string_strict());
  4893. #endif
  4894. }
  4895. #ifdef DEBUG_ENABLED
  4896. } else if (par_type.kind == GDScriptParser::DataType::BUILTIN && par_type.builtin_type == Variant::INT && arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == Variant::FLOAT) {
  4897. parser->push_warning(p_call->arguments[i], GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  4898. #endif
  4899. }
  4900. }
  4901. }
  4902. #ifdef DEBUG_ENABLED
  4903. void GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_identifier, const String &p_context, const bool p_in_local_scope) {
  4904. const StringName &name = p_identifier->name;
  4905. GDScriptParser::DataType base = parser->current_class->get_datatype();
  4906. GDScriptParser::ClassNode *base_class = base.class_type;
  4907. {
  4908. List<MethodInfo> gdscript_funcs;
  4909. GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);
  4910. for (MethodInfo &info : gdscript_funcs) {
  4911. if (info.name == name) {
  4912. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");
  4913. return;
  4914. }
  4915. }
  4916. if (Variant::has_utility_function(name)) {
  4917. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");
  4918. return;
  4919. } else if (ClassDB::class_exists(name)) {
  4920. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "native class");
  4921. return;
  4922. } else if (ScriptServer::is_global_class(name)) {
  4923. String class_path = ScriptServer::get_global_class_path(name).get_file();
  4924. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, vformat(R"(global class defined in "%s")", class_path));
  4925. return;
  4926. } else if (GDScriptParser::get_builtin_type(name) < Variant::VARIANT_MAX) {
  4927. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in type");
  4928. return;
  4929. }
  4930. }
  4931. if (p_in_local_scope) {
  4932. while (base_class != nullptr) {
  4933. if (base_class->has_member(name)) {
  4934. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE, p_context, p_identifier->name, base_class->get_member(name).get_type_name(), itos(base_class->get_member(name).get_line()));
  4935. return;
  4936. }
  4937. base_class = base_class->base_type.class_type;
  4938. }
  4939. }
  4940. StringName parent = base.native_type;
  4941. while (parent != StringName()) {
  4942. ERR_FAIL_COND_MSG(!class_exists(parent), "Non-existent native base class.");
  4943. if (ClassDB::has_method(parent, name, true)) {
  4944. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "method", parent);
  4945. return;
  4946. } else if (ClassDB::has_signal(parent, name, true)) {
  4947. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "signal", parent);
  4948. return;
  4949. } else if (ClassDB::has_property(parent, name, true)) {
  4950. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "property", parent);
  4951. return;
  4952. } else if (ClassDB::has_integer_constant(parent, name, true)) {
  4953. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "constant", parent);
  4954. return;
  4955. } else if (ClassDB::has_enum(parent, name, true)) {
  4956. parser->push_warning(p_identifier, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_identifier->name, "enum", parent);
  4957. return;
  4958. }
  4959. parent = ClassDB::get_parent_class(parent);
  4960. }
  4961. }
  4962. #endif
  4963. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source) {
  4964. // Unary version.
  4965. GDScriptParser::DataType nil_type;
  4966. nil_type.builtin_type = Variant::NIL;
  4967. nil_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  4968. return get_operation_type(p_operation, p_a, nil_type, r_valid, p_source);
  4969. }
  4970. 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) {
  4971. if (p_operation == Variant::OP_AND || p_operation == Variant::OP_OR) {
  4972. // Those work for any type of argument and always return a boolean.
  4973. // They don't use the Variant operator since they have short-circuit semantics.
  4974. r_valid = true;
  4975. GDScriptParser::DataType result;
  4976. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  4977. result.kind = GDScriptParser::DataType::BUILTIN;
  4978. result.builtin_type = Variant::BOOL;
  4979. return result;
  4980. }
  4981. Variant::Type a_type = p_a.builtin_type;
  4982. Variant::Type b_type = p_b.builtin_type;
  4983. if (p_a.kind == GDScriptParser::DataType::ENUM) {
  4984. if (p_a.is_meta_type) {
  4985. a_type = Variant::DICTIONARY;
  4986. } else {
  4987. a_type = Variant::INT;
  4988. }
  4989. }
  4990. if (p_b.kind == GDScriptParser::DataType::ENUM) {
  4991. if (p_b.is_meta_type) {
  4992. b_type = Variant::DICTIONARY;
  4993. } else {
  4994. b_type = Variant::INT;
  4995. }
  4996. }
  4997. GDScriptParser::DataType result;
  4998. bool hard_operation = p_a.is_hard_type() && p_b.is_hard_type();
  4999. if (p_operation == Variant::OP_ADD && a_type == Variant::ARRAY && b_type == Variant::ARRAY) {
  5000. if (p_a.has_container_element_type(0) && p_b.has_container_element_type(0) && p_a.get_container_element_type(0) == p_b.get_container_element_type(0)) {
  5001. r_valid = true;
  5002. result = p_a;
  5003. result.type_source = hard_operation ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  5004. return result;
  5005. }
  5006. }
  5007. Variant::ValidatedOperatorEvaluator op_eval = Variant::get_validated_operator_evaluator(p_operation, a_type, b_type);
  5008. bool validated = op_eval != nullptr;
  5009. if (validated) {
  5010. r_valid = true;
  5011. result.type_source = hard_operation ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  5012. result.kind = GDScriptParser::DataType::BUILTIN;
  5013. result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type);
  5014. } else {
  5015. r_valid = !hard_operation;
  5016. result.kind = GDScriptParser::DataType::VARIANT;
  5017. }
  5018. return result;
  5019. }
  5020. 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) {
  5021. #ifdef DEBUG_ENABLED
  5022. if (p_source_node) {
  5023. if (p_target.kind == GDScriptParser::DataType::ENUM) {
  5024. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {
  5025. parser->push_warning(p_source_node, GDScriptWarning::INT_AS_ENUM_WITHOUT_CAST);
  5026. }
  5027. }
  5028. }
  5029. #endif
  5030. return check_type_compatibility(p_target, p_source, p_allow_implicit_conversion, p_source_node);
  5031. }
  5032. // TODO: Add safe/unsafe return variable (for variant cases)
  5033. bool GDScriptAnalyzer::check_type_compatibility(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion, const GDScriptParser::Node *p_source_node) {
  5034. // These return "true" so it doesn't affect users negatively.
  5035. ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");
  5036. ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");
  5037. if (p_target.kind == GDScriptParser::DataType::VARIANT) {
  5038. // Variant can receive anything.
  5039. return true;
  5040. }
  5041. if (p_source.kind == GDScriptParser::DataType::VARIANT) {
  5042. // TODO: This is acceptable but unsafe. Make sure unsafe line is set.
  5043. return true;
  5044. }
  5045. if (p_target.kind == GDScriptParser::DataType::BUILTIN) {
  5046. bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;
  5047. if (!valid && p_allow_implicit_conversion) {
  5048. valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);
  5049. }
  5050. if (!valid && p_target.builtin_type == Variant::INT && p_source.kind == GDScriptParser::DataType::ENUM && !p_source.is_meta_type) {
  5051. // Enum value is also integer.
  5052. valid = true;
  5053. }
  5054. if (valid && p_target.builtin_type == Variant::ARRAY && p_source.builtin_type == Variant::ARRAY) {
  5055. // Check the element type.
  5056. if (p_target.has_container_element_type(0) && p_source.has_container_element_type(0)) {
  5057. valid = p_target.get_container_element_type(0) == p_source.get_container_element_type(0);
  5058. }
  5059. }
  5060. return valid;
  5061. }
  5062. if (p_target.kind == GDScriptParser::DataType::ENUM) {
  5063. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {
  5064. return true;
  5065. }
  5066. if (p_source.kind == GDScriptParser::DataType::ENUM) {
  5067. if (p_source.native_type == p_target.native_type) {
  5068. return true;
  5069. }
  5070. }
  5071. return false;
  5072. }
  5073. // From here on the target type is an object, so we have to test polymorphism.
  5074. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {
  5075. // null is acceptable in object.
  5076. return true;
  5077. }
  5078. StringName src_native;
  5079. Ref<Script> src_script;
  5080. const GDScriptParser::ClassNode *src_class = nullptr;
  5081. switch (p_source.kind) {
  5082. case GDScriptParser::DataType::NATIVE:
  5083. if (p_target.kind != GDScriptParser::DataType::NATIVE) {
  5084. // Non-native class cannot be supertype of native.
  5085. return false;
  5086. }
  5087. if (p_source.is_meta_type) {
  5088. src_native = GDScriptNativeClass::get_class_static();
  5089. } else {
  5090. src_native = p_source.native_type;
  5091. }
  5092. break;
  5093. case GDScriptParser::DataType::SCRIPT:
  5094. if (p_target.kind == GDScriptParser::DataType::CLASS) {
  5095. // A script type cannot be a subtype of a GDScript class.
  5096. return false;
  5097. }
  5098. if (p_source.script_type.is_null()) {
  5099. return false;
  5100. }
  5101. if (p_source.is_meta_type) {
  5102. src_native = p_source.script_type->get_class_name();
  5103. } else {
  5104. src_script = p_source.script_type;
  5105. src_native = src_script->get_instance_base_type();
  5106. }
  5107. break;
  5108. case GDScriptParser::DataType::CLASS:
  5109. if (p_source.is_meta_type) {
  5110. src_native = GDScript::get_class_static();
  5111. } else {
  5112. src_class = p_source.class_type;
  5113. const GDScriptParser::ClassNode *base = src_class;
  5114. while (base->base_type.kind == GDScriptParser::DataType::CLASS) {
  5115. base = base->base_type.class_type;
  5116. }
  5117. src_native = base->base_type.native_type;
  5118. src_script = base->base_type.script_type;
  5119. }
  5120. break;
  5121. case GDScriptParser::DataType::VARIANT:
  5122. case GDScriptParser::DataType::BUILTIN:
  5123. case GDScriptParser::DataType::ENUM:
  5124. case GDScriptParser::DataType::RESOLVING:
  5125. case GDScriptParser::DataType::UNRESOLVED:
  5126. break; // Already solved before.
  5127. }
  5128. switch (p_target.kind) {
  5129. case GDScriptParser::DataType::NATIVE: {
  5130. if (p_target.is_meta_type) {
  5131. return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());
  5132. }
  5133. return ClassDB::is_parent_class(src_native, p_target.native_type);
  5134. }
  5135. case GDScriptParser::DataType::SCRIPT:
  5136. if (p_target.is_meta_type) {
  5137. return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());
  5138. }
  5139. while (src_script.is_valid()) {
  5140. if (src_script == p_target.script_type) {
  5141. return true;
  5142. }
  5143. src_script = src_script->get_base_script();
  5144. }
  5145. return false;
  5146. case GDScriptParser::DataType::CLASS:
  5147. if (p_target.is_meta_type) {
  5148. return ClassDB::is_parent_class(src_native, GDScript::get_class_static());
  5149. }
  5150. while (src_class != nullptr) {
  5151. if (src_class == p_target.class_type || src_class->fqcn == p_target.class_type->fqcn) {
  5152. return true;
  5153. }
  5154. src_class = src_class->base_type.class_type;
  5155. }
  5156. return false;
  5157. case GDScriptParser::DataType::VARIANT:
  5158. case GDScriptParser::DataType::BUILTIN:
  5159. case GDScriptParser::DataType::ENUM:
  5160. case GDScriptParser::DataType::RESOLVING:
  5161. case GDScriptParser::DataType::UNRESOLVED:
  5162. break; // Already solved before.
  5163. }
  5164. return false;
  5165. }
  5166. void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {
  5167. mark_node_unsafe(p_origin);
  5168. parser->push_error(p_message, p_origin);
  5169. }
  5170. void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {
  5171. #ifdef DEBUG_ENABLED
  5172. if (p_node == nullptr) {
  5173. return;
  5174. }
  5175. for (int i = p_node->start_line; i <= p_node->end_line; i++) {
  5176. parser->unsafe_lines.insert(i);
  5177. }
  5178. #endif
  5179. }
  5180. void GDScriptAnalyzer::downgrade_node_type_source(GDScriptParser::Node *p_node) {
  5181. GDScriptParser::IdentifierNode *identifier = nullptr;
  5182. if (p_node->type == GDScriptParser::Node::IDENTIFIER) {
  5183. identifier = static_cast<GDScriptParser::IdentifierNode *>(p_node);
  5184. } else if (p_node->type == GDScriptParser::Node::SUBSCRIPT) {
  5185. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_node);
  5186. if (subscript->is_attribute) {
  5187. identifier = subscript->attribute;
  5188. }
  5189. }
  5190. if (identifier == nullptr) {
  5191. return;
  5192. }
  5193. GDScriptParser::Node *source = nullptr;
  5194. switch (identifier->source) {
  5195. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {
  5196. source = identifier->variable_source;
  5197. } break;
  5198. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER: {
  5199. source = identifier->parameter_source;
  5200. } break;
  5201. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {
  5202. source = identifier->variable_source;
  5203. } break;
  5204. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {
  5205. source = identifier->bind_source;
  5206. } break;
  5207. default:
  5208. break;
  5209. }
  5210. if (source == nullptr) {
  5211. return;
  5212. }
  5213. GDScriptParser::DataType datatype;
  5214. datatype.kind = GDScriptParser::DataType::VARIANT;
  5215. source->set_datatype(datatype);
  5216. }
  5217. void GDScriptAnalyzer::mark_lambda_use_self() {
  5218. GDScriptParser::LambdaNode *lambda = current_lambda;
  5219. while (lambda != nullptr) {
  5220. lambda->use_self = true;
  5221. lambda = lambda->parent_lambda;
  5222. }
  5223. }
  5224. void GDScriptAnalyzer::resolve_pending_lambda_bodies() {
  5225. if (pending_body_resolution_lambdas.is_empty()) {
  5226. return;
  5227. }
  5228. GDScriptParser::LambdaNode *previous_lambda = current_lambda;
  5229. bool previous_static_context = static_context;
  5230. List<GDScriptParser::LambdaNode *> lambdas = pending_body_resolution_lambdas;
  5231. pending_body_resolution_lambdas.clear();
  5232. for (GDScriptParser::LambdaNode *lambda : lambdas) {
  5233. current_lambda = lambda;
  5234. static_context = lambda->function->is_static;
  5235. resolve_function_body(lambda->function, true);
  5236. int captures_amount = lambda->captures.size();
  5237. if (captures_amount > 0) {
  5238. // Create space for lambda parameters.
  5239. // At the beginning to not mess with optional parameters.
  5240. int param_count = lambda->function->parameters.size();
  5241. lambda->function->parameters.resize(param_count + captures_amount);
  5242. for (int i = param_count - 1; i >= 0; i--) {
  5243. lambda->function->parameters.write[i + captures_amount] = lambda->function->parameters[i];
  5244. lambda->function->parameters_indices[lambda->function->parameters[i]->identifier->name] = i + captures_amount;
  5245. }
  5246. // Add captures as extra parameters at the beginning.
  5247. for (int i = 0; i < lambda->captures.size(); i++) {
  5248. GDScriptParser::IdentifierNode *capture = lambda->captures[i];
  5249. GDScriptParser::ParameterNode *capture_param = parser->alloc_node<GDScriptParser::ParameterNode>();
  5250. capture_param->identifier = capture;
  5251. capture_param->usages = capture->usages;
  5252. capture_param->set_datatype(capture->get_datatype());
  5253. lambda->function->parameters.write[i] = capture_param;
  5254. lambda->function->parameters_indices[capture->name] = i;
  5255. }
  5256. }
  5257. }
  5258. current_lambda = previous_lambda;
  5259. static_context = previous_static_context;
  5260. }
  5261. bool GDScriptAnalyzer::class_exists(const StringName &p_class) const {
  5262. return ClassDB::class_exists(p_class) && ClassDB::is_class_exposed(p_class);
  5263. }
  5264. Error GDScriptAnalyzer::resolve_inheritance() {
  5265. return resolve_class_inheritance(parser->head, true);
  5266. }
  5267. Error GDScriptAnalyzer::resolve_interface() {
  5268. resolve_class_interface(parser->head, true);
  5269. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  5270. }
  5271. Error GDScriptAnalyzer::resolve_body() {
  5272. resolve_class_body(parser->head, true);
  5273. #ifdef DEBUG_ENABLED
  5274. // Apply here, after all `@warning_ignore`s have been resolved and applied.
  5275. parser->apply_pending_warnings();
  5276. #endif
  5277. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  5278. }
  5279. Error GDScriptAnalyzer::resolve_dependencies() {
  5280. for (KeyValue<String, Ref<GDScriptParserRef>> &K : parser->depended_parsers) {
  5281. if (K.value.is_null()) {
  5282. return ERR_PARSE_ERROR;
  5283. }
  5284. K.value->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
  5285. }
  5286. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  5287. }
  5288. Error GDScriptAnalyzer::analyze() {
  5289. parser->errors.clear();
  5290. Error err = resolve_inheritance();
  5291. if (err) {
  5292. return err;
  5293. }
  5294. resolve_interface();
  5295. err = resolve_body();
  5296. if (err) {
  5297. return err;
  5298. }
  5299. return resolve_dependencies();
  5300. }
  5301. GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {
  5302. parser = p_parser;
  5303. }