gdscript_parser.cpp 199 KB

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