2
0

gdscript_parser.cpp 117 KB

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