gdscript_parser.cpp 217 KB

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