gdscript_parser.cpp 122 KB

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