gdscript_parser.cpp 129 KB

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