gdscript_parser.cpp 221 KB

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