gdscript_parser.cpp 150 KB

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