gdscript_parser.cpp 122 KB

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