gdscript_parser.cpp 217 KB

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