gdscript_parser.cpp 216 KB

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