gdscript_parser.cpp 172 KB

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