gdscript_parser.cpp 221 KB

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