gdscript_parser.cpp 198 KB

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