gdscript_parser.cpp 122 KB

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