2
0

gdscript_parser.cpp 196 KB

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