gdscript_parser.cpp 221 KB

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