gdscript_parser.cpp 105 KB

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