gdscript_parser.cpp 117 KB

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