gdscript_parser.cpp 129 KB

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