gdscript_parser.cpp 215 KB

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