gdscript_parser.cpp 214 KB

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