gdscript_parser.cpp 168 KB

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