gdscript_parser.cpp 216 KB

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