gdscript_parser.cpp 220 KB

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