gdscript_parser.cpp 199 KB

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