gdscript_parser.cpp 210 KB

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