gdscript_parser.cpp 222 KB

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