gdscript_parser.cpp 219 KB

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