gdscript_parser.cpp 210 KB

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