gdscript_parser.cpp 210 KB

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