gdscript_parser.cpp 200 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881
  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. make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, 0);
  1430. int argument_index = 0;
  1431. do {
  1432. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1433. // Allow for trailing comma.
  1434. break;
  1435. }
  1436. make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index);
  1437. set_last_completion_call_arg(argument_index++);
  1438. ExpressionNode *argument = parse_expression(false);
  1439. if (argument == nullptr) {
  1440. push_error("Expected expression as the annotation argument.");
  1441. valid = false;
  1442. continue;
  1443. }
  1444. annotation->arguments.push_back(argument);
  1445. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  1446. pop_multiline();
  1447. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after annotation arguments.)*");
  1448. pop_completion_call();
  1449. }
  1450. complete_extents(annotation);
  1451. match(GDScriptTokenizer::Token::NEWLINE); // Newline after annotation is optional.
  1452. if (valid) {
  1453. valid = validate_annotation_arguments(annotation);
  1454. }
  1455. return valid ? annotation : nullptr;
  1456. }
  1457. void GDScriptParser::clear_unused_annotations() {
  1458. for (const AnnotationNode *annotation : annotation_stack) {
  1459. push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
  1460. }
  1461. annotation_stack.clear();
  1462. }
  1463. 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) {
  1464. ERR_FAIL_COND_V_MSG(valid_annotations.has(p_info.name), false, vformat(R"(Annotation "%s" already registered.)", p_info.name));
  1465. AnnotationInfo new_annotation;
  1466. new_annotation.info = p_info;
  1467. new_annotation.info.default_arguments = p_default_arguments;
  1468. if (p_is_vararg) {
  1469. new_annotation.info.flags |= METHOD_FLAG_VARARG;
  1470. }
  1471. new_annotation.apply = p_apply;
  1472. new_annotation.target_kind = p_target_kinds;
  1473. valid_annotations[p_info.name] = new_annotation;
  1474. return true;
  1475. }
  1476. GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, SuiteNode *p_suite, bool p_for_lambda) {
  1477. SuiteNode *suite = p_suite != nullptr ? p_suite : alloc_node<SuiteNode>();
  1478. suite->parent_block = current_suite;
  1479. suite->parent_function = current_function;
  1480. current_suite = suite;
  1481. if (!p_for_lambda && suite->parent_block != nullptr && suite->parent_block->is_in_loop) {
  1482. // Do not reset to false if true is set before calling parse_suite().
  1483. suite->is_in_loop = true;
  1484. }
  1485. bool multiline = false;
  1486. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1487. multiline = true;
  1488. }
  1489. if (multiline) {
  1490. if (!consume(GDScriptTokenizer::Token::INDENT, vformat(R"(Expected indented block after %s.)", p_context))) {
  1491. current_suite = suite->parent_block;
  1492. complete_extents(suite);
  1493. return suite;
  1494. }
  1495. }
  1496. reset_extents(suite, current);
  1497. int error_count = 0;
  1498. do {
  1499. if (is_at_end() || (!multiline && previous.type == GDScriptTokenizer::Token::SEMICOLON && check(GDScriptTokenizer::Token::NEWLINE))) {
  1500. break;
  1501. }
  1502. Node *statement = parse_statement();
  1503. if (statement == nullptr) {
  1504. if (error_count++ > 100) {
  1505. push_error("Too many statement errors.", suite);
  1506. break;
  1507. }
  1508. continue;
  1509. }
  1510. suite->statements.push_back(statement);
  1511. // Register locals.
  1512. switch (statement->type) {
  1513. case Node::VARIABLE: {
  1514. VariableNode *variable = static_cast<VariableNode *>(statement);
  1515. const SuiteNode::Local &local = current_suite->get_local(variable->identifier->name);
  1516. if (local.type != SuiteNode::Local::UNDEFINED) {
  1517. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), variable->identifier->name), variable->identifier);
  1518. }
  1519. current_suite->add_local(variable, current_function);
  1520. break;
  1521. }
  1522. case Node::CONSTANT: {
  1523. ConstantNode *constant = static_cast<ConstantNode *>(statement);
  1524. const SuiteNode::Local &local = current_suite->get_local(constant->identifier->name);
  1525. if (local.type != SuiteNode::Local::UNDEFINED) {
  1526. String name;
  1527. if (local.type == SuiteNode::Local::CONSTANT) {
  1528. name = "constant";
  1529. } else {
  1530. name = "variable";
  1531. }
  1532. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", name, constant->identifier->name), constant->identifier);
  1533. }
  1534. current_suite->add_local(constant, current_function);
  1535. break;
  1536. }
  1537. default:
  1538. break;
  1539. }
  1540. } while ((multiline || previous.type == GDScriptTokenizer::Token::SEMICOLON) && !check(GDScriptTokenizer::Token::DEDENT) && !lambda_ended && !is_at_end());
  1541. complete_extents(suite);
  1542. if (multiline) {
  1543. if (!lambda_ended) {
  1544. consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context));
  1545. } else {
  1546. match(GDScriptTokenizer::Token::DEDENT);
  1547. }
  1548. } else if (previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  1549. consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after ";" at the end of %s.)", p_context));
  1550. }
  1551. if (p_for_lambda) {
  1552. lambda_ended = true;
  1553. }
  1554. current_suite = suite->parent_block;
  1555. return suite;
  1556. }
  1557. GDScriptParser::Node *GDScriptParser::parse_statement() {
  1558. Node *result = nullptr;
  1559. #ifdef DEBUG_ENABLED
  1560. bool unreachable = current_suite->has_return && !current_suite->has_unreachable_code;
  1561. #endif
  1562. List<AnnotationNode *> annotations;
  1563. if (current.type != GDScriptTokenizer::Token::ANNOTATION) {
  1564. while (!annotation_stack.is_empty()) {
  1565. AnnotationNode *last_annotation = annotation_stack.back()->get();
  1566. if (last_annotation->applies_to(AnnotationInfo::STATEMENT)) {
  1567. annotations.push_front(last_annotation);
  1568. annotation_stack.pop_back();
  1569. } else {
  1570. push_error(vformat(R"(Annotation "%s" cannot be applied to a statement.)", last_annotation->name));
  1571. clear_unused_annotations();
  1572. }
  1573. }
  1574. }
  1575. switch (current.type) {
  1576. case GDScriptTokenizer::Token::PASS:
  1577. advance();
  1578. result = alloc_node<PassNode>();
  1579. complete_extents(result);
  1580. end_statement(R"("pass")");
  1581. break;
  1582. case GDScriptTokenizer::Token::VAR:
  1583. advance();
  1584. result = parse_variable(false, false);
  1585. break;
  1586. case GDScriptTokenizer::Token::CONST:
  1587. advance();
  1588. result = parse_constant(false);
  1589. break;
  1590. case GDScriptTokenizer::Token::IF:
  1591. advance();
  1592. result = parse_if();
  1593. break;
  1594. case GDScriptTokenizer::Token::FOR:
  1595. advance();
  1596. result = parse_for();
  1597. break;
  1598. case GDScriptTokenizer::Token::WHILE:
  1599. advance();
  1600. result = parse_while();
  1601. break;
  1602. case GDScriptTokenizer::Token::MATCH:
  1603. advance();
  1604. result = parse_match();
  1605. break;
  1606. case GDScriptTokenizer::Token::BREAK:
  1607. advance();
  1608. result = parse_break();
  1609. break;
  1610. case GDScriptTokenizer::Token::CONTINUE:
  1611. advance();
  1612. result = parse_continue();
  1613. break;
  1614. case GDScriptTokenizer::Token::RETURN: {
  1615. advance();
  1616. ReturnNode *n_return = alloc_node<ReturnNode>();
  1617. if (!is_statement_end()) {
  1618. if (current_function && (current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init || current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init)) {
  1619. push_error(R"(Constructor cannot return a value.)");
  1620. }
  1621. n_return->return_value = parse_expression(false);
  1622. } else if (in_lambda && !is_statement_end_token()) {
  1623. // Try to parse it anyway as this might not be the statement end in a lambda.
  1624. // If this fails the expression will be nullptr, but that's the same as no return, so it's fine.
  1625. n_return->return_value = parse_expression(false);
  1626. }
  1627. complete_extents(n_return);
  1628. result = n_return;
  1629. current_suite->has_return = true;
  1630. end_statement("return statement");
  1631. break;
  1632. }
  1633. case GDScriptTokenizer::Token::BREAKPOINT:
  1634. advance();
  1635. result = alloc_node<BreakpointNode>();
  1636. complete_extents(result);
  1637. end_statement(R"("breakpoint")");
  1638. break;
  1639. case GDScriptTokenizer::Token::ASSERT:
  1640. advance();
  1641. result = parse_assert();
  1642. break;
  1643. case GDScriptTokenizer::Token::ANNOTATION: {
  1644. advance();
  1645. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
  1646. if (annotation != nullptr) {
  1647. annotation_stack.push_back(annotation);
  1648. }
  1649. break;
  1650. }
  1651. default: {
  1652. // Expression statement.
  1653. ExpressionNode *expression = parse_expression(true); // Allow assignment here.
  1654. bool has_ended_lambda = false;
  1655. if (expression == nullptr) {
  1656. if (in_lambda) {
  1657. // If it's not a valid expression beginning, it might be the continuation of the outer expression where this lambda is.
  1658. lambda_ended = true;
  1659. has_ended_lambda = true;
  1660. } else {
  1661. advance();
  1662. push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name()));
  1663. }
  1664. } else {
  1665. end_statement("expression");
  1666. }
  1667. lambda_ended = lambda_ended || has_ended_lambda;
  1668. result = expression;
  1669. #ifdef DEBUG_ENABLED
  1670. if (expression != nullptr) {
  1671. switch (expression->type) {
  1672. case Node::ASSIGNMENT:
  1673. case Node::AWAIT:
  1674. case Node::CALL:
  1675. // Fine.
  1676. break;
  1677. case Node::PRELOAD:
  1678. // `preload` is a function-like keyword.
  1679. push_warning(expression, GDScriptWarning::RETURN_VALUE_DISCARDED, "preload");
  1680. break;
  1681. case Node::LAMBDA:
  1682. // Standalone lambdas can't be used, so make this an error.
  1683. push_error("Standalone lambdas cannot be accessed. Consider assigning it to a variable.", expression);
  1684. break;
  1685. case Node::LITERAL:
  1686. // Allow strings as multiline comments.
  1687. if (static_cast<GDScriptParser::LiteralNode *>(expression)->value.get_type() != Variant::STRING) {
  1688. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1689. }
  1690. break;
  1691. case Node::TERNARY_OPERATOR:
  1692. push_warning(expression, GDScriptWarning::STANDALONE_TERNARY);
  1693. break;
  1694. default:
  1695. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1696. }
  1697. }
  1698. #endif
  1699. break;
  1700. }
  1701. }
  1702. if (result != nullptr && !annotations.is_empty()) {
  1703. for (AnnotationNode *&annotation : annotations) {
  1704. result->annotations.push_back(annotation);
  1705. }
  1706. }
  1707. #ifdef DEBUG_ENABLED
  1708. if (unreachable && result != nullptr) {
  1709. current_suite->has_unreachable_code = true;
  1710. if (current_function) {
  1711. push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier ? current_function->identifier->name : "<anonymous lambda>");
  1712. } else {
  1713. // TODO: Properties setters and getters with unreachable code are not being warned
  1714. }
  1715. }
  1716. #endif
  1717. if (panic_mode) {
  1718. synchronize();
  1719. }
  1720. return result;
  1721. }
  1722. GDScriptParser::AssertNode *GDScriptParser::parse_assert() {
  1723. // TODO: Add assert message.
  1724. AssertNode *assert = alloc_node<AssertNode>();
  1725. push_multiline(true);
  1726. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "assert".)");
  1727. assert->condition = parse_expression(false);
  1728. if (assert->condition == nullptr) {
  1729. push_error("Expected expression to assert.");
  1730. pop_multiline();
  1731. complete_extents(assert);
  1732. return nullptr;
  1733. }
  1734. if (match(GDScriptTokenizer::Token::COMMA) && !check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1735. assert->message = parse_expression(false);
  1736. if (assert->message == nullptr) {
  1737. push_error(R"(Expected error message for assert after ",".)");
  1738. pop_multiline();
  1739. complete_extents(assert);
  1740. return nullptr;
  1741. }
  1742. match(GDScriptTokenizer::Token::COMMA);
  1743. }
  1744. pop_multiline();
  1745. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after assert expression.)*");
  1746. complete_extents(assert);
  1747. end_statement(R"("assert")");
  1748. return assert;
  1749. }
  1750. GDScriptParser::BreakNode *GDScriptParser::parse_break() {
  1751. if (!can_break) {
  1752. push_error(R"(Cannot use "break" outside of a loop.)");
  1753. }
  1754. BreakNode *break_node = alloc_node<BreakNode>();
  1755. complete_extents(break_node);
  1756. end_statement(R"("break")");
  1757. return break_node;
  1758. }
  1759. GDScriptParser::ContinueNode *GDScriptParser::parse_continue() {
  1760. if (!can_continue) {
  1761. push_error(R"(Cannot use "continue" outside of a loop.)");
  1762. }
  1763. current_suite->has_continue = true;
  1764. ContinueNode *cont = alloc_node<ContinueNode>();
  1765. complete_extents(cont);
  1766. end_statement(R"("continue")");
  1767. return cont;
  1768. }
  1769. GDScriptParser::ForNode *GDScriptParser::parse_for() {
  1770. ForNode *n_for = alloc_node<ForNode>();
  1771. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected loop variable name after "for".)")) {
  1772. n_for->variable = parse_identifier();
  1773. }
  1774. if (match(GDScriptTokenizer::Token::COLON)) {
  1775. n_for->datatype_specifier = parse_type();
  1776. if (n_for->datatype_specifier == nullptr) {
  1777. push_error(R"(Expected type specifier after ":".)");
  1778. }
  1779. }
  1780. if (n_for->datatype_specifier == nullptr) {
  1781. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" or ":" after "for" variable name.)");
  1782. } else {
  1783. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "for" variable type specifier.)");
  1784. }
  1785. n_for->list = parse_expression(false);
  1786. if (!n_for->list) {
  1787. push_error(R"(Expected iterable after "in".)");
  1788. }
  1789. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)");
  1790. // Save break/continue state.
  1791. bool could_break = can_break;
  1792. bool could_continue = can_continue;
  1793. // Allow break/continue.
  1794. can_break = true;
  1795. can_continue = true;
  1796. SuiteNode *suite = alloc_node<SuiteNode>();
  1797. if (n_for->variable) {
  1798. const SuiteNode::Local &local = current_suite->get_local(n_for->variable->name);
  1799. if (local.type != SuiteNode::Local::UNDEFINED) {
  1800. 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);
  1801. }
  1802. suite->add_local(SuiteNode::Local(n_for->variable, current_function));
  1803. }
  1804. suite->is_in_loop = true;
  1805. n_for->loop = parse_suite(R"("for" block)", suite);
  1806. complete_extents(n_for);
  1807. // Reset break/continue state.
  1808. can_break = could_break;
  1809. can_continue = could_continue;
  1810. return n_for;
  1811. }
  1812. GDScriptParser::IfNode *GDScriptParser::parse_if(const String &p_token) {
  1813. IfNode *n_if = alloc_node<IfNode>();
  1814. n_if->condition = parse_expression(false);
  1815. if (n_if->condition == nullptr) {
  1816. push_error(vformat(R"(Expected conditional expression after "%s".)", p_token));
  1817. }
  1818. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after "%s" condition.)", p_token));
  1819. n_if->true_block = parse_suite(vformat(R"("%s" block)", p_token));
  1820. n_if->true_block->parent_if = n_if;
  1821. if (n_if->true_block->has_continue) {
  1822. current_suite->has_continue = true;
  1823. }
  1824. if (match(GDScriptTokenizer::Token::ELIF)) {
  1825. SuiteNode *else_block = alloc_node<SuiteNode>();
  1826. else_block->parent_function = current_function;
  1827. else_block->parent_block = current_suite;
  1828. SuiteNode *previous_suite = current_suite;
  1829. current_suite = else_block;
  1830. IfNode *elif = parse_if("elif");
  1831. else_block->statements.push_back(elif);
  1832. complete_extents(else_block);
  1833. n_if->false_block = else_block;
  1834. current_suite = previous_suite;
  1835. } else if (match(GDScriptTokenizer::Token::ELSE)) {
  1836. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "else".)");
  1837. n_if->false_block = parse_suite(R"("else" block)");
  1838. }
  1839. complete_extents(n_if);
  1840. if (n_if->false_block != nullptr && n_if->false_block->has_return && n_if->true_block->has_return) {
  1841. current_suite->has_return = true;
  1842. }
  1843. if (n_if->false_block != nullptr && n_if->false_block->has_continue) {
  1844. current_suite->has_continue = true;
  1845. }
  1846. return n_if;
  1847. }
  1848. GDScriptParser::MatchNode *GDScriptParser::parse_match() {
  1849. MatchNode *match_node = alloc_node<MatchNode>();
  1850. match_node->test = parse_expression(false);
  1851. if (match_node->test == nullptr) {
  1852. push_error(R"(Expected expression to test after "match".)");
  1853. }
  1854. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" expression.)");
  1855. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected a newline after "match" statement.)");
  1856. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected an indented block after "match" statement.)")) {
  1857. complete_extents(match_node);
  1858. return match_node;
  1859. }
  1860. bool all_have_return = true;
  1861. bool have_wildcard = false;
  1862. List<AnnotationNode *> match_branch_annotation_stack;
  1863. while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
  1864. if (match(GDScriptTokenizer::Token::PASS)) {
  1865. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected newline after "pass".)");
  1866. continue;
  1867. }
  1868. if (match(GDScriptTokenizer::Token::ANNOTATION)) {
  1869. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
  1870. if (annotation == nullptr) {
  1871. continue;
  1872. }
  1873. if (annotation->name != SNAME("@warning_ignore")) {
  1874. push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name), annotation);
  1875. continue;
  1876. }
  1877. match_branch_annotation_stack.push_back(annotation);
  1878. continue;
  1879. }
  1880. MatchBranchNode *branch = parse_match_branch();
  1881. if (branch == nullptr) {
  1882. advance();
  1883. continue;
  1884. }
  1885. for (AnnotationNode *annotation : match_branch_annotation_stack) {
  1886. branch->annotations.push_back(annotation);
  1887. }
  1888. match_branch_annotation_stack.clear();
  1889. #ifdef DEBUG_ENABLED
  1890. if (have_wildcard && !branch->patterns.is_empty()) {
  1891. push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
  1892. }
  1893. #endif
  1894. have_wildcard = have_wildcard || branch->has_wildcard;
  1895. all_have_return = all_have_return && branch->block->has_return;
  1896. match_node->branches.push_back(branch);
  1897. }
  1898. complete_extents(match_node);
  1899. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
  1900. if (all_have_return && have_wildcard) {
  1901. current_suite->has_return = true;
  1902. }
  1903. for (const AnnotationNode *annotation : match_branch_annotation_stack) {
  1904. push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
  1905. }
  1906. match_branch_annotation_stack.clear();
  1907. return match_node;
  1908. }
  1909. GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
  1910. MatchBranchNode *branch = alloc_node<MatchBranchNode>();
  1911. reset_extents(branch, current);
  1912. bool has_bind = false;
  1913. do {
  1914. PatternNode *pattern = parse_match_pattern();
  1915. if (pattern == nullptr) {
  1916. continue;
  1917. }
  1918. if (pattern->binds.size() > 0) {
  1919. has_bind = true;
  1920. }
  1921. if (branch->patterns.size() > 0 && has_bind) {
  1922. push_error(R"(Cannot use a variable bind with multiple patterns.)");
  1923. }
  1924. if (pattern->pattern_type == PatternNode::PT_REST) {
  1925. push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
  1926. } else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
  1927. branch->has_wildcard = true;
  1928. }
  1929. branch->patterns.push_back(pattern);
  1930. } while (match(GDScriptTokenizer::Token::COMMA));
  1931. if (branch->patterns.is_empty()) {
  1932. push_error(R"(No pattern found for "match" branch.)");
  1933. }
  1934. bool has_guard = false;
  1935. if (match(GDScriptTokenizer::Token::WHEN)) {
  1936. // Pattern guard.
  1937. // 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.
  1938. branch->guard_body = alloc_node<SuiteNode>();
  1939. if (branch->patterns.size() > 0) {
  1940. for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
  1941. SuiteNode::Local local(E.value, current_function);
  1942. local.type = SuiteNode::Local::PATTERN_BIND;
  1943. branch->guard_body->add_local(local);
  1944. }
  1945. }
  1946. SuiteNode *parent_block = current_suite;
  1947. branch->guard_body->parent_block = parent_block;
  1948. current_suite = branch->guard_body;
  1949. ExpressionNode *guard = parse_expression(false);
  1950. if (guard == nullptr) {
  1951. push_error(R"(Expected expression for pattern guard after "when".)");
  1952. } else {
  1953. branch->guard_body->statements.append(guard);
  1954. }
  1955. current_suite = parent_block;
  1956. complete_extents(branch->guard_body);
  1957. has_guard = true;
  1958. branch->has_wildcard = false; // If it has a guard, the wildcard might still not match.
  1959. }
  1960. if (!consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":"%s after "match" %s.)", has_guard ? "" : R"( or "when")", has_guard ? "pattern guard" : "patterns"))) {
  1961. complete_extents(branch);
  1962. return nullptr;
  1963. }
  1964. SuiteNode *suite = alloc_node<SuiteNode>();
  1965. if (branch->patterns.size() > 0) {
  1966. for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
  1967. SuiteNode::Local local(E.value, current_function);
  1968. local.type = SuiteNode::Local::PATTERN_BIND;
  1969. suite->add_local(local);
  1970. }
  1971. }
  1972. branch->block = parse_suite("match pattern block", suite);
  1973. complete_extents(branch);
  1974. return branch;
  1975. }
  1976. GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
  1977. PatternNode *pattern = alloc_node<PatternNode>();
  1978. reset_extents(pattern, current);
  1979. switch (current.type) {
  1980. case GDScriptTokenizer::Token::VAR: {
  1981. // Bind.
  1982. advance();
  1983. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
  1984. complete_extents(pattern);
  1985. return nullptr;
  1986. }
  1987. pattern->pattern_type = PatternNode::PT_BIND;
  1988. pattern->bind = parse_identifier();
  1989. PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
  1990. if (p_root_pattern != nullptr) {
  1991. if (p_root_pattern->has_bind(pattern->bind->name)) {
  1992. push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
  1993. complete_extents(pattern);
  1994. return nullptr;
  1995. }
  1996. }
  1997. if (current_suite->has_local(pattern->bind->name)) {
  1998. 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));
  1999. complete_extents(pattern);
  2000. return nullptr;
  2001. }
  2002. root_pattern->binds[pattern->bind->name] = pattern->bind;
  2003. } break;
  2004. case GDScriptTokenizer::Token::UNDERSCORE:
  2005. // Wildcard.
  2006. advance();
  2007. pattern->pattern_type = PatternNode::PT_WILDCARD;
  2008. break;
  2009. case GDScriptTokenizer::Token::PERIOD_PERIOD:
  2010. // Rest.
  2011. advance();
  2012. pattern->pattern_type = PatternNode::PT_REST;
  2013. break;
  2014. case GDScriptTokenizer::Token::BRACKET_OPEN: {
  2015. // Array.
  2016. push_multiline(true);
  2017. advance();
  2018. pattern->pattern_type = PatternNode::PT_ARRAY;
  2019. do {
  2020. if (is_at_end() || check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2021. break;
  2022. }
  2023. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  2024. if (sub_pattern == nullptr) {
  2025. continue;
  2026. }
  2027. if (pattern->rest_used) {
  2028. push_error(R"(The ".." pattern must be the last element in the pattern array.)");
  2029. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  2030. pattern->rest_used = true;
  2031. }
  2032. pattern->array.push_back(sub_pattern);
  2033. } while (match(GDScriptTokenizer::Token::COMMA));
  2034. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
  2035. pop_multiline();
  2036. break;
  2037. }
  2038. case GDScriptTokenizer::Token::BRACE_OPEN: {
  2039. // Dictionary.
  2040. push_multiline(true);
  2041. advance();
  2042. pattern->pattern_type = PatternNode::PT_DICTIONARY;
  2043. do {
  2044. if (check(GDScriptTokenizer::Token::BRACE_CLOSE) || is_at_end()) {
  2045. break;
  2046. }
  2047. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
  2048. // Rest.
  2049. if (pattern->rest_used) {
  2050. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  2051. } else {
  2052. PatternNode *sub_pattern = alloc_node<PatternNode>();
  2053. complete_extents(sub_pattern);
  2054. sub_pattern->pattern_type = PatternNode::PT_REST;
  2055. pattern->dictionary.push_back({ nullptr, sub_pattern });
  2056. pattern->rest_used = true;
  2057. }
  2058. } else {
  2059. ExpressionNode *key = parse_expression(false);
  2060. if (key == nullptr) {
  2061. push_error(R"(Expected expression as key for dictionary pattern.)");
  2062. }
  2063. if (match(GDScriptTokenizer::Token::COLON)) {
  2064. // Value pattern.
  2065. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  2066. if (sub_pattern == nullptr) {
  2067. continue;
  2068. }
  2069. if (pattern->rest_used) {
  2070. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  2071. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  2072. push_error(R"(The ".." pattern cannot be used as a value.)");
  2073. } else {
  2074. pattern->dictionary.push_back({ key, sub_pattern });
  2075. }
  2076. } else {
  2077. // Key match only.
  2078. pattern->dictionary.push_back({ key, nullptr });
  2079. }
  2080. }
  2081. } while (match(GDScriptTokenizer::Token::COMMA));
  2082. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
  2083. pop_multiline();
  2084. break;
  2085. }
  2086. default: {
  2087. // Expression.
  2088. ExpressionNode *expression = parse_expression(false);
  2089. if (expression == nullptr) {
  2090. push_error(R"(Expected expression for match pattern.)");
  2091. complete_extents(pattern);
  2092. return nullptr;
  2093. } else {
  2094. if (expression->type == GDScriptParser::Node::LITERAL) {
  2095. pattern->pattern_type = PatternNode::PT_LITERAL;
  2096. } else {
  2097. pattern->pattern_type = PatternNode::PT_EXPRESSION;
  2098. }
  2099. pattern->expression = expression;
  2100. }
  2101. break;
  2102. }
  2103. }
  2104. complete_extents(pattern);
  2105. return pattern;
  2106. }
  2107. bool GDScriptParser::PatternNode::has_bind(const StringName &p_name) {
  2108. return binds.has(p_name);
  2109. }
  2110. GDScriptParser::IdentifierNode *GDScriptParser::PatternNode::get_bind(const StringName &p_name) {
  2111. return binds[p_name];
  2112. }
  2113. GDScriptParser::WhileNode *GDScriptParser::parse_while() {
  2114. WhileNode *n_while = alloc_node<WhileNode>();
  2115. n_while->condition = parse_expression(false);
  2116. if (n_while->condition == nullptr) {
  2117. push_error(R"(Expected conditional expression after "while".)");
  2118. }
  2119. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "while" condition.)");
  2120. // Save break/continue state.
  2121. bool could_break = can_break;
  2122. bool could_continue = can_continue;
  2123. // Allow break/continue.
  2124. can_break = true;
  2125. can_continue = true;
  2126. SuiteNode *suite = alloc_node<SuiteNode>();
  2127. suite->is_in_loop = true;
  2128. n_while->loop = parse_suite(R"("while" block)", suite);
  2129. complete_extents(n_while);
  2130. // Reset break/continue state.
  2131. can_break = could_break;
  2132. can_continue = could_continue;
  2133. return n_while;
  2134. }
  2135. GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign) {
  2136. // Switch multiline mode on for grouping tokens.
  2137. // Do this early to avoid the tokenizer generating whitespace tokens.
  2138. switch (current.type) {
  2139. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  2140. case GDScriptTokenizer::Token::BRACE_OPEN:
  2141. case GDScriptTokenizer::Token::BRACKET_OPEN:
  2142. push_multiline(true);
  2143. break;
  2144. default:
  2145. break; // Nothing to do.
  2146. }
  2147. // Completion can appear whenever an expression is expected.
  2148. make_completion_context(COMPLETION_IDENTIFIER, nullptr, -1, false);
  2149. GDScriptTokenizer::Token token = current;
  2150. GDScriptTokenizer::Token::Type token_type = token.type;
  2151. if (token.is_identifier()) {
  2152. // Allow keywords that can be treated as identifiers.
  2153. token_type = GDScriptTokenizer::Token::IDENTIFIER;
  2154. }
  2155. ParseFunction prefix_rule = get_rule(token_type)->prefix;
  2156. if (prefix_rule == nullptr) {
  2157. // Expected expression. Let the caller give the proper error message.
  2158. return nullptr;
  2159. }
  2160. advance(); // Only consume the token if there's a valid rule.
  2161. // After a token was consumed, update the completion context regardless of a previously set context.
  2162. ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign);
  2163. #ifdef TOOLS_ENABLED
  2164. // HACK: We can't create a context in parse_identifier since it is used in places were we don't want completion.
  2165. if (previous_operand != nullptr && previous_operand->type == GDScriptParser::Node::IDENTIFIER && prefix_rule == static_cast<ParseFunction>(&GDScriptParser::parse_identifier)) {
  2166. make_completion_context(COMPLETION_IDENTIFIER, previous_operand);
  2167. }
  2168. #endif
  2169. while (p_precedence <= get_rule(current.type)->precedence) {
  2170. if (previous_operand == nullptr || (p_stop_on_assign && current.type == GDScriptTokenizer::Token::EQUAL) || lambda_ended) {
  2171. return previous_operand;
  2172. }
  2173. // Also switch multiline mode on here for infix operators.
  2174. switch (current.type) {
  2175. // case GDScriptTokenizer::Token::BRACE_OPEN: // Not an infix operator.
  2176. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  2177. case GDScriptTokenizer::Token::BRACKET_OPEN:
  2178. push_multiline(true);
  2179. break;
  2180. default:
  2181. break; // Nothing to do.
  2182. }
  2183. token = advance();
  2184. ParseFunction infix_rule = get_rule(token.type)->infix;
  2185. previous_operand = (this->*infix_rule)(previous_operand, p_can_assign);
  2186. }
  2187. return previous_operand;
  2188. }
  2189. GDScriptParser::ExpressionNode *GDScriptParser::parse_expression(bool p_can_assign, bool p_stop_on_assign) {
  2190. return parse_precedence(PREC_ASSIGNMENT, p_can_assign, p_stop_on_assign);
  2191. }
  2192. GDScriptParser::IdentifierNode *GDScriptParser::parse_identifier() {
  2193. IdentifierNode *identifier = static_cast<IdentifierNode *>(parse_identifier(nullptr, false));
  2194. #ifdef DEBUG_ENABLED
  2195. // Check for spoofing here (if available in TextServer) since this isn't called inside expressions. This is only relevant for declarations.
  2196. if (identifier && TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier->name)) {
  2197. push_warning(identifier, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier->name.operator String());
  2198. }
  2199. #endif
  2200. return identifier;
  2201. }
  2202. GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2203. if (!previous.is_identifier()) {
  2204. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing identifier node without identifier token.");
  2205. }
  2206. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  2207. complete_extents(identifier);
  2208. identifier->name = previous.get_identifier();
  2209. if (identifier->name.operator String().is_empty()) {
  2210. print_line("Empty identifier found.");
  2211. }
  2212. identifier->suite = current_suite;
  2213. if (current_suite != nullptr && current_suite->has_local(identifier->name)) {
  2214. const SuiteNode::Local &declaration = current_suite->get_local(identifier->name);
  2215. identifier->source_function = declaration.source_function;
  2216. switch (declaration.type) {
  2217. case SuiteNode::Local::CONSTANT:
  2218. identifier->source = IdentifierNode::LOCAL_CONSTANT;
  2219. identifier->constant_source = declaration.constant;
  2220. declaration.constant->usages++;
  2221. break;
  2222. case SuiteNode::Local::VARIABLE:
  2223. identifier->source = IdentifierNode::LOCAL_VARIABLE;
  2224. identifier->variable_source = declaration.variable;
  2225. declaration.variable->usages++;
  2226. break;
  2227. case SuiteNode::Local::PARAMETER:
  2228. identifier->source = IdentifierNode::FUNCTION_PARAMETER;
  2229. identifier->parameter_source = declaration.parameter;
  2230. declaration.parameter->usages++;
  2231. break;
  2232. case SuiteNode::Local::FOR_VARIABLE:
  2233. identifier->source = IdentifierNode::LOCAL_ITERATOR;
  2234. identifier->bind_source = declaration.bind;
  2235. declaration.bind->usages++;
  2236. break;
  2237. case SuiteNode::Local::PATTERN_BIND:
  2238. identifier->source = IdentifierNode::LOCAL_BIND;
  2239. identifier->bind_source = declaration.bind;
  2240. declaration.bind->usages++;
  2241. break;
  2242. case SuiteNode::Local::UNDEFINED:
  2243. ERR_FAIL_V_MSG(nullptr, "Undefined local found.");
  2244. }
  2245. }
  2246. return identifier;
  2247. }
  2248. GDScriptParser::LiteralNode *GDScriptParser::parse_literal() {
  2249. return static_cast<LiteralNode *>(parse_literal(nullptr, false));
  2250. }
  2251. GDScriptParser::ExpressionNode *GDScriptParser::parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2252. if (previous.type != GDScriptTokenizer::Token::LITERAL) {
  2253. push_error("Parser bug: parsing literal node without literal token.");
  2254. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
  2255. }
  2256. LiteralNode *literal = alloc_node<LiteralNode>();
  2257. literal->value = previous.literal;
  2258. reset_extents(literal, p_previous_operand);
  2259. update_extents(literal);
  2260. make_completion_context(COMPLETION_NONE, literal, -1);
  2261. complete_extents(literal);
  2262. return literal;
  2263. }
  2264. GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2265. if (current_function && current_function->is_static) {
  2266. push_error(R"(Cannot use "self" inside a static function.)");
  2267. }
  2268. SelfNode *self = alloc_node<SelfNode>();
  2269. complete_extents(self);
  2270. self->current_class = current_class;
  2271. return self;
  2272. }
  2273. GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2274. GDScriptTokenizer::Token::Type op_type = previous.type;
  2275. LiteralNode *constant = alloc_node<LiteralNode>();
  2276. complete_extents(constant);
  2277. switch (op_type) {
  2278. case GDScriptTokenizer::Token::CONST_PI:
  2279. constant->value = Math_PI;
  2280. break;
  2281. case GDScriptTokenizer::Token::CONST_TAU:
  2282. constant->value = Math_TAU;
  2283. break;
  2284. case GDScriptTokenizer::Token::CONST_INF:
  2285. constant->value = INFINITY;
  2286. break;
  2287. case GDScriptTokenizer::Token::CONST_NAN:
  2288. constant->value = NAN;
  2289. break;
  2290. default:
  2291. return nullptr; // Unreachable.
  2292. }
  2293. return constant;
  2294. }
  2295. GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2296. GDScriptTokenizer::Token::Type op_type = previous.type;
  2297. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2298. switch (op_type) {
  2299. case GDScriptTokenizer::Token::MINUS:
  2300. operation->operation = UnaryOpNode::OP_NEGATIVE;
  2301. operation->variant_op = Variant::OP_NEGATE;
  2302. operation->operand = parse_precedence(PREC_SIGN, false);
  2303. if (operation->operand == nullptr) {
  2304. push_error(R"(Expected expression after "-" operator.)");
  2305. }
  2306. break;
  2307. case GDScriptTokenizer::Token::PLUS:
  2308. operation->operation = UnaryOpNode::OP_POSITIVE;
  2309. operation->variant_op = Variant::OP_POSITIVE;
  2310. operation->operand = parse_precedence(PREC_SIGN, false);
  2311. if (operation->operand == nullptr) {
  2312. push_error(R"(Expected expression after "+" operator.)");
  2313. }
  2314. break;
  2315. case GDScriptTokenizer::Token::TILDE:
  2316. operation->operation = UnaryOpNode::OP_COMPLEMENT;
  2317. operation->variant_op = Variant::OP_BIT_NEGATE;
  2318. operation->operand = parse_precedence(PREC_BIT_NOT, false);
  2319. if (operation->operand == nullptr) {
  2320. push_error(R"(Expected expression after "~" operator.)");
  2321. }
  2322. break;
  2323. case GDScriptTokenizer::Token::NOT:
  2324. case GDScriptTokenizer::Token::BANG:
  2325. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2326. operation->variant_op = Variant::OP_NOT;
  2327. operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
  2328. if (operation->operand == nullptr) {
  2329. push_error(vformat(R"(Expected expression after "%s" operator.)", op_type == GDScriptTokenizer::Token::NOT ? "not" : "!"));
  2330. }
  2331. break;
  2332. default:
  2333. complete_extents(operation);
  2334. return nullptr; // Unreachable.
  2335. }
  2336. complete_extents(operation);
  2337. return operation;
  2338. }
  2339. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_not_in_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2340. // check that NOT is followed by IN by consuming it before calling parse_binary_operator which will only receive a plain IN
  2341. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2342. reset_extents(operation, p_previous_operand);
  2343. update_extents(operation);
  2344. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "not" in content-test operator.)");
  2345. ExpressionNode *in_operation = parse_binary_operator(p_previous_operand, p_can_assign);
  2346. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2347. operation->variant_op = Variant::OP_NOT;
  2348. operation->operand = in_operation;
  2349. complete_extents(operation);
  2350. return operation;
  2351. }
  2352. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2353. GDScriptTokenizer::Token op = previous;
  2354. BinaryOpNode *operation = alloc_node<BinaryOpNode>();
  2355. reset_extents(operation, p_previous_operand);
  2356. update_extents(operation);
  2357. Precedence precedence = (Precedence)(get_rule(op.type)->precedence + 1);
  2358. operation->left_operand = p_previous_operand;
  2359. operation->right_operand = parse_precedence(precedence, false);
  2360. complete_extents(operation);
  2361. if (operation->right_operand == nullptr) {
  2362. push_error(vformat(R"(Expected expression after "%s" operator.)", op.get_name()));
  2363. }
  2364. // TODO: Also for unary, ternary, and assignment.
  2365. switch (op.type) {
  2366. case GDScriptTokenizer::Token::PLUS:
  2367. operation->operation = BinaryOpNode::OP_ADDITION;
  2368. operation->variant_op = Variant::OP_ADD;
  2369. break;
  2370. case GDScriptTokenizer::Token::MINUS:
  2371. operation->operation = BinaryOpNode::OP_SUBTRACTION;
  2372. operation->variant_op = Variant::OP_SUBTRACT;
  2373. break;
  2374. case GDScriptTokenizer::Token::STAR:
  2375. operation->operation = BinaryOpNode::OP_MULTIPLICATION;
  2376. operation->variant_op = Variant::OP_MULTIPLY;
  2377. break;
  2378. case GDScriptTokenizer::Token::SLASH:
  2379. operation->operation = BinaryOpNode::OP_DIVISION;
  2380. operation->variant_op = Variant::OP_DIVIDE;
  2381. break;
  2382. case GDScriptTokenizer::Token::PERCENT:
  2383. operation->operation = BinaryOpNode::OP_MODULO;
  2384. operation->variant_op = Variant::OP_MODULE;
  2385. break;
  2386. case GDScriptTokenizer::Token::STAR_STAR:
  2387. operation->operation = BinaryOpNode::OP_POWER;
  2388. operation->variant_op = Variant::OP_POWER;
  2389. break;
  2390. case GDScriptTokenizer::Token::LESS_LESS:
  2391. operation->operation = BinaryOpNode::OP_BIT_LEFT_SHIFT;
  2392. operation->variant_op = Variant::OP_SHIFT_LEFT;
  2393. break;
  2394. case GDScriptTokenizer::Token::GREATER_GREATER:
  2395. operation->operation = BinaryOpNode::OP_BIT_RIGHT_SHIFT;
  2396. operation->variant_op = Variant::OP_SHIFT_RIGHT;
  2397. break;
  2398. case GDScriptTokenizer::Token::AMPERSAND:
  2399. operation->operation = BinaryOpNode::OP_BIT_AND;
  2400. operation->variant_op = Variant::OP_BIT_AND;
  2401. break;
  2402. case GDScriptTokenizer::Token::PIPE:
  2403. operation->operation = BinaryOpNode::OP_BIT_OR;
  2404. operation->variant_op = Variant::OP_BIT_OR;
  2405. break;
  2406. case GDScriptTokenizer::Token::CARET:
  2407. operation->operation = BinaryOpNode::OP_BIT_XOR;
  2408. operation->variant_op = Variant::OP_BIT_XOR;
  2409. break;
  2410. case GDScriptTokenizer::Token::AND:
  2411. case GDScriptTokenizer::Token::AMPERSAND_AMPERSAND:
  2412. operation->operation = BinaryOpNode::OP_LOGIC_AND;
  2413. operation->variant_op = Variant::OP_AND;
  2414. break;
  2415. case GDScriptTokenizer::Token::OR:
  2416. case GDScriptTokenizer::Token::PIPE_PIPE:
  2417. operation->operation = BinaryOpNode::OP_LOGIC_OR;
  2418. operation->variant_op = Variant::OP_OR;
  2419. break;
  2420. case GDScriptTokenizer::Token::IN:
  2421. operation->operation = BinaryOpNode::OP_CONTENT_TEST;
  2422. operation->variant_op = Variant::OP_IN;
  2423. break;
  2424. case GDScriptTokenizer::Token::EQUAL_EQUAL:
  2425. operation->operation = BinaryOpNode::OP_COMP_EQUAL;
  2426. operation->variant_op = Variant::OP_EQUAL;
  2427. break;
  2428. case GDScriptTokenizer::Token::BANG_EQUAL:
  2429. operation->operation = BinaryOpNode::OP_COMP_NOT_EQUAL;
  2430. operation->variant_op = Variant::OP_NOT_EQUAL;
  2431. break;
  2432. case GDScriptTokenizer::Token::LESS:
  2433. operation->operation = BinaryOpNode::OP_COMP_LESS;
  2434. operation->variant_op = Variant::OP_LESS;
  2435. break;
  2436. case GDScriptTokenizer::Token::LESS_EQUAL:
  2437. operation->operation = BinaryOpNode::OP_COMP_LESS_EQUAL;
  2438. operation->variant_op = Variant::OP_LESS_EQUAL;
  2439. break;
  2440. case GDScriptTokenizer::Token::GREATER:
  2441. operation->operation = BinaryOpNode::OP_COMP_GREATER;
  2442. operation->variant_op = Variant::OP_GREATER;
  2443. break;
  2444. case GDScriptTokenizer::Token::GREATER_EQUAL:
  2445. operation->operation = BinaryOpNode::OP_COMP_GREATER_EQUAL;
  2446. operation->variant_op = Variant::OP_GREATER_EQUAL;
  2447. break;
  2448. default:
  2449. return nullptr; // Unreachable.
  2450. }
  2451. return operation;
  2452. }
  2453. GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2454. // Only one ternary operation exists, so no abstraction here.
  2455. TernaryOpNode *operation = alloc_node<TernaryOpNode>();
  2456. reset_extents(operation, p_previous_operand);
  2457. update_extents(operation);
  2458. operation->true_expr = p_previous_operand;
  2459. operation->condition = parse_precedence(PREC_TERNARY, false);
  2460. if (operation->condition == nullptr) {
  2461. push_error(R"(Expected expression as ternary condition after "if".)");
  2462. }
  2463. consume(GDScriptTokenizer::Token::ELSE, R"(Expected "else" after ternary operator condition.)");
  2464. operation->false_expr = parse_precedence(PREC_TERNARY, false);
  2465. if (operation->false_expr == nullptr) {
  2466. push_error(R"(Expected expression after "else".)");
  2467. }
  2468. complete_extents(operation);
  2469. return operation;
  2470. }
  2471. GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2472. if (!p_can_assign) {
  2473. push_error("Assignment is not allowed inside an expression.");
  2474. return parse_expression(false); // Return the following expression.
  2475. }
  2476. if (p_previous_operand == nullptr) {
  2477. return parse_expression(false); // Return the following expression.
  2478. }
  2479. switch (p_previous_operand->type) {
  2480. case Node::IDENTIFIER: {
  2481. #ifdef DEBUG_ENABLED
  2482. // Get source to store assignment count.
  2483. // Also remove one usage since assignment isn't usage.
  2484. IdentifierNode *id = static_cast<IdentifierNode *>(p_previous_operand);
  2485. switch (id->source) {
  2486. case IdentifierNode::LOCAL_VARIABLE:
  2487. id->variable_source->usages--;
  2488. break;
  2489. case IdentifierNode::LOCAL_CONSTANT:
  2490. id->constant_source->usages--;
  2491. break;
  2492. case IdentifierNode::FUNCTION_PARAMETER:
  2493. id->parameter_source->usages--;
  2494. break;
  2495. case IdentifierNode::LOCAL_ITERATOR:
  2496. case IdentifierNode::LOCAL_BIND:
  2497. id->bind_source->usages--;
  2498. break;
  2499. default:
  2500. break;
  2501. }
  2502. #endif
  2503. } break;
  2504. case Node::SUBSCRIPT:
  2505. // Okay.
  2506. break;
  2507. default:
  2508. push_error(R"(Only identifier, attribute access, and subscription access can be used as assignment target.)");
  2509. return parse_expression(false); // Return the following expression.
  2510. }
  2511. AssignmentNode *assignment = alloc_node<AssignmentNode>();
  2512. reset_extents(assignment, p_previous_operand);
  2513. update_extents(assignment);
  2514. make_completion_context(COMPLETION_ASSIGN, assignment);
  2515. switch (previous.type) {
  2516. case GDScriptTokenizer::Token::EQUAL:
  2517. assignment->operation = AssignmentNode::OP_NONE;
  2518. assignment->variant_op = Variant::OP_MAX;
  2519. break;
  2520. case GDScriptTokenizer::Token::PLUS_EQUAL:
  2521. assignment->operation = AssignmentNode::OP_ADDITION;
  2522. assignment->variant_op = Variant::OP_ADD;
  2523. break;
  2524. case GDScriptTokenizer::Token::MINUS_EQUAL:
  2525. assignment->operation = AssignmentNode::OP_SUBTRACTION;
  2526. assignment->variant_op = Variant::OP_SUBTRACT;
  2527. break;
  2528. case GDScriptTokenizer::Token::STAR_EQUAL:
  2529. assignment->operation = AssignmentNode::OP_MULTIPLICATION;
  2530. assignment->variant_op = Variant::OP_MULTIPLY;
  2531. break;
  2532. case GDScriptTokenizer::Token::STAR_STAR_EQUAL:
  2533. assignment->operation = AssignmentNode::OP_POWER;
  2534. assignment->variant_op = Variant::OP_POWER;
  2535. break;
  2536. case GDScriptTokenizer::Token::SLASH_EQUAL:
  2537. assignment->operation = AssignmentNode::OP_DIVISION;
  2538. assignment->variant_op = Variant::OP_DIVIDE;
  2539. break;
  2540. case GDScriptTokenizer::Token::PERCENT_EQUAL:
  2541. assignment->operation = AssignmentNode::OP_MODULO;
  2542. assignment->variant_op = Variant::OP_MODULE;
  2543. break;
  2544. case GDScriptTokenizer::Token::LESS_LESS_EQUAL:
  2545. assignment->operation = AssignmentNode::OP_BIT_SHIFT_LEFT;
  2546. assignment->variant_op = Variant::OP_SHIFT_LEFT;
  2547. break;
  2548. case GDScriptTokenizer::Token::GREATER_GREATER_EQUAL:
  2549. assignment->operation = AssignmentNode::OP_BIT_SHIFT_RIGHT;
  2550. assignment->variant_op = Variant::OP_SHIFT_RIGHT;
  2551. break;
  2552. case GDScriptTokenizer::Token::AMPERSAND_EQUAL:
  2553. assignment->operation = AssignmentNode::OP_BIT_AND;
  2554. assignment->variant_op = Variant::OP_BIT_AND;
  2555. break;
  2556. case GDScriptTokenizer::Token::PIPE_EQUAL:
  2557. assignment->operation = AssignmentNode::OP_BIT_OR;
  2558. assignment->variant_op = Variant::OP_BIT_OR;
  2559. break;
  2560. case GDScriptTokenizer::Token::CARET_EQUAL:
  2561. assignment->operation = AssignmentNode::OP_BIT_XOR;
  2562. assignment->variant_op = Variant::OP_BIT_XOR;
  2563. break;
  2564. default:
  2565. break; // Unreachable.
  2566. }
  2567. assignment->assignee = p_previous_operand;
  2568. assignment->assigned_value = parse_expression(false);
  2569. #ifdef TOOLS_ENABLED
  2570. if (assignment->assigned_value != nullptr && assignment->assigned_value->type == GDScriptParser::Node::IDENTIFIER) {
  2571. override_completion_context(assignment->assigned_value, COMPLETION_ASSIGN, assignment);
  2572. }
  2573. #endif
  2574. if (assignment->assigned_value == nullptr) {
  2575. push_error(R"(Expected an expression after "=".)");
  2576. }
  2577. complete_extents(assignment);
  2578. return assignment;
  2579. }
  2580. GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2581. AwaitNode *await = alloc_node<AwaitNode>();
  2582. ExpressionNode *element = parse_precedence(PREC_AWAIT, false);
  2583. if (element == nullptr) {
  2584. push_error(R"(Expected signal or coroutine after "await".)");
  2585. }
  2586. await->to_await = element;
  2587. complete_extents(await);
  2588. if (current_function) { // Might be null in a getter or setter.
  2589. current_function->is_coroutine = true;
  2590. }
  2591. return await;
  2592. }
  2593. GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2594. ArrayNode *array = alloc_node<ArrayNode>();
  2595. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2596. do {
  2597. if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2598. // Allow for trailing comma.
  2599. break;
  2600. }
  2601. ExpressionNode *element = parse_expression(false);
  2602. if (element == nullptr) {
  2603. push_error(R"(Expected expression as array element.)");
  2604. } else {
  2605. array->elements.push_back(element);
  2606. }
  2607. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2608. }
  2609. pop_multiline();
  2610. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
  2611. complete_extents(array);
  2612. return array;
  2613. }
  2614. GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2615. DictionaryNode *dictionary = alloc_node<DictionaryNode>();
  2616. bool decided_style = false;
  2617. if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2618. do {
  2619. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2620. // Allow for trailing comma.
  2621. break;
  2622. }
  2623. // Key.
  2624. ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
  2625. if (key == nullptr) {
  2626. push_error(R"(Expected expression as dictionary key.)");
  2627. }
  2628. if (!decided_style) {
  2629. switch (current.type) {
  2630. case GDScriptTokenizer::Token::COLON:
  2631. dictionary->style = DictionaryNode::PYTHON_DICT;
  2632. break;
  2633. case GDScriptTokenizer::Token::EQUAL:
  2634. dictionary->style = DictionaryNode::LUA_TABLE;
  2635. break;
  2636. default:
  2637. push_error(R"(Expected ":" or "=" after dictionary key.)");
  2638. break;
  2639. }
  2640. decided_style = true;
  2641. }
  2642. switch (dictionary->style) {
  2643. case DictionaryNode::LUA_TABLE:
  2644. if (key != nullptr && key->type != Node::IDENTIFIER && key->type != Node::LITERAL) {
  2645. push_error(R"(Expected identifier or string as Lua-style dictionary key (e.g "{ key = value }").)");
  2646. advance();
  2647. break;
  2648. }
  2649. if (key != nullptr && key->type == Node::LITERAL && static_cast<LiteralNode *>(key)->value.get_type() != Variant::STRING) {
  2650. push_error(R"(Expected identifier or string as Lua-style dictionary key (e.g "{ key = value }").)");
  2651. advance();
  2652. break;
  2653. }
  2654. if (!match(GDScriptTokenizer::Token::EQUAL)) {
  2655. if (match(GDScriptTokenizer::Token::COLON)) {
  2656. push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
  2657. advance(); // Consume wrong separator anyway.
  2658. } else {
  2659. push_error(R"(Expected "=" after dictionary key.)");
  2660. }
  2661. }
  2662. if (key != nullptr) {
  2663. key->is_constant = true;
  2664. if (key->type == Node::IDENTIFIER) {
  2665. key->reduced_value = static_cast<IdentifierNode *>(key)->name;
  2666. } else if (key->type == Node::LITERAL) {
  2667. key->reduced_value = StringName(static_cast<LiteralNode *>(key)->value.operator String());
  2668. }
  2669. }
  2670. break;
  2671. case DictionaryNode::PYTHON_DICT:
  2672. if (!match(GDScriptTokenizer::Token::COLON)) {
  2673. if (match(GDScriptTokenizer::Token::EQUAL)) {
  2674. push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
  2675. advance(); // Consume wrong separator anyway.
  2676. } else {
  2677. push_error(R"(Expected ":" after dictionary key.)");
  2678. }
  2679. }
  2680. break;
  2681. }
  2682. // Value.
  2683. ExpressionNode *value = parse_expression(false);
  2684. if (value == nullptr) {
  2685. push_error(R"(Expected expression as dictionary value.)");
  2686. }
  2687. if (key != nullptr && value != nullptr) {
  2688. dictionary->elements.push_back({ key, value });
  2689. }
  2690. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2691. }
  2692. pop_multiline();
  2693. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
  2694. complete_extents(dictionary);
  2695. return dictionary;
  2696. }
  2697. GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2698. ExpressionNode *grouped = parse_expression(false);
  2699. pop_multiline();
  2700. if (grouped == nullptr) {
  2701. push_error(R"(Expected grouping expression.)");
  2702. } else {
  2703. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
  2704. }
  2705. return grouped;
  2706. }
  2707. GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2708. SubscriptNode *attribute = alloc_node<SubscriptNode>();
  2709. reset_extents(attribute, p_previous_operand);
  2710. update_extents(attribute);
  2711. if (for_completion) {
  2712. bool is_builtin = false;
  2713. if (p_previous_operand && p_previous_operand->type == Node::IDENTIFIER) {
  2714. const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
  2715. Variant::Type builtin_type = get_builtin_type(id->name);
  2716. if (builtin_type < Variant::VARIANT_MAX) {
  2717. make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT_OR_STATIC_METHOD, builtin_type);
  2718. is_builtin = true;
  2719. }
  2720. }
  2721. if (!is_builtin) {
  2722. make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1);
  2723. }
  2724. }
  2725. attribute->base = p_previous_operand;
  2726. if (current.is_node_name()) {
  2727. current.type = GDScriptTokenizer::Token::IDENTIFIER;
  2728. }
  2729. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
  2730. complete_extents(attribute);
  2731. return attribute;
  2732. }
  2733. attribute->is_attribute = true;
  2734. attribute->attribute = parse_identifier();
  2735. complete_extents(attribute);
  2736. return attribute;
  2737. }
  2738. GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2739. SubscriptNode *subscript = alloc_node<SubscriptNode>();
  2740. reset_extents(subscript, p_previous_operand);
  2741. update_extents(subscript);
  2742. make_completion_context(COMPLETION_SUBSCRIPT, subscript);
  2743. subscript->base = p_previous_operand;
  2744. subscript->index = parse_expression(false);
  2745. #ifdef TOOLS_ENABLED
  2746. if (subscript->index != nullptr && subscript->index->type == Node::LITERAL) {
  2747. override_completion_context(subscript->index, COMPLETION_SUBSCRIPT, subscript);
  2748. }
  2749. #endif
  2750. if (subscript->index == nullptr) {
  2751. push_error(R"(Expected expression after "[".)");
  2752. }
  2753. pop_multiline();
  2754. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
  2755. complete_extents(subscript);
  2756. return subscript;
  2757. }
  2758. GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2759. CastNode *cast = alloc_node<CastNode>();
  2760. reset_extents(cast, p_previous_operand);
  2761. update_extents(cast);
  2762. cast->operand = p_previous_operand;
  2763. cast->cast_type = parse_type();
  2764. complete_extents(cast);
  2765. if (cast->cast_type == nullptr) {
  2766. push_error(R"(Expected type specifier after "as".)");
  2767. return p_previous_operand;
  2768. }
  2769. return cast;
  2770. }
  2771. GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2772. CallNode *call = alloc_node<CallNode>();
  2773. reset_extents(call, p_previous_operand);
  2774. if (previous.type == GDScriptTokenizer::Token::SUPER) {
  2775. // Super call.
  2776. call->is_super = true;
  2777. push_multiline(true);
  2778. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  2779. // Implicit call to the parent method of the same name.
  2780. if (current_function == nullptr) {
  2781. push_error(R"(Cannot use implicit "super" call outside of a function.)");
  2782. pop_multiline();
  2783. complete_extents(call);
  2784. return nullptr;
  2785. }
  2786. if (current_function->identifier) {
  2787. call->function_name = current_function->identifier->name;
  2788. } else {
  2789. call->function_name = SNAME("<anonymous>");
  2790. }
  2791. } else {
  2792. consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
  2793. make_completion_context(COMPLETION_SUPER_METHOD, call, true);
  2794. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
  2795. pop_multiline();
  2796. complete_extents(call);
  2797. return nullptr;
  2798. }
  2799. IdentifierNode *identifier = parse_identifier();
  2800. call->callee = identifier;
  2801. call->function_name = identifier->name;
  2802. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)");
  2803. }
  2804. } else {
  2805. call->callee = p_previous_operand;
  2806. if (call->callee == nullptr) {
  2807. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2808. } else if (call->callee->type == Node::IDENTIFIER) {
  2809. call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
  2810. make_completion_context(COMPLETION_METHOD, call->callee);
  2811. } else if (call->callee->type == Node::SUBSCRIPT) {
  2812. SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
  2813. if (attribute->is_attribute) {
  2814. if (attribute->attribute) {
  2815. call->function_name = attribute->attribute->name;
  2816. }
  2817. make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
  2818. } else {
  2819. // TODO: The analyzer can see if this is actually a Callable and give better error message.
  2820. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2821. }
  2822. } else {
  2823. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2824. }
  2825. }
  2826. // Arguments.
  2827. CompletionType ct = COMPLETION_CALL_ARGUMENTS;
  2828. if (call->function_name == SNAME("load")) {
  2829. ct = COMPLETION_RESOURCE_PATH;
  2830. }
  2831. push_completion_call(call);
  2832. int argument_index = 0;
  2833. do {
  2834. make_completion_context(ct, call, argument_index);
  2835. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  2836. // Allow for trailing comma.
  2837. break;
  2838. }
  2839. ExpressionNode *argument = parse_expression(false);
  2840. if (argument == nullptr) {
  2841. push_error(R"(Expected expression as the function argument.)");
  2842. } else {
  2843. call->arguments.push_back(argument);
  2844. if (argument->type == Node::LITERAL) {
  2845. override_completion_context(argument, ct, call, argument_index);
  2846. }
  2847. }
  2848. ct = COMPLETION_CALL_ARGUMENTS;
  2849. argument_index++;
  2850. } while (match(GDScriptTokenizer::Token::COMMA));
  2851. pop_completion_call();
  2852. pop_multiline();
  2853. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
  2854. complete_extents(call);
  2855. return call;
  2856. }
  2857. GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2858. // We want code completion after a DOLLAR even if the current code is invalid.
  2859. make_completion_context(COMPLETION_GET_NODE, nullptr, -1);
  2860. if (!current.is_node_name() && !check(GDScriptTokenizer::Token::LITERAL) && !check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  2861. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  2862. return nullptr;
  2863. }
  2864. if (check(GDScriptTokenizer::Token::LITERAL)) {
  2865. if (current.literal.get_type() != Variant::STRING) {
  2866. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  2867. return nullptr;
  2868. }
  2869. }
  2870. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  2871. // Store the last item in the path so the parser knows what to expect.
  2872. // Allow allows more specific error messages.
  2873. enum PathState {
  2874. PATH_STATE_START,
  2875. PATH_STATE_SLASH,
  2876. PATH_STATE_PERCENT,
  2877. PATH_STATE_NODE_NAME,
  2878. } path_state = PATH_STATE_START;
  2879. if (previous.type == GDScriptTokenizer::Token::DOLLAR) {
  2880. // Detect initial slash, which will be handled in the loop if it matches.
  2881. match(GDScriptTokenizer::Token::SLASH);
  2882. } else {
  2883. get_node->use_dollar = false;
  2884. }
  2885. int context_argument = 0;
  2886. do {
  2887. if (previous.type == GDScriptTokenizer::Token::PERCENT) {
  2888. if (path_state != PATH_STATE_START && path_state != PATH_STATE_SLASH) {
  2889. push_error(R"("%" is only valid in the beginning of a node name (either after "$" or after "/"))");
  2890. complete_extents(get_node);
  2891. return nullptr;
  2892. }
  2893. get_node->full_path += "%";
  2894. path_state = PATH_STATE_PERCENT;
  2895. } else if (previous.type == GDScriptTokenizer::Token::SLASH) {
  2896. if (path_state != PATH_STATE_START && path_state != PATH_STATE_NODE_NAME) {
  2897. push_error(R"("/" is only valid at the beginning of the path or after a node name.)");
  2898. complete_extents(get_node);
  2899. return nullptr;
  2900. }
  2901. get_node->full_path += "/";
  2902. path_state = PATH_STATE_SLASH;
  2903. }
  2904. make_completion_context(COMPLETION_GET_NODE, get_node, context_argument++);
  2905. if (match(GDScriptTokenizer::Token::LITERAL)) {
  2906. if (previous.literal.get_type() != Variant::STRING) {
  2907. String previous_token;
  2908. switch (path_state) {
  2909. case PATH_STATE_START:
  2910. previous_token = "$";
  2911. break;
  2912. case PATH_STATE_PERCENT:
  2913. previous_token = "%";
  2914. break;
  2915. case PATH_STATE_SLASH:
  2916. previous_token = "/";
  2917. break;
  2918. default:
  2919. break;
  2920. }
  2921. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous_token));
  2922. complete_extents(get_node);
  2923. return nullptr;
  2924. }
  2925. get_node->full_path += previous.literal.operator String();
  2926. path_state = PATH_STATE_NODE_NAME;
  2927. } else if (current.is_node_name()) {
  2928. advance();
  2929. String identifier = previous.get_identifier();
  2930. #ifdef DEBUG_ENABLED
  2931. // Check spoofing.
  2932. if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier)) {
  2933. push_warning(get_node, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier);
  2934. }
  2935. #endif
  2936. get_node->full_path += identifier;
  2937. path_state = PATH_STATE_NODE_NAME;
  2938. } else if (!check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  2939. push_error(vformat(R"(Unexpected "%s" in node path.)", current.get_name()));
  2940. complete_extents(get_node);
  2941. return nullptr;
  2942. }
  2943. } while (match(GDScriptTokenizer::Token::SLASH) || match(GDScriptTokenizer::Token::PERCENT));
  2944. complete_extents(get_node);
  2945. return get_node;
  2946. }
  2947. GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2948. PreloadNode *preload = alloc_node<PreloadNode>();
  2949. preload->resolved_path = "<missing path>";
  2950. push_multiline(true);
  2951. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
  2952. make_completion_context(COMPLETION_RESOURCE_PATH, preload);
  2953. push_completion_call(preload);
  2954. preload->path = parse_expression(false);
  2955. if (preload->path == nullptr) {
  2956. push_error(R"(Expected resource path after "(".)");
  2957. }
  2958. pop_completion_call();
  2959. pop_multiline();
  2960. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
  2961. complete_extents(preload);
  2962. return preload;
  2963. }
  2964. GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2965. LambdaNode *lambda = alloc_node<LambdaNode>();
  2966. lambda->parent_function = current_function;
  2967. lambda->parent_lambda = current_lambda;
  2968. FunctionNode *function = alloc_node<FunctionNode>();
  2969. function->source_lambda = lambda;
  2970. function->is_static = current_function != nullptr ? current_function->is_static : false;
  2971. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2972. function->identifier = parse_identifier();
  2973. }
  2974. bool multiline_context = multiline_stack.back()->get();
  2975. // Reset the multiline stack since we don't want the multiline mode one in the lambda body.
  2976. push_multiline(false);
  2977. if (multiline_context) {
  2978. tokenizer->push_expression_indented_block();
  2979. }
  2980. push_multiline(true); // For the parameters.
  2981. if (function->identifier) {
  2982. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)");
  2983. } else {
  2984. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)");
  2985. }
  2986. FunctionNode *previous_function = current_function;
  2987. current_function = function;
  2988. LambdaNode *previous_lambda = current_lambda;
  2989. current_lambda = lambda;
  2990. SuiteNode *body = alloc_node<SuiteNode>();
  2991. body->parent_function = current_function;
  2992. body->parent_block = current_suite;
  2993. SuiteNode *previous_suite = current_suite;
  2994. current_suite = body;
  2995. parse_function_signature(function, body, "lambda");
  2996. current_suite = previous_suite;
  2997. bool previous_in_lambda = in_lambda;
  2998. in_lambda = true;
  2999. // Save break/continue state.
  3000. bool could_break = can_break;
  3001. bool could_continue = can_continue;
  3002. // Disallow break/continue.
  3003. can_break = false;
  3004. can_continue = false;
  3005. function->body = parse_suite("lambda declaration", body, true);
  3006. complete_extents(function);
  3007. complete_extents(lambda);
  3008. pop_multiline();
  3009. if (multiline_context) {
  3010. // If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens.
  3011. while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) {
  3012. current = tokenizer->scan(); // Not advance() since we don't want to change the previous token.
  3013. }
  3014. tokenizer->pop_expression_indented_block();
  3015. }
  3016. current_function = previous_function;
  3017. current_lambda = previous_lambda;
  3018. in_lambda = previous_in_lambda;
  3019. lambda->function = function;
  3020. // Reset break/continue state.
  3021. can_break = could_break;
  3022. can_continue = could_continue;
  3023. return lambda;
  3024. }
  3025. GDScriptParser::ExpressionNode *GDScriptParser::parse_type_test(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3026. // x is not int
  3027. // ^ ^^^ ExpressionNode, TypeNode
  3028. // ^^^^^^^^^^^^ TypeTestNode
  3029. // ^^^^^^^^^^^^ UnaryOpNode
  3030. UnaryOpNode *not_node = nullptr;
  3031. if (match(GDScriptTokenizer::Token::NOT)) {
  3032. not_node = alloc_node<UnaryOpNode>();
  3033. not_node->operation = UnaryOpNode::OP_LOGIC_NOT;
  3034. not_node->variant_op = Variant::OP_NOT;
  3035. reset_extents(not_node, p_previous_operand);
  3036. update_extents(not_node);
  3037. }
  3038. TypeTestNode *type_test = alloc_node<TypeTestNode>();
  3039. reset_extents(type_test, p_previous_operand);
  3040. update_extents(type_test);
  3041. type_test->operand = p_previous_operand;
  3042. type_test->test_type = parse_type();
  3043. complete_extents(type_test);
  3044. if (not_node != nullptr) {
  3045. not_node->operand = type_test;
  3046. complete_extents(not_node);
  3047. }
  3048. if (type_test->test_type == nullptr) {
  3049. if (not_node == nullptr) {
  3050. push_error(R"(Expected type specifier after "is".)");
  3051. } else {
  3052. push_error(R"(Expected type specifier after "is not".)");
  3053. }
  3054. }
  3055. if (not_node != nullptr) {
  3056. return not_node;
  3057. }
  3058. return type_test;
  3059. }
  3060. GDScriptParser::ExpressionNode *GDScriptParser::parse_yield(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3061. push_error(R"("yield" was removed in Godot 4. Use "await" instead.)");
  3062. return nullptr;
  3063. }
  3064. GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3065. // Just for better error messages.
  3066. GDScriptTokenizer::Token::Type invalid = previous.type;
  3067. switch (invalid) {
  3068. case GDScriptTokenizer::Token::QUESTION_MARK:
  3069. push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
  3070. break;
  3071. default:
  3072. return nullptr; // Unreachable.
  3073. }
  3074. // Return the previous expression.
  3075. return p_previous_operand;
  3076. }
  3077. GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
  3078. TypeNode *type = alloc_node<TypeNode>();
  3079. make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
  3080. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  3081. if (match(GDScriptTokenizer::Token::VOID)) {
  3082. if (p_allow_void) {
  3083. complete_extents(type);
  3084. TypeNode *void_type = type;
  3085. return void_type;
  3086. } else {
  3087. push_error(R"("void" is only allowed for a function return type.)");
  3088. }
  3089. }
  3090. // Leave error message to the caller who knows the context.
  3091. complete_extents(type);
  3092. return nullptr;
  3093. }
  3094. IdentifierNode *type_element = parse_identifier();
  3095. type->type_chain.push_back(type_element);
  3096. if (match(GDScriptTokenizer::Token::BRACKET_OPEN)) {
  3097. // Typed collection (like Array[int]).
  3098. bool first_pass = true;
  3099. do {
  3100. TypeNode *container_type = parse_type(false); // Don't allow void for element type.
  3101. if (container_type == nullptr) {
  3102. push_error(vformat(R"(Expected type for collection after "%s".)", first_pass ? "[" : ","));
  3103. complete_extents(type);
  3104. type = nullptr;
  3105. break;
  3106. } else if (container_type->container_types.size() > 0) {
  3107. push_error("Nested typed collections are not supported.");
  3108. } else {
  3109. type->container_types.append(container_type);
  3110. }
  3111. first_pass = false;
  3112. } while (match(GDScriptTokenizer::Token::COMMA));
  3113. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after collection type.)");
  3114. if (type != nullptr) {
  3115. complete_extents(type);
  3116. }
  3117. return type;
  3118. }
  3119. int chain_index = 1;
  3120. while (match(GDScriptTokenizer::Token::PERIOD)) {
  3121. make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
  3122. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
  3123. type_element = parse_identifier();
  3124. type->type_chain.push_back(type_element);
  3125. }
  3126. }
  3127. complete_extents(type);
  3128. return type;
  3129. }
  3130. #ifdef TOOLS_ENABLED
  3131. enum DocLineState {
  3132. DOC_LINE_NORMAL,
  3133. DOC_LINE_IN_CODE,
  3134. DOC_LINE_IN_CODEBLOCK,
  3135. DOC_LINE_IN_KBD,
  3136. };
  3137. static String _process_doc_line(const String &p_line, const String &p_text, const String &p_space_prefix, DocLineState &r_state) {
  3138. String line = p_line;
  3139. if (r_state == DOC_LINE_NORMAL) {
  3140. line = line.strip_edges(true, false);
  3141. } else {
  3142. line = line.trim_prefix(p_space_prefix);
  3143. }
  3144. String line_join;
  3145. if (!p_text.is_empty()) {
  3146. if (r_state == DOC_LINE_NORMAL) {
  3147. if (p_text.ends_with("[/codeblock]")) {
  3148. line_join = "\n";
  3149. } else if (!p_text.ends_with("[br]")) {
  3150. line_join = " ";
  3151. }
  3152. } else {
  3153. line_join = "\n";
  3154. }
  3155. }
  3156. String result;
  3157. int from = 0;
  3158. int buffer_start = 0;
  3159. const int len = line.length();
  3160. bool process = true;
  3161. while (process) {
  3162. switch (r_state) {
  3163. case DOC_LINE_NORMAL: {
  3164. int lb_pos = line.find_char('[', from);
  3165. if (lb_pos < 0) {
  3166. process = false;
  3167. break;
  3168. }
  3169. int rb_pos = line.find_char(']', lb_pos + 1);
  3170. if (rb_pos < 0) {
  3171. process = false;
  3172. break;
  3173. }
  3174. from = rb_pos + 1;
  3175. String tag = line.substr(lb_pos + 1, rb_pos - lb_pos - 1);
  3176. if (tag == "code" || tag.begins_with("code ")) {
  3177. r_state = DOC_LINE_IN_CODE;
  3178. } else if (tag == "codeblock" || tag.begins_with("codeblock ")) {
  3179. if (lb_pos == 0) {
  3180. line_join = "\n";
  3181. } else {
  3182. result += line.substr(buffer_start, lb_pos - buffer_start) + '\n';
  3183. }
  3184. result += "[" + tag + "]";
  3185. if (from < len) {
  3186. result += '\n';
  3187. }
  3188. r_state = DOC_LINE_IN_CODEBLOCK;
  3189. buffer_start = from;
  3190. } else if (tag == "kbd") {
  3191. r_state = DOC_LINE_IN_KBD;
  3192. }
  3193. } break;
  3194. case DOC_LINE_IN_CODE: {
  3195. int pos = line.find("[/code]", from);
  3196. if (pos < 0) {
  3197. process = false;
  3198. break;
  3199. }
  3200. from = pos + 7; // `len("[/code]")`.
  3201. r_state = DOC_LINE_NORMAL;
  3202. } break;
  3203. case DOC_LINE_IN_CODEBLOCK: {
  3204. int pos = line.find("[/codeblock]", from);
  3205. if (pos < 0) {
  3206. process = false;
  3207. break;
  3208. }
  3209. from = pos + 12; // `len("[/codeblock]")`.
  3210. if (pos == 0) {
  3211. line_join = "\n";
  3212. } else {
  3213. result += line.substr(buffer_start, pos - buffer_start) + '\n';
  3214. }
  3215. result += "[/codeblock]";
  3216. if (from < len) {
  3217. result += '\n';
  3218. }
  3219. r_state = DOC_LINE_NORMAL;
  3220. buffer_start = from;
  3221. } break;
  3222. case DOC_LINE_IN_KBD: {
  3223. int pos = line.find("[/kbd]", from);
  3224. if (pos < 0) {
  3225. process = false;
  3226. break;
  3227. }
  3228. from = pos + 6; // `len("[/kbd]")`.
  3229. r_state = DOC_LINE_NORMAL;
  3230. } break;
  3231. }
  3232. }
  3233. result += line.substr(buffer_start);
  3234. if (r_state == DOC_LINE_NORMAL) {
  3235. result = result.strip_edges(false, true);
  3236. }
  3237. return line_join + result;
  3238. }
  3239. bool GDScriptParser::has_comment(int p_line, bool p_must_be_doc) {
  3240. bool has_comment = tokenizer->get_comments().has(p_line);
  3241. // If there are no comments or if we don't care whether the comment
  3242. // is a docstring, we have our result.
  3243. if (!p_must_be_doc || !has_comment) {
  3244. return has_comment;
  3245. }
  3246. return tokenizer->get_comments()[p_line].comment.begins_with("##");
  3247. }
  3248. GDScriptParser::MemberDocData GDScriptParser::parse_doc_comment(int p_line, bool p_single_line) {
  3249. ERR_FAIL_COND_V(!has_comment(p_line, true), MemberDocData());
  3250. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  3251. int line = p_line;
  3252. if (!p_single_line) {
  3253. while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
  3254. line--;
  3255. }
  3256. }
  3257. max_script_doc_line = MIN(max_script_doc_line, line - 1);
  3258. String space_prefix;
  3259. {
  3260. int i = 2;
  3261. for (; i < comments[line].comment.length(); i++) {
  3262. if (comments[line].comment[i] != ' ') {
  3263. break;
  3264. }
  3265. }
  3266. space_prefix = String(" ").repeat(i - 2);
  3267. }
  3268. DocLineState state = DOC_LINE_NORMAL;
  3269. MemberDocData result;
  3270. while (line <= p_line) {
  3271. String doc_line = comments[line].comment.trim_prefix("##");
  3272. line++;
  3273. if (state == DOC_LINE_NORMAL) {
  3274. String stripped_line = doc_line.strip_edges();
  3275. if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
  3276. result.is_deprecated = true;
  3277. if (stripped_line.begins_with("@deprecated:")) {
  3278. result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
  3279. }
  3280. continue;
  3281. } else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
  3282. result.is_experimental = true;
  3283. if (stripped_line.begins_with("@experimental:")) {
  3284. result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
  3285. }
  3286. continue;
  3287. }
  3288. }
  3289. result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
  3290. }
  3291. return result;
  3292. }
  3293. GDScriptParser::ClassDocData GDScriptParser::parse_class_doc_comment(int p_line, bool p_single_line) {
  3294. ERR_FAIL_COND_V(!has_comment(p_line, true), ClassDocData());
  3295. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  3296. int line = p_line;
  3297. if (!p_single_line) {
  3298. while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
  3299. line--;
  3300. }
  3301. }
  3302. max_script_doc_line = MIN(max_script_doc_line, line - 1);
  3303. String space_prefix;
  3304. {
  3305. int i = 2;
  3306. for (; i < comments[line].comment.length(); i++) {
  3307. if (comments[line].comment[i] != ' ') {
  3308. break;
  3309. }
  3310. }
  3311. space_prefix = String(" ").repeat(i - 2);
  3312. }
  3313. DocLineState state = DOC_LINE_NORMAL;
  3314. bool is_in_brief = true;
  3315. ClassDocData result;
  3316. while (line <= p_line) {
  3317. String doc_line = comments[line].comment.trim_prefix("##");
  3318. line++;
  3319. if (state == DOC_LINE_NORMAL) {
  3320. String stripped_line = doc_line.strip_edges();
  3321. // A blank line separates the description from the brief.
  3322. if (is_in_brief && !result.brief.is_empty() && stripped_line.is_empty()) {
  3323. is_in_brief = false;
  3324. continue;
  3325. }
  3326. if (stripped_line.begins_with("@tutorial")) {
  3327. String title, link;
  3328. int begin_scan = String("@tutorial").length();
  3329. if (begin_scan >= stripped_line.length()) {
  3330. continue; // Invalid syntax.
  3331. }
  3332. if (stripped_line[begin_scan] == ':') { // No title.
  3333. // Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
  3334. title = "";
  3335. link = stripped_line.trim_prefix("@tutorial:").strip_edges();
  3336. } else {
  3337. /* Syntax:
  3338. * @tutorial ( The Title Here ) : https://the.url/
  3339. * ^ open ^ close ^ colon ^ url
  3340. */
  3341. int open_bracket_pos = begin_scan, close_bracket_pos = 0;
  3342. while (open_bracket_pos < stripped_line.length() && (stripped_line[open_bracket_pos] == ' ' || stripped_line[open_bracket_pos] == '\t')) {
  3343. open_bracket_pos++;
  3344. }
  3345. if (open_bracket_pos == stripped_line.length() || stripped_line[open_bracket_pos++] != '(') {
  3346. continue; // Invalid syntax.
  3347. }
  3348. close_bracket_pos = open_bracket_pos;
  3349. while (close_bracket_pos < stripped_line.length() && stripped_line[close_bracket_pos] != ')') {
  3350. close_bracket_pos++;
  3351. }
  3352. if (close_bracket_pos == stripped_line.length()) {
  3353. continue; // Invalid syntax.
  3354. }
  3355. int colon_pos = close_bracket_pos + 1;
  3356. while (colon_pos < stripped_line.length() && (stripped_line[colon_pos] == ' ' || stripped_line[colon_pos] == '\t')) {
  3357. colon_pos++;
  3358. }
  3359. if (colon_pos == stripped_line.length() || stripped_line[colon_pos++] != ':') {
  3360. continue; // Invalid syntax.
  3361. }
  3362. title = stripped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
  3363. link = stripped_line.substr(colon_pos).strip_edges();
  3364. }
  3365. result.tutorials.append(Pair<String, String>(title, link));
  3366. continue;
  3367. } else if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
  3368. result.is_deprecated = true;
  3369. if (stripped_line.begins_with("@deprecated:")) {
  3370. result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
  3371. }
  3372. continue;
  3373. } else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
  3374. result.is_experimental = true;
  3375. if (stripped_line.begins_with("@experimental:")) {
  3376. result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
  3377. }
  3378. continue;
  3379. }
  3380. }
  3381. if (is_in_brief) {
  3382. result.brief += _process_doc_line(doc_line, result.brief, space_prefix, state);
  3383. } else {
  3384. result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
  3385. }
  3386. }
  3387. return result;
  3388. }
  3389. #endif // TOOLS_ENABLED
  3390. GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
  3391. // Function table for expression parsing.
  3392. // clang-format destroys the alignment here, so turn off for the table.
  3393. /* clang-format off */
  3394. static ParseRule rules[] = {
  3395. // PREFIX INFIX PRECEDENCE (for infix)
  3396. { nullptr, nullptr, PREC_NONE }, // EMPTY,
  3397. // Basic
  3398. { nullptr, nullptr, PREC_NONE }, // ANNOTATION,
  3399. { &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
  3400. { &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
  3401. // Comparison
  3402. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
  3403. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
  3404. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
  3405. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
  3406. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
  3407. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
  3408. // Logical
  3409. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
  3410. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
  3411. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_not_in_operator, PREC_CONTENT_TEST }, // NOT,
  3412. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
  3413. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
  3414. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
  3415. // Bitwise
  3416. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
  3417. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
  3418. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
  3419. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
  3420. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
  3421. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
  3422. // Math
  3423. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
  3424. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
  3425. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
  3426. { nullptr, &GDScriptParser::parse_binary_operator, PREC_POWER }, // STAR_STAR,
  3427. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
  3428. { &GDScriptParser::parse_get_node, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
  3429. // Assignment
  3430. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
  3431. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
  3432. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
  3433. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
  3434. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_STAR_EQUAL,
  3435. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
  3436. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
  3437. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
  3438. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
  3439. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
  3440. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
  3441. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
  3442. // Control flow
  3443. { nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
  3444. { nullptr, nullptr, PREC_NONE }, // ELIF,
  3445. { nullptr, nullptr, PREC_NONE }, // ELSE,
  3446. { nullptr, nullptr, PREC_NONE }, // FOR,
  3447. { nullptr, nullptr, PREC_NONE }, // WHILE,
  3448. { nullptr, nullptr, PREC_NONE }, // BREAK,
  3449. { nullptr, nullptr, PREC_NONE }, // CONTINUE,
  3450. { nullptr, nullptr, PREC_NONE }, // PASS,
  3451. { nullptr, nullptr, PREC_NONE }, // RETURN,
  3452. { nullptr, nullptr, PREC_NONE }, // MATCH,
  3453. { nullptr, nullptr, PREC_NONE }, // WHEN,
  3454. // Keywords
  3455. { nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
  3456. { nullptr, nullptr, PREC_NONE }, // ASSERT,
  3457. { &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
  3458. { nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
  3459. { nullptr, nullptr, PREC_NONE }, // CLASS,
  3460. { nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
  3461. { nullptr, nullptr, PREC_NONE }, // CONST,
  3462. { nullptr, nullptr, PREC_NONE }, // ENUM,
  3463. { nullptr, nullptr, PREC_NONE }, // EXTENDS,
  3464. { &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC,
  3465. { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // IN,
  3466. { nullptr, &GDScriptParser::parse_type_test, PREC_TYPE_TEST }, // IS,
  3467. { nullptr, nullptr, PREC_NONE }, // NAMESPACE,
  3468. { &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
  3469. { &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
  3470. { nullptr, nullptr, PREC_NONE }, // SIGNAL,
  3471. { nullptr, nullptr, PREC_NONE }, // STATIC,
  3472. { &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
  3473. { nullptr, nullptr, PREC_NONE }, // TRAIT,
  3474. { nullptr, nullptr, PREC_NONE }, // VAR,
  3475. { nullptr, nullptr, PREC_NONE }, // VOID,
  3476. { &GDScriptParser::parse_yield, nullptr, PREC_NONE }, // YIELD,
  3477. // Punctuation
  3478. { &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
  3479. { nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
  3480. { &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
  3481. { nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
  3482. { &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
  3483. { nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
  3484. { nullptr, nullptr, PREC_NONE }, // COMMA,
  3485. { nullptr, nullptr, PREC_NONE }, // SEMICOLON,
  3486. { nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
  3487. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
  3488. { nullptr, nullptr, PREC_NONE }, // COLON,
  3489. { &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
  3490. { nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
  3491. { nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
  3492. // Whitespace
  3493. { nullptr, nullptr, PREC_NONE }, // NEWLINE,
  3494. { nullptr, nullptr, PREC_NONE }, // INDENT,
  3495. { nullptr, nullptr, PREC_NONE }, // DEDENT,
  3496. // Constants
  3497. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
  3498. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
  3499. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
  3500. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
  3501. // Error message improvement
  3502. { nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
  3503. { nullptr, nullptr, PREC_NONE }, // BACKTICK,
  3504. { nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
  3505. // Special
  3506. { nullptr, nullptr, PREC_NONE }, // ERROR,
  3507. { nullptr, nullptr, PREC_NONE }, // TK_EOF,
  3508. };
  3509. /* clang-format on */
  3510. // Avoid desync.
  3511. static_assert(sizeof(rules) / sizeof(rules[0]) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
  3512. // Let's assume this is never invalid, since nothing generates a TK_MAX.
  3513. return &rules[p_token_type];
  3514. }
  3515. bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
  3516. if (locals_indices.has(p_name)) {
  3517. return true;
  3518. }
  3519. if (parent_block != nullptr) {
  3520. return parent_block->has_local(p_name);
  3521. }
  3522. return false;
  3523. }
  3524. const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
  3525. if (locals_indices.has(p_name)) {
  3526. return locals[locals_indices[p_name]];
  3527. }
  3528. if (parent_block != nullptr) {
  3529. return parent_block->get_local(p_name);
  3530. }
  3531. return empty;
  3532. }
  3533. bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target, ClassNode *p_class) {
  3534. if (is_applied) {
  3535. return true;
  3536. }
  3537. is_applied = true;
  3538. return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target, p_class);
  3539. }
  3540. bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
  3541. return (info->target_kind & p_target_kinds) > 0;
  3542. }
  3543. bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
  3544. ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  3545. const MethodInfo &info = valid_annotations[p_annotation->name].info;
  3546. if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
  3547. 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()));
  3548. return false;
  3549. }
  3550. if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  3551. 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()));
  3552. return false;
  3553. }
  3554. // Some annotations need to be resolved in the parser.
  3555. if (p_annotation->name == SNAME("@icon")) {
  3556. ExpressionNode *argument = p_annotation->arguments[0];
  3557. if (argument->type != Node::LITERAL) {
  3558. push_error(R"(Argument 1 of annotation "@icon" must be a string literal.)", argument);
  3559. return false;
  3560. }
  3561. Variant value = static_cast<LiteralNode *>(argument)->value;
  3562. if (value.get_type() != Variant::STRING) {
  3563. push_error(R"(Argument 1 of annotation "@icon" must be a string literal.)", argument);
  3564. return false;
  3565. }
  3566. p_annotation->resolved_arguments.push_back(value);
  3567. }
  3568. // For other annotations, see `GDScriptAnalyzer::resolve_annotation()`.
  3569. return true;
  3570. }
  3571. bool GDScriptParser::tool_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3572. #ifdef DEBUG_ENABLED
  3573. if (_is_tool) {
  3574. push_error(R"("@tool" annotation can only be used once.)", p_annotation);
  3575. return false;
  3576. }
  3577. #endif // DEBUG_ENABLED
  3578. _is_tool = true;
  3579. return true;
  3580. }
  3581. bool GDScriptParser::icon_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3582. ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
  3583. ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
  3584. ClassNode *class_node = static_cast<ClassNode *>(p_target);
  3585. String path = p_annotation->resolved_arguments[0];
  3586. #ifdef DEBUG_ENABLED
  3587. if (!class_node->icon_path.is_empty()) {
  3588. push_error(R"("@icon" annotation can only be used once.)", p_annotation);
  3589. return false;
  3590. }
  3591. if (path.is_empty()) {
  3592. push_error(R"("@icon" annotation argument must contain the path to the icon.)", p_annotation->arguments[0]);
  3593. return false;
  3594. }
  3595. #endif // DEBUG_ENABLED
  3596. class_node->icon_path = path;
  3597. if (path.is_empty() || path.is_absolute_path()) {
  3598. class_node->simplified_icon_path = path.simplify_path();
  3599. } else if (path.is_relative_path()) {
  3600. class_node->simplified_icon_path = script_path.get_base_dir().path_join(path).simplify_path();
  3601. } else {
  3602. class_node->simplified_icon_path = path;
  3603. }
  3604. return true;
  3605. }
  3606. bool GDScriptParser::onready_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3607. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
  3608. if (current_class && !ClassDB::is_parent_class(current_class->get_datatype().native_type, SNAME("Node"))) {
  3609. push_error(R"("@onready" can only be used in classes that inherit "Node".)", p_annotation);
  3610. return false;
  3611. }
  3612. VariableNode *variable = static_cast<VariableNode *>(p_target);
  3613. if (variable->is_static) {
  3614. push_error(R"("@onready" annotation cannot be applied to a static variable.)", p_annotation);
  3615. return false;
  3616. }
  3617. if (variable->onready) {
  3618. push_error(R"("@onready" annotation can only be used once per variable.)", p_annotation);
  3619. return false;
  3620. }
  3621. variable->onready = true;
  3622. current_class->onready_used = true;
  3623. return true;
  3624. }
  3625. static String _get_annotation_error_string(const StringName &p_annotation_name, const Vector<Variant::Type> &p_expected_types, const GDScriptParser::DataType &p_provided_type) {
  3626. Vector<String> types;
  3627. for (int i = 0; i < p_expected_types.size(); i++) {
  3628. const Variant::Type &type = p_expected_types[i];
  3629. types.push_back(Variant::get_type_name(type));
  3630. types.push_back("Array[" + Variant::get_type_name(type) + "]");
  3631. switch (type) {
  3632. case Variant::INT:
  3633. types.push_back("PackedByteArray");
  3634. types.push_back("PackedInt32Array");
  3635. types.push_back("PackedInt64Array");
  3636. break;
  3637. case Variant::FLOAT:
  3638. types.push_back("PackedFloat32Array");
  3639. types.push_back("PackedFloat64Array");
  3640. break;
  3641. case Variant::STRING:
  3642. types.push_back("PackedStringArray");
  3643. break;
  3644. case Variant::VECTOR2:
  3645. types.push_back("PackedVector2Array");
  3646. break;
  3647. case Variant::VECTOR3:
  3648. types.push_back("PackedVector3Array");
  3649. break;
  3650. case Variant::COLOR:
  3651. types.push_back("PackedColorArray");
  3652. break;
  3653. case Variant::VECTOR4:
  3654. types.push_back("PackedVector4Array");
  3655. break;
  3656. default:
  3657. break;
  3658. }
  3659. }
  3660. String string;
  3661. if (types.size() == 1) {
  3662. string = types[0].quote();
  3663. } else if (types.size() == 2) {
  3664. string = types[0].quote() + " or " + types[1].quote();
  3665. } else if (types.size() >= 3) {
  3666. string = types[0].quote();
  3667. for (int i = 1; i < types.size() - 1; i++) {
  3668. string += ", " + types[i].quote();
  3669. }
  3670. string += ", or " + types[types.size() - 1].quote();
  3671. }
  3672. 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());
  3673. }
  3674. static StringName _find_narrowest_native_or_global_class(const GDScriptParser::DataType &p_type) {
  3675. switch (p_type.kind) {
  3676. case GDScriptParser::DataType::NATIVE: {
  3677. if (p_type.is_meta_type) {
  3678. return Object::get_class_static(); // `GDScriptNativeClass` is not an exposed class.
  3679. }
  3680. return p_type.native_type;
  3681. } break;
  3682. case GDScriptParser::DataType::SCRIPT: {
  3683. Ref<Script> script;
  3684. if (p_type.script_type.is_valid()) {
  3685. script = p_type.script_type;
  3686. } else {
  3687. script = ResourceLoader::load(p_type.script_path, SNAME("Script"));
  3688. }
  3689. if (p_type.is_meta_type) {
  3690. return script.is_valid() ? script->get_class() : Script::get_class_static();
  3691. }
  3692. if (script.is_null()) {
  3693. return p_type.native_type;
  3694. }
  3695. if (script->get_global_name() != StringName()) {
  3696. return script->get_global_name();
  3697. }
  3698. Ref<Script> base_script = script->get_base_script();
  3699. if (base_script.is_null()) {
  3700. return script->get_instance_base_type();
  3701. }
  3702. GDScriptParser::DataType base_type;
  3703. base_type.kind = GDScriptParser::DataType::SCRIPT;
  3704. base_type.builtin_type = Variant::OBJECT;
  3705. base_type.native_type = base_script->get_instance_base_type();
  3706. base_type.script_type = base_script;
  3707. base_type.script_path = base_script->get_path();
  3708. return _find_narrowest_native_or_global_class(base_type);
  3709. } break;
  3710. case GDScriptParser::DataType::CLASS: {
  3711. if (p_type.is_meta_type) {
  3712. return GDScript::get_class_static();
  3713. }
  3714. if (p_type.class_type == nullptr) {
  3715. return p_type.native_type;
  3716. }
  3717. if (p_type.class_type->get_global_name() != StringName()) {
  3718. return p_type.class_type->get_global_name();
  3719. }
  3720. return _find_narrowest_native_or_global_class(p_type.class_type->base_type);
  3721. } break;
  3722. default: {
  3723. ERR_FAIL_V(StringName());
  3724. } break;
  3725. }
  3726. }
  3727. template <PropertyHint t_hint, Variant::Type t_type>
  3728. bool GDScriptParser::export_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3729. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  3730. ERR_FAIL_NULL_V(p_class, false);
  3731. VariableNode *variable = static_cast<VariableNode *>(p_target);
  3732. if (variable->is_static) {
  3733. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  3734. return false;
  3735. }
  3736. if (variable->exported) {
  3737. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  3738. return false;
  3739. }
  3740. variable->exported = true;
  3741. variable->export_info.type = t_type;
  3742. variable->export_info.hint = t_hint;
  3743. String hint_string;
  3744. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  3745. String arg_string = String(p_annotation->resolved_arguments[i]);
  3746. if (p_annotation->name != SNAME("@export_placeholder")) {
  3747. if (arg_string.is_empty()) {
  3748. push_error(vformat(R"(Argument %d of annotation "%s" is empty.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
  3749. return false;
  3750. }
  3751. if (arg_string.contains(",")) {
  3752. 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]);
  3753. return false;
  3754. }
  3755. }
  3756. // WARNING: Do not merge with the previous `if` because there `!=`, not `==`!
  3757. if (p_annotation->name == SNAME("@export_flags")) {
  3758. const int64_t max_flags = 32;
  3759. Vector<String> t = arg_string.split(":", true, 1);
  3760. if (t[0].is_empty()) {
  3761. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag name.)", i + 1), p_annotation->arguments[i]);
  3762. return false;
  3763. }
  3764. if (t.size() == 2) {
  3765. if (t[1].is_empty()) {
  3766. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag value.)", i + 1), p_annotation->arguments[i]);
  3767. return false;
  3768. }
  3769. if (!t[1].is_valid_int()) {
  3770. 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]);
  3771. return false;
  3772. }
  3773. int64_t value = t[1].to_int();
  3774. if (value < 1 || value >= (1LL << max_flags)) {
  3775. 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]);
  3776. return false;
  3777. }
  3778. } else if (i >= max_flags) {
  3779. 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]);
  3780. return false;
  3781. }
  3782. } else if (p_annotation->name == SNAME("@export_node_path")) {
  3783. String native_class = arg_string;
  3784. if (ScriptServer::is_global_class(arg_string)) {
  3785. native_class = ScriptServer::get_global_class_native_base(arg_string);
  3786. }
  3787. if (!ClassDB::class_exists(native_class)) {
  3788. 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]);
  3789. return false;
  3790. } else if (!ClassDB::is_parent_class(native_class, SNAME("Node"))) {
  3791. 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]);
  3792. return false;
  3793. }
  3794. }
  3795. if (i > 0) {
  3796. hint_string += ",";
  3797. }
  3798. hint_string += arg_string;
  3799. }
  3800. variable->export_info.hint_string = hint_string;
  3801. // This is called after the analyzer is done finding the type, so this should be set here.
  3802. DataType export_type = variable->get_datatype();
  3803. // Use initializer type if specified type is `Variant`.
  3804. if (export_type.is_variant() && variable->initializer != nullptr && variable->initializer->datatype.is_set()) {
  3805. export_type = variable->initializer->get_datatype();
  3806. export_type.type_source = DataType::INFERRED;
  3807. }
  3808. const Variant::Type original_export_type_builtin = export_type.builtin_type;
  3809. // Process array and packed array annotations on the element type.
  3810. bool is_array = false;
  3811. if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type(0)) {
  3812. is_array = true;
  3813. export_type = export_type.get_container_element_type(0);
  3814. } else if (export_type.is_typed_container_type()) {
  3815. is_array = true;
  3816. export_type = export_type.get_typed_container_type();
  3817. export_type.type_source = variable->datatype.type_source;
  3818. }
  3819. bool use_default_variable_type_check = true;
  3820. if (p_annotation->name == SNAME("@export_range")) {
  3821. if (export_type.builtin_type == Variant::INT) {
  3822. variable->export_info.type = Variant::INT;
  3823. }
  3824. } else if (p_annotation->name == SNAME("@export_multiline")) {
  3825. use_default_variable_type_check = false;
  3826. if (export_type.builtin_type != Variant::STRING && export_type.builtin_type != Variant::DICTIONARY) {
  3827. Vector<Variant::Type> expected_types = { Variant::STRING, Variant::DICTIONARY };
  3828. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  3829. return false;
  3830. }
  3831. if (export_type.builtin_type == Variant::DICTIONARY) {
  3832. variable->export_info.type = Variant::DICTIONARY;
  3833. }
  3834. } else if (p_annotation->name == SNAME("@export")) {
  3835. use_default_variable_type_check = false;
  3836. if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
  3837. push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
  3838. return false;
  3839. }
  3840. if (export_type.is_variant() || export_type.has_no_type()) {
  3841. push_error(R"(Cannot use simple "@export" annotation because the type of the initialized value can't be inferred.)", p_annotation);
  3842. return false;
  3843. }
  3844. switch (export_type.kind) {
  3845. case GDScriptParser::DataType::BUILTIN:
  3846. variable->export_info.type = export_type.builtin_type;
  3847. variable->export_info.hint = PROPERTY_HINT_NONE;
  3848. variable->export_info.hint_string = String();
  3849. break;
  3850. case GDScriptParser::DataType::NATIVE:
  3851. case GDScriptParser::DataType::SCRIPT:
  3852. case GDScriptParser::DataType::CLASS: {
  3853. const StringName class_name = _find_narrowest_native_or_global_class(export_type);
  3854. if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
  3855. variable->export_info.type = Variant::OBJECT;
  3856. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  3857. variable->export_info.hint_string = class_name;
  3858. } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
  3859. variable->export_info.type = Variant::OBJECT;
  3860. variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
  3861. variable->export_info.hint_string = class_name;
  3862. } else {
  3863. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  3864. return false;
  3865. }
  3866. } break;
  3867. case GDScriptParser::DataType::ENUM: {
  3868. if (export_type.is_meta_type) {
  3869. variable->export_info.type = Variant::DICTIONARY;
  3870. } else {
  3871. variable->export_info.type = Variant::INT;
  3872. variable->export_info.hint = PROPERTY_HINT_ENUM;
  3873. String enum_hint_string;
  3874. bool first = true;
  3875. for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
  3876. if (!first) {
  3877. enum_hint_string += ",";
  3878. } else {
  3879. first = false;
  3880. }
  3881. enum_hint_string += E.key.operator String().capitalize().xml_escape();
  3882. enum_hint_string += ":";
  3883. enum_hint_string += String::num_int64(E.value).xml_escape();
  3884. }
  3885. variable->export_info.hint_string = enum_hint_string;
  3886. variable->export_info.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
  3887. variable->export_info.class_name = String(export_type.native_type).replace("::", ".");
  3888. }
  3889. } break;
  3890. default:
  3891. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  3892. return false;
  3893. }
  3894. if (variable->export_info.hint == PROPERTY_HINT_NODE_TYPE && !ClassDB::is_parent_class(p_class->base_type.native_type, SNAME("Node"))) {
  3895. 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);
  3896. return false;
  3897. }
  3898. } else if (p_annotation->name == SNAME("@export_enum")) {
  3899. use_default_variable_type_check = false;
  3900. Variant::Type enum_type = Variant::INT;
  3901. if (export_type.kind == DataType::BUILTIN && export_type.builtin_type == Variant::STRING) {
  3902. enum_type = Variant::STRING;
  3903. }
  3904. variable->export_info.type = enum_type;
  3905. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != enum_type)) {
  3906. Vector<Variant::Type> expected_types = { Variant::INT, Variant::STRING };
  3907. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  3908. return false;
  3909. }
  3910. }
  3911. if (use_default_variable_type_check) {
  3912. // Validate variable type with export.
  3913. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != t_type)) {
  3914. // Allow float/int conversion.
  3915. if ((t_type != Variant::FLOAT || export_type.builtin_type != Variant::INT) && (t_type != Variant::INT || export_type.builtin_type != Variant::FLOAT)) {
  3916. Vector<Variant::Type> expected_types = { t_type };
  3917. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  3918. return false;
  3919. }
  3920. }
  3921. }
  3922. if (is_array) {
  3923. String hint_prefix = itos(variable->export_info.type);
  3924. if (variable->export_info.hint) {
  3925. hint_prefix += "/" + itos(variable->export_info.hint);
  3926. }
  3927. variable->export_info.type = original_export_type_builtin;
  3928. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  3929. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  3930. variable->export_info.usage = PROPERTY_USAGE_DEFAULT;
  3931. variable->export_info.class_name = StringName();
  3932. }
  3933. return true;
  3934. }
  3935. // For `@export_storage` and `@export_custom`, there is no need to check the variable type, argument values,
  3936. // or handle array exports in a special way, so they are implemented as separate methods.
  3937. bool GDScriptParser::export_storage_annotation(AnnotationNode *p_annotation, Node *p_node, ClassNode *p_class) {
  3938. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  3939. VariableNode *variable = static_cast<VariableNode *>(p_node);
  3940. if (variable->is_static) {
  3941. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  3942. return false;
  3943. }
  3944. if (variable->exported) {
  3945. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  3946. return false;
  3947. }
  3948. variable->exported = true;
  3949. // Save the info because the compiler uses export info for overwriting member info.
  3950. variable->export_info = variable->get_datatype().to_property_info(variable->identifier->name);
  3951. variable->export_info.usage |= PROPERTY_USAGE_STORAGE;
  3952. return true;
  3953. }
  3954. bool GDScriptParser::export_custom_annotation(AnnotationNode *p_annotation, Node *p_node, ClassNode *p_class) {
  3955. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  3956. ERR_FAIL_COND_V_MSG(p_annotation->resolved_arguments.size() < 2, false, R"(Annotation "@export_custom" requires 2 arguments.)");
  3957. VariableNode *variable = static_cast<VariableNode *>(p_node);
  3958. if (variable->is_static) {
  3959. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  3960. return false;
  3961. }
  3962. if (variable->exported) {
  3963. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  3964. return false;
  3965. }
  3966. variable->exported = true;
  3967. DataType export_type = variable->get_datatype();
  3968. variable->export_info.type = export_type.builtin_type;
  3969. variable->export_info.hint = static_cast<PropertyHint>(p_annotation->resolved_arguments[0].operator int64_t());
  3970. variable->export_info.hint_string = p_annotation->resolved_arguments[1];
  3971. if (p_annotation->resolved_arguments.size() >= 3) {
  3972. variable->export_info.usage = p_annotation->resolved_arguments[2].operator int64_t();
  3973. }
  3974. return true;
  3975. }
  3976. template <PropertyUsageFlags t_usage>
  3977. bool GDScriptParser::export_group_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3978. if (p_annotation->resolved_arguments.is_empty()) {
  3979. return false;
  3980. }
  3981. p_annotation->export_info.name = p_annotation->resolved_arguments[0];
  3982. switch (t_usage) {
  3983. case PROPERTY_USAGE_CATEGORY: {
  3984. p_annotation->export_info.usage = t_usage;
  3985. } break;
  3986. case PROPERTY_USAGE_GROUP: {
  3987. p_annotation->export_info.usage = t_usage;
  3988. if (p_annotation->resolved_arguments.size() == 2) {
  3989. p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
  3990. }
  3991. } break;
  3992. case PROPERTY_USAGE_SUBGROUP: {
  3993. p_annotation->export_info.usage = t_usage;
  3994. if (p_annotation->resolved_arguments.size() == 2) {
  3995. p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
  3996. }
  3997. } break;
  3998. }
  3999. return true;
  4000. }
  4001. bool GDScriptParser::warning_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4002. #ifndef DEBUG_ENABLED
  4003. // Only available in debug builds.
  4004. return true;
  4005. #else // DEBUG_ENABLED
  4006. if (is_ignoring_warnings) {
  4007. return true; // We already ignore all warnings, let's optimize it.
  4008. }
  4009. bool has_error = false;
  4010. for (const Variant &warning_name : p_annotation->resolved_arguments) {
  4011. GDScriptWarning::Code warning_code = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
  4012. if (warning_code == GDScriptWarning::WARNING_MAX) {
  4013. push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
  4014. has_error = true;
  4015. } else {
  4016. int start_line = p_annotation->start_line;
  4017. int end_line = p_target->end_line;
  4018. switch (p_target->type) {
  4019. #define SIMPLE_CASE(m_type, m_class, m_property) \
  4020. case m_type: { \
  4021. m_class *node = static_cast<m_class *>(p_target); \
  4022. if (node->m_property == nullptr) { \
  4023. end_line = node->start_line; \
  4024. } else { \
  4025. end_line = node->m_property->end_line; \
  4026. } \
  4027. } break;
  4028. // Can contain properties (set/get).
  4029. SIMPLE_CASE(Node::VARIABLE, VariableNode, initializer)
  4030. // Contain bodies.
  4031. SIMPLE_CASE(Node::FOR, ForNode, list)
  4032. SIMPLE_CASE(Node::IF, IfNode, condition)
  4033. SIMPLE_CASE(Node::MATCH, MatchNode, test)
  4034. SIMPLE_CASE(Node::WHILE, WhileNode, condition)
  4035. #undef SIMPLE_CASE
  4036. case Node::CLASS: {
  4037. end_line = p_target->start_line;
  4038. for (const AnnotationNode *annotation : p_target->annotations) {
  4039. start_line = MIN(start_line, annotation->start_line);
  4040. end_line = MAX(end_line, annotation->end_line);
  4041. }
  4042. } break;
  4043. case Node::FUNCTION: {
  4044. // `@warning_ignore` on function has a controversial feature that is used in tests.
  4045. // It's better not to remove it for now, while there is no way to mass-ignore warnings.
  4046. } break;
  4047. case Node::MATCH_BRANCH: {
  4048. MatchBranchNode *branch = static_cast<MatchBranchNode *>(p_target);
  4049. end_line = branch->start_line;
  4050. for (int i = 0; i < branch->patterns.size(); i++) {
  4051. end_line = MAX(end_line, branch->patterns[i]->end_line);
  4052. }
  4053. } break;
  4054. default: {
  4055. } break;
  4056. }
  4057. end_line = MAX(start_line, end_line); // Prevent infinite loop.
  4058. for (int line = start_line; line <= end_line; line++) {
  4059. warning_ignored_lines[warning_code].insert(line);
  4060. }
  4061. }
  4062. }
  4063. return !has_error;
  4064. #endif // DEBUG_ENABLED
  4065. }
  4066. bool GDScriptParser::rpc_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4067. ERR_FAIL_COND_V_MSG(p_target->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to functions.)", p_annotation->name));
  4068. FunctionNode *function = static_cast<FunctionNode *>(p_target);
  4069. if (function->rpc_config.get_type() != Variant::NIL) {
  4070. push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
  4071. return false;
  4072. }
  4073. Dictionary rpc_config;
  4074. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  4075. if (!p_annotation->resolved_arguments.is_empty()) {
  4076. unsigned char locality_args = 0;
  4077. unsigned char permission_args = 0;
  4078. unsigned char transfer_mode_args = 0;
  4079. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  4080. if (i == 3) {
  4081. rpc_config["channel"] = p_annotation->resolved_arguments[i].operator int();
  4082. continue;
  4083. }
  4084. String arg = p_annotation->resolved_arguments[i].operator String();
  4085. if (arg == "call_local") {
  4086. locality_args++;
  4087. rpc_config["call_local"] = true;
  4088. } else if (arg == "call_remote") {
  4089. locality_args++;
  4090. rpc_config["call_local"] = false;
  4091. } else if (arg == "any_peer") {
  4092. permission_args++;
  4093. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_ANY_PEER;
  4094. } else if (arg == "authority") {
  4095. permission_args++;
  4096. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  4097. } else if (arg == "reliable") {
  4098. transfer_mode_args++;
  4099. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_RELIABLE;
  4100. } else if (arg == "unreliable") {
  4101. transfer_mode_args++;
  4102. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE;
  4103. } else if (arg == "unreliable_ordered") {
  4104. transfer_mode_args++;
  4105. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE_ORDERED;
  4106. } else {
  4107. 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);
  4108. }
  4109. }
  4110. if (locality_args > 1) {
  4111. push_error(R"(Invalid RPC config. The locality ("call_local"/"call_remote") must be specified no more than once.)", p_annotation);
  4112. } else if (permission_args > 1) {
  4113. push_error(R"(Invalid RPC config. The permission ("any_peer"/"authority") must be specified no more than once.)", p_annotation);
  4114. } else if (transfer_mode_args > 1) {
  4115. push_error(R"(Invalid RPC config. The transfer mode ("reliable"/"unreliable"/"unreliable_ordered") must be specified no more than once.)", p_annotation);
  4116. }
  4117. }
  4118. function->rpc_config = rpc_config;
  4119. return true;
  4120. }
  4121. bool GDScriptParser::static_unload_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4122. ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, vformat(R"("%s" annotation can only be applied to classes.)", p_annotation->name));
  4123. ClassNode *class_node = static_cast<ClassNode *>(p_target);
  4124. if (class_node->annotated_static_unload) {
  4125. push_error(vformat(R"("%s" annotation can only be used once per script.)", p_annotation->name), p_annotation);
  4126. return false;
  4127. }
  4128. class_node->annotated_static_unload = true;
  4129. return true;
  4130. }
  4131. GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
  4132. switch (type) {
  4133. case CONSTANT:
  4134. return constant->get_datatype();
  4135. case VARIABLE:
  4136. return variable->get_datatype();
  4137. case PARAMETER:
  4138. return parameter->get_datatype();
  4139. case FOR_VARIABLE:
  4140. case PATTERN_BIND:
  4141. return bind->get_datatype();
  4142. case UNDEFINED:
  4143. return DataType();
  4144. }
  4145. return DataType();
  4146. }
  4147. String GDScriptParser::SuiteNode::Local::get_name() const {
  4148. switch (type) {
  4149. case SuiteNode::Local::PARAMETER:
  4150. return "parameter";
  4151. case SuiteNode::Local::CONSTANT:
  4152. return "constant";
  4153. case SuiteNode::Local::VARIABLE:
  4154. return "variable";
  4155. case SuiteNode::Local::FOR_VARIABLE:
  4156. return "for loop iterator";
  4157. case SuiteNode::Local::PATTERN_BIND:
  4158. return "pattern bind";
  4159. case SuiteNode::Local::UNDEFINED:
  4160. return "<undefined>";
  4161. default:
  4162. return String();
  4163. }
  4164. }
  4165. String GDScriptParser::DataType::to_string() const {
  4166. switch (kind) {
  4167. case VARIANT:
  4168. return "Variant";
  4169. case BUILTIN:
  4170. if (builtin_type == Variant::NIL) {
  4171. return "null";
  4172. }
  4173. if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
  4174. return vformat("Array[%s]", container_element_types[0].to_string());
  4175. }
  4176. return Variant::get_type_name(builtin_type);
  4177. case NATIVE:
  4178. if (is_meta_type) {
  4179. return GDScriptNativeClass::get_class_static();
  4180. }
  4181. return native_type.operator String();
  4182. case CLASS:
  4183. if (class_type->identifier != nullptr) {
  4184. return class_type->identifier->name.operator String();
  4185. }
  4186. return class_type->fqcn;
  4187. case SCRIPT: {
  4188. if (is_meta_type) {
  4189. return script_type != nullptr ? script_type->get_class_name().operator String() : "";
  4190. }
  4191. String name = script_type != nullptr ? script_type->get_name() : "";
  4192. if (!name.is_empty()) {
  4193. return name;
  4194. }
  4195. name = script_path;
  4196. if (!name.is_empty()) {
  4197. return name;
  4198. }
  4199. return native_type.operator String();
  4200. }
  4201. case ENUM: {
  4202. // native_type contains either the native class defining the enum
  4203. // or the fully qualified class name of the script defining the enum
  4204. return String(native_type).get_file(); // Remove path, keep filename
  4205. }
  4206. case RESOLVING:
  4207. case UNRESOLVED:
  4208. return "<unresolved type>";
  4209. }
  4210. ERR_FAIL_V_MSG("<unresolved type>", "Kind set outside the enum range.");
  4211. }
  4212. PropertyInfo GDScriptParser::DataType::to_property_info(const String &p_name) const {
  4213. PropertyInfo result;
  4214. result.name = p_name;
  4215. result.usage = PROPERTY_USAGE_NONE;
  4216. if (!is_hard_type()) {
  4217. result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4218. return result;
  4219. }
  4220. switch (kind) {
  4221. case BUILTIN:
  4222. result.type = builtin_type;
  4223. if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
  4224. const DataType elem_type = get_container_element_type(0);
  4225. switch (elem_type.kind) {
  4226. case BUILTIN:
  4227. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4228. result.hint_string = Variant::get_type_name(elem_type.builtin_type);
  4229. break;
  4230. case NATIVE:
  4231. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4232. result.hint_string = elem_type.native_type;
  4233. break;
  4234. case SCRIPT:
  4235. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4236. if (elem_type.script_type.is_valid() && elem_type.script_type->get_global_name() != StringName()) {
  4237. result.hint_string = elem_type.script_type->get_global_name();
  4238. } else {
  4239. result.hint_string = elem_type.native_type;
  4240. }
  4241. break;
  4242. case CLASS:
  4243. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4244. if (elem_type.class_type != nullptr && elem_type.class_type->get_global_name() != StringName()) {
  4245. result.hint_string = elem_type.class_type->get_global_name();
  4246. } else {
  4247. result.hint_string = elem_type.native_type;
  4248. }
  4249. break;
  4250. case ENUM:
  4251. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4252. result.hint_string = String(elem_type.native_type).replace("::", ".");
  4253. break;
  4254. case VARIANT:
  4255. case RESOLVING:
  4256. case UNRESOLVED:
  4257. break;
  4258. }
  4259. }
  4260. break;
  4261. case NATIVE:
  4262. result.type = Variant::OBJECT;
  4263. if (is_meta_type) {
  4264. result.class_name = GDScriptNativeClass::get_class_static();
  4265. } else {
  4266. result.class_name = native_type;
  4267. }
  4268. break;
  4269. case SCRIPT:
  4270. result.type = Variant::OBJECT;
  4271. if (is_meta_type) {
  4272. result.class_name = script_type.is_valid() ? script_type->get_class() : Script::get_class_static();
  4273. } else if (script_type.is_valid() && script_type->get_global_name() != StringName()) {
  4274. result.class_name = script_type->get_global_name();
  4275. } else {
  4276. result.class_name = native_type;
  4277. }
  4278. break;
  4279. case CLASS:
  4280. result.type = Variant::OBJECT;
  4281. if (is_meta_type) {
  4282. result.class_name = GDScript::get_class_static();
  4283. } else if (class_type != nullptr && class_type->get_global_name() != StringName()) {
  4284. result.class_name = class_type->get_global_name();
  4285. } else {
  4286. result.class_name = native_type;
  4287. }
  4288. break;
  4289. case ENUM:
  4290. if (is_meta_type) {
  4291. result.type = Variant::DICTIONARY;
  4292. } else {
  4293. result.type = Variant::INT;
  4294. result.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
  4295. result.class_name = String(native_type).replace("::", ".");
  4296. }
  4297. break;
  4298. case VARIANT:
  4299. case RESOLVING:
  4300. case UNRESOLVED:
  4301. result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4302. break;
  4303. }
  4304. return result;
  4305. }
  4306. static Variant::Type _variant_type_to_typed_array_element_type(Variant::Type p_type) {
  4307. switch (p_type) {
  4308. case Variant::PACKED_BYTE_ARRAY:
  4309. case Variant::PACKED_INT32_ARRAY:
  4310. case Variant::PACKED_INT64_ARRAY:
  4311. return Variant::INT;
  4312. case Variant::PACKED_FLOAT32_ARRAY:
  4313. case Variant::PACKED_FLOAT64_ARRAY:
  4314. return Variant::FLOAT;
  4315. case Variant::PACKED_STRING_ARRAY:
  4316. return Variant::STRING;
  4317. case Variant::PACKED_VECTOR2_ARRAY:
  4318. return Variant::VECTOR2;
  4319. case Variant::PACKED_VECTOR3_ARRAY:
  4320. return Variant::VECTOR3;
  4321. case Variant::PACKED_COLOR_ARRAY:
  4322. return Variant::COLOR;
  4323. case Variant::PACKED_VECTOR4_ARRAY:
  4324. return Variant::VECTOR4;
  4325. default:
  4326. return Variant::NIL;
  4327. }
  4328. }
  4329. bool GDScriptParser::DataType::is_typed_container_type() const {
  4330. return kind == GDScriptParser::DataType::BUILTIN && _variant_type_to_typed_array_element_type(builtin_type) != Variant::NIL;
  4331. }
  4332. GDScriptParser::DataType GDScriptParser::DataType::get_typed_container_type() const {
  4333. GDScriptParser::DataType type;
  4334. type.kind = GDScriptParser::DataType::BUILTIN;
  4335. type.builtin_type = _variant_type_to_typed_array_element_type(builtin_type);
  4336. return type;
  4337. }
  4338. void GDScriptParser::complete_extents(Node *p_node) {
  4339. while (!nodes_in_progress.is_empty() && nodes_in_progress.back()->get() != p_node) {
  4340. ERR_PRINT("Parser bug: Mismatch in extents tracking stack.");
  4341. nodes_in_progress.pop_back();
  4342. }
  4343. if (nodes_in_progress.is_empty()) {
  4344. ERR_PRINT("Parser bug: Extents tracking stack is empty.");
  4345. } else {
  4346. nodes_in_progress.pop_back();
  4347. }
  4348. }
  4349. void GDScriptParser::update_extents(Node *p_node) {
  4350. p_node->end_line = previous.end_line;
  4351. p_node->end_column = previous.end_column;
  4352. p_node->leftmost_column = MIN(p_node->leftmost_column, previous.leftmost_column);
  4353. p_node->rightmost_column = MAX(p_node->rightmost_column, previous.rightmost_column);
  4354. }
  4355. void GDScriptParser::reset_extents(Node *p_node, GDScriptTokenizer::Token p_token) {
  4356. p_node->start_line = p_token.start_line;
  4357. p_node->end_line = p_token.end_line;
  4358. p_node->start_column = p_token.start_column;
  4359. p_node->end_column = p_token.end_column;
  4360. p_node->leftmost_column = p_token.leftmost_column;
  4361. p_node->rightmost_column = p_token.rightmost_column;
  4362. }
  4363. void GDScriptParser::reset_extents(Node *p_node, Node *p_from) {
  4364. if (p_from == nullptr) {
  4365. return;
  4366. }
  4367. p_node->start_line = p_from->start_line;
  4368. p_node->end_line = p_from->end_line;
  4369. p_node->start_column = p_from->start_column;
  4370. p_node->end_column = p_from->end_column;
  4371. p_node->leftmost_column = p_from->leftmost_column;
  4372. p_node->rightmost_column = p_from->rightmost_column;
  4373. }
  4374. /*---------- PRETTY PRINT FOR DEBUG ----------*/
  4375. #ifdef DEBUG_ENABLED
  4376. void GDScriptParser::TreePrinter::increase_indent() {
  4377. indent_level++;
  4378. indent = "";
  4379. for (int i = 0; i < indent_level * 4; i++) {
  4380. if (i % 4 == 0) {
  4381. indent += "|";
  4382. } else {
  4383. indent += " ";
  4384. }
  4385. }
  4386. }
  4387. void GDScriptParser::TreePrinter::decrease_indent() {
  4388. indent_level--;
  4389. indent = "";
  4390. for (int i = 0; i < indent_level * 4; i++) {
  4391. if (i % 4 == 0) {
  4392. indent += "|";
  4393. } else {
  4394. indent += " ";
  4395. }
  4396. }
  4397. }
  4398. void GDScriptParser::TreePrinter::push_line(const String &p_line) {
  4399. if (!p_line.is_empty()) {
  4400. push_text(p_line);
  4401. }
  4402. printed += "\n";
  4403. pending_indent = true;
  4404. }
  4405. void GDScriptParser::TreePrinter::push_text(const String &p_text) {
  4406. if (pending_indent) {
  4407. printed += indent;
  4408. pending_indent = false;
  4409. }
  4410. printed += p_text;
  4411. }
  4412. void GDScriptParser::TreePrinter::print_annotation(const AnnotationNode *p_annotation) {
  4413. push_text(p_annotation->name);
  4414. push_text(" (");
  4415. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  4416. if (i > 0) {
  4417. push_text(" , ");
  4418. }
  4419. print_expression(p_annotation->arguments[i]);
  4420. }
  4421. push_line(")");
  4422. }
  4423. void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
  4424. push_text("[ ");
  4425. for (int i = 0; i < p_array->elements.size(); i++) {
  4426. if (i > 0) {
  4427. push_text(" , ");
  4428. }
  4429. print_expression(p_array->elements[i]);
  4430. }
  4431. push_text(" ]");
  4432. }
  4433. void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
  4434. push_text("Assert ( ");
  4435. print_expression(p_assert->condition);
  4436. push_line(" )");
  4437. }
  4438. void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
  4439. switch (p_assignment->assignee->type) {
  4440. case Node::IDENTIFIER:
  4441. print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
  4442. break;
  4443. case Node::SUBSCRIPT:
  4444. print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
  4445. break;
  4446. default:
  4447. break; // Unreachable.
  4448. }
  4449. push_text(" ");
  4450. switch (p_assignment->operation) {
  4451. case AssignmentNode::OP_ADDITION:
  4452. push_text("+");
  4453. break;
  4454. case AssignmentNode::OP_SUBTRACTION:
  4455. push_text("-");
  4456. break;
  4457. case AssignmentNode::OP_MULTIPLICATION:
  4458. push_text("*");
  4459. break;
  4460. case AssignmentNode::OP_DIVISION:
  4461. push_text("/");
  4462. break;
  4463. case AssignmentNode::OP_MODULO:
  4464. push_text("%");
  4465. break;
  4466. case AssignmentNode::OP_POWER:
  4467. push_text("**");
  4468. break;
  4469. case AssignmentNode::OP_BIT_SHIFT_LEFT:
  4470. push_text("<<");
  4471. break;
  4472. case AssignmentNode::OP_BIT_SHIFT_RIGHT:
  4473. push_text(">>");
  4474. break;
  4475. case AssignmentNode::OP_BIT_AND:
  4476. push_text("&");
  4477. break;
  4478. case AssignmentNode::OP_BIT_OR:
  4479. push_text("|");
  4480. break;
  4481. case AssignmentNode::OP_BIT_XOR:
  4482. push_text("^");
  4483. break;
  4484. case AssignmentNode::OP_NONE:
  4485. break;
  4486. }
  4487. push_text("= ");
  4488. print_expression(p_assignment->assigned_value);
  4489. push_line();
  4490. }
  4491. void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
  4492. push_text("Await ");
  4493. print_expression(p_await->to_await);
  4494. }
  4495. void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
  4496. // Surround in parenthesis for disambiguation.
  4497. push_text("(");
  4498. print_expression(p_binary_op->left_operand);
  4499. switch (p_binary_op->operation) {
  4500. case BinaryOpNode::OP_ADDITION:
  4501. push_text(" + ");
  4502. break;
  4503. case BinaryOpNode::OP_SUBTRACTION:
  4504. push_text(" - ");
  4505. break;
  4506. case BinaryOpNode::OP_MULTIPLICATION:
  4507. push_text(" * ");
  4508. break;
  4509. case BinaryOpNode::OP_DIVISION:
  4510. push_text(" / ");
  4511. break;
  4512. case BinaryOpNode::OP_MODULO:
  4513. push_text(" % ");
  4514. break;
  4515. case BinaryOpNode::OP_POWER:
  4516. push_text(" ** ");
  4517. break;
  4518. case BinaryOpNode::OP_BIT_LEFT_SHIFT:
  4519. push_text(" << ");
  4520. break;
  4521. case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
  4522. push_text(" >> ");
  4523. break;
  4524. case BinaryOpNode::OP_BIT_AND:
  4525. push_text(" & ");
  4526. break;
  4527. case BinaryOpNode::OP_BIT_OR:
  4528. push_text(" | ");
  4529. break;
  4530. case BinaryOpNode::OP_BIT_XOR:
  4531. push_text(" ^ ");
  4532. break;
  4533. case BinaryOpNode::OP_LOGIC_AND:
  4534. push_text(" AND ");
  4535. break;
  4536. case BinaryOpNode::OP_LOGIC_OR:
  4537. push_text(" OR ");
  4538. break;
  4539. case BinaryOpNode::OP_CONTENT_TEST:
  4540. push_text(" IN ");
  4541. break;
  4542. case BinaryOpNode::OP_COMP_EQUAL:
  4543. push_text(" == ");
  4544. break;
  4545. case BinaryOpNode::OP_COMP_NOT_EQUAL:
  4546. push_text(" != ");
  4547. break;
  4548. case BinaryOpNode::OP_COMP_LESS:
  4549. push_text(" < ");
  4550. break;
  4551. case BinaryOpNode::OP_COMP_LESS_EQUAL:
  4552. push_text(" <= ");
  4553. break;
  4554. case BinaryOpNode::OP_COMP_GREATER:
  4555. push_text(" > ");
  4556. break;
  4557. case BinaryOpNode::OP_COMP_GREATER_EQUAL:
  4558. push_text(" >= ");
  4559. break;
  4560. }
  4561. print_expression(p_binary_op->right_operand);
  4562. // Surround in parenthesis for disambiguation.
  4563. push_text(")");
  4564. }
  4565. void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
  4566. if (p_call->is_super) {
  4567. push_text("super");
  4568. if (p_call->callee != nullptr) {
  4569. push_text(".");
  4570. print_expression(p_call->callee);
  4571. }
  4572. } else {
  4573. print_expression(p_call->callee);
  4574. }
  4575. push_text("( ");
  4576. for (int i = 0; i < p_call->arguments.size(); i++) {
  4577. if (i > 0) {
  4578. push_text(" , ");
  4579. }
  4580. print_expression(p_call->arguments[i]);
  4581. }
  4582. push_text(" )");
  4583. }
  4584. void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
  4585. print_expression(p_cast->operand);
  4586. push_text(" AS ");
  4587. print_type(p_cast->cast_type);
  4588. }
  4589. void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
  4590. push_text("Class ");
  4591. if (p_class->identifier == nullptr) {
  4592. push_text("<unnamed>");
  4593. } else {
  4594. print_identifier(p_class->identifier);
  4595. }
  4596. if (p_class->extends_used) {
  4597. bool first = true;
  4598. push_text(" Extends ");
  4599. if (!p_class->extends_path.is_empty()) {
  4600. push_text(vformat(R"("%s")", p_class->extends_path));
  4601. first = false;
  4602. }
  4603. for (int i = 0; i < p_class->extends.size(); i++) {
  4604. if (!first) {
  4605. push_text(".");
  4606. } else {
  4607. first = false;
  4608. }
  4609. push_text(p_class->extends[i]->name);
  4610. }
  4611. }
  4612. push_line(" :");
  4613. increase_indent();
  4614. for (int i = 0; i < p_class->members.size(); i++) {
  4615. const ClassNode::Member &m = p_class->members[i];
  4616. switch (m.type) {
  4617. case ClassNode::Member::CLASS:
  4618. print_class(m.m_class);
  4619. break;
  4620. case ClassNode::Member::VARIABLE:
  4621. print_variable(m.variable);
  4622. break;
  4623. case ClassNode::Member::CONSTANT:
  4624. print_constant(m.constant);
  4625. break;
  4626. case ClassNode::Member::SIGNAL:
  4627. print_signal(m.signal);
  4628. break;
  4629. case ClassNode::Member::FUNCTION:
  4630. print_function(m.function);
  4631. break;
  4632. case ClassNode::Member::ENUM:
  4633. print_enum(m.m_enum);
  4634. break;
  4635. case ClassNode::Member::ENUM_VALUE:
  4636. break; // Nothing. Will be printed by enum.
  4637. case ClassNode::Member::GROUP:
  4638. break; // Nothing. Groups are only used by inspector.
  4639. case ClassNode::Member::UNDEFINED:
  4640. push_line("<unknown member>");
  4641. break;
  4642. }
  4643. }
  4644. decrease_indent();
  4645. }
  4646. void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
  4647. push_text("Constant ");
  4648. print_identifier(p_constant->identifier);
  4649. increase_indent();
  4650. push_line();
  4651. push_text("= ");
  4652. if (p_constant->initializer == nullptr) {
  4653. push_text("<missing value>");
  4654. } else {
  4655. print_expression(p_constant->initializer);
  4656. }
  4657. decrease_indent();
  4658. push_line();
  4659. }
  4660. void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
  4661. push_line("{");
  4662. increase_indent();
  4663. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  4664. print_expression(p_dictionary->elements[i].key);
  4665. if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
  4666. push_text(" : ");
  4667. } else {
  4668. push_text(" = ");
  4669. }
  4670. print_expression(p_dictionary->elements[i].value);
  4671. push_line(" ,");
  4672. }
  4673. decrease_indent();
  4674. push_text("}");
  4675. }
  4676. void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
  4677. if (p_expression == nullptr) {
  4678. push_text("<invalid expression>");
  4679. return;
  4680. }
  4681. switch (p_expression->type) {
  4682. case Node::ARRAY:
  4683. print_array(static_cast<ArrayNode *>(p_expression));
  4684. break;
  4685. case Node::ASSIGNMENT:
  4686. print_assignment(static_cast<AssignmentNode *>(p_expression));
  4687. break;
  4688. case Node::AWAIT:
  4689. print_await(static_cast<AwaitNode *>(p_expression));
  4690. break;
  4691. case Node::BINARY_OPERATOR:
  4692. print_binary_op(static_cast<BinaryOpNode *>(p_expression));
  4693. break;
  4694. case Node::CALL:
  4695. print_call(static_cast<CallNode *>(p_expression));
  4696. break;
  4697. case Node::CAST:
  4698. print_cast(static_cast<CastNode *>(p_expression));
  4699. break;
  4700. case Node::DICTIONARY:
  4701. print_dictionary(static_cast<DictionaryNode *>(p_expression));
  4702. break;
  4703. case Node::GET_NODE:
  4704. print_get_node(static_cast<GetNodeNode *>(p_expression));
  4705. break;
  4706. case Node::IDENTIFIER:
  4707. print_identifier(static_cast<IdentifierNode *>(p_expression));
  4708. break;
  4709. case Node::LAMBDA:
  4710. print_lambda(static_cast<LambdaNode *>(p_expression));
  4711. break;
  4712. case Node::LITERAL:
  4713. print_literal(static_cast<LiteralNode *>(p_expression));
  4714. break;
  4715. case Node::PRELOAD:
  4716. print_preload(static_cast<PreloadNode *>(p_expression));
  4717. break;
  4718. case Node::SELF:
  4719. print_self(static_cast<SelfNode *>(p_expression));
  4720. break;
  4721. case Node::SUBSCRIPT:
  4722. print_subscript(static_cast<SubscriptNode *>(p_expression));
  4723. break;
  4724. case Node::TERNARY_OPERATOR:
  4725. print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
  4726. break;
  4727. case Node::TYPE_TEST:
  4728. print_type_test(static_cast<TypeTestNode *>(p_expression));
  4729. break;
  4730. case Node::UNARY_OPERATOR:
  4731. print_unary_op(static_cast<UnaryOpNode *>(p_expression));
  4732. break;
  4733. default:
  4734. push_text(vformat("<unknown expression %d>", p_expression->type));
  4735. break;
  4736. }
  4737. }
  4738. void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
  4739. push_text("Enum ");
  4740. if (p_enum->identifier != nullptr) {
  4741. print_identifier(p_enum->identifier);
  4742. } else {
  4743. push_text("<unnamed>");
  4744. }
  4745. push_line(" {");
  4746. increase_indent();
  4747. for (int i = 0; i < p_enum->values.size(); i++) {
  4748. const EnumNode::Value &item = p_enum->values[i];
  4749. print_identifier(item.identifier);
  4750. push_text(" = ");
  4751. push_text(itos(item.value));
  4752. push_line(" ,");
  4753. }
  4754. decrease_indent();
  4755. push_line("}");
  4756. }
  4757. void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
  4758. push_text("For ");
  4759. print_identifier(p_for->variable);
  4760. push_text(" IN ");
  4761. print_expression(p_for->list);
  4762. push_line(" :");
  4763. increase_indent();
  4764. print_suite(p_for->loop);
  4765. decrease_indent();
  4766. }
  4767. void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function, const String &p_context) {
  4768. for (const AnnotationNode *E : p_function->annotations) {
  4769. print_annotation(E);
  4770. }
  4771. if (p_function->is_static) {
  4772. push_text("Static ");
  4773. }
  4774. push_text(p_context);
  4775. push_text(" ");
  4776. if (p_function->identifier) {
  4777. print_identifier(p_function->identifier);
  4778. } else {
  4779. push_text("<anonymous>");
  4780. }
  4781. push_text("( ");
  4782. for (int i = 0; i < p_function->parameters.size(); i++) {
  4783. if (i > 0) {
  4784. push_text(" , ");
  4785. }
  4786. print_parameter(p_function->parameters[i]);
  4787. }
  4788. push_line(" ) :");
  4789. increase_indent();
  4790. print_suite(p_function->body);
  4791. decrease_indent();
  4792. }
  4793. void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
  4794. if (p_get_node->use_dollar) {
  4795. push_text("$");
  4796. }
  4797. push_text(p_get_node->full_path);
  4798. }
  4799. void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
  4800. if (p_identifier != nullptr) {
  4801. push_text(p_identifier->name);
  4802. } else {
  4803. push_text("<invalid identifier>");
  4804. }
  4805. }
  4806. void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
  4807. if (p_is_elif) {
  4808. push_text("Elif ");
  4809. } else {
  4810. push_text("If ");
  4811. }
  4812. print_expression(p_if->condition);
  4813. push_line(" :");
  4814. increase_indent();
  4815. print_suite(p_if->true_block);
  4816. decrease_indent();
  4817. // FIXME: Properly detect "elif" blocks.
  4818. if (p_if->false_block != nullptr) {
  4819. push_line("Else :");
  4820. increase_indent();
  4821. print_suite(p_if->false_block);
  4822. decrease_indent();
  4823. }
  4824. }
  4825. void GDScriptParser::TreePrinter::print_lambda(LambdaNode *p_lambda) {
  4826. print_function(p_lambda->function, "Lambda");
  4827. push_text("| captures [ ");
  4828. for (int i = 0; i < p_lambda->captures.size(); i++) {
  4829. if (i > 0) {
  4830. push_text(" , ");
  4831. }
  4832. push_text(p_lambda->captures[i]->name.operator String());
  4833. }
  4834. push_line(" ]");
  4835. }
  4836. void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
  4837. // Prefix for string types.
  4838. switch (p_literal->value.get_type()) {
  4839. case Variant::NODE_PATH:
  4840. push_text("^\"");
  4841. break;
  4842. case Variant::STRING:
  4843. push_text("\"");
  4844. break;
  4845. case Variant::STRING_NAME:
  4846. push_text("&\"");
  4847. break;
  4848. default:
  4849. break;
  4850. }
  4851. push_text(p_literal->value);
  4852. // Suffix for string types.
  4853. switch (p_literal->value.get_type()) {
  4854. case Variant::NODE_PATH:
  4855. case Variant::STRING:
  4856. case Variant::STRING_NAME:
  4857. push_text("\"");
  4858. break;
  4859. default:
  4860. break;
  4861. }
  4862. }
  4863. void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
  4864. push_text("Match ");
  4865. print_expression(p_match->test);
  4866. push_line(" :");
  4867. increase_indent();
  4868. for (int i = 0; i < p_match->branches.size(); i++) {
  4869. print_match_branch(p_match->branches[i]);
  4870. }
  4871. decrease_indent();
  4872. }
  4873. void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
  4874. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  4875. if (i > 0) {
  4876. push_text(" , ");
  4877. }
  4878. print_match_pattern(p_match_branch->patterns[i]);
  4879. }
  4880. push_line(" :");
  4881. increase_indent();
  4882. print_suite(p_match_branch->block);
  4883. decrease_indent();
  4884. }
  4885. void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
  4886. switch (p_match_pattern->pattern_type) {
  4887. case PatternNode::PT_LITERAL:
  4888. print_literal(p_match_pattern->literal);
  4889. break;
  4890. case PatternNode::PT_WILDCARD:
  4891. push_text("_");
  4892. break;
  4893. case PatternNode::PT_REST:
  4894. push_text("..");
  4895. break;
  4896. case PatternNode::PT_BIND:
  4897. push_text("Var ");
  4898. print_identifier(p_match_pattern->bind);
  4899. break;
  4900. case PatternNode::PT_EXPRESSION:
  4901. print_expression(p_match_pattern->expression);
  4902. break;
  4903. case PatternNode::PT_ARRAY:
  4904. push_text("[ ");
  4905. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  4906. if (i > 0) {
  4907. push_text(" , ");
  4908. }
  4909. print_match_pattern(p_match_pattern->array[i]);
  4910. }
  4911. push_text(" ]");
  4912. break;
  4913. case PatternNode::PT_DICTIONARY:
  4914. push_text("{ ");
  4915. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  4916. if (i > 0) {
  4917. push_text(" , ");
  4918. }
  4919. if (p_match_pattern->dictionary[i].key != nullptr) {
  4920. // Key can be null for rest pattern.
  4921. print_expression(p_match_pattern->dictionary[i].key);
  4922. push_text(" : ");
  4923. }
  4924. print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
  4925. }
  4926. push_text(" }");
  4927. break;
  4928. }
  4929. }
  4930. void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
  4931. print_identifier(p_parameter->identifier);
  4932. if (p_parameter->datatype_specifier != nullptr) {
  4933. push_text(" : ");
  4934. print_type(p_parameter->datatype_specifier);
  4935. }
  4936. if (p_parameter->initializer != nullptr) {
  4937. push_text(" = ");
  4938. print_expression(p_parameter->initializer);
  4939. }
  4940. }
  4941. void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
  4942. push_text(R"(Preload ( ")");
  4943. push_text(p_preload->resolved_path);
  4944. push_text(R"(" )");
  4945. }
  4946. void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
  4947. push_text("Return");
  4948. if (p_return->return_value != nullptr) {
  4949. push_text(" ");
  4950. print_expression(p_return->return_value);
  4951. }
  4952. push_line();
  4953. }
  4954. void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
  4955. push_text("Self(");
  4956. if (p_self->current_class->identifier != nullptr) {
  4957. print_identifier(p_self->current_class->identifier);
  4958. } else {
  4959. push_text("<main class>");
  4960. }
  4961. push_text(")");
  4962. }
  4963. void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
  4964. push_text("Signal ");
  4965. print_identifier(p_signal->identifier);
  4966. push_text("( ");
  4967. for (int i = 0; i < p_signal->parameters.size(); i++) {
  4968. print_parameter(p_signal->parameters[i]);
  4969. }
  4970. push_line(" )");
  4971. }
  4972. void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
  4973. print_expression(p_subscript->base);
  4974. if (p_subscript->is_attribute) {
  4975. push_text(".");
  4976. print_identifier(p_subscript->attribute);
  4977. } else {
  4978. push_text("[ ");
  4979. print_expression(p_subscript->index);
  4980. push_text(" ]");
  4981. }
  4982. }
  4983. void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
  4984. switch (p_statement->type) {
  4985. case Node::ASSERT:
  4986. print_assert(static_cast<AssertNode *>(p_statement));
  4987. break;
  4988. case Node::VARIABLE:
  4989. print_variable(static_cast<VariableNode *>(p_statement));
  4990. break;
  4991. case Node::CONSTANT:
  4992. print_constant(static_cast<ConstantNode *>(p_statement));
  4993. break;
  4994. case Node::IF:
  4995. print_if(static_cast<IfNode *>(p_statement));
  4996. break;
  4997. case Node::FOR:
  4998. print_for(static_cast<ForNode *>(p_statement));
  4999. break;
  5000. case Node::WHILE:
  5001. print_while(static_cast<WhileNode *>(p_statement));
  5002. break;
  5003. case Node::MATCH:
  5004. print_match(static_cast<MatchNode *>(p_statement));
  5005. break;
  5006. case Node::RETURN:
  5007. print_return(static_cast<ReturnNode *>(p_statement));
  5008. break;
  5009. case Node::BREAK:
  5010. push_line("Break");
  5011. break;
  5012. case Node::CONTINUE:
  5013. push_line("Continue");
  5014. break;
  5015. case Node::PASS:
  5016. push_line("Pass");
  5017. break;
  5018. case Node::BREAKPOINT:
  5019. push_line("Breakpoint");
  5020. break;
  5021. case Node::ASSIGNMENT:
  5022. print_assignment(static_cast<AssignmentNode *>(p_statement));
  5023. break;
  5024. default:
  5025. if (p_statement->is_expression()) {
  5026. print_expression(static_cast<ExpressionNode *>(p_statement));
  5027. push_line();
  5028. } else {
  5029. push_line(vformat("<unknown statement %d>", p_statement->type));
  5030. }
  5031. break;
  5032. }
  5033. }
  5034. void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
  5035. for (int i = 0; i < p_suite->statements.size(); i++) {
  5036. print_statement(p_suite->statements[i]);
  5037. }
  5038. }
  5039. void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
  5040. // Surround in parenthesis for disambiguation.
  5041. push_text("(");
  5042. print_expression(p_ternary_op->true_expr);
  5043. push_text(") IF (");
  5044. print_expression(p_ternary_op->condition);
  5045. push_text(") ELSE (");
  5046. print_expression(p_ternary_op->false_expr);
  5047. push_text(")");
  5048. }
  5049. void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
  5050. if (p_type->type_chain.is_empty()) {
  5051. push_text("Void");
  5052. } else {
  5053. for (int i = 0; i < p_type->type_chain.size(); i++) {
  5054. if (i > 0) {
  5055. push_text(".");
  5056. }
  5057. print_identifier(p_type->type_chain[i]);
  5058. }
  5059. }
  5060. }
  5061. void GDScriptParser::TreePrinter::print_type_test(TypeTestNode *p_test) {
  5062. print_expression(p_test->operand);
  5063. push_text(" IS ");
  5064. print_type(p_test->test_type);
  5065. }
  5066. void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
  5067. // Surround in parenthesis for disambiguation.
  5068. push_text("(");
  5069. switch (p_unary_op->operation) {
  5070. case UnaryOpNode::OP_POSITIVE:
  5071. push_text("+");
  5072. break;
  5073. case UnaryOpNode::OP_NEGATIVE:
  5074. push_text("-");
  5075. break;
  5076. case UnaryOpNode::OP_LOGIC_NOT:
  5077. push_text("NOT");
  5078. break;
  5079. case UnaryOpNode::OP_COMPLEMENT:
  5080. push_text("~");
  5081. break;
  5082. }
  5083. print_expression(p_unary_op->operand);
  5084. // Surround in parenthesis for disambiguation.
  5085. push_text(")");
  5086. }
  5087. void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
  5088. for (const AnnotationNode *E : p_variable->annotations) {
  5089. print_annotation(E);
  5090. }
  5091. if (p_variable->is_static) {
  5092. push_text("Static ");
  5093. }
  5094. push_text("Variable ");
  5095. print_identifier(p_variable->identifier);
  5096. push_text(" : ");
  5097. if (p_variable->datatype_specifier != nullptr) {
  5098. print_type(p_variable->datatype_specifier);
  5099. } else if (p_variable->infer_datatype) {
  5100. push_text("<inferred type>");
  5101. } else {
  5102. push_text("Variant");
  5103. }
  5104. increase_indent();
  5105. push_line();
  5106. push_text("= ");
  5107. if (p_variable->initializer == nullptr) {
  5108. push_text("<default value>");
  5109. } else {
  5110. print_expression(p_variable->initializer);
  5111. }
  5112. push_line();
  5113. if (p_variable->property != VariableNode::PROP_NONE) {
  5114. if (p_variable->getter != nullptr) {
  5115. push_text("Get");
  5116. if (p_variable->property == VariableNode::PROP_INLINE) {
  5117. push_line(":");
  5118. increase_indent();
  5119. print_suite(p_variable->getter->body);
  5120. decrease_indent();
  5121. } else {
  5122. push_line(" =");
  5123. increase_indent();
  5124. print_identifier(p_variable->getter_pointer);
  5125. push_line();
  5126. decrease_indent();
  5127. }
  5128. }
  5129. if (p_variable->setter != nullptr) {
  5130. push_text("Set (");
  5131. if (p_variable->property == VariableNode::PROP_INLINE) {
  5132. if (p_variable->setter_parameter != nullptr) {
  5133. print_identifier(p_variable->setter_parameter);
  5134. } else {
  5135. push_text("<missing>");
  5136. }
  5137. push_line("):");
  5138. increase_indent();
  5139. print_suite(p_variable->setter->body);
  5140. decrease_indent();
  5141. } else {
  5142. push_line(" =");
  5143. increase_indent();
  5144. print_identifier(p_variable->setter_pointer);
  5145. push_line();
  5146. decrease_indent();
  5147. }
  5148. }
  5149. }
  5150. decrease_indent();
  5151. push_line();
  5152. }
  5153. void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
  5154. push_text("While ");
  5155. print_expression(p_while->condition);
  5156. push_line(" :");
  5157. increase_indent();
  5158. print_suite(p_while->loop);
  5159. decrease_indent();
  5160. }
  5161. void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
  5162. ERR_FAIL_NULL_MSG(p_parser.get_tree(), "Parse the code before printing the parse tree.");
  5163. if (p_parser.is_tool()) {
  5164. push_line("@tool");
  5165. }
  5166. if (!p_parser.get_tree()->icon_path.is_empty()) {
  5167. push_text(R"(@icon (")");
  5168. push_text(p_parser.get_tree()->icon_path);
  5169. push_line("\")");
  5170. }
  5171. print_class(p_parser.get_tree());
  5172. print_line(String(printed));
  5173. }
  5174. #endif // DEBUG_ENABLED