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