2
0

gdscript_parser.cpp 199 KB

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