gdscript_parser.cpp 222 KB

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