gdscript_parser.cpp 208 KB

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