gdscript_parser.cpp 223 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432
  1. /**************************************************************************/
  2. /* gdscript_parser.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_parser.h"
  31. #include "gdscript.h"
  32. #include "gdscript_tokenizer_buffer.h"
  33. #include "core/config/project_settings.h"
  34. #include "core/io/resource_loader.h"
  35. #include "core/math/math_defs.h"
  36. #include "scene/main/multiplayer_api.h"
  37. #ifdef DEBUG_ENABLED
  38. #include "core/string/string_builder.h"
  39. #include "servers/text_server.h"
  40. #endif
  41. #ifdef TOOLS_ENABLED
  42. #include "editor/editor_settings.h"
  43. #endif
  44. // This function is used to determine that a type is "built-in" as opposed to native
  45. // and custom classes. So `Variant::NIL` and `Variant::OBJECT` are excluded:
  46. // `Variant::NIL` - `null` is literal, not a type.
  47. // `Variant::OBJECT` - `Object` should be treated as a class, not as a built-in type.
  48. static HashMap<StringName, Variant::Type> builtin_types;
  49. Variant::Type GDScriptParser::get_builtin_type(const StringName &p_type) {
  50. if (unlikely(builtin_types.is_empty())) {
  51. for (int i = 0; i < Variant::VARIANT_MAX; i++) {
  52. Variant::Type type = (Variant::Type)i;
  53. if (type != Variant::NIL && type != Variant::OBJECT) {
  54. builtin_types[Variant::get_type_name(type)] = type;
  55. }
  56. }
  57. }
  58. if (builtin_types.has(p_type)) {
  59. return builtin_types[p_type];
  60. }
  61. return Variant::VARIANT_MAX;
  62. }
  63. #ifdef TOOLS_ENABLED
  64. HashMap<String, String> GDScriptParser::theme_color_names;
  65. #endif
  66. HashMap<StringName, GDScriptParser::AnnotationInfo> GDScriptParser::valid_annotations;
  67. void GDScriptParser::cleanup() {
  68. builtin_types.clear();
  69. valid_annotations.clear();
  70. }
  71. void GDScriptParser::get_annotation_list(List<MethodInfo> *r_annotations) const {
  72. for (const KeyValue<StringName, AnnotationInfo> &E : valid_annotations) {
  73. r_annotations->push_back(E.value.info);
  74. }
  75. }
  76. bool GDScriptParser::annotation_exists(const String &p_annotation_name) const {
  77. return valid_annotations.has(p_annotation_name);
  78. }
  79. GDScriptParser::GDScriptParser() {
  80. // Register valid annotations.
  81. if (unlikely(valid_annotations.is_empty())) {
  82. // Script annotations.
  83. register_annotation(MethodInfo("@tool"), AnnotationInfo::SCRIPT, &GDScriptParser::tool_annotation);
  84. register_annotation(MethodInfo("@icon", PropertyInfo(Variant::STRING, "icon_path")), AnnotationInfo::SCRIPT, &GDScriptParser::icon_annotation);
  85. register_annotation(MethodInfo("@static_unload"), AnnotationInfo::SCRIPT, &GDScriptParser::static_unload_annotation);
  86. // Onready annotation.
  87. register_annotation(MethodInfo("@onready"), AnnotationInfo::VARIABLE, &GDScriptParser::onready_annotation);
  88. // Export annotations.
  89. register_annotation(MethodInfo("@export"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NONE, Variant::NIL>);
  90. register_annotation(MethodInfo("@export_enum", PropertyInfo(Variant::STRING, "names")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_ENUM, Variant::NIL>, varray(), true);
  91. register_annotation(MethodInfo("@export_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FILE, Variant::STRING>, varray(""), true);
  92. register_annotation(MethodInfo("@export_file_path", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FILE_PATH, Variant::STRING>, varray(""), true);
  93. register_annotation(MethodInfo("@export_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_DIR, Variant::STRING>);
  94. register_annotation(MethodInfo("@export_global_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_FILE, Variant::STRING>, varray(""), true);
  95. register_annotation(MethodInfo("@export_global_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_DIR, Variant::STRING>);
  96. register_annotation(MethodInfo("@export_multiline"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_MULTILINE_TEXT, Variant::STRING>);
  97. register_annotation(MethodInfo("@export_placeholder", PropertyInfo(Variant::STRING, "placeholder")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>);
  98. register_annotation(MethodInfo("@export_range", PropertyInfo(Variant::FLOAT, "min"), PropertyInfo(Variant::FLOAT, "max"), PropertyInfo(Variant::FLOAT, "step"), PropertyInfo(Variant::STRING, "extra_hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_RANGE, Variant::FLOAT>, varray(1.0, ""), true);
  99. register_annotation(MethodInfo("@export_exp_easing", PropertyInfo(Variant::STRING, "hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_EASING, Variant::FLOAT>, varray(""), true);
  100. register_annotation(MethodInfo("@export_color_no_alpha"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_COLOR_NO_ALPHA, Variant::COLOR>);
  101. register_annotation(MethodInfo("@export_node_path", PropertyInfo(Variant::STRING, "type")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NODE_PATH_VALID_TYPES, Variant::NODE_PATH>, varray(""), true);
  102. register_annotation(MethodInfo("@export_flags", PropertyInfo(Variant::STRING, "names")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FLAGS, Variant::INT>, varray(), true);
  103. register_annotation(MethodInfo("@export_flags_2d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_RENDER, Variant::INT>);
  104. register_annotation(MethodInfo("@export_flags_2d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_PHYSICS, Variant::INT>);
  105. register_annotation(MethodInfo("@export_flags_2d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_NAVIGATION, Variant::INT>);
  106. register_annotation(MethodInfo("@export_flags_3d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_RENDER, Variant::INT>);
  107. register_annotation(MethodInfo("@export_flags_3d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_PHYSICS, Variant::INT>);
  108. register_annotation(MethodInfo("@export_flags_3d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_NAVIGATION, Variant::INT>);
  109. register_annotation(MethodInfo("@export_flags_avoidance"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_AVOIDANCE, Variant::INT>);
  110. register_annotation(MethodInfo("@export_storage"), AnnotationInfo::VARIABLE, &GDScriptParser::export_storage_annotation);
  111. register_annotation(MethodInfo("@export_custom", PropertyInfo(Variant::INT, "hint", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CLASS_IS_ENUM, "PropertyHint"), PropertyInfo(Variant::STRING, "hint_string"), PropertyInfo(Variant::INT, "usage", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CLASS_IS_BITFIELD, "PropertyUsageFlags")), AnnotationInfo::VARIABLE, &GDScriptParser::export_custom_annotation, varray(PROPERTY_USAGE_DEFAULT));
  112. register_annotation(MethodInfo("@export_tool_button", PropertyInfo(Variant::STRING, "text"), PropertyInfo(Variant::STRING, "icon")), AnnotationInfo::VARIABLE, &GDScriptParser::export_tool_button_annotation, varray(""));
  113. // Export grouping annotations.
  114. register_annotation(MethodInfo("@export_category", PropertyInfo(Variant::STRING, "name")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_CATEGORY>);
  115. register_annotation(MethodInfo("@export_group", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "prefix")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_GROUP>, varray(""));
  116. register_annotation(MethodInfo("@export_subgroup", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "prefix")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_SUBGROUP>, varray(""));
  117. // Warning annotations.
  118. register_annotation(MethodInfo("@warning_ignore", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STATEMENT, &GDScriptParser::warning_ignore_annotation, varray(), true);
  119. register_annotation(MethodInfo("@warning_ignore_start", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::STANDALONE, &GDScriptParser::warning_ignore_region_annotations, varray(), true);
  120. register_annotation(MethodInfo("@warning_ignore_restore", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::STANDALONE, &GDScriptParser::warning_ignore_region_annotations, varray(), true);
  121. // Networking.
  122. register_annotation(MethodInfo("@rpc", PropertyInfo(Variant::STRING, "mode"), PropertyInfo(Variant::STRING, "sync"), PropertyInfo(Variant::STRING, "transfer_mode"), PropertyInfo(Variant::INT, "transfer_channel")), AnnotationInfo::FUNCTION, &GDScriptParser::rpc_annotation, varray("authority", "call_remote", "unreliable", 0));
  123. }
  124. #ifdef DEBUG_ENABLED
  125. is_ignoring_warnings = !(bool)GLOBAL_GET("debug/gdscript/warnings/enable");
  126. for (int i = 0; i < GDScriptWarning::WARNING_MAX; i++) {
  127. warning_ignore_start_lines[i] = INT_MAX;
  128. }
  129. #endif
  130. #ifdef TOOLS_ENABLED
  131. if (unlikely(theme_color_names.is_empty())) {
  132. // Vectors.
  133. theme_color_names.insert("x", "axis_x_color");
  134. theme_color_names.insert("y", "axis_y_color");
  135. theme_color_names.insert("z", "axis_z_color");
  136. theme_color_names.insert("w", "axis_w_color");
  137. // Color.
  138. theme_color_names.insert("r", "axis_x_color");
  139. theme_color_names.insert("r8", "axis_x_color");
  140. theme_color_names.insert("g", "axis_y_color");
  141. theme_color_names.insert("g8", "axis_y_color");
  142. theme_color_names.insert("b", "axis_z_color");
  143. theme_color_names.insert("b8", "axis_z_color");
  144. theme_color_names.insert("a", "axis_w_color");
  145. theme_color_names.insert("a8", "axis_w_color");
  146. }
  147. #endif
  148. }
  149. GDScriptParser::~GDScriptParser() {
  150. while (list != nullptr) {
  151. Node *element = list;
  152. list = list->next;
  153. memdelete(element);
  154. }
  155. }
  156. void GDScriptParser::clear() {
  157. GDScriptParser tmp;
  158. tmp = *this;
  159. *this = GDScriptParser();
  160. }
  161. void GDScriptParser::push_error(const String &p_message, const Node *p_origin) {
  162. // TODO: Improve error reporting by pointing at source code.
  163. // TODO: Errors might point at more than one place at once (e.g. show previous declaration).
  164. panic_mode = true;
  165. // TODO: Improve positional information.
  166. if (p_origin == nullptr) {
  167. errors.push_back({ p_message, previous.start_line, previous.start_column });
  168. } else {
  169. errors.push_back({ p_message, p_origin->start_line, p_origin->start_column });
  170. }
  171. }
  172. #ifdef DEBUG_ENABLED
  173. void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_code, const Vector<String> &p_symbols) {
  174. ERR_FAIL_NULL(p_source);
  175. ERR_FAIL_INDEX(p_code, GDScriptWarning::WARNING_MAX);
  176. if (is_ignoring_warnings) {
  177. return;
  178. }
  179. if (GLOBAL_GET_CACHED(bool, "debug/gdscript/warnings/exclude_addons") && script_path.begins_with("res://addons/")) {
  180. return;
  181. }
  182. GDScriptWarning::WarnLevel warn_level = (GDScriptWarning::WarnLevel)(int)GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(p_code));
  183. if (warn_level == GDScriptWarning::IGNORE) {
  184. return;
  185. }
  186. PendingWarning pw;
  187. pw.source = p_source;
  188. pw.code = p_code;
  189. pw.treated_as_error = warn_level == GDScriptWarning::ERROR;
  190. pw.symbols = p_symbols;
  191. pending_warnings.push_back(pw);
  192. }
  193. void GDScriptParser::apply_pending_warnings() {
  194. for (const PendingWarning &pw : pending_warnings) {
  195. if (warning_ignored_lines[pw.code].has(pw.source->start_line)) {
  196. continue;
  197. }
  198. if (warning_ignore_start_lines[pw.code] <= pw.source->start_line) {
  199. continue;
  200. }
  201. GDScriptWarning warning;
  202. warning.code = pw.code;
  203. warning.symbols = pw.symbols;
  204. warning.start_line = pw.source->start_line;
  205. warning.end_line = pw.source->end_line;
  206. if (pw.treated_as_error) {
  207. push_error(warning.get_message() + String(" (Warning treated as error.)"), pw.source);
  208. continue;
  209. }
  210. List<GDScriptWarning>::Element *before = nullptr;
  211. for (List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) {
  212. if (E->get().start_line > warning.start_line) {
  213. break;
  214. }
  215. before = E;
  216. }
  217. if (before) {
  218. warnings.insert_after(before, warning);
  219. } else {
  220. warnings.push_front(warning);
  221. }
  222. }
  223. pending_warnings.clear();
  224. }
  225. #endif // DEBUG_ENABLED
  226. void GDScriptParser::override_completion_context(const Node *p_for_node, CompletionType p_type, Node *p_node, int p_argument) {
  227. if (!for_completion) {
  228. return;
  229. }
  230. if (p_for_node == nullptr || completion_context.node != p_for_node) {
  231. return;
  232. }
  233. CompletionContext context;
  234. context.type = p_type;
  235. context.current_class = current_class;
  236. context.current_function = current_function;
  237. context.current_suite = current_suite;
  238. context.current_line = tokenizer->get_cursor_line();
  239. context.current_argument = p_argument;
  240. context.node = p_node;
  241. context.parser = this;
  242. if (!completion_call_stack.is_empty()) {
  243. context.call = completion_call_stack.back()->get();
  244. }
  245. completion_context = context;
  246. }
  247. void GDScriptParser::make_completion_context(CompletionType p_type, Node *p_node, int p_argument, bool p_force) {
  248. if (!for_completion || (!p_force && completion_context.type != COMPLETION_NONE)) {
  249. return;
  250. }
  251. if (previous.cursor_place != GDScriptTokenizerText::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizerText::CURSOR_END && current.cursor_place == GDScriptTokenizerText::CURSOR_NONE) {
  252. return;
  253. }
  254. CompletionContext context;
  255. context.type = p_type;
  256. context.current_class = current_class;
  257. context.current_function = current_function;
  258. context.current_suite = current_suite;
  259. context.current_line = tokenizer->get_cursor_line();
  260. context.current_argument = p_argument;
  261. context.node = p_node;
  262. context.parser = this;
  263. if (!completion_call_stack.is_empty()) {
  264. context.call = completion_call_stack.back()->get();
  265. }
  266. completion_context = context;
  267. }
  268. void GDScriptParser::make_completion_context(CompletionType p_type, Variant::Type p_builtin_type, bool p_force) {
  269. if (!for_completion || (!p_force && completion_context.type != COMPLETION_NONE)) {
  270. return;
  271. }
  272. if (previous.cursor_place != GDScriptTokenizerText::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizerText::CURSOR_END && current.cursor_place == GDScriptTokenizerText::CURSOR_NONE) {
  273. return;
  274. }
  275. CompletionContext context;
  276. context.type = p_type;
  277. context.current_class = current_class;
  278. context.current_function = current_function;
  279. context.current_suite = current_suite;
  280. context.current_line = tokenizer->get_cursor_line();
  281. context.builtin_type = p_builtin_type;
  282. context.parser = this;
  283. if (!completion_call_stack.is_empty()) {
  284. context.call = completion_call_stack.back()->get();
  285. }
  286. completion_context = context;
  287. }
  288. void GDScriptParser::push_completion_call(Node *p_call) {
  289. if (!for_completion) {
  290. return;
  291. }
  292. CompletionCall call;
  293. call.call = p_call;
  294. call.argument = 0;
  295. completion_call_stack.push_back(call);
  296. }
  297. void GDScriptParser::pop_completion_call() {
  298. if (!for_completion) {
  299. return;
  300. }
  301. ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to pop empty completion call stack");
  302. completion_call_stack.pop_back();
  303. }
  304. void GDScriptParser::set_last_completion_call_arg(int p_argument) {
  305. if (!for_completion) {
  306. return;
  307. }
  308. ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to set argument on empty completion call stack");
  309. completion_call_stack.back()->get().argument = p_argument;
  310. }
  311. Error GDScriptParser::parse(const String &p_source_code, const String &p_script_path, bool p_for_completion, bool p_parse_body) {
  312. clear();
  313. String source = p_source_code;
  314. int cursor_line = -1;
  315. int cursor_column = -1;
  316. for_completion = p_for_completion;
  317. parse_body = p_parse_body;
  318. int tab_size = 4;
  319. #ifdef TOOLS_ENABLED
  320. if (EditorSettings::get_singleton()) {
  321. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
  322. }
  323. #endif // TOOLS_ENABLED
  324. if (p_for_completion) {
  325. // Remove cursor sentinel char.
  326. const Vector<String> lines = p_source_code.split("\n");
  327. cursor_line = 1;
  328. cursor_column = 1;
  329. for (int i = 0; i < lines.size(); i++) {
  330. bool found = false;
  331. const String &line = lines[i];
  332. for (int j = 0; j < line.size(); j++) {
  333. if (line[j] == char32_t(0xFFFF)) {
  334. found = true;
  335. break;
  336. } else if (line[j] == '\t') {
  337. cursor_column += tab_size - 1;
  338. }
  339. cursor_column++;
  340. }
  341. if (found) {
  342. break;
  343. }
  344. cursor_line++;
  345. cursor_column = 1;
  346. }
  347. source = source.replace_first(String::chr(0xFFFF), String());
  348. }
  349. GDScriptTokenizerText *text_tokenizer = memnew(GDScriptTokenizerText);
  350. text_tokenizer->set_source_code(source);
  351. tokenizer = text_tokenizer;
  352. tokenizer->set_cursor_position(cursor_line, cursor_column);
  353. script_path = p_script_path.simplify_path();
  354. current = tokenizer->scan();
  355. // Avoid error or newline as the first token.
  356. // The latter can mess with the parser when opening files filled exclusively with comments and newlines.
  357. while (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::NEWLINE) {
  358. if (current.type == GDScriptTokenizer::Token::ERROR) {
  359. push_error(current.literal);
  360. }
  361. current = tokenizer->scan();
  362. }
  363. #ifdef DEBUG_ENABLED
  364. // Warn about parsing an empty script file:
  365. if (current.type == GDScriptTokenizer::Token::TK_EOF) {
  366. // Create a dummy Node for the warning, pointing to the very beginning of the file
  367. Node *nd = alloc_node<PassNode>();
  368. nd->start_line = 1;
  369. nd->start_column = 0;
  370. nd->end_line = 1;
  371. push_warning(nd, GDScriptWarning::EMPTY_FILE);
  372. }
  373. #endif
  374. push_multiline(false); // Keep one for the whole parsing.
  375. parse_program();
  376. pop_multiline();
  377. #ifdef TOOLS_ENABLED
  378. comment_data = tokenizer->get_comments();
  379. #endif
  380. memdelete(text_tokenizer);
  381. tokenizer = nullptr;
  382. #ifdef DEBUG_ENABLED
  383. if (multiline_stack.size() > 0) {
  384. ERR_PRINT("Parser bug: Imbalanced multiline stack.");
  385. }
  386. #endif
  387. if (errors.is_empty()) {
  388. return OK;
  389. } else {
  390. return ERR_PARSE_ERROR;
  391. }
  392. }
  393. Error GDScriptParser::parse_binary(const Vector<uint8_t> &p_binary, const String &p_script_path) {
  394. GDScriptTokenizerBuffer *buffer_tokenizer = memnew(GDScriptTokenizerBuffer);
  395. Error err = buffer_tokenizer->set_code_buffer(p_binary);
  396. if (err) {
  397. memdelete(buffer_tokenizer);
  398. return err;
  399. }
  400. tokenizer = buffer_tokenizer;
  401. script_path = p_script_path.simplify_path();
  402. current = tokenizer->scan();
  403. // Avoid error or newline as the first token.
  404. // The latter can mess with the parser when opening files filled exclusively with comments and newlines.
  405. while (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::NEWLINE) {
  406. if (current.type == GDScriptTokenizer::Token::ERROR) {
  407. push_error(current.literal);
  408. }
  409. current = tokenizer->scan();
  410. }
  411. push_multiline(false); // Keep one for the whole parsing.
  412. parse_program();
  413. pop_multiline();
  414. memdelete(buffer_tokenizer);
  415. tokenizer = nullptr;
  416. if (errors.is_empty()) {
  417. return OK;
  418. } else {
  419. return ERR_PARSE_ERROR;
  420. }
  421. }
  422. GDScriptTokenizer::Token GDScriptParser::advance() {
  423. lambda_ended = false; // Empty marker since we're past the end in any case.
  424. if (current.type == GDScriptTokenizer::Token::TK_EOF) {
  425. ERR_FAIL_COND_V_MSG(current.type == GDScriptTokenizer::Token::TK_EOF, current, "GDScript parser bug: Trying to advance past the end of stream.");
  426. }
  427. previous = current;
  428. current = tokenizer->scan();
  429. while (current.type == GDScriptTokenizer::Token::ERROR) {
  430. push_error(current.literal);
  431. current = tokenizer->scan();
  432. }
  433. if (previous.type != GDScriptTokenizer::Token::DEDENT) { // `DEDENT` belongs to the next non-empty line.
  434. for (Node *n : nodes_in_progress) {
  435. update_extents(n);
  436. }
  437. }
  438. return previous;
  439. }
  440. bool GDScriptParser::match(GDScriptTokenizer::Token::Type p_token_type) {
  441. if (!check(p_token_type)) {
  442. return false;
  443. }
  444. advance();
  445. return true;
  446. }
  447. bool GDScriptParser::check(GDScriptTokenizer::Token::Type p_token_type) const {
  448. if (p_token_type == GDScriptTokenizer::Token::IDENTIFIER) {
  449. return current.is_identifier();
  450. }
  451. return current.type == p_token_type;
  452. }
  453. bool GDScriptParser::consume(GDScriptTokenizer::Token::Type p_token_type, const String &p_error_message) {
  454. if (match(p_token_type)) {
  455. return true;
  456. }
  457. push_error(p_error_message);
  458. return false;
  459. }
  460. bool GDScriptParser::is_at_end() const {
  461. return check(GDScriptTokenizer::Token::TK_EOF);
  462. }
  463. void GDScriptParser::synchronize() {
  464. panic_mode = false;
  465. while (!is_at_end()) {
  466. if (previous.type == GDScriptTokenizer::Token::NEWLINE || previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  467. return;
  468. }
  469. switch (current.type) {
  470. case GDScriptTokenizer::Token::CLASS:
  471. case GDScriptTokenizer::Token::FUNC:
  472. case GDScriptTokenizer::Token::STATIC:
  473. case GDScriptTokenizer::Token::VAR:
  474. case GDScriptTokenizer::Token::TK_CONST:
  475. case GDScriptTokenizer::Token::SIGNAL:
  476. //case GDScriptTokenizer::Token::IF: // Can also be inside expressions.
  477. case GDScriptTokenizer::Token::FOR:
  478. case GDScriptTokenizer::Token::WHILE:
  479. case GDScriptTokenizer::Token::MATCH:
  480. case GDScriptTokenizer::Token::RETURN:
  481. case GDScriptTokenizer::Token::ANNOTATION:
  482. return;
  483. default:
  484. // Do nothing.
  485. break;
  486. }
  487. advance();
  488. }
  489. }
  490. void GDScriptParser::push_multiline(bool p_state) {
  491. multiline_stack.push_back(p_state);
  492. tokenizer->set_multiline_mode(p_state);
  493. if (p_state) {
  494. // Consume potential whitespace tokens already waiting in line.
  495. while (current.type == GDScriptTokenizer::Token::NEWLINE || current.type == GDScriptTokenizer::Token::INDENT || current.type == GDScriptTokenizer::Token::DEDENT) {
  496. current = tokenizer->scan(); // Don't call advance() here, as we don't want to change the previous token.
  497. }
  498. }
  499. }
  500. void GDScriptParser::pop_multiline() {
  501. ERR_FAIL_COND_MSG(multiline_stack.is_empty(), "Parser bug: trying to pop from multiline stack without available value.");
  502. multiline_stack.pop_back();
  503. tokenizer->set_multiline_mode(multiline_stack.size() > 0 ? multiline_stack.back()->get() : false);
  504. }
  505. bool GDScriptParser::is_statement_end_token() const {
  506. return check(GDScriptTokenizer::Token::NEWLINE) || check(GDScriptTokenizer::Token::SEMICOLON) || check(GDScriptTokenizer::Token::TK_EOF);
  507. }
  508. bool GDScriptParser::is_statement_end() const {
  509. return lambda_ended || in_lambda || is_statement_end_token();
  510. }
  511. void GDScriptParser::end_statement(const String &p_context) {
  512. bool found = false;
  513. while (is_statement_end() && !is_at_end()) {
  514. // Remove sequential newlines/semicolons.
  515. if (is_statement_end_token()) {
  516. // Only consume if this is an actual token.
  517. advance();
  518. } else if (lambda_ended) {
  519. lambda_ended = false; // Consume this "token".
  520. found = true;
  521. break;
  522. } else {
  523. if (!found) {
  524. lambda_ended = true; // Mark the lambda as done since we found something else to end the statement.
  525. found = true;
  526. }
  527. break;
  528. }
  529. found = true;
  530. }
  531. if (!found && !is_at_end()) {
  532. push_error(vformat(R"(Expected end of statement after %s, found "%s" instead.)", p_context, current.get_name()));
  533. }
  534. }
  535. void GDScriptParser::parse_program() {
  536. head = alloc_node<ClassNode>();
  537. head->start_line = 1;
  538. head->end_line = 1;
  539. head->fqcn = GDScript::canonicalize_path(script_path);
  540. current_class = head;
  541. bool can_have_class_or_extends = true;
  542. #define PUSH_PENDING_ANNOTATIONS_TO_HEAD \
  543. if (!annotation_stack.is_empty()) { \
  544. for (AnnotationNode *annot : annotation_stack) { \
  545. head->annotations.push_back(annot); \
  546. } \
  547. annotation_stack.clear(); \
  548. }
  549. while (!check(GDScriptTokenizer::Token::TK_EOF)) {
  550. if (match(GDScriptTokenizer::Token::ANNOTATION)) {
  551. AnnotationNode *annotation = parse_annotation(AnnotationInfo::SCRIPT | AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STANDALONE);
  552. if (annotation != nullptr) {
  553. if (annotation->applies_to(AnnotationInfo::CLASS)) {
  554. // We do not know in advance what the annotation will be applied to: the `head` class or the subsequent inner class.
  555. // If we encounter `class_name`, `extends` or pure `SCRIPT` annotation, then it's `head`, otherwise it's an inner class.
  556. annotation_stack.push_back(annotation);
  557. } else if (annotation->applies_to(AnnotationInfo::SCRIPT)) {
  558. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  559. if (annotation->name == SNAME("@tool") || annotation->name == SNAME("@icon")) {
  560. // Some annotations need to be resolved and applied in the parser.
  561. // The root class is not in any class, so `head->outer == nullptr`.
  562. annotation->apply(this, head, nullptr);
  563. } else {
  564. head->annotations.push_back(annotation);
  565. }
  566. } else if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
  567. if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
  568. push_error(R"(Expected newline after a standalone annotation.)");
  569. }
  570. if (annotation->name == SNAME("@export_category") || annotation->name == SNAME("@export_group") || annotation->name == SNAME("@export_subgroup")) {
  571. head->add_member_group(annotation);
  572. // This annotation must appear after script-level annotations and `class_name`/`extends`,
  573. // so we stop looking for script-level stuff.
  574. can_have_class_or_extends = false;
  575. break;
  576. } else if (annotation->name == SNAME("@warning_ignore_start") || annotation->name == SNAME("@warning_ignore_restore")) {
  577. // Some annotations need to be resolved and applied in the parser.
  578. annotation->apply(this, nullptr, nullptr);
  579. } else {
  580. push_error(R"(Unexpected standalone annotation.)");
  581. }
  582. } else {
  583. annotation_stack.push_back(annotation);
  584. // This annotation must appear after script-level annotations and `class_name`/`extends`,
  585. // so we stop looking for script-level stuff.
  586. can_have_class_or_extends = false;
  587. break;
  588. }
  589. }
  590. } else if (check(GDScriptTokenizer::Token::LITERAL) && current.literal.get_type() == Variant::STRING) {
  591. // Allow strings in class body as multiline comments.
  592. advance();
  593. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  594. push_error("Expected newline after comment string.");
  595. }
  596. } else {
  597. break;
  598. }
  599. }
  600. if (current.type == GDScriptTokenizer::Token::CLASS_NAME || current.type == GDScriptTokenizer::Token::EXTENDS) {
  601. // Set range of the class to only start at extends or class_name if present.
  602. reset_extents(head, current);
  603. }
  604. bool first_is_abstract = false;
  605. while (can_have_class_or_extends) {
  606. // Order here doesn't matter, but there should be only one of each at most.
  607. switch (current.type) {
  608. case GDScriptTokenizer::Token::ABSTRACT: {
  609. if (head->is_abstract) {
  610. // The root class is already marked as abstract, so this is
  611. // the beginning of an abstract function or inner class.
  612. can_have_class_or_extends = false;
  613. break;
  614. }
  615. const GDScriptTokenizer::Token abstract_token = current;
  616. advance();
  617. // A standalone "abstract" is only allowed for script-level stuff.
  618. bool is_standalone = false;
  619. if (current.type == GDScriptTokenizer::Token::NEWLINE) {
  620. is_standalone = true;
  621. end_statement("standalone \"abstract\"");
  622. }
  623. switch (current.type) {
  624. case GDScriptTokenizer::Token::CLASS_NAME:
  625. case GDScriptTokenizer::Token::EXTENDS:
  626. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  627. head->is_abstract = true;
  628. if (head->start_line == 1) {
  629. reset_extents(head, abstract_token);
  630. }
  631. break;
  632. case GDScriptTokenizer::Token::CLASS:
  633. case GDScriptTokenizer::Token::FUNC:
  634. if (is_standalone) {
  635. push_error(R"(Expected "class_name" or "extends" after a standalone "abstract".)");
  636. } else {
  637. first_is_abstract = true;
  638. }
  639. // This is the beginning of an abstract function or inner class.
  640. can_have_class_or_extends = false;
  641. break;
  642. default:
  643. push_error(R"(Expected "class_name", "extends", "class", or "func" after "abstract".)");
  644. break;
  645. }
  646. } break;
  647. case GDScriptTokenizer::Token::CLASS_NAME:
  648. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  649. advance();
  650. if (head->identifier != nullptr) {
  651. push_error(R"("class_name" can only be used once.)");
  652. } else {
  653. parse_class_name();
  654. }
  655. break;
  656. case GDScriptTokenizer::Token::EXTENDS:
  657. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  658. advance();
  659. if (head->extends_used) {
  660. push_error(R"("extends" can only be used once.)");
  661. } else {
  662. parse_extends();
  663. end_statement("superclass");
  664. }
  665. break;
  666. case GDScriptTokenizer::Token::TK_EOF:
  667. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  668. can_have_class_or_extends = false;
  669. break;
  670. case GDScriptTokenizer::Token::LITERAL:
  671. if (current.literal.get_type() == Variant::STRING) {
  672. // Allow strings in class body as multiline comments.
  673. advance();
  674. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  675. push_error("Expected newline after comment string.");
  676. }
  677. break;
  678. }
  679. [[fallthrough]];
  680. default:
  681. // No tokens are allowed between script annotations and class/extends.
  682. can_have_class_or_extends = false;
  683. break;
  684. }
  685. if (panic_mode) {
  686. synchronize();
  687. }
  688. }
  689. // When the only thing needed is the class name and the icon, we don't need to parse the hole file.
  690. // It really speed up the call to GDScriptLanguage::get_global_class_name especially for large script.
  691. if (!parse_body) {
  692. return;
  693. }
  694. #undef PUSH_PENDING_ANNOTATIONS_TO_HEAD
  695. parse_class_body(first_is_abstract, true);
  696. head->end_line = current.end_line;
  697. head->end_column = current.end_column;
  698. complete_extents(head);
  699. #ifdef TOOLS_ENABLED
  700. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  701. int max_line = head->end_line;
  702. if (!head->members.is_empty()) {
  703. max_line = MIN(max_script_doc_line, head->members[0].get_line() - 1);
  704. }
  705. int line = 0;
  706. while (line <= max_line) {
  707. // Find the start.
  708. if (comments.has(line) && comments[line].new_line && comments[line].comment.begins_with("##")) {
  709. // Find the end.
  710. while (line + 1 <= max_line && comments.has(line + 1) && comments[line + 1].new_line && comments[line + 1].comment.begins_with("##")) {
  711. line++;
  712. }
  713. head->doc_data = parse_class_doc_comment(line);
  714. break;
  715. }
  716. line++;
  717. }
  718. #endif // TOOLS_ENABLED
  719. if (!check(GDScriptTokenizer::Token::TK_EOF)) {
  720. push_error("Expected end of file.");
  721. }
  722. clear_unused_annotations();
  723. }
  724. Ref<GDScriptParserRef> GDScriptParser::get_depended_parser_for(const String &p_path) {
  725. Ref<GDScriptParserRef> ref;
  726. if (depended_parsers.has(p_path)) {
  727. ref = depended_parsers[p_path];
  728. } else {
  729. Error err = OK;
  730. ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err, script_path);
  731. if (ref.is_valid()) {
  732. depended_parsers[p_path] = ref;
  733. }
  734. }
  735. return ref;
  736. }
  737. const HashMap<String, Ref<GDScriptParserRef>> &GDScriptParser::get_depended_parsers() {
  738. return depended_parsers;
  739. }
  740. GDScriptParser::ClassNode *GDScriptParser::find_class(const String &p_qualified_name) const {
  741. String first = p_qualified_name.get_slice("::", 0);
  742. Vector<String> class_names;
  743. GDScriptParser::ClassNode *result = nullptr;
  744. // Empty initial name means start at the head.
  745. if (first.is_empty() || (head->identifier && first == head->identifier->name)) {
  746. class_names = p_qualified_name.split("::");
  747. result = head;
  748. } else if (p_qualified_name.begins_with(script_path)) {
  749. // Script path could have a class path separator("::") in it.
  750. class_names = p_qualified_name.trim_prefix(script_path).split("::");
  751. result = head;
  752. } else if (head->has_member(first)) {
  753. class_names = p_qualified_name.split("::");
  754. GDScriptParser::ClassNode::Member member = head->get_member(first);
  755. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  756. result = member.m_class;
  757. }
  758. }
  759. // Starts at index 1 because index 0 was handled above.
  760. for (int i = 1; result != nullptr && i < class_names.size(); i++) {
  761. const String &current_name = class_names[i];
  762. GDScriptParser::ClassNode *next = nullptr;
  763. if (result->has_member(current_name)) {
  764. GDScriptParser::ClassNode::Member member = result->get_member(current_name);
  765. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  766. next = member.m_class;
  767. }
  768. }
  769. result = next;
  770. }
  771. return result;
  772. }
  773. bool GDScriptParser::has_class(const GDScriptParser::ClassNode *p_class) const {
  774. if (head->fqcn.is_empty() && p_class->fqcn.get_slice("::", 0).is_empty()) {
  775. return p_class == head;
  776. } else if (p_class->fqcn.begins_with(head->fqcn)) {
  777. return find_class(p_class->fqcn.trim_prefix(head->fqcn)) == p_class;
  778. }
  779. return false;
  780. }
  781. GDScriptParser::ClassNode *GDScriptParser::parse_class(bool p_is_abstract, bool p_is_static) {
  782. ClassNode *n_class = alloc_node<ClassNode>();
  783. ClassNode *previous_class = current_class;
  784. current_class = n_class;
  785. n_class->outer = previous_class;
  786. n_class->is_abstract = p_is_abstract;
  787. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the class name after "class".)")) {
  788. n_class->identifier = parse_identifier();
  789. if (n_class->outer) {
  790. String fqcn = n_class->outer->fqcn;
  791. if (fqcn.is_empty()) {
  792. fqcn = GDScript::canonicalize_path(script_path);
  793. }
  794. n_class->fqcn = fqcn + "::" + n_class->identifier->name;
  795. } else {
  796. n_class->fqcn = n_class->identifier->name;
  797. }
  798. }
  799. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  800. parse_extends();
  801. }
  802. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after class declaration.)");
  803. bool multiline = match(GDScriptTokenizer::Token::NEWLINE);
  804. if (multiline && !consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block after class declaration.)")) {
  805. current_class = previous_class;
  806. complete_extents(n_class);
  807. return n_class;
  808. }
  809. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  810. if (n_class->extends_used) {
  811. push_error(R"(Cannot use "extends" more than once in the same class.)");
  812. }
  813. parse_extends();
  814. end_statement("superclass");
  815. }
  816. parse_class_body(false, multiline);
  817. complete_extents(n_class);
  818. if (multiline) {
  819. consume(GDScriptTokenizer::Token::DEDENT, R"(Missing unindent at the end of the class body.)");
  820. }
  821. current_class = previous_class;
  822. return n_class;
  823. }
  824. void GDScriptParser::parse_class_name() {
  825. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the global class name after "class_name".)")) {
  826. current_class->identifier = parse_identifier();
  827. current_class->fqcn = String(current_class->identifier->name);
  828. }
  829. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  830. // Allow extends on the same line.
  831. parse_extends();
  832. end_statement("superclass");
  833. } else {
  834. end_statement("class_name statement");
  835. }
  836. }
  837. void GDScriptParser::parse_extends() {
  838. current_class->extends_used = true;
  839. int chain_index = 0;
  840. if (match(GDScriptTokenizer::Token::LITERAL)) {
  841. if (previous.literal.get_type() != Variant::STRING) {
  842. push_error(vformat(R"(Only strings or identifiers can be used after "extends", found "%s" instead.)", Variant::get_type_name(previous.literal.get_type())));
  843. }
  844. current_class->extends_path = previous.literal;
  845. if (!match(GDScriptTokenizer::Token::PERIOD)) {
  846. return;
  847. }
  848. }
  849. make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
  850. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after "extends".)")) {
  851. return;
  852. }
  853. current_class->extends.push_back(parse_identifier());
  854. while (match(GDScriptTokenizer::Token::PERIOD)) {
  855. make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
  856. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after ".".)")) {
  857. return;
  858. }
  859. current_class->extends.push_back(parse_identifier());
  860. }
  861. }
  862. template <typename T>
  863. void GDScriptParser::parse_class_member(T *(GDScriptParser::*p_parse_function)(bool, bool), AnnotationInfo::TargetKind p_target, const String &p_member_kind, bool p_is_abstract, bool p_is_static) {
  864. advance();
  865. // Consume annotations.
  866. List<AnnotationNode *> annotations;
  867. while (!annotation_stack.is_empty()) {
  868. AnnotationNode *last_annotation = annotation_stack.back()->get();
  869. if (last_annotation->applies_to(p_target)) {
  870. annotations.push_front(last_annotation);
  871. annotation_stack.pop_back();
  872. } else {
  873. push_error(vformat(R"(Annotation "%s" cannot be applied to a %s.)", last_annotation->name, p_member_kind));
  874. clear_unused_annotations();
  875. }
  876. }
  877. T *member = (this->*p_parse_function)(p_is_abstract, p_is_static);
  878. if (member == nullptr) {
  879. return;
  880. }
  881. #ifdef TOOLS_ENABLED
  882. int doc_comment_line = member->start_line - 1;
  883. #endif // TOOLS_ENABLED
  884. for (AnnotationNode *&annotation : annotations) {
  885. member->annotations.push_back(annotation);
  886. #ifdef TOOLS_ENABLED
  887. if (annotation->start_line <= doc_comment_line) {
  888. doc_comment_line = annotation->start_line - 1;
  889. }
  890. #endif // TOOLS_ENABLED
  891. }
  892. #ifdef TOOLS_ENABLED
  893. if constexpr (std::is_same_v<T, ClassNode>) {
  894. if (has_comment(member->start_line, true)) {
  895. // Inline doc comment.
  896. member->doc_data = parse_class_doc_comment(member->start_line, true);
  897. } else if (has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  898. // Normal doc comment. Don't check `min_member_doc_line` because a class ends parsing after its members.
  899. // This may not work correctly for cases like `var a; class B`, but it doesn't matter in practice.
  900. member->doc_data = parse_class_doc_comment(doc_comment_line);
  901. }
  902. } else {
  903. if (has_comment(member->start_line, true)) {
  904. // Inline doc comment.
  905. member->doc_data = parse_doc_comment(member->start_line, true);
  906. } else if (doc_comment_line >= min_member_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  907. // Normal doc comment.
  908. member->doc_data = parse_doc_comment(doc_comment_line);
  909. }
  910. }
  911. min_member_doc_line = member->end_line + 1; // Prevent multiple members from using the same doc comment.
  912. #endif // TOOLS_ENABLED
  913. if (member->identifier != nullptr) {
  914. if (!((String)member->identifier->name).is_empty()) { // Enums may be unnamed.
  915. if (current_class->members_indices.has(member->identifier->name)) {
  916. push_error(vformat(R"(%s "%s" has the same name as a previously declared %s.)", p_member_kind.capitalize(), member->identifier->name, current_class->get_member(member->identifier->name).get_type_name()), member->identifier);
  917. } else {
  918. current_class->add_member(member);
  919. }
  920. } else {
  921. current_class->add_member(member);
  922. }
  923. }
  924. }
  925. void GDScriptParser::parse_class_body(bool p_first_is_abstract, bool p_is_multiline) {
  926. bool class_end = false;
  927. // The header parsing code could consume `abstract` for the first function or inner class.
  928. bool next_is_abstract = p_first_is_abstract;
  929. bool next_is_static = false;
  930. while (!class_end && !is_at_end()) {
  931. GDScriptTokenizer::Token token = current;
  932. switch (token.type) {
  933. case GDScriptTokenizer::Token::ABSTRACT: {
  934. advance();
  935. next_is_abstract = true;
  936. if (!check(GDScriptTokenizer::Token::CLASS) && !check(GDScriptTokenizer::Token::FUNC)) {
  937. push_error(R"(Expected "class" or "func" after "abstract".)");
  938. }
  939. } break;
  940. case GDScriptTokenizer::Token::VAR:
  941. parse_class_member(&GDScriptParser::parse_variable, AnnotationInfo::VARIABLE, "variable", false, next_is_static);
  942. if (next_is_static) {
  943. current_class->has_static_data = true;
  944. }
  945. break;
  946. case GDScriptTokenizer::Token::TK_CONST:
  947. parse_class_member(&GDScriptParser::parse_constant, AnnotationInfo::CONSTANT, "constant");
  948. break;
  949. case GDScriptTokenizer::Token::SIGNAL:
  950. parse_class_member(&GDScriptParser::parse_signal, AnnotationInfo::SIGNAL, "signal");
  951. break;
  952. case GDScriptTokenizer::Token::FUNC:
  953. parse_class_member(&GDScriptParser::parse_function, AnnotationInfo::FUNCTION, "function", next_is_abstract, next_is_static);
  954. break;
  955. case GDScriptTokenizer::Token::CLASS:
  956. parse_class_member(&GDScriptParser::parse_class, AnnotationInfo::CLASS, "class", next_is_abstract);
  957. break;
  958. case GDScriptTokenizer::Token::ENUM:
  959. parse_class_member(&GDScriptParser::parse_enum, AnnotationInfo::NONE, "enum");
  960. break;
  961. case GDScriptTokenizer::Token::STATIC: {
  962. advance();
  963. next_is_static = true;
  964. if (!check(GDScriptTokenizer::Token::FUNC) && !check(GDScriptTokenizer::Token::VAR)) {
  965. push_error(R"(Expected "func" or "var" after "static".)");
  966. }
  967. } break;
  968. case GDScriptTokenizer::Token::ANNOTATION: {
  969. advance();
  970. // Check for class-level and standalone annotations.
  971. AnnotationNode *annotation = parse_annotation(AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STANDALONE);
  972. if (annotation != nullptr) {
  973. if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
  974. if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
  975. push_error(R"(Expected newline after a standalone annotation.)");
  976. }
  977. if (annotation->name == SNAME("@export_category") || annotation->name == SNAME("@export_group") || annotation->name == SNAME("@export_subgroup")) {
  978. current_class->add_member_group(annotation);
  979. } else if (annotation->name == SNAME("@warning_ignore_start") || annotation->name == SNAME("@warning_ignore_restore")) {
  980. // Some annotations need to be resolved and applied in the parser.
  981. annotation->apply(this, nullptr, nullptr);
  982. } else {
  983. push_error(R"(Unexpected standalone annotation.)");
  984. }
  985. } else { // `AnnotationInfo::CLASS_LEVEL`.
  986. annotation_stack.push_back(annotation);
  987. }
  988. }
  989. break;
  990. }
  991. case GDScriptTokenizer::Token::PASS:
  992. advance();
  993. end_statement(R"("pass")");
  994. break;
  995. case GDScriptTokenizer::Token::DEDENT:
  996. class_end = true;
  997. break;
  998. case GDScriptTokenizer::Token::LITERAL:
  999. if (current.literal.get_type() == Variant::STRING) {
  1000. // Allow strings in class body as multiline comments.
  1001. advance();
  1002. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  1003. push_error("Expected newline after comment string.");
  1004. }
  1005. break;
  1006. }
  1007. [[fallthrough]];
  1008. default:
  1009. // Display a completion with identifiers.
  1010. make_completion_context(COMPLETION_IDENTIFIER, nullptr);
  1011. advance();
  1012. if (previous.get_identifier() == "export") {
  1013. push_error(R"(The "export" keyword was removed in Godot 4. Use an export annotation ("@export", "@export_range", etc.) instead.)");
  1014. } else if (previous.get_identifier() == "tool") {
  1015. push_error(R"(The "tool" keyword was removed in Godot 4. Use the "@tool" annotation instead.)");
  1016. } else if (previous.get_identifier() == "onready") {
  1017. push_error(R"(The "onready" keyword was removed in Godot 4. Use the "@onready" annotation instead.)");
  1018. } else if (previous.get_identifier() == "remote") {
  1019. push_error(R"(The "remote" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" instead.)");
  1020. } else if (previous.get_identifier() == "remotesync") {
  1021. push_error(R"(The "remotesync" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" and "call_local" instead.)");
  1022. } else if (previous.get_identifier() == "puppet") {
  1023. push_error(R"(The "puppet" keyword was removed in Godot 4. Use the "@rpc" annotation with "authority" instead.)");
  1024. } else if (previous.get_identifier() == "puppetsync") {
  1025. push_error(R"(The "puppetsync" keyword was removed in Godot 4. Use the "@rpc" annotation with "authority" and "call_local" instead.)");
  1026. } else if (previous.get_identifier() == "master") {
  1027. push_error(R"(The "master" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" and perform a check inside the function instead.)");
  1028. } else if (previous.get_identifier() == "mastersync") {
  1029. push_error(R"(The "mastersync" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" and "call_local", and perform a check inside the function instead.)");
  1030. } else {
  1031. push_error(vformat(R"(Unexpected %s in class body.)", previous.get_debug_name()));
  1032. }
  1033. break;
  1034. }
  1035. if (token.type != GDScriptTokenizer::Token::ABSTRACT) {
  1036. next_is_abstract = false;
  1037. }
  1038. if (token.type != GDScriptTokenizer::Token::STATIC) {
  1039. next_is_static = false;
  1040. }
  1041. if (panic_mode) {
  1042. synchronize();
  1043. }
  1044. if (!p_is_multiline) {
  1045. class_end = true;
  1046. }
  1047. }
  1048. }
  1049. GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_is_abstract, bool p_is_static) {
  1050. return parse_variable(p_is_abstract, p_is_static, true);
  1051. }
  1052. GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_is_abstract, bool p_is_static, bool p_allow_property) {
  1053. VariableNode *variable = alloc_node<VariableNode>();
  1054. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected variable name after "var".)")) {
  1055. complete_extents(variable);
  1056. return nullptr;
  1057. }
  1058. variable->identifier = parse_identifier();
  1059. variable->export_info.name = variable->identifier->name;
  1060. variable->is_static = p_is_static;
  1061. if (match(GDScriptTokenizer::Token::COLON)) {
  1062. if (check(GDScriptTokenizer::Token::NEWLINE)) {
  1063. if (p_allow_property) {
  1064. advance();
  1065. return parse_property(variable, true);
  1066. } else {
  1067. push_error(R"(Expected type after ":")");
  1068. complete_extents(variable);
  1069. return nullptr;
  1070. }
  1071. } else if (check((GDScriptTokenizer::Token::EQUAL))) {
  1072. // Infer type.
  1073. variable->infer_datatype = true;
  1074. } else {
  1075. if (p_allow_property) {
  1076. make_completion_context(COMPLETION_PROPERTY_DECLARATION_OR_TYPE, variable);
  1077. if (check(GDScriptTokenizer::Token::IDENTIFIER)) {
  1078. // Check if get or set.
  1079. if (current.get_identifier() == "get" || current.get_identifier() == "set") {
  1080. return parse_property(variable, false);
  1081. }
  1082. }
  1083. }
  1084. // Parse type.
  1085. variable->datatype_specifier = parse_type();
  1086. }
  1087. }
  1088. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1089. // Initializer.
  1090. variable->initializer = parse_expression(false);
  1091. if (variable->initializer == nullptr) {
  1092. push_error(R"(Expected expression for variable initial value after "=".)");
  1093. }
  1094. variable->assignments++;
  1095. }
  1096. if (p_allow_property && match(GDScriptTokenizer::Token::COLON)) {
  1097. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1098. return parse_property(variable, true);
  1099. } else {
  1100. return parse_property(variable, false);
  1101. }
  1102. }
  1103. complete_extents(variable);
  1104. end_statement("variable declaration");
  1105. return variable;
  1106. }
  1107. GDScriptParser::VariableNode *GDScriptParser::parse_property(VariableNode *p_variable, bool p_need_indent) {
  1108. if (p_need_indent) {
  1109. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block for property after ":".)")) {
  1110. complete_extents(p_variable);
  1111. return nullptr;
  1112. }
  1113. }
  1114. VariableNode *property = p_variable;
  1115. make_completion_context(COMPLETION_PROPERTY_DECLARATION, property);
  1116. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected "get" or "set" for property declaration.)")) {
  1117. complete_extents(p_variable);
  1118. return nullptr;
  1119. }
  1120. IdentifierNode *function = parse_identifier();
  1121. if (check(GDScriptTokenizer::Token::EQUAL)) {
  1122. p_variable->property = VariableNode::PROP_SETGET;
  1123. } else {
  1124. p_variable->property = VariableNode::PROP_INLINE;
  1125. if (!p_need_indent) {
  1126. push_error("Property with inline code must go to an indented block.");
  1127. }
  1128. }
  1129. bool getter_used = false;
  1130. bool setter_used = false;
  1131. // Run with a loop because order doesn't matter.
  1132. for (int i = 0; i < 2; i++) {
  1133. if (function->name == SNAME("set")) {
  1134. if (setter_used) {
  1135. push_error(R"(Properties can only have one setter.)");
  1136. } else {
  1137. parse_property_setter(property);
  1138. setter_used = true;
  1139. }
  1140. } else if (function->name == SNAME("get")) {
  1141. if (getter_used) {
  1142. push_error(R"(Properties can only have one getter.)");
  1143. } else {
  1144. parse_property_getter(property);
  1145. getter_used = true;
  1146. }
  1147. } else {
  1148. // TODO: Update message to only have the missing one if it's the case.
  1149. push_error(R"(Expected "get" or "set" for property declaration.)");
  1150. }
  1151. if (i == 0 && p_variable->property == VariableNode::PROP_SETGET) {
  1152. if (match(GDScriptTokenizer::Token::COMMA)) {
  1153. // Consume potential newline.
  1154. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1155. if (!p_need_indent) {
  1156. push_error(R"(Inline setter/getter setting cannot span across multiple lines (use "\\"" if needed).)");
  1157. }
  1158. }
  1159. } else {
  1160. break;
  1161. }
  1162. }
  1163. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  1164. break;
  1165. }
  1166. function = parse_identifier();
  1167. }
  1168. complete_extents(p_variable);
  1169. if (p_variable->property == VariableNode::PROP_SETGET) {
  1170. end_statement("property declaration");
  1171. }
  1172. if (p_need_indent) {
  1173. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected end of indented block for property.)");
  1174. }
  1175. return property;
  1176. }
  1177. void GDScriptParser::parse_property_setter(VariableNode *p_variable) {
  1178. switch (p_variable->property) {
  1179. case VariableNode::PROP_INLINE: {
  1180. FunctionNode *function = alloc_node<FunctionNode>();
  1181. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  1182. complete_extents(identifier);
  1183. identifier->name = "@" + p_variable->identifier->name + "_setter";
  1184. function->identifier = identifier;
  1185. function->is_static = p_variable->is_static;
  1186. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "set".)");
  1187. ParameterNode *parameter = alloc_node<ParameterNode>();
  1188. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name after "(".)")) {
  1189. reset_extents(parameter, previous);
  1190. p_variable->setter_parameter = parse_identifier();
  1191. parameter->identifier = p_variable->setter_parameter;
  1192. function->parameters_indices[parameter->identifier->name] = 0;
  1193. function->parameters.push_back(parameter);
  1194. }
  1195. complete_extents(parameter);
  1196. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after parameter name.)*");
  1197. consume(GDScriptTokenizer::Token::COLON, R"*(Expected ":" after ")".)*");
  1198. FunctionNode *previous_function = current_function;
  1199. current_function = function;
  1200. if (p_variable->setter_parameter != nullptr) {
  1201. SuiteNode *body = alloc_node<SuiteNode>();
  1202. body->add_local(parameter, function);
  1203. function->body = parse_suite("setter declaration", body);
  1204. p_variable->setter = function;
  1205. }
  1206. current_function = previous_function;
  1207. complete_extents(function);
  1208. break;
  1209. }
  1210. case VariableNode::PROP_SETGET:
  1211. consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "set")");
  1212. make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
  1213. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected setter function name after "=".)")) {
  1214. p_variable->setter_pointer = parse_identifier();
  1215. }
  1216. break;
  1217. case VariableNode::PROP_NONE:
  1218. break; // Unreachable.
  1219. }
  1220. }
  1221. void GDScriptParser::parse_property_getter(VariableNode *p_variable) {
  1222. switch (p_variable->property) {
  1223. case VariableNode::PROP_INLINE: {
  1224. FunctionNode *function = alloc_node<FunctionNode>();
  1225. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1226. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after "get(".)*");
  1227. consume(GDScriptTokenizer::Token::COLON, R"*(Expected ":" after "get()".)*");
  1228. } else {
  1229. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" or "(" after "get".)");
  1230. }
  1231. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  1232. complete_extents(identifier);
  1233. identifier->name = "@" + p_variable->identifier->name + "_getter";
  1234. function->identifier = identifier;
  1235. function->is_static = p_variable->is_static;
  1236. FunctionNode *previous_function = current_function;
  1237. current_function = function;
  1238. SuiteNode *body = alloc_node<SuiteNode>();
  1239. function->body = parse_suite("getter declaration", body);
  1240. p_variable->getter = function;
  1241. current_function = previous_function;
  1242. complete_extents(function);
  1243. break;
  1244. }
  1245. case VariableNode::PROP_SETGET:
  1246. consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "get")");
  1247. make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
  1248. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected getter function name after "=".)")) {
  1249. p_variable->getter_pointer = parse_identifier();
  1250. }
  1251. break;
  1252. case VariableNode::PROP_NONE:
  1253. break; // Unreachable.
  1254. }
  1255. }
  1256. GDScriptParser::ConstantNode *GDScriptParser::parse_constant(bool p_is_abstract, bool p_is_static) {
  1257. ConstantNode *constant = alloc_node<ConstantNode>();
  1258. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected constant name after "const".)")) {
  1259. complete_extents(constant);
  1260. return nullptr;
  1261. }
  1262. constant->identifier = parse_identifier();
  1263. if (match(GDScriptTokenizer::Token::COLON)) {
  1264. if (check((GDScriptTokenizer::Token::EQUAL))) {
  1265. // Infer type.
  1266. constant->infer_datatype = true;
  1267. } else {
  1268. // Parse type.
  1269. constant->datatype_specifier = parse_type();
  1270. }
  1271. }
  1272. if (consume(GDScriptTokenizer::Token::EQUAL, R"(Expected initializer after constant name.)")) {
  1273. // Initializer.
  1274. constant->initializer = parse_expression(false);
  1275. if (constant->initializer == nullptr) {
  1276. push_error(R"(Expected initializer expression for constant.)");
  1277. complete_extents(constant);
  1278. return nullptr;
  1279. }
  1280. } else {
  1281. complete_extents(constant);
  1282. return nullptr;
  1283. }
  1284. complete_extents(constant);
  1285. end_statement("constant declaration");
  1286. return constant;
  1287. }
  1288. GDScriptParser::ParameterNode *GDScriptParser::parse_parameter() {
  1289. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name.)")) {
  1290. return nullptr;
  1291. }
  1292. ParameterNode *parameter = alloc_node<ParameterNode>();
  1293. parameter->identifier = parse_identifier();
  1294. if (match(GDScriptTokenizer::Token::COLON)) {
  1295. if (check((GDScriptTokenizer::Token::EQUAL))) {
  1296. // Infer type.
  1297. parameter->infer_datatype = true;
  1298. } else {
  1299. // Parse type.
  1300. make_completion_context(COMPLETION_TYPE_NAME, parameter);
  1301. parameter->datatype_specifier = parse_type();
  1302. }
  1303. }
  1304. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1305. // Default value.
  1306. parameter->initializer = parse_expression(false);
  1307. }
  1308. complete_extents(parameter);
  1309. return parameter;
  1310. }
  1311. GDScriptParser::SignalNode *GDScriptParser::parse_signal(bool p_is_abstract, bool p_is_static) {
  1312. SignalNode *signal = alloc_node<SignalNode>();
  1313. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected signal name after "signal".)")) {
  1314. complete_extents(signal);
  1315. return nullptr;
  1316. }
  1317. signal->identifier = parse_identifier();
  1318. if (check(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1319. push_multiline(true);
  1320. advance();
  1321. do {
  1322. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1323. // Allow for trailing comma.
  1324. break;
  1325. }
  1326. ParameterNode *parameter = parse_parameter();
  1327. if (parameter == nullptr) {
  1328. push_error("Expected signal parameter name.");
  1329. break;
  1330. }
  1331. if (parameter->initializer != nullptr) {
  1332. push_error(R"(Signal parameters cannot have a default value.)");
  1333. }
  1334. if (signal->parameters_indices.has(parameter->identifier->name)) {
  1335. push_error(vformat(R"(Parameter with name "%s" was already declared for this signal.)", parameter->identifier->name));
  1336. } else {
  1337. signal->parameters_indices[parameter->identifier->name] = signal->parameters.size();
  1338. signal->parameters.push_back(parameter);
  1339. }
  1340. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  1341. pop_multiline();
  1342. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after signal parameters.)*");
  1343. }
  1344. complete_extents(signal);
  1345. end_statement("signal declaration");
  1346. return signal;
  1347. }
  1348. GDScriptParser::EnumNode *GDScriptParser::parse_enum(bool p_is_abstract, bool p_is_static) {
  1349. EnumNode *enum_node = alloc_node<EnumNode>();
  1350. bool named = false;
  1351. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  1352. enum_node->identifier = parse_identifier();
  1353. named = true;
  1354. }
  1355. push_multiline(true);
  1356. consume(GDScriptTokenizer::Token::BRACE_OPEN, vformat(R"(Expected "{" after %s.)", named ? "enum name" : R"("enum")"));
  1357. #ifdef TOOLS_ENABLED
  1358. int min_enum_value_doc_line = previous.end_line + 1;
  1359. #endif
  1360. HashMap<StringName, int> elements;
  1361. #ifdef DEBUG_ENABLED
  1362. List<MethodInfo> gdscript_funcs;
  1363. GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);
  1364. #endif
  1365. do {
  1366. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  1367. break; // Allow trailing comma.
  1368. }
  1369. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for enum key.)")) {
  1370. GDScriptParser::IdentifierNode *identifier = parse_identifier();
  1371. EnumNode::Value item;
  1372. item.identifier = identifier;
  1373. item.parent_enum = enum_node;
  1374. item.line = previous.start_line;
  1375. item.start_column = previous.start_column;
  1376. item.end_column = previous.end_column;
  1377. if (elements.has(item.identifier->name)) {
  1378. push_error(vformat(R"(Name "%s" was already in this enum (at line %d).)", item.identifier->name, elements[item.identifier->name]), item.identifier);
  1379. } else if (!named) {
  1380. if (current_class->members_indices.has(item.identifier->name)) {
  1381. push_error(vformat(R"(Name "%s" is already used as a class %s.)", item.identifier->name, current_class->get_member(item.identifier->name).get_type_name()));
  1382. }
  1383. }
  1384. elements[item.identifier->name] = item.line;
  1385. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1386. ExpressionNode *value = parse_expression(false);
  1387. if (value == nullptr) {
  1388. push_error(R"(Expected expression value after "=".)");
  1389. }
  1390. item.custom_value = value;
  1391. }
  1392. item.index = enum_node->values.size();
  1393. enum_node->values.push_back(item);
  1394. if (!named) {
  1395. // Add as member of current class.
  1396. current_class->add_member(item);
  1397. }
  1398. }
  1399. } while (match(GDScriptTokenizer::Token::COMMA));
  1400. #ifdef TOOLS_ENABLED
  1401. // Enum values documentation.
  1402. for (int i = 0; i < enum_node->values.size(); i++) {
  1403. int enum_value_line = enum_node->values[i].line;
  1404. int doc_comment_line = enum_value_line - 1;
  1405. MemberDocData doc_data;
  1406. if (has_comment(enum_value_line, true)) {
  1407. // Inline doc comment.
  1408. if (i == enum_node->values.size() - 1 || enum_node->values[i + 1].line > enum_value_line) {
  1409. doc_data = parse_doc_comment(enum_value_line, true);
  1410. }
  1411. } else if (doc_comment_line >= min_enum_value_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  1412. // Normal doc comment.
  1413. doc_data = parse_doc_comment(doc_comment_line);
  1414. }
  1415. if (named) {
  1416. enum_node->values.write[i].doc_data = doc_data;
  1417. } else {
  1418. current_class->set_enum_value_doc_data(enum_node->values[i].identifier->name, doc_data);
  1419. }
  1420. min_enum_value_doc_line = enum_value_line + 1; // Prevent multiple enum values from using the same doc comment.
  1421. }
  1422. #endif // TOOLS_ENABLED
  1423. pop_multiline();
  1424. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" for enum.)");
  1425. complete_extents(enum_node);
  1426. end_statement("enum");
  1427. return enum_node;
  1428. }
  1429. void GDScriptParser::parse_function_signature(FunctionNode *p_function, SuiteNode *p_body, const String &p_type, int p_signature_start) {
  1430. if (!check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE) && !is_at_end()) {
  1431. bool default_used = false;
  1432. do {
  1433. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1434. // Allow for trailing comma.
  1435. break;
  1436. }
  1437. bool is_rest = false;
  1438. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD_PERIOD)) {
  1439. is_rest = true;
  1440. }
  1441. ParameterNode *parameter = parse_parameter();
  1442. if (parameter == nullptr) {
  1443. break;
  1444. }
  1445. if (p_function->is_vararg()) {
  1446. push_error("Cannot have parameters after the rest parameter.");
  1447. continue;
  1448. }
  1449. if (parameter->initializer != nullptr) {
  1450. if (is_rest) {
  1451. push_error("The rest parameter cannot have a default value.");
  1452. continue;
  1453. }
  1454. default_used = true;
  1455. } else {
  1456. if (default_used && !is_rest) {
  1457. push_error("Cannot have mandatory parameters after optional parameters.");
  1458. continue;
  1459. }
  1460. }
  1461. if (p_function->parameters_indices.has(parameter->identifier->name)) {
  1462. push_error(vformat(R"(Parameter with name "%s" was already declared for this %s.)", parameter->identifier->name, p_type));
  1463. } else if (is_rest) {
  1464. p_function->rest_parameter = parameter;
  1465. p_body->add_local(parameter, current_function);
  1466. } else {
  1467. p_function->parameters_indices[parameter->identifier->name] = p_function->parameters.size();
  1468. p_function->parameters.push_back(parameter);
  1469. p_body->add_local(parameter, current_function);
  1470. }
  1471. } while (match(GDScriptTokenizer::Token::COMMA));
  1472. }
  1473. pop_multiline();
  1474. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, vformat(R"*(Expected closing ")" after %s parameters.)*", p_type));
  1475. if (match(GDScriptTokenizer::Token::FORWARD_ARROW)) {
  1476. make_completion_context(COMPLETION_TYPE_NAME_OR_VOID, p_function);
  1477. p_function->return_type = parse_type(true);
  1478. if (p_function->return_type == nullptr) {
  1479. push_error(R"(Expected return type or "void" after "->".)");
  1480. }
  1481. }
  1482. if (!p_function->source_lambda && p_function->identifier && p_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init) {
  1483. if (!p_function->is_static) {
  1484. push_error(R"(Static constructor must be declared static.)");
  1485. }
  1486. if (!p_function->parameters.is_empty() || p_function->is_vararg()) {
  1487. push_error(R"(Static constructor cannot have parameters.)");
  1488. }
  1489. current_class->has_static_data = true;
  1490. }
  1491. #ifdef TOOLS_ENABLED
  1492. if (p_type == "function" && p_signature_start != -1) {
  1493. const int signature_end_pos = tokenizer->get_current_position() - 1;
  1494. const String source_code = tokenizer->get_source_code();
  1495. p_function->signature = source_code.substr(p_signature_start, signature_end_pos - p_signature_start).strip_edges(false, true);
  1496. }
  1497. #endif // TOOLS_ENABLED
  1498. if (p_function->is_abstract) {
  1499. end_statement("abstract function declaration");
  1500. } else {
  1501. // TODO: Improve token consumption so it synchronizes to a statement boundary. This way we can get into the function body with unrecognized tokens.
  1502. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after %s declaration.)", p_type));
  1503. }
  1504. }
  1505. GDScriptParser::FunctionNode *GDScriptParser::parse_function(bool p_is_abstract, bool p_is_static) {
  1506. FunctionNode *function = alloc_node<FunctionNode>();
  1507. function->is_abstract = p_is_abstract;
  1508. function->is_static = p_is_static;
  1509. make_completion_context(COMPLETION_OVERRIDE_METHOD, function);
  1510. #ifdef TOOLS_ENABLED
  1511. // The signature is something like `(a: int, b: int = 0) -> void`.
  1512. // We start one token earlier, since the parser looks one token ahead.
  1513. const int signature_start_pos = tokenizer->get_current_position();
  1514. #endif // TOOLS_ENABLED
  1515. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after "func".)")) {
  1516. complete_extents(function);
  1517. return nullptr;
  1518. }
  1519. FunctionNode *previous_function = current_function;
  1520. current_function = function;
  1521. function->identifier = parse_identifier();
  1522. SuiteNode *body = alloc_node<SuiteNode>();
  1523. SuiteNode *previous_suite = current_suite;
  1524. current_suite = body;
  1525. push_multiline(true);
  1526. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after function name.)");
  1527. #ifdef TOOLS_ENABLED
  1528. parse_function_signature(function, body, "function", signature_start_pos);
  1529. #else // !TOOLS_ENABLED
  1530. parse_function_signature(function, body, "function", -1);
  1531. #endif // TOOLS_ENABLED
  1532. current_suite = previous_suite;
  1533. #ifdef TOOLS_ENABLED
  1534. function->min_local_doc_line = previous.end_line + 1;
  1535. #endif // TOOLS_ENABLED
  1536. if (function->is_abstract) {
  1537. reset_extents(body, current);
  1538. complete_extents(body);
  1539. function->body = body;
  1540. } else {
  1541. function->body = parse_suite("function declaration", body);
  1542. }
  1543. current_function = previous_function;
  1544. complete_extents(function);
  1545. return function;
  1546. }
  1547. GDScriptParser::AnnotationNode *GDScriptParser::parse_annotation(uint32_t p_valid_targets) {
  1548. AnnotationNode *annotation = alloc_node<AnnotationNode>();
  1549. annotation->name = previous.literal;
  1550. make_completion_context(COMPLETION_ANNOTATION, annotation);
  1551. bool valid = true;
  1552. if (!valid_annotations.has(annotation->name)) {
  1553. if (annotation->name == "@deprecated") {
  1554. push_error(R"("@deprecated" annotation does not exist. Use "## @deprecated: Reason here." instead.)");
  1555. } else if (annotation->name == "@experimental") {
  1556. push_error(R"("@experimental" annotation does not exist. Use "## @experimental: Reason here." instead.)");
  1557. } else if (annotation->name == "@tutorial") {
  1558. push_error(R"("@tutorial" annotation does not exist. Use "## @tutorial(Title): https://example.com" instead.)");
  1559. } else {
  1560. push_error(vformat(R"(Unrecognized annotation: "%s".)", annotation->name));
  1561. }
  1562. valid = false;
  1563. }
  1564. if (valid) {
  1565. annotation->info = &valid_annotations[annotation->name];
  1566. if (!annotation->applies_to(p_valid_targets)) {
  1567. if (annotation->applies_to(AnnotationInfo::SCRIPT)) {
  1568. push_error(vformat(R"(Annotation "%s" must be at the top of the script, before "extends" and "class_name".)", annotation->name));
  1569. } else {
  1570. push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name));
  1571. }
  1572. valid = false;
  1573. }
  1574. }
  1575. if (check(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1576. push_multiline(true);
  1577. advance();
  1578. // Arguments.
  1579. push_completion_call(annotation);
  1580. int argument_index = 0;
  1581. do {
  1582. make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index);
  1583. set_last_completion_call_arg(argument_index);
  1584. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1585. // Allow for trailing comma.
  1586. break;
  1587. }
  1588. ExpressionNode *argument = parse_expression(false);
  1589. if (argument == nullptr) {
  1590. push_error("Expected expression as the annotation argument.");
  1591. valid = false;
  1592. } else {
  1593. annotation->arguments.push_back(argument);
  1594. if (argument->type == Node::LITERAL) {
  1595. override_completion_context(argument, COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index);
  1596. }
  1597. }
  1598. argument_index++;
  1599. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  1600. pop_multiline();
  1601. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after annotation arguments.)*");
  1602. pop_completion_call();
  1603. }
  1604. complete_extents(annotation);
  1605. match(GDScriptTokenizer::Token::NEWLINE); // Newline after annotation is optional.
  1606. if (valid) {
  1607. valid = validate_annotation_arguments(annotation);
  1608. }
  1609. return valid ? annotation : nullptr;
  1610. }
  1611. void GDScriptParser::clear_unused_annotations() {
  1612. for (const AnnotationNode *annotation : annotation_stack) {
  1613. push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
  1614. }
  1615. annotation_stack.clear();
  1616. }
  1617. bool GDScriptParser::register_annotation(const MethodInfo &p_info, uint32_t p_target_kinds, AnnotationAction p_apply, const Vector<Variant> &p_default_arguments, bool p_is_vararg) {
  1618. ERR_FAIL_COND_V_MSG(valid_annotations.has(p_info.name), false, vformat(R"(Annotation "%s" already registered.)", p_info.name));
  1619. AnnotationInfo new_annotation;
  1620. new_annotation.info = p_info;
  1621. new_annotation.info.default_arguments = p_default_arguments;
  1622. if (p_is_vararg) {
  1623. new_annotation.info.flags |= METHOD_FLAG_VARARG;
  1624. }
  1625. new_annotation.apply = p_apply;
  1626. new_annotation.target_kind = p_target_kinds;
  1627. valid_annotations[p_info.name] = new_annotation;
  1628. return true;
  1629. }
  1630. GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, SuiteNode *p_suite, bool p_for_lambda) {
  1631. SuiteNode *suite = p_suite != nullptr ? p_suite : alloc_node<SuiteNode>();
  1632. suite->parent_block = current_suite;
  1633. suite->parent_function = current_function;
  1634. current_suite = suite;
  1635. if (!p_for_lambda && suite->parent_block != nullptr && suite->parent_block->is_in_loop) {
  1636. // Do not reset to false if true is set before calling parse_suite().
  1637. suite->is_in_loop = true;
  1638. }
  1639. bool multiline = false;
  1640. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1641. multiline = true;
  1642. }
  1643. if (multiline) {
  1644. if (!consume(GDScriptTokenizer::Token::INDENT, vformat(R"(Expected indented block after %s.)", p_context))) {
  1645. current_suite = suite->parent_block;
  1646. complete_extents(suite);
  1647. return suite;
  1648. }
  1649. }
  1650. reset_extents(suite, current);
  1651. int error_count = 0;
  1652. do {
  1653. if (is_at_end() || (!multiline && previous.type == GDScriptTokenizer::Token::SEMICOLON && check(GDScriptTokenizer::Token::NEWLINE))) {
  1654. break;
  1655. }
  1656. Node *statement = parse_statement();
  1657. if (statement == nullptr) {
  1658. if (error_count++ > 100) {
  1659. push_error("Too many statement errors.", suite);
  1660. break;
  1661. }
  1662. continue;
  1663. }
  1664. suite->statements.push_back(statement);
  1665. // Register locals.
  1666. switch (statement->type) {
  1667. case Node::VARIABLE: {
  1668. VariableNode *variable = static_cast<VariableNode *>(statement);
  1669. const SuiteNode::Local &local = current_suite->get_local(variable->identifier->name);
  1670. if (local.type != SuiteNode::Local::UNDEFINED) {
  1671. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), variable->identifier->name), variable->identifier);
  1672. }
  1673. current_suite->add_local(variable, current_function);
  1674. break;
  1675. }
  1676. case Node::CONSTANT: {
  1677. ConstantNode *constant = static_cast<ConstantNode *>(statement);
  1678. const SuiteNode::Local &local = current_suite->get_local(constant->identifier->name);
  1679. if (local.type != SuiteNode::Local::UNDEFINED) {
  1680. String name;
  1681. if (local.type == SuiteNode::Local::CONSTANT) {
  1682. name = "constant";
  1683. } else {
  1684. name = "variable";
  1685. }
  1686. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", name, constant->identifier->name), constant->identifier);
  1687. }
  1688. current_suite->add_local(constant, current_function);
  1689. break;
  1690. }
  1691. default:
  1692. break;
  1693. }
  1694. } while ((multiline || previous.type == GDScriptTokenizer::Token::SEMICOLON) && !check(GDScriptTokenizer::Token::DEDENT) && !lambda_ended && !is_at_end());
  1695. complete_extents(suite);
  1696. if (multiline) {
  1697. if (!lambda_ended) {
  1698. consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context));
  1699. } else {
  1700. match(GDScriptTokenizer::Token::DEDENT);
  1701. }
  1702. } else if (previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  1703. consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after ";" at the end of %s.)", p_context));
  1704. }
  1705. if (p_for_lambda) {
  1706. lambda_ended = true;
  1707. }
  1708. current_suite = suite->parent_block;
  1709. return suite;
  1710. }
  1711. GDScriptParser::Node *GDScriptParser::parse_statement() {
  1712. Node *result = nullptr;
  1713. #ifdef DEBUG_ENABLED
  1714. bool unreachable = current_suite->has_return && !current_suite->has_unreachable_code;
  1715. #endif
  1716. List<AnnotationNode *> annotations;
  1717. if (current.type != GDScriptTokenizer::Token::ANNOTATION) {
  1718. while (!annotation_stack.is_empty()) {
  1719. AnnotationNode *last_annotation = annotation_stack.back()->get();
  1720. if (last_annotation->applies_to(AnnotationInfo::STATEMENT)) {
  1721. annotations.push_front(last_annotation);
  1722. annotation_stack.pop_back();
  1723. } else {
  1724. push_error(vformat(R"(Annotation "%s" cannot be applied to a statement.)", last_annotation->name));
  1725. clear_unused_annotations();
  1726. }
  1727. }
  1728. }
  1729. switch (current.type) {
  1730. case GDScriptTokenizer::Token::PASS:
  1731. advance();
  1732. result = alloc_node<PassNode>();
  1733. complete_extents(result);
  1734. end_statement(R"("pass")");
  1735. break;
  1736. case GDScriptTokenizer::Token::VAR:
  1737. advance();
  1738. result = parse_variable(false, false, false);
  1739. break;
  1740. case GDScriptTokenizer::Token::TK_CONST:
  1741. advance();
  1742. result = parse_constant(false, false);
  1743. break;
  1744. case GDScriptTokenizer::Token::IF:
  1745. advance();
  1746. result = parse_if();
  1747. break;
  1748. case GDScriptTokenizer::Token::FOR:
  1749. advance();
  1750. result = parse_for();
  1751. break;
  1752. case GDScriptTokenizer::Token::WHILE:
  1753. advance();
  1754. result = parse_while();
  1755. break;
  1756. case GDScriptTokenizer::Token::MATCH:
  1757. advance();
  1758. result = parse_match();
  1759. break;
  1760. case GDScriptTokenizer::Token::BREAK:
  1761. advance();
  1762. result = parse_break();
  1763. break;
  1764. case GDScriptTokenizer::Token::CONTINUE:
  1765. advance();
  1766. result = parse_continue();
  1767. break;
  1768. case GDScriptTokenizer::Token::RETURN: {
  1769. advance();
  1770. ReturnNode *n_return = alloc_node<ReturnNode>();
  1771. if (!is_statement_end()) {
  1772. if (current_function && (current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init || current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init)) {
  1773. push_error(R"(Constructor cannot return a value.)");
  1774. }
  1775. n_return->return_value = parse_expression(false);
  1776. } else if (in_lambda && !is_statement_end_token()) {
  1777. // Try to parse it anyway as this might not be the statement end in a lambda.
  1778. // If this fails the expression will be nullptr, but that's the same as no return, so it's fine.
  1779. n_return->return_value = parse_expression(false);
  1780. }
  1781. complete_extents(n_return);
  1782. result = n_return;
  1783. current_suite->has_return = true;
  1784. end_statement("return statement");
  1785. break;
  1786. }
  1787. case GDScriptTokenizer::Token::BREAKPOINT:
  1788. advance();
  1789. result = alloc_node<BreakpointNode>();
  1790. complete_extents(result);
  1791. end_statement(R"("breakpoint")");
  1792. break;
  1793. case GDScriptTokenizer::Token::ASSERT:
  1794. advance();
  1795. result = parse_assert();
  1796. break;
  1797. case GDScriptTokenizer::Token::ANNOTATION: {
  1798. advance();
  1799. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT | AnnotationInfo::STANDALONE);
  1800. if (annotation != nullptr) {
  1801. if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
  1802. if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
  1803. push_error(R"(Expected newline after a standalone annotation.)");
  1804. }
  1805. if (annotation->name == SNAME("@warning_ignore_start") || annotation->name == SNAME("@warning_ignore_restore")) {
  1806. // Some annotations need to be resolved and applied in the parser.
  1807. annotation->apply(this, nullptr, nullptr);
  1808. } else {
  1809. push_error(R"(Unexpected standalone annotation.)");
  1810. }
  1811. } else {
  1812. annotation_stack.push_back(annotation);
  1813. }
  1814. }
  1815. break;
  1816. }
  1817. default: {
  1818. // Expression statement.
  1819. ExpressionNode *expression = parse_expression(true); // Allow assignment here.
  1820. bool has_ended_lambda = false;
  1821. if (expression == nullptr) {
  1822. if (in_lambda) {
  1823. // If it's not a valid expression beginning, it might be the continuation of the outer expression where this lambda is.
  1824. lambda_ended = true;
  1825. has_ended_lambda = true;
  1826. } else {
  1827. advance();
  1828. push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name()));
  1829. }
  1830. } else {
  1831. end_statement("expression");
  1832. }
  1833. lambda_ended = lambda_ended || has_ended_lambda;
  1834. result = expression;
  1835. #ifdef DEBUG_ENABLED
  1836. if (expression != nullptr) {
  1837. switch (expression->type) {
  1838. case Node::ASSIGNMENT:
  1839. case Node::AWAIT:
  1840. case Node::CALL:
  1841. // Fine.
  1842. break;
  1843. case Node::PRELOAD:
  1844. // `preload` is a function-like keyword.
  1845. push_warning(expression, GDScriptWarning::RETURN_VALUE_DISCARDED, "preload");
  1846. break;
  1847. case Node::LAMBDA:
  1848. // Standalone lambdas can't be used, so make this an error.
  1849. push_error("Standalone lambdas cannot be accessed. Consider assigning it to a variable.", expression);
  1850. break;
  1851. case Node::LITERAL:
  1852. // Allow strings as multiline comments.
  1853. if (static_cast<GDScriptParser::LiteralNode *>(expression)->value.get_type() != Variant::STRING) {
  1854. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1855. }
  1856. break;
  1857. case Node::TERNARY_OPERATOR:
  1858. push_warning(expression, GDScriptWarning::STANDALONE_TERNARY);
  1859. break;
  1860. default:
  1861. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1862. }
  1863. }
  1864. #endif
  1865. break;
  1866. }
  1867. }
  1868. #ifdef TOOLS_ENABLED
  1869. int doc_comment_line = 0;
  1870. if (result != nullptr) {
  1871. doc_comment_line = result->start_line - 1;
  1872. }
  1873. #endif // TOOLS_ENABLED
  1874. if (result != nullptr && !annotations.is_empty()) {
  1875. for (AnnotationNode *&annotation : annotations) {
  1876. result->annotations.push_back(annotation);
  1877. #ifdef TOOLS_ENABLED
  1878. if (annotation->start_line <= doc_comment_line) {
  1879. doc_comment_line = annotation->start_line - 1;
  1880. }
  1881. #endif // TOOLS_ENABLED
  1882. }
  1883. }
  1884. #ifdef TOOLS_ENABLED
  1885. if (result != nullptr) {
  1886. MemberDocData doc_data;
  1887. if (has_comment(result->start_line, true)) {
  1888. // Inline doc comment.
  1889. doc_data = parse_doc_comment(result->start_line, true);
  1890. } else if (doc_comment_line >= current_function->min_local_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  1891. // Normal doc comment.
  1892. doc_data = parse_doc_comment(doc_comment_line);
  1893. }
  1894. if (result->type == Node::CONSTANT) {
  1895. static_cast<ConstantNode *>(result)->doc_data = doc_data;
  1896. } else if (result->type == Node::VARIABLE) {
  1897. static_cast<VariableNode *>(result)->doc_data = doc_data;
  1898. }
  1899. current_function->min_local_doc_line = result->end_line + 1; // Prevent multiple locals from using the same doc comment.
  1900. }
  1901. #endif // TOOLS_ENABLED
  1902. #ifdef DEBUG_ENABLED
  1903. if (unreachable && result != nullptr) {
  1904. current_suite->has_unreachable_code = true;
  1905. if (current_function) {
  1906. push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier ? current_function->identifier->name : "<anonymous lambda>");
  1907. } else {
  1908. // TODO: Properties setters and getters with unreachable code are not being warned
  1909. }
  1910. }
  1911. #endif
  1912. if (panic_mode) {
  1913. synchronize();
  1914. }
  1915. return result;
  1916. }
  1917. GDScriptParser::AssertNode *GDScriptParser::parse_assert() {
  1918. // TODO: Add assert message.
  1919. AssertNode *assert = alloc_node<AssertNode>();
  1920. push_multiline(true);
  1921. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "assert".)");
  1922. assert->condition = parse_expression(false);
  1923. if (assert->condition == nullptr) {
  1924. push_error("Expected expression to assert.");
  1925. pop_multiline();
  1926. complete_extents(assert);
  1927. return nullptr;
  1928. }
  1929. if (match(GDScriptTokenizer::Token::COMMA) && !check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1930. assert->message = parse_expression(false);
  1931. if (assert->message == nullptr) {
  1932. push_error(R"(Expected error message for assert after ",".)");
  1933. pop_multiline();
  1934. complete_extents(assert);
  1935. return nullptr;
  1936. }
  1937. match(GDScriptTokenizer::Token::COMMA);
  1938. }
  1939. pop_multiline();
  1940. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after assert expression.)*");
  1941. complete_extents(assert);
  1942. end_statement(R"("assert")");
  1943. return assert;
  1944. }
  1945. GDScriptParser::BreakNode *GDScriptParser::parse_break() {
  1946. if (!can_break) {
  1947. push_error(R"(Cannot use "break" outside of a loop.)");
  1948. }
  1949. BreakNode *break_node = alloc_node<BreakNode>();
  1950. complete_extents(break_node);
  1951. end_statement(R"("break")");
  1952. return break_node;
  1953. }
  1954. GDScriptParser::ContinueNode *GDScriptParser::parse_continue() {
  1955. if (!can_continue) {
  1956. push_error(R"(Cannot use "continue" outside of a loop.)");
  1957. }
  1958. current_suite->has_continue = true;
  1959. ContinueNode *cont = alloc_node<ContinueNode>();
  1960. complete_extents(cont);
  1961. end_statement(R"("continue")");
  1962. return cont;
  1963. }
  1964. GDScriptParser::ForNode *GDScriptParser::parse_for() {
  1965. ForNode *n_for = alloc_node<ForNode>();
  1966. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected loop variable name after "for".)")) {
  1967. n_for->variable = parse_identifier();
  1968. }
  1969. if (match(GDScriptTokenizer::Token::COLON)) {
  1970. n_for->datatype_specifier = parse_type();
  1971. if (n_for->datatype_specifier == nullptr) {
  1972. push_error(R"(Expected type specifier after ":".)");
  1973. }
  1974. }
  1975. if (n_for->datatype_specifier == nullptr) {
  1976. consume(GDScriptTokenizer::Token::TK_IN, R"(Expected "in" or ":" after "for" variable name.)");
  1977. } else {
  1978. consume(GDScriptTokenizer::Token::TK_IN, R"(Expected "in" after "for" variable type specifier.)");
  1979. }
  1980. n_for->list = parse_expression(false);
  1981. if (!n_for->list) {
  1982. push_error(R"(Expected iterable after "in".)");
  1983. }
  1984. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)");
  1985. // Save break/continue state.
  1986. bool could_break = can_break;
  1987. bool could_continue = can_continue;
  1988. // Allow break/continue.
  1989. can_break = true;
  1990. can_continue = true;
  1991. SuiteNode *suite = alloc_node<SuiteNode>();
  1992. if (n_for->variable) {
  1993. const SuiteNode::Local &local = current_suite->get_local(n_for->variable->name);
  1994. if (local.type != SuiteNode::Local::UNDEFINED) {
  1995. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), n_for->variable->name), n_for->variable);
  1996. }
  1997. suite->add_local(SuiteNode::Local(n_for->variable, current_function));
  1998. }
  1999. suite->is_in_loop = true;
  2000. n_for->loop = parse_suite(R"("for" block)", suite);
  2001. complete_extents(n_for);
  2002. // Reset break/continue state.
  2003. can_break = could_break;
  2004. can_continue = could_continue;
  2005. return n_for;
  2006. }
  2007. GDScriptParser::IfNode *GDScriptParser::parse_if(const String &p_token) {
  2008. IfNode *n_if = alloc_node<IfNode>();
  2009. n_if->condition = parse_expression(false);
  2010. if (n_if->condition == nullptr) {
  2011. push_error(vformat(R"(Expected conditional expression after "%s".)", p_token));
  2012. }
  2013. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after "%s" condition.)", p_token));
  2014. n_if->true_block = parse_suite(vformat(R"("%s" block)", p_token));
  2015. n_if->true_block->parent_if = n_if;
  2016. if (n_if->true_block->has_continue) {
  2017. current_suite->has_continue = true;
  2018. }
  2019. if (match(GDScriptTokenizer::Token::ELIF)) {
  2020. SuiteNode *else_block = alloc_node<SuiteNode>();
  2021. else_block->parent_function = current_function;
  2022. else_block->parent_block = current_suite;
  2023. SuiteNode *previous_suite = current_suite;
  2024. current_suite = else_block;
  2025. IfNode *elif = parse_if("elif");
  2026. else_block->statements.push_back(elif);
  2027. complete_extents(else_block);
  2028. n_if->false_block = else_block;
  2029. current_suite = previous_suite;
  2030. } else if (match(GDScriptTokenizer::Token::ELSE)) {
  2031. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "else".)");
  2032. n_if->false_block = parse_suite(R"("else" block)");
  2033. }
  2034. complete_extents(n_if);
  2035. if (n_if->false_block != nullptr && n_if->false_block->has_return && n_if->true_block->has_return) {
  2036. current_suite->has_return = true;
  2037. }
  2038. if (n_if->false_block != nullptr && n_if->false_block->has_continue) {
  2039. current_suite->has_continue = true;
  2040. }
  2041. return n_if;
  2042. }
  2043. GDScriptParser::MatchNode *GDScriptParser::parse_match() {
  2044. MatchNode *match_node = alloc_node<MatchNode>();
  2045. match_node->test = parse_expression(false);
  2046. if (match_node->test == nullptr) {
  2047. push_error(R"(Expected expression to test after "match".)");
  2048. }
  2049. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" expression.)");
  2050. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected a newline after "match" statement.)");
  2051. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected an indented block after "match" statement.)")) {
  2052. complete_extents(match_node);
  2053. return match_node;
  2054. }
  2055. bool all_have_return = true;
  2056. bool have_wildcard = false;
  2057. List<AnnotationNode *> match_branch_annotation_stack;
  2058. while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
  2059. if (match(GDScriptTokenizer::Token::PASS)) {
  2060. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected newline after "pass".)");
  2061. continue;
  2062. }
  2063. if (match(GDScriptTokenizer::Token::ANNOTATION)) {
  2064. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
  2065. if (annotation == nullptr) {
  2066. continue;
  2067. }
  2068. if (annotation->name != SNAME("@warning_ignore")) {
  2069. push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name), annotation);
  2070. continue;
  2071. }
  2072. match_branch_annotation_stack.push_back(annotation);
  2073. continue;
  2074. }
  2075. MatchBranchNode *branch = parse_match_branch();
  2076. if (branch == nullptr) {
  2077. advance();
  2078. continue;
  2079. }
  2080. for (AnnotationNode *annotation : match_branch_annotation_stack) {
  2081. branch->annotations.push_back(annotation);
  2082. }
  2083. match_branch_annotation_stack.clear();
  2084. #ifdef DEBUG_ENABLED
  2085. if (have_wildcard && !branch->patterns.is_empty()) {
  2086. push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
  2087. }
  2088. #endif
  2089. have_wildcard = have_wildcard || branch->has_wildcard;
  2090. all_have_return = all_have_return && branch->block->has_return;
  2091. match_node->branches.push_back(branch);
  2092. }
  2093. complete_extents(match_node);
  2094. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
  2095. if (all_have_return && have_wildcard) {
  2096. current_suite->has_return = true;
  2097. }
  2098. for (const AnnotationNode *annotation : match_branch_annotation_stack) {
  2099. push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
  2100. }
  2101. match_branch_annotation_stack.clear();
  2102. return match_node;
  2103. }
  2104. GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
  2105. MatchBranchNode *branch = alloc_node<MatchBranchNode>();
  2106. reset_extents(branch, current);
  2107. bool has_bind = false;
  2108. do {
  2109. PatternNode *pattern = parse_match_pattern();
  2110. if (pattern == nullptr) {
  2111. continue;
  2112. }
  2113. if (pattern->binds.size() > 0) {
  2114. has_bind = true;
  2115. }
  2116. if (branch->patterns.size() > 0 && has_bind) {
  2117. push_error(R"(Cannot use a variable bind with multiple patterns.)");
  2118. }
  2119. if (pattern->pattern_type == PatternNode::PT_REST) {
  2120. push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
  2121. } else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
  2122. branch->has_wildcard = true;
  2123. }
  2124. branch->patterns.push_back(pattern);
  2125. } while (match(GDScriptTokenizer::Token::COMMA));
  2126. if (branch->patterns.is_empty()) {
  2127. push_error(R"(No pattern found for "match" branch.)");
  2128. }
  2129. bool has_guard = false;
  2130. if (match(GDScriptTokenizer::Token::WHEN)) {
  2131. // Pattern guard.
  2132. // Create block for guard because it also needs to access the bound variables from patterns, and we don't want to add them to the outer scope.
  2133. branch->guard_body = alloc_node<SuiteNode>();
  2134. if (branch->patterns.size() > 0) {
  2135. for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
  2136. SuiteNode::Local local(E.value, current_function);
  2137. local.type = SuiteNode::Local::PATTERN_BIND;
  2138. branch->guard_body->add_local(local);
  2139. }
  2140. }
  2141. SuiteNode *parent_block = current_suite;
  2142. branch->guard_body->parent_block = parent_block;
  2143. current_suite = branch->guard_body;
  2144. ExpressionNode *guard = parse_expression(false);
  2145. if (guard == nullptr) {
  2146. push_error(R"(Expected expression for pattern guard after "when".)");
  2147. } else {
  2148. branch->guard_body->statements.append(guard);
  2149. }
  2150. current_suite = parent_block;
  2151. complete_extents(branch->guard_body);
  2152. has_guard = true;
  2153. branch->has_wildcard = false; // If it has a guard, the wildcard might still not match.
  2154. }
  2155. if (!consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":"%s after "match" %s.)", has_guard ? "" : R"( or "when")", has_guard ? "pattern guard" : "patterns"))) {
  2156. branch->block = alloc_recovery_suite();
  2157. complete_extents(branch);
  2158. // Consume the whole line and treat the next one as new match branch.
  2159. while (current.type != GDScriptTokenizer::Token::NEWLINE && !is_at_end()) {
  2160. advance();
  2161. }
  2162. if (!is_at_end()) {
  2163. advance();
  2164. }
  2165. return branch;
  2166. }
  2167. SuiteNode *suite = alloc_node<SuiteNode>();
  2168. if (branch->patterns.size() > 0) {
  2169. for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
  2170. SuiteNode::Local local(E.value, current_function);
  2171. local.type = SuiteNode::Local::PATTERN_BIND;
  2172. suite->add_local(local);
  2173. }
  2174. }
  2175. branch->block = parse_suite("match pattern block", suite);
  2176. complete_extents(branch);
  2177. return branch;
  2178. }
  2179. GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
  2180. PatternNode *pattern = alloc_node<PatternNode>();
  2181. reset_extents(pattern, current);
  2182. switch (current.type) {
  2183. case GDScriptTokenizer::Token::VAR: {
  2184. // Bind.
  2185. advance();
  2186. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
  2187. complete_extents(pattern);
  2188. return nullptr;
  2189. }
  2190. pattern->pattern_type = PatternNode::PT_BIND;
  2191. pattern->bind = parse_identifier();
  2192. PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
  2193. if (p_root_pattern != nullptr) {
  2194. if (p_root_pattern->has_bind(pattern->bind->name)) {
  2195. push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
  2196. complete_extents(pattern);
  2197. return nullptr;
  2198. }
  2199. }
  2200. if (current_suite->has_local(pattern->bind->name)) {
  2201. push_error(vformat(R"(There's already a %s named "%s" in this scope.)", current_suite->get_local(pattern->bind->name).get_name(), pattern->bind->name));
  2202. complete_extents(pattern);
  2203. return nullptr;
  2204. }
  2205. root_pattern->binds[pattern->bind->name] = pattern->bind;
  2206. } break;
  2207. case GDScriptTokenizer::Token::UNDERSCORE:
  2208. // Wildcard.
  2209. advance();
  2210. pattern->pattern_type = PatternNode::PT_WILDCARD;
  2211. break;
  2212. case GDScriptTokenizer::Token::PERIOD_PERIOD:
  2213. // Rest.
  2214. advance();
  2215. pattern->pattern_type = PatternNode::PT_REST;
  2216. break;
  2217. case GDScriptTokenizer::Token::BRACKET_OPEN: {
  2218. // Array.
  2219. push_multiline(true);
  2220. advance();
  2221. pattern->pattern_type = PatternNode::PT_ARRAY;
  2222. do {
  2223. if (is_at_end() || check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2224. break;
  2225. }
  2226. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  2227. if (sub_pattern == nullptr) {
  2228. continue;
  2229. }
  2230. if (pattern->rest_used) {
  2231. push_error(R"(The ".." pattern must be the last element in the pattern array.)");
  2232. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  2233. pattern->rest_used = true;
  2234. }
  2235. pattern->array.push_back(sub_pattern);
  2236. } while (match(GDScriptTokenizer::Token::COMMA));
  2237. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
  2238. pop_multiline();
  2239. break;
  2240. }
  2241. case GDScriptTokenizer::Token::BRACE_OPEN: {
  2242. // Dictionary.
  2243. push_multiline(true);
  2244. advance();
  2245. pattern->pattern_type = PatternNode::PT_DICTIONARY;
  2246. do {
  2247. if (check(GDScriptTokenizer::Token::BRACE_CLOSE) || is_at_end()) {
  2248. break;
  2249. }
  2250. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
  2251. // Rest.
  2252. if (pattern->rest_used) {
  2253. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  2254. } else {
  2255. PatternNode *sub_pattern = alloc_node<PatternNode>();
  2256. complete_extents(sub_pattern);
  2257. sub_pattern->pattern_type = PatternNode::PT_REST;
  2258. pattern->dictionary.push_back({ nullptr, sub_pattern });
  2259. pattern->rest_used = true;
  2260. }
  2261. } else {
  2262. ExpressionNode *key = parse_expression(false);
  2263. if (key == nullptr) {
  2264. push_error(R"(Expected expression as key for dictionary pattern.)");
  2265. }
  2266. if (match(GDScriptTokenizer::Token::COLON)) {
  2267. // Value pattern.
  2268. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  2269. if (sub_pattern == nullptr) {
  2270. continue;
  2271. }
  2272. if (pattern->rest_used) {
  2273. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  2274. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  2275. push_error(R"(The ".." pattern cannot be used as a value.)");
  2276. } else {
  2277. pattern->dictionary.push_back({ key, sub_pattern });
  2278. }
  2279. } else {
  2280. // Key match only.
  2281. pattern->dictionary.push_back({ key, nullptr });
  2282. }
  2283. }
  2284. } while (match(GDScriptTokenizer::Token::COMMA));
  2285. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
  2286. pop_multiline();
  2287. break;
  2288. }
  2289. default: {
  2290. // Expression.
  2291. ExpressionNode *expression = parse_expression(false);
  2292. if (expression == nullptr) {
  2293. push_error(R"(Expected expression for match pattern.)");
  2294. complete_extents(pattern);
  2295. return nullptr;
  2296. } else {
  2297. if (expression->type == GDScriptParser::Node::LITERAL) {
  2298. pattern->pattern_type = PatternNode::PT_LITERAL;
  2299. } else {
  2300. pattern->pattern_type = PatternNode::PT_EXPRESSION;
  2301. }
  2302. pattern->expression = expression;
  2303. }
  2304. break;
  2305. }
  2306. }
  2307. complete_extents(pattern);
  2308. return pattern;
  2309. }
  2310. bool GDScriptParser::PatternNode::has_bind(const StringName &p_name) {
  2311. return binds.has(p_name);
  2312. }
  2313. GDScriptParser::IdentifierNode *GDScriptParser::PatternNode::get_bind(const StringName &p_name) {
  2314. return binds[p_name];
  2315. }
  2316. GDScriptParser::WhileNode *GDScriptParser::parse_while() {
  2317. WhileNode *n_while = alloc_node<WhileNode>();
  2318. n_while->condition = parse_expression(false);
  2319. if (n_while->condition == nullptr) {
  2320. push_error(R"(Expected conditional expression after "while".)");
  2321. }
  2322. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "while" condition.)");
  2323. // Save break/continue state.
  2324. bool could_break = can_break;
  2325. bool could_continue = can_continue;
  2326. // Allow break/continue.
  2327. can_break = true;
  2328. can_continue = true;
  2329. SuiteNode *suite = alloc_node<SuiteNode>();
  2330. suite->is_in_loop = true;
  2331. n_while->loop = parse_suite(R"("while" block)", suite);
  2332. complete_extents(n_while);
  2333. // Reset break/continue state.
  2334. can_break = could_break;
  2335. can_continue = could_continue;
  2336. return n_while;
  2337. }
  2338. GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign) {
  2339. // Switch multiline mode on for grouping tokens.
  2340. // Do this early to avoid the tokenizer generating whitespace tokens.
  2341. switch (current.type) {
  2342. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  2343. case GDScriptTokenizer::Token::BRACE_OPEN:
  2344. case GDScriptTokenizer::Token::BRACKET_OPEN:
  2345. push_multiline(true);
  2346. break;
  2347. default:
  2348. break; // Nothing to do.
  2349. }
  2350. // Completion can appear whenever an expression is expected.
  2351. make_completion_context(COMPLETION_IDENTIFIER, nullptr, -1, false);
  2352. GDScriptTokenizer::Token token = current;
  2353. GDScriptTokenizer::Token::Type token_type = token.type;
  2354. if (token.is_identifier()) {
  2355. // Allow keywords that can be treated as identifiers.
  2356. token_type = GDScriptTokenizer::Token::IDENTIFIER;
  2357. }
  2358. ParseFunction prefix_rule = get_rule(token_type)->prefix;
  2359. if (prefix_rule == nullptr) {
  2360. // Expected expression. Let the caller give the proper error message.
  2361. return nullptr;
  2362. }
  2363. advance(); // Only consume the token if there's a valid rule.
  2364. // After a token was consumed, update the completion context regardless of a previously set context.
  2365. ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign);
  2366. #ifdef TOOLS_ENABLED
  2367. // HACK: We can't create a context in parse_identifier since it is used in places were we don't want completion.
  2368. if (previous_operand != nullptr && previous_operand->type == GDScriptParser::Node::IDENTIFIER && prefix_rule == static_cast<ParseFunction>(&GDScriptParser::parse_identifier)) {
  2369. make_completion_context(COMPLETION_IDENTIFIER, previous_operand);
  2370. }
  2371. #endif
  2372. while (p_precedence <= get_rule(current.type)->precedence) {
  2373. if (previous_operand == nullptr || (p_stop_on_assign && current.type == GDScriptTokenizer::Token::EQUAL) || lambda_ended) {
  2374. return previous_operand;
  2375. }
  2376. // Also switch multiline mode on here for infix operators.
  2377. switch (current.type) {
  2378. // case GDScriptTokenizer::Token::BRACE_OPEN: // Not an infix operator.
  2379. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  2380. case GDScriptTokenizer::Token::BRACKET_OPEN:
  2381. push_multiline(true);
  2382. break;
  2383. default:
  2384. break; // Nothing to do.
  2385. }
  2386. token = advance();
  2387. ParseFunction infix_rule = get_rule(token.type)->infix;
  2388. previous_operand = (this->*infix_rule)(previous_operand, p_can_assign);
  2389. }
  2390. return previous_operand;
  2391. }
  2392. GDScriptParser::ExpressionNode *GDScriptParser::parse_expression(bool p_can_assign, bool p_stop_on_assign) {
  2393. return parse_precedence(PREC_ASSIGNMENT, p_can_assign, p_stop_on_assign);
  2394. }
  2395. GDScriptParser::IdentifierNode *GDScriptParser::parse_identifier() {
  2396. IdentifierNode *identifier = static_cast<IdentifierNode *>(parse_identifier(nullptr, false));
  2397. #ifdef DEBUG_ENABLED
  2398. // Check for spoofing here (if available in TextServer) since this isn't called inside expressions. This is only relevant for declarations.
  2399. if (identifier && TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier->name)) {
  2400. push_warning(identifier, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier->name.operator String());
  2401. }
  2402. #endif
  2403. return identifier;
  2404. }
  2405. GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2406. if (!previous.is_identifier()) {
  2407. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing identifier node without identifier token.");
  2408. }
  2409. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  2410. complete_extents(identifier);
  2411. identifier->name = previous.get_identifier();
  2412. if (identifier->name.operator String().is_empty()) {
  2413. print_line("Empty identifier found.");
  2414. }
  2415. identifier->suite = current_suite;
  2416. if (current_suite != nullptr && current_suite->has_local(identifier->name)) {
  2417. const SuiteNode::Local &declaration = current_suite->get_local(identifier->name);
  2418. identifier->source_function = declaration.source_function;
  2419. switch (declaration.type) {
  2420. case SuiteNode::Local::CONSTANT:
  2421. identifier->source = IdentifierNode::LOCAL_CONSTANT;
  2422. identifier->constant_source = declaration.constant;
  2423. declaration.constant->usages++;
  2424. break;
  2425. case SuiteNode::Local::VARIABLE:
  2426. identifier->source = IdentifierNode::LOCAL_VARIABLE;
  2427. identifier->variable_source = declaration.variable;
  2428. declaration.variable->usages++;
  2429. break;
  2430. case SuiteNode::Local::PARAMETER:
  2431. identifier->source = IdentifierNode::FUNCTION_PARAMETER;
  2432. identifier->parameter_source = declaration.parameter;
  2433. declaration.parameter->usages++;
  2434. break;
  2435. case SuiteNode::Local::FOR_VARIABLE:
  2436. identifier->source = IdentifierNode::LOCAL_ITERATOR;
  2437. identifier->bind_source = declaration.bind;
  2438. declaration.bind->usages++;
  2439. break;
  2440. case SuiteNode::Local::PATTERN_BIND:
  2441. identifier->source = IdentifierNode::LOCAL_BIND;
  2442. identifier->bind_source = declaration.bind;
  2443. declaration.bind->usages++;
  2444. break;
  2445. case SuiteNode::Local::UNDEFINED:
  2446. ERR_FAIL_V_MSG(nullptr, "Undefined local found.");
  2447. }
  2448. }
  2449. return identifier;
  2450. }
  2451. GDScriptParser::LiteralNode *GDScriptParser::parse_literal() {
  2452. return static_cast<LiteralNode *>(parse_literal(nullptr, false));
  2453. }
  2454. GDScriptParser::ExpressionNode *GDScriptParser::parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2455. if (previous.type != GDScriptTokenizer::Token::LITERAL) {
  2456. push_error("Parser bug: parsing literal node without literal token.");
  2457. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
  2458. }
  2459. LiteralNode *literal = alloc_node<LiteralNode>();
  2460. literal->value = previous.literal;
  2461. reset_extents(literal, p_previous_operand);
  2462. update_extents(literal);
  2463. make_completion_context(COMPLETION_NONE, literal, -1);
  2464. complete_extents(literal);
  2465. return literal;
  2466. }
  2467. GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2468. if (current_function && current_function->is_static) {
  2469. push_error(R"(Cannot use "self" inside a static function.)");
  2470. }
  2471. SelfNode *self = alloc_node<SelfNode>();
  2472. complete_extents(self);
  2473. self->current_class = current_class;
  2474. return self;
  2475. }
  2476. GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2477. GDScriptTokenizer::Token::Type op_type = previous.type;
  2478. LiteralNode *constant = alloc_node<LiteralNode>();
  2479. complete_extents(constant);
  2480. switch (op_type) {
  2481. case GDScriptTokenizer::Token::CONST_PI:
  2482. constant->value = Math::PI;
  2483. break;
  2484. case GDScriptTokenizer::Token::CONST_TAU:
  2485. constant->value = Math::TAU;
  2486. break;
  2487. case GDScriptTokenizer::Token::CONST_INF:
  2488. constant->value = Math::INF;
  2489. break;
  2490. case GDScriptTokenizer::Token::CONST_NAN:
  2491. constant->value = Math::NaN;
  2492. break;
  2493. default:
  2494. return nullptr; // Unreachable.
  2495. }
  2496. return constant;
  2497. }
  2498. GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2499. GDScriptTokenizer::Token::Type op_type = previous.type;
  2500. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2501. switch (op_type) {
  2502. case GDScriptTokenizer::Token::MINUS:
  2503. operation->operation = UnaryOpNode::OP_NEGATIVE;
  2504. operation->variant_op = Variant::OP_NEGATE;
  2505. operation->operand = parse_precedence(PREC_SIGN, false);
  2506. if (operation->operand == nullptr) {
  2507. push_error(R"(Expected expression after "-" operator.)");
  2508. }
  2509. break;
  2510. case GDScriptTokenizer::Token::PLUS:
  2511. operation->operation = UnaryOpNode::OP_POSITIVE;
  2512. operation->variant_op = Variant::OP_POSITIVE;
  2513. operation->operand = parse_precedence(PREC_SIGN, false);
  2514. if (operation->operand == nullptr) {
  2515. push_error(R"(Expected expression after "+" operator.)");
  2516. }
  2517. break;
  2518. case GDScriptTokenizer::Token::TILDE:
  2519. operation->operation = UnaryOpNode::OP_COMPLEMENT;
  2520. operation->variant_op = Variant::OP_BIT_NEGATE;
  2521. operation->operand = parse_precedence(PREC_BIT_NOT, false);
  2522. if (operation->operand == nullptr) {
  2523. push_error(R"(Expected expression after "~" operator.)");
  2524. }
  2525. break;
  2526. case GDScriptTokenizer::Token::NOT:
  2527. case GDScriptTokenizer::Token::BANG:
  2528. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2529. operation->variant_op = Variant::OP_NOT;
  2530. operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
  2531. if (operation->operand == nullptr) {
  2532. push_error(vformat(R"(Expected expression after "%s" operator.)", op_type == GDScriptTokenizer::Token::NOT ? "not" : "!"));
  2533. }
  2534. break;
  2535. default:
  2536. complete_extents(operation);
  2537. return nullptr; // Unreachable.
  2538. }
  2539. complete_extents(operation);
  2540. return operation;
  2541. }
  2542. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_not_in_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2543. // check that NOT is followed by IN by consuming it before calling parse_binary_operator which will only receive a plain IN
  2544. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2545. reset_extents(operation, p_previous_operand);
  2546. update_extents(operation);
  2547. consume(GDScriptTokenizer::Token::TK_IN, R"(Expected "in" after "not" in content-test operator.)");
  2548. ExpressionNode *in_operation = parse_binary_operator(p_previous_operand, p_can_assign);
  2549. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2550. operation->variant_op = Variant::OP_NOT;
  2551. operation->operand = in_operation;
  2552. complete_extents(operation);
  2553. return operation;
  2554. }
  2555. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2556. GDScriptTokenizer::Token op = previous;
  2557. BinaryOpNode *operation = alloc_node<BinaryOpNode>();
  2558. reset_extents(operation, p_previous_operand);
  2559. update_extents(operation);
  2560. Precedence precedence = (Precedence)(get_rule(op.type)->precedence + 1);
  2561. operation->left_operand = p_previous_operand;
  2562. operation->right_operand = parse_precedence(precedence, false);
  2563. complete_extents(operation);
  2564. if (operation->right_operand == nullptr) {
  2565. push_error(vformat(R"(Expected expression after "%s" operator.)", op.get_name()));
  2566. }
  2567. // TODO: Also for unary, ternary, and assignment.
  2568. switch (op.type) {
  2569. case GDScriptTokenizer::Token::PLUS:
  2570. operation->operation = BinaryOpNode::OP_ADDITION;
  2571. operation->variant_op = Variant::OP_ADD;
  2572. break;
  2573. case GDScriptTokenizer::Token::MINUS:
  2574. operation->operation = BinaryOpNode::OP_SUBTRACTION;
  2575. operation->variant_op = Variant::OP_SUBTRACT;
  2576. break;
  2577. case GDScriptTokenizer::Token::STAR:
  2578. operation->operation = BinaryOpNode::OP_MULTIPLICATION;
  2579. operation->variant_op = Variant::OP_MULTIPLY;
  2580. break;
  2581. case GDScriptTokenizer::Token::SLASH:
  2582. operation->operation = BinaryOpNode::OP_DIVISION;
  2583. operation->variant_op = Variant::OP_DIVIDE;
  2584. break;
  2585. case GDScriptTokenizer::Token::PERCENT:
  2586. operation->operation = BinaryOpNode::OP_MODULO;
  2587. operation->variant_op = Variant::OP_MODULE;
  2588. break;
  2589. case GDScriptTokenizer::Token::STAR_STAR:
  2590. operation->operation = BinaryOpNode::OP_POWER;
  2591. operation->variant_op = Variant::OP_POWER;
  2592. break;
  2593. case GDScriptTokenizer::Token::LESS_LESS:
  2594. operation->operation = BinaryOpNode::OP_BIT_LEFT_SHIFT;
  2595. operation->variant_op = Variant::OP_SHIFT_LEFT;
  2596. break;
  2597. case GDScriptTokenizer::Token::GREATER_GREATER:
  2598. operation->operation = BinaryOpNode::OP_BIT_RIGHT_SHIFT;
  2599. operation->variant_op = Variant::OP_SHIFT_RIGHT;
  2600. break;
  2601. case GDScriptTokenizer::Token::AMPERSAND:
  2602. operation->operation = BinaryOpNode::OP_BIT_AND;
  2603. operation->variant_op = Variant::OP_BIT_AND;
  2604. break;
  2605. case GDScriptTokenizer::Token::PIPE:
  2606. operation->operation = BinaryOpNode::OP_BIT_OR;
  2607. operation->variant_op = Variant::OP_BIT_OR;
  2608. break;
  2609. case GDScriptTokenizer::Token::CARET:
  2610. operation->operation = BinaryOpNode::OP_BIT_XOR;
  2611. operation->variant_op = Variant::OP_BIT_XOR;
  2612. break;
  2613. case GDScriptTokenizer::Token::AND:
  2614. case GDScriptTokenizer::Token::AMPERSAND_AMPERSAND:
  2615. operation->operation = BinaryOpNode::OP_LOGIC_AND;
  2616. operation->variant_op = Variant::OP_AND;
  2617. break;
  2618. case GDScriptTokenizer::Token::OR:
  2619. case GDScriptTokenizer::Token::PIPE_PIPE:
  2620. operation->operation = BinaryOpNode::OP_LOGIC_OR;
  2621. operation->variant_op = Variant::OP_OR;
  2622. break;
  2623. case GDScriptTokenizer::Token::TK_IN:
  2624. operation->operation = BinaryOpNode::OP_CONTENT_TEST;
  2625. operation->variant_op = Variant::OP_IN;
  2626. break;
  2627. case GDScriptTokenizer::Token::EQUAL_EQUAL:
  2628. operation->operation = BinaryOpNode::OP_COMP_EQUAL;
  2629. operation->variant_op = Variant::OP_EQUAL;
  2630. break;
  2631. case GDScriptTokenizer::Token::BANG_EQUAL:
  2632. operation->operation = BinaryOpNode::OP_COMP_NOT_EQUAL;
  2633. operation->variant_op = Variant::OP_NOT_EQUAL;
  2634. break;
  2635. case GDScriptTokenizer::Token::LESS:
  2636. operation->operation = BinaryOpNode::OP_COMP_LESS;
  2637. operation->variant_op = Variant::OP_LESS;
  2638. break;
  2639. case GDScriptTokenizer::Token::LESS_EQUAL:
  2640. operation->operation = BinaryOpNode::OP_COMP_LESS_EQUAL;
  2641. operation->variant_op = Variant::OP_LESS_EQUAL;
  2642. break;
  2643. case GDScriptTokenizer::Token::GREATER:
  2644. operation->operation = BinaryOpNode::OP_COMP_GREATER;
  2645. operation->variant_op = Variant::OP_GREATER;
  2646. break;
  2647. case GDScriptTokenizer::Token::GREATER_EQUAL:
  2648. operation->operation = BinaryOpNode::OP_COMP_GREATER_EQUAL;
  2649. operation->variant_op = Variant::OP_GREATER_EQUAL;
  2650. break;
  2651. default:
  2652. return nullptr; // Unreachable.
  2653. }
  2654. return operation;
  2655. }
  2656. GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2657. // Only one ternary operation exists, so no abstraction here.
  2658. TernaryOpNode *operation = alloc_node<TernaryOpNode>();
  2659. reset_extents(operation, p_previous_operand);
  2660. update_extents(operation);
  2661. operation->true_expr = p_previous_operand;
  2662. operation->condition = parse_precedence(PREC_TERNARY, false);
  2663. if (operation->condition == nullptr) {
  2664. push_error(R"(Expected expression as ternary condition after "if".)");
  2665. }
  2666. consume(GDScriptTokenizer::Token::ELSE, R"(Expected "else" after ternary operator condition.)");
  2667. operation->false_expr = parse_precedence(PREC_TERNARY, false);
  2668. if (operation->false_expr == nullptr) {
  2669. push_error(R"(Expected expression after "else".)");
  2670. }
  2671. complete_extents(operation);
  2672. return operation;
  2673. }
  2674. GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2675. if (!p_can_assign) {
  2676. push_error("Assignment is not allowed inside an expression.");
  2677. return parse_expression(false); // Return the following expression.
  2678. }
  2679. if (p_previous_operand == nullptr) {
  2680. return parse_expression(false); // Return the following expression.
  2681. }
  2682. switch (p_previous_operand->type) {
  2683. case Node::IDENTIFIER: {
  2684. #ifdef DEBUG_ENABLED
  2685. // Get source to store assignment count.
  2686. // Also remove one usage since assignment isn't usage.
  2687. IdentifierNode *id = static_cast<IdentifierNode *>(p_previous_operand);
  2688. switch (id->source) {
  2689. case IdentifierNode::LOCAL_VARIABLE:
  2690. id->variable_source->usages--;
  2691. break;
  2692. case IdentifierNode::LOCAL_CONSTANT:
  2693. id->constant_source->usages--;
  2694. break;
  2695. case IdentifierNode::FUNCTION_PARAMETER:
  2696. id->parameter_source->usages--;
  2697. break;
  2698. case IdentifierNode::LOCAL_ITERATOR:
  2699. case IdentifierNode::LOCAL_BIND:
  2700. id->bind_source->usages--;
  2701. break;
  2702. default:
  2703. break;
  2704. }
  2705. #endif
  2706. } break;
  2707. case Node::SUBSCRIPT:
  2708. // Okay.
  2709. break;
  2710. default:
  2711. push_error(R"(Only identifier, attribute access, and subscription access can be used as assignment target.)");
  2712. return parse_expression(false); // Return the following expression.
  2713. }
  2714. AssignmentNode *assignment = alloc_node<AssignmentNode>();
  2715. reset_extents(assignment, p_previous_operand);
  2716. update_extents(assignment);
  2717. make_completion_context(COMPLETION_ASSIGN, assignment);
  2718. switch (previous.type) {
  2719. case GDScriptTokenizer::Token::EQUAL:
  2720. assignment->operation = AssignmentNode::OP_NONE;
  2721. assignment->variant_op = Variant::OP_MAX;
  2722. break;
  2723. case GDScriptTokenizer::Token::PLUS_EQUAL:
  2724. assignment->operation = AssignmentNode::OP_ADDITION;
  2725. assignment->variant_op = Variant::OP_ADD;
  2726. break;
  2727. case GDScriptTokenizer::Token::MINUS_EQUAL:
  2728. assignment->operation = AssignmentNode::OP_SUBTRACTION;
  2729. assignment->variant_op = Variant::OP_SUBTRACT;
  2730. break;
  2731. case GDScriptTokenizer::Token::STAR_EQUAL:
  2732. assignment->operation = AssignmentNode::OP_MULTIPLICATION;
  2733. assignment->variant_op = Variant::OP_MULTIPLY;
  2734. break;
  2735. case GDScriptTokenizer::Token::STAR_STAR_EQUAL:
  2736. assignment->operation = AssignmentNode::OP_POWER;
  2737. assignment->variant_op = Variant::OP_POWER;
  2738. break;
  2739. case GDScriptTokenizer::Token::SLASH_EQUAL:
  2740. assignment->operation = AssignmentNode::OP_DIVISION;
  2741. assignment->variant_op = Variant::OP_DIVIDE;
  2742. break;
  2743. case GDScriptTokenizer::Token::PERCENT_EQUAL:
  2744. assignment->operation = AssignmentNode::OP_MODULO;
  2745. assignment->variant_op = Variant::OP_MODULE;
  2746. break;
  2747. case GDScriptTokenizer::Token::LESS_LESS_EQUAL:
  2748. assignment->operation = AssignmentNode::OP_BIT_SHIFT_LEFT;
  2749. assignment->variant_op = Variant::OP_SHIFT_LEFT;
  2750. break;
  2751. case GDScriptTokenizer::Token::GREATER_GREATER_EQUAL:
  2752. assignment->operation = AssignmentNode::OP_BIT_SHIFT_RIGHT;
  2753. assignment->variant_op = Variant::OP_SHIFT_RIGHT;
  2754. break;
  2755. case GDScriptTokenizer::Token::AMPERSAND_EQUAL:
  2756. assignment->operation = AssignmentNode::OP_BIT_AND;
  2757. assignment->variant_op = Variant::OP_BIT_AND;
  2758. break;
  2759. case GDScriptTokenizer::Token::PIPE_EQUAL:
  2760. assignment->operation = AssignmentNode::OP_BIT_OR;
  2761. assignment->variant_op = Variant::OP_BIT_OR;
  2762. break;
  2763. case GDScriptTokenizer::Token::CARET_EQUAL:
  2764. assignment->operation = AssignmentNode::OP_BIT_XOR;
  2765. assignment->variant_op = Variant::OP_BIT_XOR;
  2766. break;
  2767. default:
  2768. break; // Unreachable.
  2769. }
  2770. assignment->assignee = p_previous_operand;
  2771. assignment->assigned_value = parse_expression(false);
  2772. #ifdef TOOLS_ENABLED
  2773. if (assignment->assigned_value != nullptr && assignment->assigned_value->type == GDScriptParser::Node::IDENTIFIER) {
  2774. override_completion_context(assignment->assigned_value, COMPLETION_ASSIGN, assignment);
  2775. }
  2776. #endif
  2777. if (assignment->assigned_value == nullptr) {
  2778. push_error(R"(Expected an expression after "=".)");
  2779. }
  2780. complete_extents(assignment);
  2781. return assignment;
  2782. }
  2783. GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2784. AwaitNode *await = alloc_node<AwaitNode>();
  2785. ExpressionNode *element = parse_precedence(PREC_AWAIT, false);
  2786. if (element == nullptr) {
  2787. push_error(R"(Expected signal or coroutine after "await".)");
  2788. }
  2789. await->to_await = element;
  2790. complete_extents(await);
  2791. if (current_function) { // Might be null in a getter or setter.
  2792. current_function->is_coroutine = true;
  2793. }
  2794. return await;
  2795. }
  2796. GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2797. ArrayNode *array = alloc_node<ArrayNode>();
  2798. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2799. do {
  2800. if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2801. // Allow for trailing comma.
  2802. break;
  2803. }
  2804. ExpressionNode *element = parse_expression(false);
  2805. if (element == nullptr) {
  2806. push_error(R"(Expected expression as array element.)");
  2807. } else {
  2808. array->elements.push_back(element);
  2809. }
  2810. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2811. }
  2812. pop_multiline();
  2813. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
  2814. complete_extents(array);
  2815. return array;
  2816. }
  2817. GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2818. DictionaryNode *dictionary = alloc_node<DictionaryNode>();
  2819. bool decided_style = false;
  2820. if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2821. do {
  2822. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2823. // Allow for trailing comma.
  2824. break;
  2825. }
  2826. // Key.
  2827. ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
  2828. if (key == nullptr) {
  2829. push_error(R"(Expected expression as dictionary key.)");
  2830. }
  2831. if (!decided_style) {
  2832. switch (current.type) {
  2833. case GDScriptTokenizer::Token::COLON:
  2834. dictionary->style = DictionaryNode::PYTHON_DICT;
  2835. break;
  2836. case GDScriptTokenizer::Token::EQUAL:
  2837. dictionary->style = DictionaryNode::LUA_TABLE;
  2838. break;
  2839. default:
  2840. push_error(R"(Expected ":" or "=" after dictionary key.)");
  2841. break;
  2842. }
  2843. decided_style = true;
  2844. }
  2845. switch (dictionary->style) {
  2846. case DictionaryNode::LUA_TABLE:
  2847. if (key != nullptr && key->type != Node::IDENTIFIER && key->type != Node::LITERAL) {
  2848. push_error(R"(Expected identifier or string as Lua-style dictionary key (e.g "{ key = value }").)");
  2849. }
  2850. if (key != nullptr && key->type == Node::LITERAL && static_cast<LiteralNode *>(key)->value.get_type() != Variant::STRING) {
  2851. push_error(R"(Expected identifier or string as Lua-style dictionary key (e.g "{ key = value }").)");
  2852. }
  2853. if (!match(GDScriptTokenizer::Token::EQUAL)) {
  2854. if (match(GDScriptTokenizer::Token::COLON)) {
  2855. push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
  2856. advance(); // Consume wrong separator anyway.
  2857. } else {
  2858. push_error(R"(Expected "=" after dictionary key.)");
  2859. }
  2860. }
  2861. if (key != nullptr) {
  2862. key->is_constant = true;
  2863. if (key->type == Node::IDENTIFIER) {
  2864. key->reduced_value = static_cast<IdentifierNode *>(key)->name;
  2865. } else if (key->type == Node::LITERAL) {
  2866. key->reduced_value = StringName(static_cast<LiteralNode *>(key)->value.operator String());
  2867. }
  2868. }
  2869. break;
  2870. case DictionaryNode::PYTHON_DICT:
  2871. if (!match(GDScriptTokenizer::Token::COLON)) {
  2872. if (match(GDScriptTokenizer::Token::EQUAL)) {
  2873. push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
  2874. advance(); // Consume wrong separator anyway.
  2875. } else {
  2876. push_error(R"(Expected ":" after dictionary key.)");
  2877. }
  2878. }
  2879. break;
  2880. }
  2881. // Value.
  2882. ExpressionNode *value = parse_expression(false);
  2883. if (value == nullptr) {
  2884. push_error(R"(Expected expression as dictionary value.)");
  2885. }
  2886. if (key != nullptr && value != nullptr) {
  2887. dictionary->elements.push_back({ key, value });
  2888. }
  2889. // Do phrase level recovery by inserting an imaginary expression for missing keys or values.
  2890. // This ensures the successfully parsed expression is part of the AST and can be analyzed.
  2891. if (key != nullptr && value == nullptr) {
  2892. LiteralNode *dummy = alloc_recovery_node<LiteralNode>();
  2893. dummy->value = Variant();
  2894. dictionary->elements.push_back({ key, dummy });
  2895. } else if (key == nullptr && value != nullptr) {
  2896. LiteralNode *dummy = alloc_recovery_node<LiteralNode>();
  2897. dummy->value = Variant();
  2898. dictionary->elements.push_back({ dummy, value });
  2899. }
  2900. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2901. }
  2902. pop_multiline();
  2903. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
  2904. complete_extents(dictionary);
  2905. return dictionary;
  2906. }
  2907. GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2908. ExpressionNode *grouped = parse_expression(false);
  2909. pop_multiline();
  2910. if (grouped == nullptr) {
  2911. push_error(R"(Expected grouping expression.)");
  2912. } else {
  2913. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
  2914. }
  2915. return grouped;
  2916. }
  2917. GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2918. SubscriptNode *attribute = alloc_node<SubscriptNode>();
  2919. reset_extents(attribute, p_previous_operand);
  2920. update_extents(attribute);
  2921. if (for_completion) {
  2922. bool is_builtin = false;
  2923. if (p_previous_operand && p_previous_operand->type == Node::IDENTIFIER) {
  2924. const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
  2925. Variant::Type builtin_type = get_builtin_type(id->name);
  2926. if (builtin_type < Variant::VARIANT_MAX) {
  2927. make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT_OR_STATIC_METHOD, builtin_type);
  2928. is_builtin = true;
  2929. }
  2930. }
  2931. if (!is_builtin) {
  2932. make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1);
  2933. }
  2934. }
  2935. attribute->base = p_previous_operand;
  2936. if (current.is_node_name()) {
  2937. current.type = GDScriptTokenizer::Token::IDENTIFIER;
  2938. }
  2939. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
  2940. complete_extents(attribute);
  2941. return attribute;
  2942. }
  2943. attribute->is_attribute = true;
  2944. attribute->attribute = parse_identifier();
  2945. complete_extents(attribute);
  2946. return attribute;
  2947. }
  2948. GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2949. SubscriptNode *subscript = alloc_node<SubscriptNode>();
  2950. reset_extents(subscript, p_previous_operand);
  2951. update_extents(subscript);
  2952. make_completion_context(COMPLETION_SUBSCRIPT, subscript);
  2953. subscript->base = p_previous_operand;
  2954. subscript->index = parse_expression(false);
  2955. #ifdef TOOLS_ENABLED
  2956. if (subscript->index != nullptr && subscript->index->type == Node::LITERAL) {
  2957. override_completion_context(subscript->index, COMPLETION_SUBSCRIPT, subscript);
  2958. }
  2959. #endif
  2960. if (subscript->index == nullptr) {
  2961. push_error(R"(Expected expression after "[".)");
  2962. }
  2963. pop_multiline();
  2964. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
  2965. complete_extents(subscript);
  2966. return subscript;
  2967. }
  2968. GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2969. CastNode *cast = alloc_node<CastNode>();
  2970. reset_extents(cast, p_previous_operand);
  2971. update_extents(cast);
  2972. cast->operand = p_previous_operand;
  2973. cast->cast_type = parse_type();
  2974. complete_extents(cast);
  2975. if (cast->cast_type == nullptr) {
  2976. push_error(R"(Expected type specifier after "as".)");
  2977. return p_previous_operand;
  2978. }
  2979. return cast;
  2980. }
  2981. GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2982. CallNode *call = alloc_node<CallNode>();
  2983. reset_extents(call, p_previous_operand);
  2984. if (previous.type == GDScriptTokenizer::Token::SUPER) {
  2985. // Super call.
  2986. call->is_super = true;
  2987. push_multiline(true);
  2988. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  2989. // Implicit call to the parent method of the same name.
  2990. if (current_function == nullptr) {
  2991. push_error(R"(Cannot use implicit "super" call outside of a function.)");
  2992. pop_multiline();
  2993. complete_extents(call);
  2994. return nullptr;
  2995. }
  2996. if (current_function->identifier) {
  2997. call->function_name = current_function->identifier->name;
  2998. } else {
  2999. call->function_name = SNAME("<anonymous>");
  3000. }
  3001. } else {
  3002. consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
  3003. make_completion_context(COMPLETION_SUPER_METHOD, call, true);
  3004. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
  3005. pop_multiline();
  3006. complete_extents(call);
  3007. return nullptr;
  3008. }
  3009. IdentifierNode *identifier = parse_identifier();
  3010. call->callee = identifier;
  3011. call->function_name = identifier->name;
  3012. if (!consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)")) {
  3013. pop_multiline();
  3014. complete_extents(call);
  3015. return nullptr;
  3016. }
  3017. }
  3018. } else {
  3019. call->callee = p_previous_operand;
  3020. if (call->callee == nullptr) {
  3021. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  3022. } else if (call->callee->type == Node::IDENTIFIER) {
  3023. call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
  3024. make_completion_context(COMPLETION_METHOD, call->callee);
  3025. } else if (call->callee->type == Node::SUBSCRIPT) {
  3026. SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
  3027. if (attribute->is_attribute) {
  3028. if (attribute->attribute) {
  3029. call->function_name = attribute->attribute->name;
  3030. }
  3031. make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
  3032. } else {
  3033. // TODO: The analyzer can see if this is actually a Callable and give better error message.
  3034. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  3035. }
  3036. } else {
  3037. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  3038. }
  3039. }
  3040. // Arguments.
  3041. CompletionType ct = COMPLETION_CALL_ARGUMENTS;
  3042. if (call->function_name == SNAME("load")) {
  3043. ct = COMPLETION_RESOURCE_PATH;
  3044. }
  3045. push_completion_call(call);
  3046. int argument_index = 0;
  3047. do {
  3048. make_completion_context(ct, call, argument_index);
  3049. set_last_completion_call_arg(argument_index);
  3050. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  3051. // Allow for trailing comma.
  3052. break;
  3053. }
  3054. ExpressionNode *argument = parse_expression(false);
  3055. if (argument == nullptr) {
  3056. push_error(R"(Expected expression as the function argument.)");
  3057. } else {
  3058. call->arguments.push_back(argument);
  3059. if (argument->type == Node::LITERAL) {
  3060. override_completion_context(argument, ct, call, argument_index);
  3061. }
  3062. }
  3063. ct = COMPLETION_CALL_ARGUMENTS;
  3064. argument_index++;
  3065. } while (match(GDScriptTokenizer::Token::COMMA));
  3066. pop_completion_call();
  3067. pop_multiline();
  3068. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
  3069. complete_extents(call);
  3070. return call;
  3071. }
  3072. GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3073. // We want code completion after a DOLLAR even if the current code is invalid.
  3074. make_completion_context(COMPLETION_GET_NODE, nullptr, -1);
  3075. if (!current.is_node_name() && !check(GDScriptTokenizer::Token::LITERAL) && !check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  3076. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  3077. return nullptr;
  3078. }
  3079. if (check(GDScriptTokenizer::Token::LITERAL)) {
  3080. if (current.literal.get_type() != Variant::STRING) {
  3081. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  3082. return nullptr;
  3083. }
  3084. }
  3085. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  3086. // Store the last item in the path so the parser knows what to expect.
  3087. // Allow allows more specific error messages.
  3088. enum PathState {
  3089. PATH_STATE_START,
  3090. PATH_STATE_SLASH,
  3091. PATH_STATE_PERCENT,
  3092. PATH_STATE_NODE_NAME,
  3093. } path_state = PATH_STATE_START;
  3094. if (previous.type == GDScriptTokenizer::Token::DOLLAR) {
  3095. // Detect initial slash, which will be handled in the loop if it matches.
  3096. match(GDScriptTokenizer::Token::SLASH);
  3097. } else {
  3098. get_node->use_dollar = false;
  3099. }
  3100. int context_argument = 0;
  3101. do {
  3102. if (previous.type == GDScriptTokenizer::Token::PERCENT) {
  3103. if (path_state != PATH_STATE_START && path_state != PATH_STATE_SLASH) {
  3104. push_error(R"("%" is only valid in the beginning of a node name (either after "$" or after "/"))");
  3105. complete_extents(get_node);
  3106. return nullptr;
  3107. }
  3108. get_node->full_path += "%";
  3109. path_state = PATH_STATE_PERCENT;
  3110. } else if (previous.type == GDScriptTokenizer::Token::SLASH) {
  3111. if (path_state != PATH_STATE_START && path_state != PATH_STATE_NODE_NAME) {
  3112. push_error(R"("/" is only valid at the beginning of the path or after a node name.)");
  3113. complete_extents(get_node);
  3114. return nullptr;
  3115. }
  3116. get_node->full_path += "/";
  3117. path_state = PATH_STATE_SLASH;
  3118. }
  3119. make_completion_context(COMPLETION_GET_NODE, get_node, context_argument++);
  3120. if (match(GDScriptTokenizer::Token::LITERAL)) {
  3121. if (previous.literal.get_type() != Variant::STRING) {
  3122. String previous_token;
  3123. switch (path_state) {
  3124. case PATH_STATE_START:
  3125. previous_token = "$";
  3126. break;
  3127. case PATH_STATE_PERCENT:
  3128. previous_token = "%";
  3129. break;
  3130. case PATH_STATE_SLASH:
  3131. previous_token = "/";
  3132. break;
  3133. default:
  3134. break;
  3135. }
  3136. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous_token));
  3137. complete_extents(get_node);
  3138. return nullptr;
  3139. }
  3140. get_node->full_path += previous.literal.operator String();
  3141. path_state = PATH_STATE_NODE_NAME;
  3142. } else if (current.is_node_name()) {
  3143. advance();
  3144. String identifier = previous.get_identifier();
  3145. #ifdef DEBUG_ENABLED
  3146. // Check spoofing.
  3147. if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier)) {
  3148. push_warning(get_node, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier);
  3149. }
  3150. #endif
  3151. get_node->full_path += identifier;
  3152. path_state = PATH_STATE_NODE_NAME;
  3153. } else if (!check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  3154. push_error(vformat(R"(Unexpected "%s" in node path.)", current.get_name()));
  3155. complete_extents(get_node);
  3156. return nullptr;
  3157. }
  3158. } while (match(GDScriptTokenizer::Token::SLASH) || match(GDScriptTokenizer::Token::PERCENT));
  3159. complete_extents(get_node);
  3160. return get_node;
  3161. }
  3162. GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3163. PreloadNode *preload = alloc_node<PreloadNode>();
  3164. preload->resolved_path = "<missing path>";
  3165. push_multiline(true);
  3166. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
  3167. make_completion_context(COMPLETION_RESOURCE_PATH, preload);
  3168. push_completion_call(preload);
  3169. preload->path = parse_expression(false);
  3170. if (preload->path == nullptr) {
  3171. push_error(R"(Expected resource path after "(".)");
  3172. } else if (preload->path->type == Node::LITERAL) {
  3173. override_completion_context(preload->path, COMPLETION_RESOURCE_PATH, preload);
  3174. }
  3175. pop_completion_call();
  3176. pop_multiline();
  3177. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
  3178. complete_extents(preload);
  3179. return preload;
  3180. }
  3181. GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3182. LambdaNode *lambda = alloc_node<LambdaNode>();
  3183. lambda->parent_function = current_function;
  3184. lambda->parent_lambda = current_lambda;
  3185. FunctionNode *function = alloc_node<FunctionNode>();
  3186. function->source_lambda = lambda;
  3187. function->is_static = current_function != nullptr ? current_function->is_static : false;
  3188. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  3189. function->identifier = parse_identifier();
  3190. }
  3191. bool multiline_context = multiline_stack.back()->get();
  3192. // Reset the multiline stack since we don't want the multiline mode one in the lambda body.
  3193. push_multiline(false);
  3194. if (multiline_context) {
  3195. tokenizer->push_expression_indented_block();
  3196. }
  3197. push_multiline(true); // For the parameters.
  3198. if (function->identifier) {
  3199. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)");
  3200. } else {
  3201. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)");
  3202. }
  3203. FunctionNode *previous_function = current_function;
  3204. current_function = function;
  3205. LambdaNode *previous_lambda = current_lambda;
  3206. current_lambda = lambda;
  3207. SuiteNode *body = alloc_node<SuiteNode>();
  3208. body->parent_function = current_function;
  3209. body->parent_block = current_suite;
  3210. SuiteNode *previous_suite = current_suite;
  3211. current_suite = body;
  3212. parse_function_signature(function, body, "lambda", -1);
  3213. current_suite = previous_suite;
  3214. bool previous_in_lambda = in_lambda;
  3215. in_lambda = true;
  3216. // Save break/continue state.
  3217. bool could_break = can_break;
  3218. bool could_continue = can_continue;
  3219. // Disallow break/continue.
  3220. can_break = false;
  3221. can_continue = false;
  3222. function->body = parse_suite("lambda declaration", body, true);
  3223. complete_extents(function);
  3224. complete_extents(lambda);
  3225. pop_multiline();
  3226. if (multiline_context) {
  3227. // If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens.
  3228. while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) {
  3229. current = tokenizer->scan(); // Not advance() since we don't want to change the previous token.
  3230. }
  3231. tokenizer->pop_expression_indented_block();
  3232. }
  3233. current_function = previous_function;
  3234. current_lambda = previous_lambda;
  3235. in_lambda = previous_in_lambda;
  3236. lambda->function = function;
  3237. // Reset break/continue state.
  3238. can_break = could_break;
  3239. can_continue = could_continue;
  3240. return lambda;
  3241. }
  3242. GDScriptParser::ExpressionNode *GDScriptParser::parse_type_test(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3243. // x is not int
  3244. // ^ ^^^ ExpressionNode, TypeNode
  3245. // ^^^^^^^^^^^^ TypeTestNode
  3246. // ^^^^^^^^^^^^ UnaryOpNode
  3247. UnaryOpNode *not_node = nullptr;
  3248. if (match(GDScriptTokenizer::Token::NOT)) {
  3249. not_node = alloc_node<UnaryOpNode>();
  3250. not_node->operation = UnaryOpNode::OP_LOGIC_NOT;
  3251. not_node->variant_op = Variant::OP_NOT;
  3252. reset_extents(not_node, p_previous_operand);
  3253. update_extents(not_node);
  3254. }
  3255. TypeTestNode *type_test = alloc_node<TypeTestNode>();
  3256. reset_extents(type_test, p_previous_operand);
  3257. update_extents(type_test);
  3258. type_test->operand = p_previous_operand;
  3259. type_test->test_type = parse_type();
  3260. complete_extents(type_test);
  3261. if (not_node != nullptr) {
  3262. not_node->operand = type_test;
  3263. complete_extents(not_node);
  3264. }
  3265. if (type_test->test_type == nullptr) {
  3266. if (not_node == nullptr) {
  3267. push_error(R"(Expected type specifier after "is".)");
  3268. } else {
  3269. push_error(R"(Expected type specifier after "is not".)");
  3270. }
  3271. }
  3272. if (not_node != nullptr) {
  3273. return not_node;
  3274. }
  3275. return type_test;
  3276. }
  3277. GDScriptParser::ExpressionNode *GDScriptParser::parse_yield(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3278. push_error(R"("yield" was removed in Godot 4. Use "await" instead.)");
  3279. return nullptr;
  3280. }
  3281. GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3282. // Just for better error messages.
  3283. GDScriptTokenizer::Token::Type invalid = previous.type;
  3284. switch (invalid) {
  3285. case GDScriptTokenizer::Token::QUESTION_MARK:
  3286. push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
  3287. break;
  3288. default:
  3289. return nullptr; // Unreachable.
  3290. }
  3291. // Return the previous expression.
  3292. return p_previous_operand;
  3293. }
  3294. GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
  3295. TypeNode *type = alloc_node<TypeNode>();
  3296. make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
  3297. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  3298. if (match(GDScriptTokenizer::Token::TK_VOID)) {
  3299. if (p_allow_void) {
  3300. complete_extents(type);
  3301. TypeNode *void_type = type;
  3302. return void_type;
  3303. } else {
  3304. push_error(R"("void" is only allowed for a function return type.)");
  3305. }
  3306. }
  3307. // Leave error message to the caller who knows the context.
  3308. complete_extents(type);
  3309. return nullptr;
  3310. }
  3311. IdentifierNode *type_element = parse_identifier();
  3312. type->type_chain.push_back(type_element);
  3313. if (match(GDScriptTokenizer::Token::BRACKET_OPEN)) {
  3314. // Typed collection (like Array[int], Dictionary[String, int]).
  3315. bool first_pass = true;
  3316. do {
  3317. TypeNode *container_type = parse_type(false); // Don't allow void for element type.
  3318. if (container_type == nullptr) {
  3319. push_error(vformat(R"(Expected type for collection after "%s".)", first_pass ? "[" : ","));
  3320. complete_extents(type);
  3321. type = nullptr;
  3322. break;
  3323. } else if (container_type->container_types.size() > 0) {
  3324. push_error("Nested typed collections are not supported.");
  3325. } else {
  3326. type->container_types.append(container_type);
  3327. }
  3328. first_pass = false;
  3329. } while (match(GDScriptTokenizer::Token::COMMA));
  3330. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after collection type.)");
  3331. if (type != nullptr) {
  3332. complete_extents(type);
  3333. }
  3334. return type;
  3335. }
  3336. int chain_index = 1;
  3337. while (match(GDScriptTokenizer::Token::PERIOD)) {
  3338. make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
  3339. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
  3340. type_element = parse_identifier();
  3341. type->type_chain.push_back(type_element);
  3342. }
  3343. }
  3344. complete_extents(type);
  3345. return type;
  3346. }
  3347. #ifdef TOOLS_ENABLED
  3348. enum DocLineState {
  3349. DOC_LINE_NORMAL,
  3350. DOC_LINE_IN_CODE,
  3351. DOC_LINE_IN_CODEBLOCK,
  3352. DOC_LINE_IN_KBD,
  3353. };
  3354. static String _process_doc_line(const String &p_line, const String &p_text, const String &p_space_prefix, DocLineState &r_state) {
  3355. String line = p_line;
  3356. if (r_state == DOC_LINE_NORMAL) {
  3357. line = line.strip_edges(true, false);
  3358. } else {
  3359. line = line.trim_prefix(p_space_prefix);
  3360. }
  3361. String line_join;
  3362. if (!p_text.is_empty()) {
  3363. if (r_state == DOC_LINE_NORMAL) {
  3364. if (p_text.ends_with("[/codeblock]")) {
  3365. line_join = "\n";
  3366. } else if (!p_text.ends_with("[br]")) {
  3367. line_join = " ";
  3368. }
  3369. } else {
  3370. line_join = "\n";
  3371. }
  3372. }
  3373. String result;
  3374. int from = 0;
  3375. int buffer_start = 0;
  3376. const int len = line.length();
  3377. bool process = true;
  3378. while (process) {
  3379. switch (r_state) {
  3380. case DOC_LINE_NORMAL: {
  3381. int lb_pos = line.find_char('[', from);
  3382. if (lb_pos < 0) {
  3383. process = false;
  3384. break;
  3385. }
  3386. int rb_pos = line.find_char(']', lb_pos + 1);
  3387. if (rb_pos < 0) {
  3388. process = false;
  3389. break;
  3390. }
  3391. from = rb_pos + 1;
  3392. String tag = line.substr(lb_pos + 1, rb_pos - lb_pos - 1);
  3393. if (tag == "code" || tag.begins_with("code ")) {
  3394. r_state = DOC_LINE_IN_CODE;
  3395. } else if (tag == "codeblock" || tag.begins_with("codeblock ")) {
  3396. if (lb_pos == 0) {
  3397. line_join = "\n";
  3398. } else {
  3399. result += line.substr(buffer_start, lb_pos - buffer_start) + '\n';
  3400. }
  3401. result += "[" + tag + "]";
  3402. if (from < len) {
  3403. result += '\n';
  3404. }
  3405. r_state = DOC_LINE_IN_CODEBLOCK;
  3406. buffer_start = from;
  3407. } else if (tag == "kbd") {
  3408. r_state = DOC_LINE_IN_KBD;
  3409. }
  3410. } break;
  3411. case DOC_LINE_IN_CODE: {
  3412. int pos = line.find("[/code]", from);
  3413. if (pos < 0) {
  3414. process = false;
  3415. break;
  3416. }
  3417. from = pos + 7; // `len("[/code]")`.
  3418. r_state = DOC_LINE_NORMAL;
  3419. } break;
  3420. case DOC_LINE_IN_CODEBLOCK: {
  3421. int pos = line.find("[/codeblock]", from);
  3422. if (pos < 0) {
  3423. process = false;
  3424. break;
  3425. }
  3426. from = pos + 12; // `len("[/codeblock]")`.
  3427. if (pos == 0) {
  3428. line_join = "\n";
  3429. } else {
  3430. result += line.substr(buffer_start, pos - buffer_start) + '\n';
  3431. }
  3432. result += "[/codeblock]";
  3433. if (from < len) {
  3434. result += '\n';
  3435. }
  3436. r_state = DOC_LINE_NORMAL;
  3437. buffer_start = from;
  3438. } break;
  3439. case DOC_LINE_IN_KBD: {
  3440. int pos = line.find("[/kbd]", from);
  3441. if (pos < 0) {
  3442. process = false;
  3443. break;
  3444. }
  3445. from = pos + 6; // `len("[/kbd]")`.
  3446. r_state = DOC_LINE_NORMAL;
  3447. } break;
  3448. }
  3449. }
  3450. result += line.substr(buffer_start);
  3451. if (r_state == DOC_LINE_NORMAL) {
  3452. result = result.strip_edges(false, true);
  3453. }
  3454. return line_join + result;
  3455. }
  3456. bool GDScriptParser::has_comment(int p_line, bool p_must_be_doc) {
  3457. bool has_comment = tokenizer->get_comments().has(p_line);
  3458. // If there are no comments or if we don't care whether the comment
  3459. // is a docstring, we have our result.
  3460. if (!p_must_be_doc || !has_comment) {
  3461. return has_comment;
  3462. }
  3463. return tokenizer->get_comments()[p_line].comment.begins_with("##");
  3464. }
  3465. GDScriptParser::MemberDocData GDScriptParser::parse_doc_comment(int p_line, bool p_single_line) {
  3466. ERR_FAIL_COND_V(!has_comment(p_line, true), MemberDocData());
  3467. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  3468. int line = p_line;
  3469. if (!p_single_line) {
  3470. while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
  3471. line--;
  3472. }
  3473. }
  3474. max_script_doc_line = MIN(max_script_doc_line, line - 1);
  3475. String space_prefix;
  3476. {
  3477. int i = 2;
  3478. for (; i < comments[line].comment.length(); i++) {
  3479. if (comments[line].comment[i] != ' ') {
  3480. break;
  3481. }
  3482. }
  3483. space_prefix = String(" ").repeat(i - 2);
  3484. }
  3485. DocLineState state = DOC_LINE_NORMAL;
  3486. MemberDocData result;
  3487. while (line <= p_line) {
  3488. String doc_line = comments[line].comment.trim_prefix("##");
  3489. line++;
  3490. if (state == DOC_LINE_NORMAL) {
  3491. String stripped_line = doc_line.strip_edges();
  3492. if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
  3493. result.is_deprecated = true;
  3494. if (stripped_line.begins_with("@deprecated:")) {
  3495. result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
  3496. }
  3497. continue;
  3498. } else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
  3499. result.is_experimental = true;
  3500. if (stripped_line.begins_with("@experimental:")) {
  3501. result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
  3502. }
  3503. continue;
  3504. }
  3505. }
  3506. result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
  3507. }
  3508. return result;
  3509. }
  3510. GDScriptParser::ClassDocData GDScriptParser::parse_class_doc_comment(int p_line, bool p_single_line) {
  3511. ERR_FAIL_COND_V(!has_comment(p_line, true), ClassDocData());
  3512. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  3513. int line = p_line;
  3514. if (!p_single_line) {
  3515. while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
  3516. line--;
  3517. }
  3518. }
  3519. max_script_doc_line = MIN(max_script_doc_line, line - 1);
  3520. String space_prefix;
  3521. {
  3522. int i = 2;
  3523. for (; i < comments[line].comment.length(); i++) {
  3524. if (comments[line].comment[i] != ' ') {
  3525. break;
  3526. }
  3527. }
  3528. space_prefix = String(" ").repeat(i - 2);
  3529. }
  3530. DocLineState state = DOC_LINE_NORMAL;
  3531. bool is_in_brief = true;
  3532. ClassDocData result;
  3533. while (line <= p_line) {
  3534. String doc_line = comments[line].comment.trim_prefix("##");
  3535. line++;
  3536. if (state == DOC_LINE_NORMAL) {
  3537. String stripped_line = doc_line.strip_edges();
  3538. // A blank line separates the description from the brief.
  3539. if (is_in_brief && !result.brief.is_empty() && stripped_line.is_empty()) {
  3540. is_in_brief = false;
  3541. continue;
  3542. }
  3543. if (stripped_line.begins_with("@tutorial")) {
  3544. String title, link;
  3545. int begin_scan = String("@tutorial").length();
  3546. if (begin_scan >= stripped_line.length()) {
  3547. continue; // Invalid syntax.
  3548. }
  3549. if (stripped_line[begin_scan] == ':') { // No title.
  3550. // Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
  3551. title = "";
  3552. link = stripped_line.trim_prefix("@tutorial:").strip_edges();
  3553. } else {
  3554. /* Syntax:
  3555. * @tutorial ( The Title Here ) : https://the.url/
  3556. * ^ open ^ close ^ colon ^ url
  3557. */
  3558. int open_bracket_pos = begin_scan, close_bracket_pos = 0;
  3559. while (open_bracket_pos < stripped_line.length() && (stripped_line[open_bracket_pos] == ' ' || stripped_line[open_bracket_pos] == '\t')) {
  3560. open_bracket_pos++;
  3561. }
  3562. if (open_bracket_pos == stripped_line.length() || stripped_line[open_bracket_pos++] != '(') {
  3563. continue; // Invalid syntax.
  3564. }
  3565. close_bracket_pos = open_bracket_pos;
  3566. while (close_bracket_pos < stripped_line.length() && stripped_line[close_bracket_pos] != ')') {
  3567. close_bracket_pos++;
  3568. }
  3569. if (close_bracket_pos == stripped_line.length()) {
  3570. continue; // Invalid syntax.
  3571. }
  3572. int colon_pos = close_bracket_pos + 1;
  3573. while (colon_pos < stripped_line.length() && (stripped_line[colon_pos] == ' ' || stripped_line[colon_pos] == '\t')) {
  3574. colon_pos++;
  3575. }
  3576. if (colon_pos == stripped_line.length() || stripped_line[colon_pos++] != ':') {
  3577. continue; // Invalid syntax.
  3578. }
  3579. title = stripped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
  3580. link = stripped_line.substr(colon_pos).strip_edges();
  3581. }
  3582. result.tutorials.append(Pair<String, String>(title, link));
  3583. continue;
  3584. } else if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
  3585. result.is_deprecated = true;
  3586. if (stripped_line.begins_with("@deprecated:")) {
  3587. result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
  3588. }
  3589. continue;
  3590. } else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
  3591. result.is_experimental = true;
  3592. if (stripped_line.begins_with("@experimental:")) {
  3593. result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
  3594. }
  3595. continue;
  3596. }
  3597. }
  3598. if (is_in_brief) {
  3599. result.brief += _process_doc_line(doc_line, result.brief, space_prefix, state);
  3600. } else {
  3601. result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
  3602. }
  3603. }
  3604. return result;
  3605. }
  3606. #endif // TOOLS_ENABLED
  3607. GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
  3608. // Function table for expression parsing.
  3609. // clang-format destroys the alignment here, so turn off for the table.
  3610. /* clang-format off */
  3611. static ParseRule rules[] = {
  3612. // PREFIX INFIX PRECEDENCE (for infix)
  3613. { nullptr, nullptr, PREC_NONE }, // EMPTY,
  3614. // Basic
  3615. { nullptr, nullptr, PREC_NONE }, // ANNOTATION,
  3616. { &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
  3617. { &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
  3618. // Comparison
  3619. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
  3620. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
  3621. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
  3622. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
  3623. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
  3624. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
  3625. // Logical
  3626. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
  3627. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
  3628. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_not_in_operator, PREC_CONTENT_TEST }, // NOT,
  3629. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
  3630. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
  3631. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
  3632. // Bitwise
  3633. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
  3634. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
  3635. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
  3636. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
  3637. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
  3638. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
  3639. // Math
  3640. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
  3641. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
  3642. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
  3643. { nullptr, &GDScriptParser::parse_binary_operator, PREC_POWER }, // STAR_STAR,
  3644. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
  3645. { &GDScriptParser::parse_get_node, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
  3646. // Assignment
  3647. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
  3648. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
  3649. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
  3650. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
  3651. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_STAR_EQUAL,
  3652. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
  3653. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
  3654. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
  3655. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
  3656. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
  3657. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
  3658. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
  3659. // Control flow
  3660. { nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
  3661. { nullptr, nullptr, PREC_NONE }, // ELIF,
  3662. { nullptr, nullptr, PREC_NONE }, // ELSE,
  3663. { nullptr, nullptr, PREC_NONE }, // FOR,
  3664. { nullptr, nullptr, PREC_NONE }, // WHILE,
  3665. { nullptr, nullptr, PREC_NONE }, // BREAK,
  3666. { nullptr, nullptr, PREC_NONE }, // CONTINUE,
  3667. { nullptr, nullptr, PREC_NONE }, // PASS,
  3668. { nullptr, nullptr, PREC_NONE }, // RETURN,
  3669. { nullptr, nullptr, PREC_NONE }, // MATCH,
  3670. { nullptr, nullptr, PREC_NONE }, // WHEN,
  3671. // Keywords
  3672. { nullptr, nullptr, PREC_NONE }, // ABSTRACT
  3673. { nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
  3674. { nullptr, nullptr, PREC_NONE }, // ASSERT,
  3675. { &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
  3676. { nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
  3677. { nullptr, nullptr, PREC_NONE }, // CLASS,
  3678. { nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
  3679. { nullptr, nullptr, PREC_NONE }, // TK_CONST,
  3680. { nullptr, nullptr, PREC_NONE }, // ENUM,
  3681. { nullptr, nullptr, PREC_NONE }, // EXTENDS,
  3682. { &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC,
  3683. { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // TK_IN,
  3684. { nullptr, &GDScriptParser::parse_type_test, PREC_TYPE_TEST }, // IS,
  3685. { nullptr, nullptr, PREC_NONE }, // NAMESPACE,
  3686. { &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
  3687. { &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
  3688. { nullptr, nullptr, PREC_NONE }, // SIGNAL,
  3689. { nullptr, nullptr, PREC_NONE }, // STATIC,
  3690. { &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
  3691. { nullptr, nullptr, PREC_NONE }, // TRAIT,
  3692. { nullptr, nullptr, PREC_NONE }, // VAR,
  3693. { nullptr, nullptr, PREC_NONE }, // TK_VOID,
  3694. { &GDScriptParser::parse_yield, nullptr, PREC_NONE }, // YIELD,
  3695. // Punctuation
  3696. { &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
  3697. { nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
  3698. { &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
  3699. { nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
  3700. { &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
  3701. { nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
  3702. { nullptr, nullptr, PREC_NONE }, // COMMA,
  3703. { nullptr, nullptr, PREC_NONE }, // SEMICOLON,
  3704. { nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
  3705. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
  3706. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD_PERIOD,
  3707. { nullptr, nullptr, PREC_NONE }, // COLON,
  3708. { &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
  3709. { nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
  3710. { nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
  3711. // Whitespace
  3712. { nullptr, nullptr, PREC_NONE }, // NEWLINE,
  3713. { nullptr, nullptr, PREC_NONE }, // INDENT,
  3714. { nullptr, nullptr, PREC_NONE }, // DEDENT,
  3715. // Constants
  3716. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
  3717. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
  3718. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
  3719. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
  3720. // Error message improvement
  3721. { nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
  3722. { nullptr, nullptr, PREC_NONE }, // BACKTICK,
  3723. { nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
  3724. // Special
  3725. { nullptr, nullptr, PREC_NONE }, // ERROR,
  3726. { nullptr, nullptr, PREC_NONE }, // TK_EOF,
  3727. };
  3728. /* clang-format on */
  3729. // Avoid desync.
  3730. static_assert(std::size(rules) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
  3731. // Let's assume this is never invalid, since nothing generates a TK_MAX.
  3732. return &rules[p_token_type];
  3733. }
  3734. bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
  3735. if (locals_indices.has(p_name)) {
  3736. return true;
  3737. }
  3738. if (parent_block != nullptr) {
  3739. return parent_block->has_local(p_name);
  3740. }
  3741. return false;
  3742. }
  3743. const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
  3744. if (locals_indices.has(p_name)) {
  3745. return locals[locals_indices[p_name]];
  3746. }
  3747. if (parent_block != nullptr) {
  3748. return parent_block->get_local(p_name);
  3749. }
  3750. return empty;
  3751. }
  3752. bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target, ClassNode *p_class) {
  3753. if (is_applied) {
  3754. return true;
  3755. }
  3756. is_applied = true;
  3757. return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target, p_class);
  3758. }
  3759. bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
  3760. return (info->target_kind & p_target_kinds) > 0;
  3761. }
  3762. bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
  3763. ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  3764. const MethodInfo &info = valid_annotations[p_annotation->name].info;
  3765. if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
  3766. push_error(vformat(R"(Annotation "%s" requires at most %d arguments, but %d were given.)", p_annotation->name, info.arguments.size(), p_annotation->arguments.size()));
  3767. return false;
  3768. }
  3769. if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  3770. push_error(vformat(R"(Annotation "%s" requires at least %d arguments, but %d were given.)", p_annotation->name, info.arguments.size() - info.default_arguments.size(), p_annotation->arguments.size()));
  3771. return false;
  3772. }
  3773. // Some annotations need to be resolved and applied in the parser.
  3774. if (p_annotation->name == SNAME("@icon") || p_annotation->name == SNAME("@warning_ignore_start") || p_annotation->name == SNAME("@warning_ignore_restore")) {
  3775. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  3776. ExpressionNode *argument = p_annotation->arguments[i];
  3777. if (argument->type != Node::LITERAL) {
  3778. push_error(vformat(R"(Argument %d of annotation "%s" must be a string literal.)", i + 1, p_annotation->name), argument);
  3779. return false;
  3780. }
  3781. Variant value = static_cast<LiteralNode *>(argument)->value;
  3782. if (value.get_type() != Variant::STRING) {
  3783. push_error(vformat(R"(Argument %d of annotation "%s" must be a string literal.)", i + 1, p_annotation->name), argument);
  3784. return false;
  3785. }
  3786. p_annotation->resolved_arguments.push_back(value);
  3787. }
  3788. }
  3789. // For other annotations, see `GDScriptAnalyzer::resolve_annotation()`.
  3790. return true;
  3791. }
  3792. bool GDScriptParser::tool_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3793. #ifdef DEBUG_ENABLED
  3794. if (_is_tool) {
  3795. push_error(R"("@tool" annotation can only be used once.)", p_annotation);
  3796. return false;
  3797. }
  3798. #endif // DEBUG_ENABLED
  3799. _is_tool = true;
  3800. return true;
  3801. }
  3802. bool GDScriptParser::icon_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3803. ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
  3804. ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
  3805. ClassNode *class_node = static_cast<ClassNode *>(p_target);
  3806. String path = p_annotation->resolved_arguments[0];
  3807. #ifdef DEBUG_ENABLED
  3808. if (!class_node->icon_path.is_empty()) {
  3809. push_error(R"("@icon" annotation can only be used once.)", p_annotation);
  3810. return false;
  3811. }
  3812. if (path.is_empty()) {
  3813. push_error(R"("@icon" annotation argument must contain the path to the icon.)", p_annotation->arguments[0]);
  3814. return false;
  3815. }
  3816. #endif // DEBUG_ENABLED
  3817. class_node->icon_path = path;
  3818. if (path.is_empty() || path.is_absolute_path()) {
  3819. class_node->simplified_icon_path = path.simplify_path();
  3820. } else if (path.is_relative_path()) {
  3821. class_node->simplified_icon_path = script_path.get_base_dir().path_join(path).simplify_path();
  3822. } else {
  3823. class_node->simplified_icon_path = path;
  3824. }
  3825. return true;
  3826. }
  3827. bool GDScriptParser::static_unload_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3828. ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, vformat(R"("%s" annotation can only be applied to classes.)", p_annotation->name));
  3829. ClassNode *class_node = static_cast<ClassNode *>(p_target);
  3830. if (class_node->annotated_static_unload) {
  3831. push_error(vformat(R"("%s" annotation can only be used once per script.)", p_annotation->name), p_annotation);
  3832. return false;
  3833. }
  3834. class_node->annotated_static_unload = true;
  3835. return true;
  3836. }
  3837. bool GDScriptParser::onready_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3838. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
  3839. if (current_class && !ClassDB::is_parent_class(current_class->get_datatype().native_type, SNAME("Node"))) {
  3840. push_error(R"("@onready" can only be used in classes that inherit "Node".)", p_annotation);
  3841. return false;
  3842. }
  3843. VariableNode *variable = static_cast<VariableNode *>(p_target);
  3844. if (variable->is_static) {
  3845. push_error(R"("@onready" annotation cannot be applied to a static variable.)", p_annotation);
  3846. return false;
  3847. }
  3848. if (variable->onready) {
  3849. push_error(R"("@onready" annotation can only be used once per variable.)", p_annotation);
  3850. return false;
  3851. }
  3852. variable->onready = true;
  3853. current_class->onready_used = true;
  3854. return true;
  3855. }
  3856. static String _get_annotation_error_string(const StringName &p_annotation_name, const Vector<Variant::Type> &p_expected_types, const GDScriptParser::DataType &p_provided_type) {
  3857. Vector<String> types;
  3858. for (int i = 0; i < p_expected_types.size(); i++) {
  3859. const Variant::Type &type = p_expected_types[i];
  3860. types.push_back(Variant::get_type_name(type));
  3861. types.push_back("Array[" + Variant::get_type_name(type) + "]");
  3862. switch (type) {
  3863. case Variant::INT:
  3864. types.push_back("PackedByteArray");
  3865. types.push_back("PackedInt32Array");
  3866. types.push_back("PackedInt64Array");
  3867. break;
  3868. case Variant::FLOAT:
  3869. types.push_back("PackedFloat32Array");
  3870. types.push_back("PackedFloat64Array");
  3871. break;
  3872. case Variant::STRING:
  3873. types.push_back("PackedStringArray");
  3874. break;
  3875. case Variant::VECTOR2:
  3876. types.push_back("PackedVector2Array");
  3877. break;
  3878. case Variant::VECTOR3:
  3879. types.push_back("PackedVector3Array");
  3880. break;
  3881. case Variant::COLOR:
  3882. types.push_back("PackedColorArray");
  3883. break;
  3884. case Variant::VECTOR4:
  3885. types.push_back("PackedVector4Array");
  3886. break;
  3887. default:
  3888. break;
  3889. }
  3890. }
  3891. String string;
  3892. if (types.size() == 1) {
  3893. string = types[0].quote();
  3894. } else if (types.size() == 2) {
  3895. string = types[0].quote() + " or " + types[1].quote();
  3896. } else if (types.size() >= 3) {
  3897. string = types[0].quote();
  3898. for (int i = 1; i < types.size() - 1; i++) {
  3899. string += ", " + types[i].quote();
  3900. }
  3901. string += ", or " + types[types.size() - 1].quote();
  3902. }
  3903. return vformat(R"("%s" annotation requires a variable of type %s, but type "%s" was given instead.)", p_annotation_name, string, p_provided_type.to_string());
  3904. }
  3905. static StringName _find_narrowest_native_or_global_class(const GDScriptParser::DataType &p_type) {
  3906. switch (p_type.kind) {
  3907. case GDScriptParser::DataType::NATIVE: {
  3908. if (p_type.is_meta_type) {
  3909. return Object::get_class_static(); // `GDScriptNativeClass` is not an exposed class.
  3910. }
  3911. return p_type.native_type;
  3912. } break;
  3913. case GDScriptParser::DataType::SCRIPT: {
  3914. Ref<Script> script;
  3915. if (p_type.script_type.is_valid()) {
  3916. script = p_type.script_type;
  3917. } else {
  3918. script = ResourceLoader::load(p_type.script_path, SNAME("Script"));
  3919. }
  3920. if (p_type.is_meta_type) {
  3921. return script.is_valid() ? script->get_class_name() : Script::get_class_static();
  3922. }
  3923. if (script.is_null()) {
  3924. return p_type.native_type;
  3925. }
  3926. if (script->get_global_name() != StringName()) {
  3927. return script->get_global_name();
  3928. }
  3929. Ref<Script> base_script = script->get_base_script();
  3930. if (base_script.is_null()) {
  3931. return script->get_instance_base_type();
  3932. }
  3933. GDScriptParser::DataType base_type;
  3934. base_type.kind = GDScriptParser::DataType::SCRIPT;
  3935. base_type.builtin_type = Variant::OBJECT;
  3936. base_type.native_type = base_script->get_instance_base_type();
  3937. base_type.script_type = base_script;
  3938. base_type.script_path = base_script->get_path();
  3939. return _find_narrowest_native_or_global_class(base_type);
  3940. } break;
  3941. case GDScriptParser::DataType::CLASS: {
  3942. if (p_type.is_meta_type) {
  3943. return GDScript::get_class_static();
  3944. }
  3945. if (p_type.class_type == nullptr) {
  3946. return p_type.native_type;
  3947. }
  3948. if (p_type.class_type->get_global_name() != StringName()) {
  3949. return p_type.class_type->get_global_name();
  3950. }
  3951. return _find_narrowest_native_or_global_class(p_type.class_type->base_type);
  3952. } break;
  3953. default: {
  3954. ERR_FAIL_V(StringName());
  3955. } break;
  3956. }
  3957. }
  3958. template <PropertyHint t_hint, Variant::Type t_type>
  3959. bool GDScriptParser::export_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3960. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  3961. ERR_FAIL_NULL_V(p_class, false);
  3962. VariableNode *variable = static_cast<VariableNode *>(p_target);
  3963. if (variable->is_static) {
  3964. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  3965. return false;
  3966. }
  3967. if (variable->exported) {
  3968. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  3969. return false;
  3970. }
  3971. variable->exported = true;
  3972. variable->export_info.type = t_type;
  3973. variable->export_info.hint = t_hint;
  3974. String hint_string;
  3975. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  3976. String arg_string = String(p_annotation->resolved_arguments[i]);
  3977. if (p_annotation->name != SNAME("@export_placeholder")) {
  3978. if (arg_string.is_empty()) {
  3979. push_error(vformat(R"(Argument %d of annotation "%s" is empty.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
  3980. return false;
  3981. }
  3982. if (arg_string.contains_char(',')) {
  3983. push_error(vformat(R"(Argument %d of annotation "%s" contains a comma. Use separate arguments instead.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
  3984. return false;
  3985. }
  3986. }
  3987. // WARNING: Do not merge with the previous `if` because there `!=`, not `==`!
  3988. if (p_annotation->name == SNAME("@export_flags")) {
  3989. const int64_t max_flags = 32;
  3990. Vector<String> t = arg_string.split(":", true, 1);
  3991. if (t[0].is_empty()) {
  3992. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag name.)", i + 1), p_annotation->arguments[i]);
  3993. return false;
  3994. }
  3995. if (t.size() == 2) {
  3996. if (t[1].is_empty()) {
  3997. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag value.)", i + 1), p_annotation->arguments[i]);
  3998. return false;
  3999. }
  4000. if (!t[1].is_valid_int()) {
  4001. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": The flag value must be a valid integer.)", i + 1), p_annotation->arguments[i]);
  4002. return false;
  4003. }
  4004. int64_t value = t[1].to_int();
  4005. if (value < 1 || value >= (1LL << max_flags)) {
  4006. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": The flag value must be at least 1 and at most 2 ** %d - 1.)", i + 1, max_flags), p_annotation->arguments[i]);
  4007. return false;
  4008. }
  4009. } else if (i >= max_flags) {
  4010. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Starting from argument %d, the flag value must be specified explicitly.)", i + 1, max_flags + 1), p_annotation->arguments[i]);
  4011. return false;
  4012. }
  4013. } else if (p_annotation->name == SNAME("@export_node_path")) {
  4014. String native_class = arg_string;
  4015. if (ScriptServer::is_global_class(arg_string)) {
  4016. native_class = ScriptServer::get_global_class_native_base(arg_string);
  4017. }
  4018. if (!ClassDB::class_exists(native_class)) {
  4019. push_error(vformat(R"(Invalid argument %d of annotation "@export_node_path": The class "%s" was not found in the global scope.)", i + 1, arg_string), p_annotation->arguments[i]);
  4020. return false;
  4021. } else if (!ClassDB::is_parent_class(native_class, SNAME("Node"))) {
  4022. push_error(vformat(R"(Invalid argument %d of annotation "@export_node_path": The class "%s" does not inherit "Node".)", i + 1, arg_string), p_annotation->arguments[i]);
  4023. return false;
  4024. }
  4025. }
  4026. if (i > 0) {
  4027. hint_string += ",";
  4028. }
  4029. hint_string += arg_string;
  4030. }
  4031. variable->export_info.hint_string = hint_string;
  4032. // This is called after the analyzer is done finding the type, so this should be set here.
  4033. DataType export_type = variable->get_datatype();
  4034. // Use initializer type if specified type is `Variant`.
  4035. if (export_type.is_variant() && variable->initializer != nullptr && variable->initializer->datatype.is_set()) {
  4036. export_type = variable->initializer->get_datatype();
  4037. export_type.type_source = DataType::INFERRED;
  4038. }
  4039. const Variant::Type original_export_type_builtin = export_type.builtin_type;
  4040. // Process array and packed array annotations on the element type.
  4041. bool is_array = false;
  4042. if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type(0)) {
  4043. is_array = true;
  4044. export_type = export_type.get_container_element_type(0);
  4045. } else if (export_type.is_typed_container_type()) {
  4046. is_array = true;
  4047. export_type = export_type.get_typed_container_type();
  4048. export_type.type_source = variable->datatype.type_source;
  4049. }
  4050. bool is_dict = false;
  4051. if (export_type.builtin_type == Variant::DICTIONARY && export_type.has_container_element_types()) {
  4052. is_dict = true;
  4053. DataType inner_type = export_type.get_container_element_type_or_variant(1);
  4054. export_type = export_type.get_container_element_type_or_variant(0);
  4055. export_type.set_container_element_type(0, inner_type); // Store earlier extracted value within key to separately parse after.
  4056. }
  4057. bool use_default_variable_type_check = true;
  4058. if (p_annotation->name == SNAME("@export_range")) {
  4059. if (export_type.builtin_type == Variant::INT) {
  4060. variable->export_info.type = Variant::INT;
  4061. }
  4062. } else if (p_annotation->name == SNAME("@export_multiline")) {
  4063. use_default_variable_type_check = false;
  4064. if (export_type.builtin_type != Variant::STRING && export_type.builtin_type != Variant::DICTIONARY) {
  4065. Vector<Variant::Type> expected_types = { Variant::STRING, Variant::DICTIONARY };
  4066. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  4067. return false;
  4068. }
  4069. if (export_type.builtin_type == Variant::DICTIONARY) {
  4070. variable->export_info.type = Variant::DICTIONARY;
  4071. }
  4072. } else if (p_annotation->name == SNAME("@export")) {
  4073. use_default_variable_type_check = false;
  4074. if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
  4075. push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
  4076. return false;
  4077. }
  4078. if (export_type.has_no_type()) {
  4079. push_error(R"(Cannot use simple "@export" annotation because the type of the initialized value can't be inferred.)", p_annotation);
  4080. return false;
  4081. }
  4082. switch (export_type.kind) {
  4083. case GDScriptParser::DataType::BUILTIN:
  4084. variable->export_info.type = export_type.builtin_type;
  4085. variable->export_info.hint = PROPERTY_HINT_NONE;
  4086. variable->export_info.hint_string = String();
  4087. break;
  4088. case GDScriptParser::DataType::NATIVE:
  4089. case GDScriptParser::DataType::SCRIPT:
  4090. case GDScriptParser::DataType::CLASS: {
  4091. const StringName class_name = _find_narrowest_native_or_global_class(export_type);
  4092. if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
  4093. variable->export_info.type = Variant::OBJECT;
  4094. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  4095. variable->export_info.hint_string = class_name;
  4096. } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
  4097. variable->export_info.type = Variant::OBJECT;
  4098. variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
  4099. variable->export_info.hint_string = class_name;
  4100. } else {
  4101. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  4102. return false;
  4103. }
  4104. } break;
  4105. case GDScriptParser::DataType::ENUM: {
  4106. if (export_type.is_meta_type) {
  4107. variable->export_info.type = Variant::DICTIONARY;
  4108. } else {
  4109. variable->export_info.type = Variant::INT;
  4110. variable->export_info.hint = PROPERTY_HINT_ENUM;
  4111. String enum_hint_string;
  4112. bool first = true;
  4113. for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
  4114. if (!first) {
  4115. enum_hint_string += ",";
  4116. } else {
  4117. first = false;
  4118. }
  4119. enum_hint_string += E.key.operator String().capitalize().xml_escape();
  4120. enum_hint_string += ":";
  4121. enum_hint_string += String::num_int64(E.value).xml_escape();
  4122. }
  4123. variable->export_info.hint_string = enum_hint_string;
  4124. variable->export_info.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
  4125. variable->export_info.class_name = String(export_type.native_type).replace("::", ".");
  4126. }
  4127. } break;
  4128. case GDScriptParser::DataType::VARIANT: {
  4129. if (export_type.is_variant()) {
  4130. variable->export_info.type = Variant::NIL;
  4131. variable->export_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4132. }
  4133. } break;
  4134. default:
  4135. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  4136. return false;
  4137. }
  4138. if (variable->export_info.hint == PROPERTY_HINT_NODE_TYPE && !ClassDB::is_parent_class(p_class->base_type.native_type, SNAME("Node"))) {
  4139. push_error(vformat(R"(Node export is only supported in Node-derived classes, but the current class inherits "%s".)", p_class->base_type.to_string()), p_annotation);
  4140. return false;
  4141. }
  4142. if (is_dict) {
  4143. String key_prefix = itos(variable->export_info.type);
  4144. if (variable->export_info.hint) {
  4145. key_prefix += "/" + itos(variable->export_info.hint);
  4146. }
  4147. key_prefix += ":" + variable->export_info.hint_string;
  4148. // Now parse value.
  4149. export_type = export_type.get_container_element_type(0);
  4150. if (export_type.is_variant() || export_type.has_no_type()) {
  4151. export_type.kind = GDScriptParser::DataType::BUILTIN;
  4152. }
  4153. switch (export_type.kind) {
  4154. case GDScriptParser::DataType::BUILTIN:
  4155. variable->export_info.type = export_type.builtin_type;
  4156. variable->export_info.hint = PROPERTY_HINT_NONE;
  4157. variable->export_info.hint_string = String();
  4158. break;
  4159. case GDScriptParser::DataType::NATIVE:
  4160. case GDScriptParser::DataType::SCRIPT:
  4161. case GDScriptParser::DataType::CLASS: {
  4162. const StringName class_name = _find_narrowest_native_or_global_class(export_type);
  4163. if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
  4164. variable->export_info.type = Variant::OBJECT;
  4165. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  4166. variable->export_info.hint_string = class_name;
  4167. } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
  4168. variable->export_info.type = Variant::OBJECT;
  4169. variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
  4170. variable->export_info.hint_string = class_name;
  4171. } else {
  4172. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  4173. return false;
  4174. }
  4175. } break;
  4176. case GDScriptParser::DataType::ENUM: {
  4177. if (export_type.is_meta_type) {
  4178. variable->export_info.type = Variant::DICTIONARY;
  4179. } else {
  4180. variable->export_info.type = Variant::INT;
  4181. variable->export_info.hint = PROPERTY_HINT_ENUM;
  4182. String enum_hint_string;
  4183. bool first = true;
  4184. for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
  4185. if (!first) {
  4186. enum_hint_string += ",";
  4187. } else {
  4188. first = false;
  4189. }
  4190. enum_hint_string += E.key.operator String().capitalize().xml_escape();
  4191. enum_hint_string += ":";
  4192. enum_hint_string += String::num_int64(E.value).xml_escape();
  4193. }
  4194. variable->export_info.hint_string = enum_hint_string;
  4195. variable->export_info.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
  4196. variable->export_info.class_name = String(export_type.native_type).replace("::", ".");
  4197. }
  4198. } break;
  4199. default:
  4200. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  4201. return false;
  4202. }
  4203. if (variable->export_info.hint == PROPERTY_HINT_NODE_TYPE && !ClassDB::is_parent_class(p_class->base_type.native_type, SNAME("Node"))) {
  4204. push_error(vformat(R"(Node export is only supported in Node-derived classes, but the current class inherits "%s".)", p_class->base_type.to_string()), p_annotation);
  4205. return false;
  4206. }
  4207. String value_prefix = itos(variable->export_info.type);
  4208. if (variable->export_info.hint) {
  4209. value_prefix += "/" + itos(variable->export_info.hint);
  4210. }
  4211. value_prefix += ":" + variable->export_info.hint_string;
  4212. variable->export_info.type = Variant::DICTIONARY;
  4213. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  4214. variable->export_info.hint_string = key_prefix + ";" + value_prefix;
  4215. variable->export_info.usage = PROPERTY_USAGE_DEFAULT;
  4216. variable->export_info.class_name = StringName();
  4217. }
  4218. } else if (p_annotation->name == SNAME("@export_enum")) {
  4219. use_default_variable_type_check = false;
  4220. Variant::Type enum_type = Variant::INT;
  4221. if (export_type.kind == DataType::BUILTIN && export_type.builtin_type == Variant::STRING) {
  4222. enum_type = Variant::STRING;
  4223. }
  4224. variable->export_info.type = enum_type;
  4225. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != enum_type)) {
  4226. Vector<Variant::Type> expected_types = { Variant::INT, Variant::STRING };
  4227. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  4228. return false;
  4229. }
  4230. }
  4231. if (use_default_variable_type_check) {
  4232. // Validate variable type with export.
  4233. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != t_type)) {
  4234. // Allow float/int conversion.
  4235. if ((t_type != Variant::FLOAT || export_type.builtin_type != Variant::INT) && (t_type != Variant::INT || export_type.builtin_type != Variant::FLOAT)) {
  4236. Vector<Variant::Type> expected_types = { t_type };
  4237. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  4238. return false;
  4239. }
  4240. }
  4241. }
  4242. if (is_array) {
  4243. String hint_prefix = itos(variable->export_info.type);
  4244. if (variable->export_info.hint) {
  4245. hint_prefix += "/" + itos(variable->export_info.hint);
  4246. }
  4247. variable->export_info.type = original_export_type_builtin;
  4248. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  4249. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  4250. variable->export_info.usage = PROPERTY_USAGE_DEFAULT;
  4251. variable->export_info.class_name = StringName();
  4252. }
  4253. return true;
  4254. }
  4255. // For `@export_storage` and `@export_custom`, there is no need to check the variable type, argument values,
  4256. // or handle array exports in a special way, so they are implemented as separate methods.
  4257. bool GDScriptParser::export_storage_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4258. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  4259. VariableNode *variable = static_cast<VariableNode *>(p_target);
  4260. if (variable->is_static) {
  4261. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  4262. return false;
  4263. }
  4264. if (variable->exported) {
  4265. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  4266. return false;
  4267. }
  4268. variable->exported = true;
  4269. // Save the info because the compiler uses export info for overwriting member info.
  4270. variable->export_info = variable->get_datatype().to_property_info(variable->identifier->name);
  4271. variable->export_info.usage |= PROPERTY_USAGE_STORAGE;
  4272. return true;
  4273. }
  4274. bool GDScriptParser::export_custom_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4275. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  4276. ERR_FAIL_COND_V_MSG(p_annotation->resolved_arguments.size() < 2, false, R"(Annotation "@export_custom" requires 2 arguments.)");
  4277. VariableNode *variable = static_cast<VariableNode *>(p_target);
  4278. if (variable->is_static) {
  4279. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  4280. return false;
  4281. }
  4282. if (variable->exported) {
  4283. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  4284. return false;
  4285. }
  4286. variable->exported = true;
  4287. DataType export_type = variable->get_datatype();
  4288. variable->export_info.type = export_type.builtin_type;
  4289. variable->export_info.hint = static_cast<PropertyHint>(p_annotation->resolved_arguments[0].operator int64_t());
  4290. variable->export_info.hint_string = p_annotation->resolved_arguments[1];
  4291. if (p_annotation->resolved_arguments.size() >= 3) {
  4292. variable->export_info.usage = p_annotation->resolved_arguments[2].operator int64_t();
  4293. }
  4294. return true;
  4295. }
  4296. bool GDScriptParser::export_tool_button_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4297. #ifdef TOOLS_ENABLED
  4298. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  4299. ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
  4300. if (!is_tool()) {
  4301. push_error(R"(Tool buttons can only be used in tool scripts (add "@tool" to the top of the script).)", p_annotation);
  4302. return false;
  4303. }
  4304. VariableNode *variable = static_cast<VariableNode *>(p_target);
  4305. if (variable->is_static) {
  4306. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  4307. return false;
  4308. }
  4309. if (variable->exported) {
  4310. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  4311. return false;
  4312. }
  4313. const DataType variable_type = variable->get_datatype();
  4314. if (!variable_type.is_variant() && variable_type.is_hard_type()) {
  4315. if (variable_type.kind != DataType::BUILTIN || variable_type.builtin_type != Variant::CALLABLE) {
  4316. push_error(vformat(R"("@export_tool_button" annotation requires a variable of type "Callable", but type "%s" was given instead.)", variable_type.to_string()), p_annotation);
  4317. return false;
  4318. }
  4319. }
  4320. variable->exported = true;
  4321. // Build the hint string (format: `<text>[,<icon>]`).
  4322. String hint_string = p_annotation->resolved_arguments[0].operator String(); // Button text.
  4323. if (p_annotation->resolved_arguments.size() > 1) {
  4324. hint_string += "," + p_annotation->resolved_arguments[1].operator String(); // Button icon.
  4325. }
  4326. variable->export_info.type = Variant::CALLABLE;
  4327. variable->export_info.hint = PROPERTY_HINT_TOOL_BUTTON;
  4328. variable->export_info.hint_string = hint_string;
  4329. variable->export_info.usage = PROPERTY_USAGE_EDITOR;
  4330. #endif // TOOLS_ENABLED
  4331. return true; // Only available in editor.
  4332. }
  4333. template <PropertyUsageFlags t_usage>
  4334. bool GDScriptParser::export_group_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4335. ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
  4336. p_annotation->export_info.name = p_annotation->resolved_arguments[0];
  4337. switch (t_usage) {
  4338. case PROPERTY_USAGE_CATEGORY: {
  4339. p_annotation->export_info.usage = t_usage;
  4340. } break;
  4341. case PROPERTY_USAGE_GROUP: {
  4342. p_annotation->export_info.usage = t_usage;
  4343. if (p_annotation->resolved_arguments.size() == 2) {
  4344. p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
  4345. }
  4346. } break;
  4347. case PROPERTY_USAGE_SUBGROUP: {
  4348. p_annotation->export_info.usage = t_usage;
  4349. if (p_annotation->resolved_arguments.size() == 2) {
  4350. p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
  4351. }
  4352. } break;
  4353. }
  4354. return true;
  4355. }
  4356. bool GDScriptParser::warning_ignore_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4357. #ifdef DEBUG_ENABLED
  4358. if (is_ignoring_warnings) {
  4359. return true; // We already ignore all warnings, let's optimize it.
  4360. }
  4361. bool has_error = false;
  4362. for (const Variant &warning_name : p_annotation->resolved_arguments) {
  4363. GDScriptWarning::Code warning_code = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
  4364. if (warning_code == GDScriptWarning::WARNING_MAX) {
  4365. push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
  4366. has_error = true;
  4367. } else {
  4368. int start_line = p_annotation->start_line;
  4369. int end_line = p_target->end_line;
  4370. switch (p_target->type) {
  4371. #define SIMPLE_CASE(m_type, m_class, m_property) \
  4372. case m_type: { \
  4373. m_class *node = static_cast<m_class *>(p_target); \
  4374. if (node->m_property == nullptr) { \
  4375. end_line = node->start_line; \
  4376. } else { \
  4377. end_line = node->m_property->end_line; \
  4378. } \
  4379. } break;
  4380. // Can contain properties (set/get).
  4381. SIMPLE_CASE(Node::VARIABLE, VariableNode, initializer)
  4382. // Contain bodies.
  4383. SIMPLE_CASE(Node::FOR, ForNode, list)
  4384. SIMPLE_CASE(Node::IF, IfNode, condition)
  4385. SIMPLE_CASE(Node::MATCH, MatchNode, test)
  4386. SIMPLE_CASE(Node::WHILE, WhileNode, condition)
  4387. #undef SIMPLE_CASE
  4388. case Node::CLASS: {
  4389. end_line = p_target->start_line;
  4390. for (const AnnotationNode *annotation : p_target->annotations) {
  4391. start_line = MIN(start_line, annotation->start_line);
  4392. end_line = MAX(end_line, annotation->end_line);
  4393. }
  4394. } break;
  4395. case Node::FUNCTION: {
  4396. FunctionNode *function = static_cast<FunctionNode *>(p_target);
  4397. end_line = function->start_line;
  4398. for (int i = 0; i < function->parameters.size(); i++) {
  4399. end_line = MAX(end_line, function->parameters[i]->end_line);
  4400. if (function->parameters[i]->initializer != nullptr) {
  4401. end_line = MAX(end_line, function->parameters[i]->initializer->end_line);
  4402. }
  4403. }
  4404. } break;
  4405. case Node::MATCH_BRANCH: {
  4406. MatchBranchNode *branch = static_cast<MatchBranchNode *>(p_target);
  4407. end_line = branch->start_line;
  4408. for (int i = 0; i < branch->patterns.size(); i++) {
  4409. end_line = MAX(end_line, branch->patterns[i]->end_line);
  4410. }
  4411. } break;
  4412. default: {
  4413. } break;
  4414. }
  4415. end_line = MAX(start_line, end_line); // Prevent infinite loop.
  4416. for (int line = start_line; line <= end_line; line++) {
  4417. warning_ignored_lines[warning_code].insert(line);
  4418. }
  4419. }
  4420. }
  4421. return !has_error;
  4422. #else // !DEBUG_ENABLED
  4423. // Only available in debug builds.
  4424. return true;
  4425. #endif // DEBUG_ENABLED
  4426. }
  4427. bool GDScriptParser::warning_ignore_region_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4428. #ifdef DEBUG_ENABLED
  4429. bool has_error = false;
  4430. const bool is_start = p_annotation->name == SNAME("@warning_ignore_start");
  4431. for (const Variant &warning_name : p_annotation->resolved_arguments) {
  4432. GDScriptWarning::Code warning_code = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
  4433. if (warning_code == GDScriptWarning::WARNING_MAX) {
  4434. push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
  4435. has_error = true;
  4436. continue;
  4437. }
  4438. if (is_start) {
  4439. if (warning_ignore_start_lines[warning_code] != INT_MAX) {
  4440. push_error(vformat(R"(Warning "%s" is already being ignored by "@warning_ignore_start" at line %d.)", String(warning_name).to_upper(), warning_ignore_start_lines[warning_code]), p_annotation);
  4441. has_error = true;
  4442. continue;
  4443. }
  4444. warning_ignore_start_lines[warning_code] = p_annotation->start_line;
  4445. } else {
  4446. if (warning_ignore_start_lines[warning_code] == INT_MAX) {
  4447. push_error(vformat(R"(Warning "%s" is not being ignored by "@warning_ignore_start".)", String(warning_name).to_upper()), p_annotation);
  4448. has_error = true;
  4449. continue;
  4450. }
  4451. const int start_line = warning_ignore_start_lines[warning_code];
  4452. const int end_line = MAX(start_line, p_annotation->start_line); // Prevent infinite loop.
  4453. for (int i = start_line; i <= end_line; i++) {
  4454. warning_ignored_lines[warning_code].insert(i);
  4455. }
  4456. warning_ignore_start_lines[warning_code] = INT_MAX;
  4457. }
  4458. }
  4459. return !has_error;
  4460. #else // !DEBUG_ENABLED
  4461. // Only available in debug builds.
  4462. return true;
  4463. #endif // DEBUG_ENABLED
  4464. }
  4465. bool GDScriptParser::rpc_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4466. ERR_FAIL_COND_V_MSG(p_target->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to functions.)", p_annotation->name));
  4467. FunctionNode *function = static_cast<FunctionNode *>(p_target);
  4468. if (function->rpc_config.get_type() != Variant::NIL) {
  4469. push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
  4470. return false;
  4471. }
  4472. Dictionary rpc_config;
  4473. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  4474. if (!p_annotation->resolved_arguments.is_empty()) {
  4475. unsigned char locality_args = 0;
  4476. unsigned char permission_args = 0;
  4477. unsigned char transfer_mode_args = 0;
  4478. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  4479. if (i == 3) {
  4480. rpc_config["channel"] = p_annotation->resolved_arguments[i].operator int();
  4481. continue;
  4482. }
  4483. String arg = p_annotation->resolved_arguments[i].operator String();
  4484. if (arg == "call_local") {
  4485. locality_args++;
  4486. rpc_config["call_local"] = true;
  4487. } else if (arg == "call_remote") {
  4488. locality_args++;
  4489. rpc_config["call_local"] = false;
  4490. } else if (arg == "any_peer") {
  4491. permission_args++;
  4492. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_ANY_PEER;
  4493. } else if (arg == "authority") {
  4494. permission_args++;
  4495. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  4496. } else if (arg == "reliable") {
  4497. transfer_mode_args++;
  4498. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_RELIABLE;
  4499. } else if (arg == "unreliable") {
  4500. transfer_mode_args++;
  4501. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE;
  4502. } else if (arg == "unreliable_ordered") {
  4503. transfer_mode_args++;
  4504. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE_ORDERED;
  4505. } else {
  4506. push_error(R"(Invalid RPC argument. Must be one of: "call_local"/"call_remote" (local calls), "any_peer"/"authority" (permission), "reliable"/"unreliable"/"unreliable_ordered" (transfer mode).)", p_annotation);
  4507. }
  4508. }
  4509. if (locality_args > 1) {
  4510. push_error(R"(Invalid RPC config. The locality ("call_local"/"call_remote") must be specified no more than once.)", p_annotation);
  4511. } else if (permission_args > 1) {
  4512. push_error(R"(Invalid RPC config. The permission ("any_peer"/"authority") must be specified no more than once.)", p_annotation);
  4513. } else if (transfer_mode_args > 1) {
  4514. push_error(R"(Invalid RPC config. The transfer mode ("reliable"/"unreliable"/"unreliable_ordered") must be specified no more than once.)", p_annotation);
  4515. }
  4516. }
  4517. function->rpc_config = rpc_config;
  4518. return true;
  4519. }
  4520. GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
  4521. switch (type) {
  4522. case CONSTANT:
  4523. return constant->get_datatype();
  4524. case VARIABLE:
  4525. return variable->get_datatype();
  4526. case PARAMETER:
  4527. return parameter->get_datatype();
  4528. case FOR_VARIABLE:
  4529. case PATTERN_BIND:
  4530. return bind->get_datatype();
  4531. case UNDEFINED:
  4532. return DataType();
  4533. }
  4534. return DataType();
  4535. }
  4536. String GDScriptParser::SuiteNode::Local::get_name() const {
  4537. switch (type) {
  4538. case SuiteNode::Local::PARAMETER:
  4539. return "parameter";
  4540. case SuiteNode::Local::CONSTANT:
  4541. return "constant";
  4542. case SuiteNode::Local::VARIABLE:
  4543. return "variable";
  4544. case SuiteNode::Local::FOR_VARIABLE:
  4545. return "for loop iterator";
  4546. case SuiteNode::Local::PATTERN_BIND:
  4547. return "pattern bind";
  4548. case SuiteNode::Local::UNDEFINED:
  4549. return "<undefined>";
  4550. default:
  4551. return String();
  4552. }
  4553. }
  4554. String GDScriptParser::DataType::to_string() const {
  4555. switch (kind) {
  4556. case VARIANT:
  4557. return "Variant";
  4558. case BUILTIN:
  4559. if (builtin_type == Variant::NIL) {
  4560. return "null";
  4561. }
  4562. if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
  4563. return vformat("Array[%s]", get_container_element_type(0).to_string());
  4564. }
  4565. if (builtin_type == Variant::DICTIONARY && has_container_element_types()) {
  4566. return vformat("Dictionary[%s, %s]", get_container_element_type_or_variant(0).to_string(), get_container_element_type_or_variant(1).to_string());
  4567. }
  4568. return Variant::get_type_name(builtin_type);
  4569. case NATIVE:
  4570. if (is_meta_type) {
  4571. return GDScriptNativeClass::get_class_static();
  4572. }
  4573. return native_type.operator String();
  4574. case CLASS:
  4575. if (class_type->identifier != nullptr) {
  4576. return class_type->identifier->name.operator String();
  4577. }
  4578. return class_type->fqcn;
  4579. case SCRIPT: {
  4580. if (is_meta_type) {
  4581. return script_type.is_valid() ? script_type->get_class_name().operator String() : "";
  4582. }
  4583. String name = script_type.is_valid() ? script_type->get_name() : "";
  4584. if (!name.is_empty()) {
  4585. return name;
  4586. }
  4587. name = script_path;
  4588. if (!name.is_empty()) {
  4589. return name;
  4590. }
  4591. return native_type.operator String();
  4592. }
  4593. case ENUM: {
  4594. // native_type contains either the native class defining the enum
  4595. // or the fully qualified class name of the script defining the enum
  4596. return String(native_type).get_file(); // Remove path, keep filename
  4597. }
  4598. case RESOLVING:
  4599. case UNRESOLVED:
  4600. return "<unresolved type>";
  4601. }
  4602. ERR_FAIL_V_MSG("<unresolved type>", "Kind set outside the enum range.");
  4603. }
  4604. PropertyInfo GDScriptParser::DataType::to_property_info(const String &p_name) const {
  4605. PropertyInfo result;
  4606. result.name = p_name;
  4607. result.usage = PROPERTY_USAGE_NONE;
  4608. if (!is_hard_type()) {
  4609. result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4610. return result;
  4611. }
  4612. switch (kind) {
  4613. case BUILTIN:
  4614. result.type = builtin_type;
  4615. if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
  4616. const DataType elem_type = get_container_element_type(0);
  4617. switch (elem_type.kind) {
  4618. case BUILTIN:
  4619. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4620. result.hint_string = Variant::get_type_name(elem_type.builtin_type);
  4621. break;
  4622. case NATIVE:
  4623. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4624. result.hint_string = elem_type.native_type;
  4625. break;
  4626. case SCRIPT:
  4627. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4628. if (elem_type.script_type.is_valid() && elem_type.script_type->get_global_name() != StringName()) {
  4629. result.hint_string = elem_type.script_type->get_global_name();
  4630. } else {
  4631. result.hint_string = elem_type.native_type;
  4632. }
  4633. break;
  4634. case CLASS:
  4635. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4636. if (elem_type.class_type != nullptr && elem_type.class_type->get_global_name() != StringName()) {
  4637. result.hint_string = elem_type.class_type->get_global_name();
  4638. } else {
  4639. result.hint_string = elem_type.native_type;
  4640. }
  4641. break;
  4642. case ENUM:
  4643. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4644. result.hint_string = String(elem_type.native_type).replace("::", ".");
  4645. break;
  4646. case VARIANT:
  4647. case RESOLVING:
  4648. case UNRESOLVED:
  4649. break;
  4650. }
  4651. } else if (builtin_type == Variant::DICTIONARY && has_container_element_types()) {
  4652. const DataType key_type = get_container_element_type_or_variant(0);
  4653. const DataType value_type = get_container_element_type_or_variant(1);
  4654. if ((key_type.kind == VARIANT && value_type.kind == VARIANT) || key_type.kind == RESOLVING ||
  4655. key_type.kind == UNRESOLVED || value_type.kind == RESOLVING || value_type.kind == UNRESOLVED) {
  4656. break;
  4657. }
  4658. String key_hint, value_hint;
  4659. switch (key_type.kind) {
  4660. case BUILTIN:
  4661. key_hint = Variant::get_type_name(key_type.builtin_type);
  4662. break;
  4663. case NATIVE:
  4664. key_hint = key_type.native_type;
  4665. break;
  4666. case SCRIPT:
  4667. if (key_type.script_type.is_valid() && key_type.script_type->get_global_name() != StringName()) {
  4668. key_hint = key_type.script_type->get_global_name();
  4669. } else {
  4670. key_hint = key_type.native_type;
  4671. }
  4672. break;
  4673. case CLASS:
  4674. if (key_type.class_type != nullptr && key_type.class_type->get_global_name() != StringName()) {
  4675. key_hint = key_type.class_type->get_global_name();
  4676. } else {
  4677. key_hint = key_type.native_type;
  4678. }
  4679. break;
  4680. case ENUM:
  4681. key_hint = String(key_type.native_type).replace("::", ".");
  4682. break;
  4683. default:
  4684. key_hint = "Variant";
  4685. break;
  4686. }
  4687. switch (value_type.kind) {
  4688. case BUILTIN:
  4689. value_hint = Variant::get_type_name(value_type.builtin_type);
  4690. break;
  4691. case NATIVE:
  4692. value_hint = value_type.native_type;
  4693. break;
  4694. case SCRIPT:
  4695. if (value_type.script_type.is_valid() && value_type.script_type->get_global_name() != StringName()) {
  4696. value_hint = value_type.script_type->get_global_name();
  4697. } else {
  4698. value_hint = value_type.native_type;
  4699. }
  4700. break;
  4701. case CLASS:
  4702. if (value_type.class_type != nullptr && value_type.class_type->get_global_name() != StringName()) {
  4703. value_hint = value_type.class_type->get_global_name();
  4704. } else {
  4705. value_hint = value_type.native_type;
  4706. }
  4707. break;
  4708. case ENUM:
  4709. value_hint = String(value_type.native_type).replace("::", ".");
  4710. break;
  4711. default:
  4712. value_hint = "Variant";
  4713. break;
  4714. }
  4715. result.hint = PROPERTY_HINT_DICTIONARY_TYPE;
  4716. result.hint_string = key_hint + ";" + value_hint;
  4717. }
  4718. break;
  4719. case NATIVE:
  4720. result.type = Variant::OBJECT;
  4721. if (is_meta_type) {
  4722. result.class_name = GDScriptNativeClass::get_class_static();
  4723. } else {
  4724. result.class_name = native_type;
  4725. }
  4726. break;
  4727. case SCRIPT:
  4728. result.type = Variant::OBJECT;
  4729. if (is_meta_type) {
  4730. result.class_name = script_type.is_valid() ? script_type->get_class_name() : Script::get_class_static();
  4731. } else if (script_type.is_valid() && script_type->get_global_name() != StringName()) {
  4732. result.class_name = script_type->get_global_name();
  4733. } else {
  4734. result.class_name = native_type;
  4735. }
  4736. break;
  4737. case CLASS:
  4738. result.type = Variant::OBJECT;
  4739. if (is_meta_type) {
  4740. result.class_name = GDScript::get_class_static();
  4741. } else if (class_type != nullptr && class_type->get_global_name() != StringName()) {
  4742. result.class_name = class_type->get_global_name();
  4743. } else {
  4744. result.class_name = native_type;
  4745. }
  4746. break;
  4747. case ENUM:
  4748. if (is_meta_type) {
  4749. result.type = Variant::DICTIONARY;
  4750. } else {
  4751. result.type = Variant::INT;
  4752. result.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
  4753. result.class_name = String(native_type).replace("::", ".");
  4754. }
  4755. break;
  4756. case VARIANT:
  4757. case RESOLVING:
  4758. case UNRESOLVED:
  4759. result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4760. break;
  4761. }
  4762. return result;
  4763. }
  4764. static Variant::Type _variant_type_to_typed_array_element_type(Variant::Type p_type) {
  4765. switch (p_type) {
  4766. case Variant::PACKED_BYTE_ARRAY:
  4767. case Variant::PACKED_INT32_ARRAY:
  4768. case Variant::PACKED_INT64_ARRAY:
  4769. return Variant::INT;
  4770. case Variant::PACKED_FLOAT32_ARRAY:
  4771. case Variant::PACKED_FLOAT64_ARRAY:
  4772. return Variant::FLOAT;
  4773. case Variant::PACKED_STRING_ARRAY:
  4774. return Variant::STRING;
  4775. case Variant::PACKED_VECTOR2_ARRAY:
  4776. return Variant::VECTOR2;
  4777. case Variant::PACKED_VECTOR3_ARRAY:
  4778. return Variant::VECTOR3;
  4779. case Variant::PACKED_COLOR_ARRAY:
  4780. return Variant::COLOR;
  4781. case Variant::PACKED_VECTOR4_ARRAY:
  4782. return Variant::VECTOR4;
  4783. default:
  4784. return Variant::NIL;
  4785. }
  4786. }
  4787. bool GDScriptParser::DataType::is_typed_container_type() const {
  4788. return kind == GDScriptParser::DataType::BUILTIN && _variant_type_to_typed_array_element_type(builtin_type) != Variant::NIL;
  4789. }
  4790. GDScriptParser::DataType GDScriptParser::DataType::get_typed_container_type() const {
  4791. GDScriptParser::DataType type;
  4792. type.kind = GDScriptParser::DataType::BUILTIN;
  4793. type.builtin_type = _variant_type_to_typed_array_element_type(builtin_type);
  4794. return type;
  4795. }
  4796. bool GDScriptParser::DataType::can_reference(const GDScriptParser::DataType &p_other) const {
  4797. if (p_other.is_meta_type) {
  4798. return false;
  4799. } else if (builtin_type != p_other.builtin_type) {
  4800. return false;
  4801. } else if (builtin_type != Variant::OBJECT) {
  4802. return true;
  4803. }
  4804. if (native_type == StringName()) {
  4805. return true;
  4806. } else if (p_other.native_type == StringName()) {
  4807. return false;
  4808. } else if (native_type != p_other.native_type && !ClassDB::is_parent_class(p_other.native_type, native_type)) {
  4809. return false;
  4810. }
  4811. Ref<Script> script = script_type;
  4812. if (kind == GDScriptParser::DataType::CLASS && script.is_null()) {
  4813. Error err = OK;
  4814. Ref<GDScript> scr = GDScriptCache::get_shallow_script(script_path, err);
  4815. ERR_FAIL_COND_V_MSG(err, false, vformat(R"(Error while getting cache for script "%s".)", script_path));
  4816. script.reference_ptr(scr->find_class(class_type->fqcn));
  4817. }
  4818. Ref<Script> script_other = p_other.script_type;
  4819. if (p_other.kind == GDScriptParser::DataType::CLASS && script_other.is_null()) {
  4820. Error err = OK;
  4821. Ref<GDScript> scr = GDScriptCache::get_shallow_script(p_other.script_path, err);
  4822. ERR_FAIL_COND_V_MSG(err, false, vformat(R"(Error while getting cache for script "%s".)", p_other.script_path));
  4823. script_other.reference_ptr(scr->find_class(p_other.class_type->fqcn));
  4824. }
  4825. if (script.is_null()) {
  4826. return true;
  4827. } else if (script_other.is_null()) {
  4828. return false;
  4829. } else if (script != script_other && !script_other->inherits_script(script)) {
  4830. return false;
  4831. }
  4832. return true;
  4833. }
  4834. void GDScriptParser::complete_extents(Node *p_node) {
  4835. while (!nodes_in_progress.is_empty() && nodes_in_progress.back()->get() != p_node) {
  4836. ERR_PRINT("Parser bug: Mismatch in extents tracking stack.");
  4837. nodes_in_progress.pop_back();
  4838. }
  4839. if (nodes_in_progress.is_empty()) {
  4840. ERR_PRINT("Parser bug: Extents tracking stack is empty.");
  4841. } else {
  4842. nodes_in_progress.pop_back();
  4843. }
  4844. }
  4845. void GDScriptParser::update_extents(Node *p_node) {
  4846. p_node->end_line = previous.end_line;
  4847. p_node->end_column = previous.end_column;
  4848. }
  4849. void GDScriptParser::reset_extents(Node *p_node, GDScriptTokenizer::Token p_token) {
  4850. p_node->start_line = p_token.start_line;
  4851. p_node->end_line = p_token.end_line;
  4852. p_node->start_column = p_token.start_column;
  4853. p_node->end_column = p_token.end_column;
  4854. }
  4855. void GDScriptParser::reset_extents(Node *p_node, Node *p_from) {
  4856. if (p_from == nullptr) {
  4857. return;
  4858. }
  4859. p_node->start_line = p_from->start_line;
  4860. p_node->end_line = p_from->end_line;
  4861. p_node->start_column = p_from->start_column;
  4862. p_node->end_column = p_from->end_column;
  4863. }
  4864. /*---------- PRETTY PRINT FOR DEBUG ----------*/
  4865. #ifdef DEBUG_ENABLED
  4866. void GDScriptParser::TreePrinter::increase_indent() {
  4867. indent_level++;
  4868. indent = "";
  4869. for (int i = 0; i < indent_level * 4; i++) {
  4870. if (i % 4 == 0) {
  4871. indent += "|";
  4872. } else {
  4873. indent += " ";
  4874. }
  4875. }
  4876. }
  4877. void GDScriptParser::TreePrinter::decrease_indent() {
  4878. indent_level--;
  4879. indent = "";
  4880. for (int i = 0; i < indent_level * 4; i++) {
  4881. if (i % 4 == 0) {
  4882. indent += "|";
  4883. } else {
  4884. indent += " ";
  4885. }
  4886. }
  4887. }
  4888. void GDScriptParser::TreePrinter::push_line(const String &p_line) {
  4889. if (!p_line.is_empty()) {
  4890. push_text(p_line);
  4891. }
  4892. printed += "\n";
  4893. pending_indent = true;
  4894. }
  4895. void GDScriptParser::TreePrinter::push_text(const String &p_text) {
  4896. if (pending_indent) {
  4897. printed += indent;
  4898. pending_indent = false;
  4899. }
  4900. printed += p_text;
  4901. }
  4902. void GDScriptParser::TreePrinter::print_annotation(const AnnotationNode *p_annotation) {
  4903. push_text(p_annotation->name);
  4904. push_text(" (");
  4905. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  4906. if (i > 0) {
  4907. push_text(" , ");
  4908. }
  4909. print_expression(p_annotation->arguments[i]);
  4910. }
  4911. push_line(")");
  4912. }
  4913. void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
  4914. push_text("[ ");
  4915. for (int i = 0; i < p_array->elements.size(); i++) {
  4916. if (i > 0) {
  4917. push_text(" , ");
  4918. }
  4919. print_expression(p_array->elements[i]);
  4920. }
  4921. push_text(" ]");
  4922. }
  4923. void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
  4924. push_text("Assert ( ");
  4925. print_expression(p_assert->condition);
  4926. push_line(" )");
  4927. }
  4928. void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
  4929. switch (p_assignment->assignee->type) {
  4930. case Node::IDENTIFIER:
  4931. print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
  4932. break;
  4933. case Node::SUBSCRIPT:
  4934. print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
  4935. break;
  4936. default:
  4937. break; // Unreachable.
  4938. }
  4939. push_text(" ");
  4940. switch (p_assignment->operation) {
  4941. case AssignmentNode::OP_ADDITION:
  4942. push_text("+");
  4943. break;
  4944. case AssignmentNode::OP_SUBTRACTION:
  4945. push_text("-");
  4946. break;
  4947. case AssignmentNode::OP_MULTIPLICATION:
  4948. push_text("*");
  4949. break;
  4950. case AssignmentNode::OP_DIVISION:
  4951. push_text("/");
  4952. break;
  4953. case AssignmentNode::OP_MODULO:
  4954. push_text("%");
  4955. break;
  4956. case AssignmentNode::OP_POWER:
  4957. push_text("**");
  4958. break;
  4959. case AssignmentNode::OP_BIT_SHIFT_LEFT:
  4960. push_text("<<");
  4961. break;
  4962. case AssignmentNode::OP_BIT_SHIFT_RIGHT:
  4963. push_text(">>");
  4964. break;
  4965. case AssignmentNode::OP_BIT_AND:
  4966. push_text("&");
  4967. break;
  4968. case AssignmentNode::OP_BIT_OR:
  4969. push_text("|");
  4970. break;
  4971. case AssignmentNode::OP_BIT_XOR:
  4972. push_text("^");
  4973. break;
  4974. case AssignmentNode::OP_NONE:
  4975. break;
  4976. }
  4977. push_text("= ");
  4978. print_expression(p_assignment->assigned_value);
  4979. push_line();
  4980. }
  4981. void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
  4982. push_text("Await ");
  4983. print_expression(p_await->to_await);
  4984. }
  4985. void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
  4986. // Surround in parenthesis for disambiguation.
  4987. push_text("(");
  4988. print_expression(p_binary_op->left_operand);
  4989. switch (p_binary_op->operation) {
  4990. case BinaryOpNode::OP_ADDITION:
  4991. push_text(" + ");
  4992. break;
  4993. case BinaryOpNode::OP_SUBTRACTION:
  4994. push_text(" - ");
  4995. break;
  4996. case BinaryOpNode::OP_MULTIPLICATION:
  4997. push_text(" * ");
  4998. break;
  4999. case BinaryOpNode::OP_DIVISION:
  5000. push_text(" / ");
  5001. break;
  5002. case BinaryOpNode::OP_MODULO:
  5003. push_text(" % ");
  5004. break;
  5005. case BinaryOpNode::OP_POWER:
  5006. push_text(" ** ");
  5007. break;
  5008. case BinaryOpNode::OP_BIT_LEFT_SHIFT:
  5009. push_text(" << ");
  5010. break;
  5011. case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
  5012. push_text(" >> ");
  5013. break;
  5014. case BinaryOpNode::OP_BIT_AND:
  5015. push_text(" & ");
  5016. break;
  5017. case BinaryOpNode::OP_BIT_OR:
  5018. push_text(" | ");
  5019. break;
  5020. case BinaryOpNode::OP_BIT_XOR:
  5021. push_text(" ^ ");
  5022. break;
  5023. case BinaryOpNode::OP_LOGIC_AND:
  5024. push_text(" AND ");
  5025. break;
  5026. case BinaryOpNode::OP_LOGIC_OR:
  5027. push_text(" OR ");
  5028. break;
  5029. case BinaryOpNode::OP_CONTENT_TEST:
  5030. push_text(" IN ");
  5031. break;
  5032. case BinaryOpNode::OP_COMP_EQUAL:
  5033. push_text(" == ");
  5034. break;
  5035. case BinaryOpNode::OP_COMP_NOT_EQUAL:
  5036. push_text(" != ");
  5037. break;
  5038. case BinaryOpNode::OP_COMP_LESS:
  5039. push_text(" < ");
  5040. break;
  5041. case BinaryOpNode::OP_COMP_LESS_EQUAL:
  5042. push_text(" <= ");
  5043. break;
  5044. case BinaryOpNode::OP_COMP_GREATER:
  5045. push_text(" > ");
  5046. break;
  5047. case BinaryOpNode::OP_COMP_GREATER_EQUAL:
  5048. push_text(" >= ");
  5049. break;
  5050. }
  5051. print_expression(p_binary_op->right_operand);
  5052. // Surround in parenthesis for disambiguation.
  5053. push_text(")");
  5054. }
  5055. void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
  5056. if (p_call->is_super) {
  5057. push_text("super");
  5058. if (p_call->callee != nullptr) {
  5059. push_text(".");
  5060. print_expression(p_call->callee);
  5061. }
  5062. } else {
  5063. print_expression(p_call->callee);
  5064. }
  5065. push_text("( ");
  5066. for (int i = 0; i < p_call->arguments.size(); i++) {
  5067. if (i > 0) {
  5068. push_text(" , ");
  5069. }
  5070. print_expression(p_call->arguments[i]);
  5071. }
  5072. push_text(" )");
  5073. }
  5074. void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
  5075. print_expression(p_cast->operand);
  5076. push_text(" AS ");
  5077. print_type(p_cast->cast_type);
  5078. }
  5079. void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
  5080. if (p_class->is_abstract) {
  5081. push_text("Abstract ");
  5082. }
  5083. push_text("Class ");
  5084. if (p_class->identifier == nullptr) {
  5085. push_text("<unnamed>");
  5086. } else {
  5087. print_identifier(p_class->identifier);
  5088. }
  5089. if (p_class->extends_used) {
  5090. bool first = true;
  5091. push_text(" Extends ");
  5092. if (!p_class->extends_path.is_empty()) {
  5093. push_text(vformat(R"("%s")", p_class->extends_path));
  5094. first = false;
  5095. }
  5096. for (int i = 0; i < p_class->extends.size(); i++) {
  5097. if (!first) {
  5098. push_text(".");
  5099. } else {
  5100. first = false;
  5101. }
  5102. push_text(p_class->extends[i]->name);
  5103. }
  5104. }
  5105. push_line(" :");
  5106. increase_indent();
  5107. for (int i = 0; i < p_class->members.size(); i++) {
  5108. const ClassNode::Member &m = p_class->members[i];
  5109. switch (m.type) {
  5110. case ClassNode::Member::CLASS:
  5111. print_class(m.m_class);
  5112. break;
  5113. case ClassNode::Member::VARIABLE:
  5114. print_variable(m.variable);
  5115. break;
  5116. case ClassNode::Member::CONSTANT:
  5117. print_constant(m.constant);
  5118. break;
  5119. case ClassNode::Member::SIGNAL:
  5120. print_signal(m.signal);
  5121. break;
  5122. case ClassNode::Member::FUNCTION:
  5123. print_function(m.function);
  5124. break;
  5125. case ClassNode::Member::ENUM:
  5126. print_enum(m.m_enum);
  5127. break;
  5128. case ClassNode::Member::ENUM_VALUE:
  5129. break; // Nothing. Will be printed by enum.
  5130. case ClassNode::Member::GROUP:
  5131. break; // Nothing. Groups are only used by inspector.
  5132. case ClassNode::Member::UNDEFINED:
  5133. push_line("<unknown member>");
  5134. break;
  5135. }
  5136. }
  5137. decrease_indent();
  5138. }
  5139. void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
  5140. push_text("Constant ");
  5141. print_identifier(p_constant->identifier);
  5142. increase_indent();
  5143. push_line();
  5144. push_text("= ");
  5145. if (p_constant->initializer == nullptr) {
  5146. push_text("<missing value>");
  5147. } else {
  5148. print_expression(p_constant->initializer);
  5149. }
  5150. decrease_indent();
  5151. push_line();
  5152. }
  5153. void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
  5154. push_line("{");
  5155. increase_indent();
  5156. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  5157. print_expression(p_dictionary->elements[i].key);
  5158. if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
  5159. push_text(" : ");
  5160. } else {
  5161. push_text(" = ");
  5162. }
  5163. print_expression(p_dictionary->elements[i].value);
  5164. push_line(" ,");
  5165. }
  5166. decrease_indent();
  5167. push_text("}");
  5168. }
  5169. void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
  5170. if (p_expression == nullptr) {
  5171. push_text("<invalid expression>");
  5172. return;
  5173. }
  5174. switch (p_expression->type) {
  5175. case Node::ARRAY:
  5176. print_array(static_cast<ArrayNode *>(p_expression));
  5177. break;
  5178. case Node::ASSIGNMENT:
  5179. print_assignment(static_cast<AssignmentNode *>(p_expression));
  5180. break;
  5181. case Node::AWAIT:
  5182. print_await(static_cast<AwaitNode *>(p_expression));
  5183. break;
  5184. case Node::BINARY_OPERATOR:
  5185. print_binary_op(static_cast<BinaryOpNode *>(p_expression));
  5186. break;
  5187. case Node::CALL:
  5188. print_call(static_cast<CallNode *>(p_expression));
  5189. break;
  5190. case Node::CAST:
  5191. print_cast(static_cast<CastNode *>(p_expression));
  5192. break;
  5193. case Node::DICTIONARY:
  5194. print_dictionary(static_cast<DictionaryNode *>(p_expression));
  5195. break;
  5196. case Node::GET_NODE:
  5197. print_get_node(static_cast<GetNodeNode *>(p_expression));
  5198. break;
  5199. case Node::IDENTIFIER:
  5200. print_identifier(static_cast<IdentifierNode *>(p_expression));
  5201. break;
  5202. case Node::LAMBDA:
  5203. print_lambda(static_cast<LambdaNode *>(p_expression));
  5204. break;
  5205. case Node::LITERAL:
  5206. print_literal(static_cast<LiteralNode *>(p_expression));
  5207. break;
  5208. case Node::PRELOAD:
  5209. print_preload(static_cast<PreloadNode *>(p_expression));
  5210. break;
  5211. case Node::SELF:
  5212. print_self(static_cast<SelfNode *>(p_expression));
  5213. break;
  5214. case Node::SUBSCRIPT:
  5215. print_subscript(static_cast<SubscriptNode *>(p_expression));
  5216. break;
  5217. case Node::TERNARY_OPERATOR:
  5218. print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
  5219. break;
  5220. case Node::TYPE_TEST:
  5221. print_type_test(static_cast<TypeTestNode *>(p_expression));
  5222. break;
  5223. case Node::UNARY_OPERATOR:
  5224. print_unary_op(static_cast<UnaryOpNode *>(p_expression));
  5225. break;
  5226. default:
  5227. push_text(vformat("<unknown expression %d>", p_expression->type));
  5228. break;
  5229. }
  5230. }
  5231. void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
  5232. push_text("Enum ");
  5233. if (p_enum->identifier != nullptr) {
  5234. print_identifier(p_enum->identifier);
  5235. } else {
  5236. push_text("<unnamed>");
  5237. }
  5238. push_line(" {");
  5239. increase_indent();
  5240. for (int i = 0; i < p_enum->values.size(); i++) {
  5241. const EnumNode::Value &item = p_enum->values[i];
  5242. print_identifier(item.identifier);
  5243. push_text(" = ");
  5244. push_text(itos(item.value));
  5245. push_line(" ,");
  5246. }
  5247. decrease_indent();
  5248. push_line("}");
  5249. }
  5250. void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
  5251. push_text("For ");
  5252. print_identifier(p_for->variable);
  5253. push_text(" IN ");
  5254. print_expression(p_for->list);
  5255. push_line(" :");
  5256. increase_indent();
  5257. print_suite(p_for->loop);
  5258. decrease_indent();
  5259. }
  5260. void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function, const String &p_context) {
  5261. for (const AnnotationNode *E : p_function->annotations) {
  5262. print_annotation(E);
  5263. }
  5264. if (p_function->is_abstract) {
  5265. push_text("Abstract ");
  5266. }
  5267. if (p_function->is_static) {
  5268. push_text("Static ");
  5269. }
  5270. push_text(p_context);
  5271. push_text(" ");
  5272. if (p_function->identifier) {
  5273. print_identifier(p_function->identifier);
  5274. } else {
  5275. push_text("<anonymous>");
  5276. }
  5277. push_text("( ");
  5278. for (int i = 0; i < p_function->parameters.size(); i++) {
  5279. if (i > 0) {
  5280. push_text(" , ");
  5281. }
  5282. print_parameter(p_function->parameters[i]);
  5283. }
  5284. push_line(" ) :");
  5285. increase_indent();
  5286. print_suite(p_function->body);
  5287. decrease_indent();
  5288. }
  5289. void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
  5290. if (p_get_node->use_dollar) {
  5291. push_text("$");
  5292. }
  5293. push_text(p_get_node->full_path);
  5294. }
  5295. void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
  5296. if (p_identifier != nullptr) {
  5297. push_text(p_identifier->name);
  5298. } else {
  5299. push_text("<invalid identifier>");
  5300. }
  5301. }
  5302. void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
  5303. if (p_is_elif) {
  5304. push_text("Elif ");
  5305. } else {
  5306. push_text("If ");
  5307. }
  5308. print_expression(p_if->condition);
  5309. push_line(" :");
  5310. increase_indent();
  5311. print_suite(p_if->true_block);
  5312. decrease_indent();
  5313. // FIXME: Properly detect "elif" blocks.
  5314. if (p_if->false_block != nullptr) {
  5315. push_line("Else :");
  5316. increase_indent();
  5317. print_suite(p_if->false_block);
  5318. decrease_indent();
  5319. }
  5320. }
  5321. void GDScriptParser::TreePrinter::print_lambda(LambdaNode *p_lambda) {
  5322. print_function(p_lambda->function, "Lambda");
  5323. push_text("| captures [ ");
  5324. for (int i = 0; i < p_lambda->captures.size(); i++) {
  5325. if (i > 0) {
  5326. push_text(" , ");
  5327. }
  5328. push_text(p_lambda->captures[i]->name.operator String());
  5329. }
  5330. push_line(" ]");
  5331. }
  5332. void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
  5333. // Prefix for string types.
  5334. switch (p_literal->value.get_type()) {
  5335. case Variant::NODE_PATH:
  5336. push_text("^\"");
  5337. break;
  5338. case Variant::STRING:
  5339. push_text("\"");
  5340. break;
  5341. case Variant::STRING_NAME:
  5342. push_text("&\"");
  5343. break;
  5344. default:
  5345. break;
  5346. }
  5347. push_text(p_literal->value);
  5348. // Suffix for string types.
  5349. switch (p_literal->value.get_type()) {
  5350. case Variant::NODE_PATH:
  5351. case Variant::STRING:
  5352. case Variant::STRING_NAME:
  5353. push_text("\"");
  5354. break;
  5355. default:
  5356. break;
  5357. }
  5358. }
  5359. void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
  5360. push_text("Match ");
  5361. print_expression(p_match->test);
  5362. push_line(" :");
  5363. increase_indent();
  5364. for (int i = 0; i < p_match->branches.size(); i++) {
  5365. print_match_branch(p_match->branches[i]);
  5366. }
  5367. decrease_indent();
  5368. }
  5369. void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
  5370. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  5371. if (i > 0) {
  5372. push_text(" , ");
  5373. }
  5374. print_match_pattern(p_match_branch->patterns[i]);
  5375. }
  5376. push_line(" :");
  5377. increase_indent();
  5378. print_suite(p_match_branch->block);
  5379. decrease_indent();
  5380. }
  5381. void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
  5382. switch (p_match_pattern->pattern_type) {
  5383. case PatternNode::PT_LITERAL:
  5384. print_literal(p_match_pattern->literal);
  5385. break;
  5386. case PatternNode::PT_WILDCARD:
  5387. push_text("_");
  5388. break;
  5389. case PatternNode::PT_REST:
  5390. push_text("..");
  5391. break;
  5392. case PatternNode::PT_BIND:
  5393. push_text("Var ");
  5394. print_identifier(p_match_pattern->bind);
  5395. break;
  5396. case PatternNode::PT_EXPRESSION:
  5397. print_expression(p_match_pattern->expression);
  5398. break;
  5399. case PatternNode::PT_ARRAY:
  5400. push_text("[ ");
  5401. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  5402. if (i > 0) {
  5403. push_text(" , ");
  5404. }
  5405. print_match_pattern(p_match_pattern->array[i]);
  5406. }
  5407. push_text(" ]");
  5408. break;
  5409. case PatternNode::PT_DICTIONARY:
  5410. push_text("{ ");
  5411. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  5412. if (i > 0) {
  5413. push_text(" , ");
  5414. }
  5415. if (p_match_pattern->dictionary[i].key != nullptr) {
  5416. // Key can be null for rest pattern.
  5417. print_expression(p_match_pattern->dictionary[i].key);
  5418. push_text(" : ");
  5419. }
  5420. print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
  5421. }
  5422. push_text(" }");
  5423. break;
  5424. }
  5425. }
  5426. void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
  5427. print_identifier(p_parameter->identifier);
  5428. if (p_parameter->datatype_specifier != nullptr) {
  5429. push_text(" : ");
  5430. print_type(p_parameter->datatype_specifier);
  5431. }
  5432. if (p_parameter->initializer != nullptr) {
  5433. push_text(" = ");
  5434. print_expression(p_parameter->initializer);
  5435. }
  5436. }
  5437. void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
  5438. push_text(R"(Preload ( ")");
  5439. push_text(p_preload->resolved_path);
  5440. push_text(R"(" )");
  5441. }
  5442. void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
  5443. push_text("Return");
  5444. if (p_return->return_value != nullptr) {
  5445. push_text(" ");
  5446. print_expression(p_return->return_value);
  5447. }
  5448. push_line();
  5449. }
  5450. void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
  5451. push_text("Self(");
  5452. if (p_self->current_class->identifier != nullptr) {
  5453. print_identifier(p_self->current_class->identifier);
  5454. } else {
  5455. push_text("<main class>");
  5456. }
  5457. push_text(")");
  5458. }
  5459. void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
  5460. push_text("Signal ");
  5461. print_identifier(p_signal->identifier);
  5462. push_text("( ");
  5463. for (int i = 0; i < p_signal->parameters.size(); i++) {
  5464. print_parameter(p_signal->parameters[i]);
  5465. }
  5466. push_line(" )");
  5467. }
  5468. void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
  5469. print_expression(p_subscript->base);
  5470. if (p_subscript->is_attribute) {
  5471. push_text(".");
  5472. print_identifier(p_subscript->attribute);
  5473. } else {
  5474. push_text("[ ");
  5475. print_expression(p_subscript->index);
  5476. push_text(" ]");
  5477. }
  5478. }
  5479. void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
  5480. switch (p_statement->type) {
  5481. case Node::ASSERT:
  5482. print_assert(static_cast<AssertNode *>(p_statement));
  5483. break;
  5484. case Node::VARIABLE:
  5485. print_variable(static_cast<VariableNode *>(p_statement));
  5486. break;
  5487. case Node::CONSTANT:
  5488. print_constant(static_cast<ConstantNode *>(p_statement));
  5489. break;
  5490. case Node::IF:
  5491. print_if(static_cast<IfNode *>(p_statement));
  5492. break;
  5493. case Node::FOR:
  5494. print_for(static_cast<ForNode *>(p_statement));
  5495. break;
  5496. case Node::WHILE:
  5497. print_while(static_cast<WhileNode *>(p_statement));
  5498. break;
  5499. case Node::MATCH:
  5500. print_match(static_cast<MatchNode *>(p_statement));
  5501. break;
  5502. case Node::RETURN:
  5503. print_return(static_cast<ReturnNode *>(p_statement));
  5504. break;
  5505. case Node::BREAK:
  5506. push_line("Break");
  5507. break;
  5508. case Node::CONTINUE:
  5509. push_line("Continue");
  5510. break;
  5511. case Node::PASS:
  5512. push_line("Pass");
  5513. break;
  5514. case Node::BREAKPOINT:
  5515. push_line("Breakpoint");
  5516. break;
  5517. case Node::ASSIGNMENT:
  5518. print_assignment(static_cast<AssignmentNode *>(p_statement));
  5519. break;
  5520. default:
  5521. if (p_statement->is_expression()) {
  5522. print_expression(static_cast<ExpressionNode *>(p_statement));
  5523. push_line();
  5524. } else {
  5525. push_line(vformat("<unknown statement %d>", p_statement->type));
  5526. }
  5527. break;
  5528. }
  5529. }
  5530. void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
  5531. for (int i = 0; i < p_suite->statements.size(); i++) {
  5532. print_statement(p_suite->statements[i]);
  5533. }
  5534. }
  5535. void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
  5536. // Surround in parenthesis for disambiguation.
  5537. push_text("(");
  5538. print_expression(p_ternary_op->true_expr);
  5539. push_text(") IF (");
  5540. print_expression(p_ternary_op->condition);
  5541. push_text(") ELSE (");
  5542. print_expression(p_ternary_op->false_expr);
  5543. push_text(")");
  5544. }
  5545. void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
  5546. if (p_type->type_chain.is_empty()) {
  5547. push_text("Void");
  5548. } else {
  5549. for (int i = 0; i < p_type->type_chain.size(); i++) {
  5550. if (i > 0) {
  5551. push_text(".");
  5552. }
  5553. print_identifier(p_type->type_chain[i]);
  5554. }
  5555. }
  5556. }
  5557. void GDScriptParser::TreePrinter::print_type_test(TypeTestNode *p_test) {
  5558. print_expression(p_test->operand);
  5559. push_text(" IS ");
  5560. print_type(p_test->test_type);
  5561. }
  5562. void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
  5563. // Surround in parenthesis for disambiguation.
  5564. push_text("(");
  5565. switch (p_unary_op->operation) {
  5566. case UnaryOpNode::OP_POSITIVE:
  5567. push_text("+");
  5568. break;
  5569. case UnaryOpNode::OP_NEGATIVE:
  5570. push_text("-");
  5571. break;
  5572. case UnaryOpNode::OP_LOGIC_NOT:
  5573. push_text("NOT");
  5574. break;
  5575. case UnaryOpNode::OP_COMPLEMENT:
  5576. push_text("~");
  5577. break;
  5578. }
  5579. print_expression(p_unary_op->operand);
  5580. // Surround in parenthesis for disambiguation.
  5581. push_text(")");
  5582. }
  5583. void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
  5584. for (const AnnotationNode *E : p_variable->annotations) {
  5585. print_annotation(E);
  5586. }
  5587. if (p_variable->is_static) {
  5588. push_text("Static ");
  5589. }
  5590. push_text("Variable ");
  5591. print_identifier(p_variable->identifier);
  5592. push_text(" : ");
  5593. if (p_variable->datatype_specifier != nullptr) {
  5594. print_type(p_variable->datatype_specifier);
  5595. } else if (p_variable->infer_datatype) {
  5596. push_text("<inferred type>");
  5597. } else {
  5598. push_text("Variant");
  5599. }
  5600. increase_indent();
  5601. push_line();
  5602. push_text("= ");
  5603. if (p_variable->initializer == nullptr) {
  5604. push_text("<default value>");
  5605. } else {
  5606. print_expression(p_variable->initializer);
  5607. }
  5608. push_line();
  5609. if (p_variable->property != VariableNode::PROP_NONE) {
  5610. if (p_variable->getter != nullptr) {
  5611. push_text("Get");
  5612. if (p_variable->property == VariableNode::PROP_INLINE) {
  5613. push_line(":");
  5614. increase_indent();
  5615. print_suite(p_variable->getter->body);
  5616. decrease_indent();
  5617. } else {
  5618. push_line(" =");
  5619. increase_indent();
  5620. print_identifier(p_variable->getter_pointer);
  5621. push_line();
  5622. decrease_indent();
  5623. }
  5624. }
  5625. if (p_variable->setter != nullptr) {
  5626. push_text("Set (");
  5627. if (p_variable->property == VariableNode::PROP_INLINE) {
  5628. if (p_variable->setter_parameter != nullptr) {
  5629. print_identifier(p_variable->setter_parameter);
  5630. } else {
  5631. push_text("<missing>");
  5632. }
  5633. push_line("):");
  5634. increase_indent();
  5635. print_suite(p_variable->setter->body);
  5636. decrease_indent();
  5637. } else {
  5638. push_line(" =");
  5639. increase_indent();
  5640. print_identifier(p_variable->setter_pointer);
  5641. push_line();
  5642. decrease_indent();
  5643. }
  5644. }
  5645. }
  5646. decrease_indent();
  5647. push_line();
  5648. }
  5649. void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
  5650. push_text("While ");
  5651. print_expression(p_while->condition);
  5652. push_line(" :");
  5653. increase_indent();
  5654. print_suite(p_while->loop);
  5655. decrease_indent();
  5656. }
  5657. void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
  5658. ClassNode *class_tree = p_parser.get_tree();
  5659. ERR_FAIL_NULL_MSG(class_tree, "Parse the code before printing the parse tree.");
  5660. if (p_parser.is_tool()) {
  5661. push_line("@tool");
  5662. }
  5663. if (!class_tree->icon_path.is_empty()) {
  5664. push_text(R"(@icon (")");
  5665. push_text(class_tree->icon_path);
  5666. push_line("\")");
  5667. }
  5668. print_class(class_tree);
  5669. print_line(String(printed));
  5670. }
  5671. #endif // DEBUG_ENABLED