gdscript_parser.cpp 216 KB

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