gdscript_analyzer.cpp 261 KB

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