gdscript_parser.cpp 199 KB

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