gdscript_parser.cpp 216 KB

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