gdscript_parser.cpp 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869
  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/config/project_settings.h"
  32. #include "core/io/resource_loader.h"
  33. #include "core/math/math_defs.h"
  34. #include "core/os/file_access.h"
  35. #include "gdscript.h"
  36. #ifdef DEBUG_ENABLED
  37. #include "core/os/os.h"
  38. #include "core/string/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] == char32_t(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 identifier 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. if (current_function) {
  1245. push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier->name);
  1246. } else {
  1247. // TODO: Properties setters and getters with unreachable code are not being warned
  1248. }
  1249. }
  1250. #endif
  1251. if (panic_mode) {
  1252. synchronize();
  1253. }
  1254. return result;
  1255. }
  1256. GDScriptParser::AssertNode *GDScriptParser::parse_assert() {
  1257. // TODO: Add assert message.
  1258. AssertNode *assert = alloc_node<AssertNode>();
  1259. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "assert".)");
  1260. assert->condition = parse_expression(false);
  1261. if (assert->condition == nullptr) {
  1262. push_error("Expected expression to assert.");
  1263. return nullptr;
  1264. }
  1265. if (match(GDScriptTokenizer::Token::COMMA)) {
  1266. // Error message.
  1267. if (consume(GDScriptTokenizer::Token::LITERAL, R"(Expected error message for assert after ",".)")) {
  1268. assert->message = parse_literal();
  1269. if (assert->message->value.get_type() != Variant::STRING) {
  1270. push_error(R"(Expected string for assert error message.)");
  1271. }
  1272. } else {
  1273. return nullptr;
  1274. }
  1275. }
  1276. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after assert expression.)*");
  1277. end_statement(R"("assert")");
  1278. return assert;
  1279. }
  1280. GDScriptParser::BreakNode *GDScriptParser::parse_break() {
  1281. if (!can_break) {
  1282. push_error(R"(Cannot use "break" outside of a loop.)");
  1283. }
  1284. end_statement(R"("break")");
  1285. return alloc_node<BreakNode>();
  1286. }
  1287. GDScriptParser::ContinueNode *GDScriptParser::parse_continue() {
  1288. if (!can_continue) {
  1289. push_error(R"(Cannot use "continue" outside of a loop or pattern matching block.)");
  1290. }
  1291. current_suite->has_continue = true;
  1292. end_statement(R"("continue")");
  1293. ContinueNode *cont = alloc_node<ContinueNode>();
  1294. cont->is_for_match = is_continue_match;
  1295. return cont;
  1296. }
  1297. GDScriptParser::ForNode *GDScriptParser::parse_for() {
  1298. ForNode *n_for = alloc_node<ForNode>();
  1299. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected loop variable name after "for".)")) {
  1300. n_for->variable = parse_identifier();
  1301. }
  1302. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "for" variable name.)");
  1303. n_for->list = parse_expression(false);
  1304. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)");
  1305. // Save break/continue state.
  1306. bool could_break = can_break;
  1307. bool could_continue = can_continue;
  1308. bool was_continue_match = is_continue_match;
  1309. // Allow break/continue.
  1310. can_break = true;
  1311. can_continue = true;
  1312. is_continue_match = false;
  1313. SuiteNode *suite = alloc_node<SuiteNode>();
  1314. if (n_for->variable) {
  1315. suite->add_local(SuiteNode::Local(n_for->variable));
  1316. }
  1317. suite->parent_for = n_for;
  1318. n_for->loop = parse_suite(R"("for" block)", suite);
  1319. // Reset break/continue state.
  1320. can_break = could_break;
  1321. can_continue = could_continue;
  1322. is_continue_match = was_continue_match;
  1323. return n_for;
  1324. }
  1325. GDScriptParser::IfNode *GDScriptParser::parse_if(const String &p_token) {
  1326. IfNode *n_if = alloc_node<IfNode>();
  1327. n_if->condition = parse_expression(false);
  1328. if (n_if->condition == nullptr) {
  1329. push_error(vformat(R"(Expected conditional expression after "%s".)", p_token));
  1330. }
  1331. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after "%s" condition.)", p_token));
  1332. n_if->true_block = parse_suite(vformat(R"("%s" block)", p_token));
  1333. n_if->true_block->parent_if = n_if;
  1334. if (n_if->true_block->has_continue) {
  1335. current_suite->has_continue = true;
  1336. }
  1337. if (match(GDScriptTokenizer::Token::ELIF)) {
  1338. IfNode *elif = parse_if("elif");
  1339. SuiteNode *else_block = alloc_node<SuiteNode>();
  1340. else_block->statements.push_back(elif);
  1341. n_if->false_block = else_block;
  1342. } else if (match(GDScriptTokenizer::Token::ELSE)) {
  1343. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "else".)");
  1344. n_if->false_block = parse_suite(R"("else" block)");
  1345. }
  1346. if (n_if->false_block != nullptr && n_if->false_block->has_return && n_if->true_block->has_return) {
  1347. current_suite->has_return = true;
  1348. }
  1349. if (n_if->false_block != nullptr && n_if->false_block->has_continue) {
  1350. current_suite->has_continue = true;
  1351. }
  1352. return n_if;
  1353. }
  1354. GDScriptParser::MatchNode *GDScriptParser::parse_match() {
  1355. MatchNode *match = alloc_node<MatchNode>();
  1356. match->test = parse_expression(false);
  1357. if (match->test == nullptr) {
  1358. push_error(R"(Expected expression to test after "match".)");
  1359. }
  1360. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" expression.)");
  1361. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected a newline after "match" statement.)");
  1362. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected an indented block after "match" statement.)")) {
  1363. return match;
  1364. }
  1365. #ifdef DEBUG_ENABLED
  1366. bool all_have_return = true;
  1367. bool have_wildcard = false;
  1368. bool wildcard_has_return = false;
  1369. bool have_wildcard_without_continue = false;
  1370. #endif
  1371. while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
  1372. MatchBranchNode *branch = parse_match_branch();
  1373. if (branch == nullptr) {
  1374. continue;
  1375. }
  1376. #ifdef DEBUG_ENABLED
  1377. if (have_wildcard_without_continue) {
  1378. push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
  1379. }
  1380. if (branch->has_wildcard) {
  1381. have_wildcard = true;
  1382. if (branch->block->has_return) {
  1383. wildcard_has_return = true;
  1384. }
  1385. if (!branch->block->has_continue) {
  1386. have_wildcard_without_continue = true;
  1387. }
  1388. }
  1389. if (!branch->block->has_return) {
  1390. all_have_return = false;
  1391. }
  1392. #endif
  1393. match->branches.push_back(branch);
  1394. }
  1395. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
  1396. #ifdef DEBUG_ENABLED
  1397. if (wildcard_has_return || (all_have_return && have_wildcard)) {
  1398. current_suite->has_return = true;
  1399. }
  1400. #endif
  1401. return match;
  1402. }
  1403. GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
  1404. MatchBranchNode *branch = alloc_node<MatchBranchNode>();
  1405. bool has_bind = false;
  1406. do {
  1407. PatternNode *pattern = parse_match_pattern();
  1408. if (pattern == nullptr) {
  1409. continue;
  1410. }
  1411. if (pattern->pattern_type == PatternNode::PT_BIND) {
  1412. has_bind = true;
  1413. }
  1414. if (branch->patterns.size() > 0 && has_bind) {
  1415. push_error(R"(Cannot use a variable bind with multiple patterns.)");
  1416. }
  1417. if (pattern->pattern_type == PatternNode::PT_REST) {
  1418. push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
  1419. } else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
  1420. branch->has_wildcard = true;
  1421. }
  1422. branch->patterns.push_back(pattern);
  1423. } while (match(GDScriptTokenizer::Token::COMMA));
  1424. if (branch->patterns.empty()) {
  1425. push_error(R"(No pattern found for "match" branch.)");
  1426. }
  1427. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" patterns.)");
  1428. // Save continue state.
  1429. bool could_continue = can_continue;
  1430. bool was_continue_match = is_continue_match;
  1431. // Allow continue for match.
  1432. can_continue = true;
  1433. is_continue_match = true;
  1434. SuiteNode *suite = alloc_node<SuiteNode>();
  1435. if (branch->patterns.size() > 0) {
  1436. List<StringName> binds;
  1437. branch->patterns[0]->binds.get_key_list(&binds);
  1438. for (List<StringName>::Element *E = binds.front(); E != nullptr; E = E->next()) {
  1439. SuiteNode::Local local(branch->patterns[0]->binds[E->get()]);
  1440. suite->add_local(local);
  1441. }
  1442. }
  1443. branch->block = parse_suite("match pattern block", suite);
  1444. // Restore continue state.
  1445. can_continue = could_continue;
  1446. is_continue_match = was_continue_match;
  1447. return branch;
  1448. }
  1449. GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
  1450. PatternNode *pattern = alloc_node<PatternNode>();
  1451. switch (current.type) {
  1452. case GDScriptTokenizer::Token::LITERAL:
  1453. advance();
  1454. pattern->pattern_type = PatternNode::PT_LITERAL;
  1455. pattern->literal = parse_literal();
  1456. if (pattern->literal == nullptr) {
  1457. // Error happened.
  1458. return nullptr;
  1459. }
  1460. break;
  1461. case GDScriptTokenizer::Token::VAR: {
  1462. // Bind.
  1463. advance();
  1464. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
  1465. return nullptr;
  1466. }
  1467. pattern->pattern_type = PatternNode::PT_BIND;
  1468. pattern->bind = parse_identifier();
  1469. PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
  1470. if (p_root_pattern != nullptr) {
  1471. if (p_root_pattern->has_bind(pattern->bind->name)) {
  1472. push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
  1473. return nullptr;
  1474. }
  1475. }
  1476. if (current_suite->has_local(pattern->bind->name)) {
  1477. 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));
  1478. return nullptr;
  1479. }
  1480. root_pattern->binds[pattern->bind->name] = pattern->bind;
  1481. } break;
  1482. case GDScriptTokenizer::Token::UNDERSCORE:
  1483. // Wildcard.
  1484. advance();
  1485. pattern->pattern_type = PatternNode::PT_WILDCARD;
  1486. break;
  1487. case GDScriptTokenizer::Token::PERIOD_PERIOD:
  1488. // Rest.
  1489. advance();
  1490. pattern->pattern_type = PatternNode::PT_REST;
  1491. break;
  1492. case GDScriptTokenizer::Token::BRACKET_OPEN: {
  1493. // Array.
  1494. advance();
  1495. pattern->pattern_type = PatternNode::PT_ARRAY;
  1496. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  1497. do {
  1498. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  1499. if (sub_pattern == nullptr) {
  1500. continue;
  1501. }
  1502. if (pattern->rest_used) {
  1503. push_error(R"(The ".." pattern must be the last element in the pattern array.)");
  1504. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  1505. pattern->rest_used = true;
  1506. }
  1507. pattern->array.push_back(sub_pattern);
  1508. } while (match(GDScriptTokenizer::Token::COMMA));
  1509. }
  1510. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
  1511. break;
  1512. }
  1513. case GDScriptTokenizer::Token::BRACE_OPEN: {
  1514. // Dictionary.
  1515. advance();
  1516. pattern->pattern_type = PatternNode::PT_DICTIONARY;
  1517. if (!check(GDScriptTokenizer::Token::BRACE_CLOSE) && !is_at_end()) {
  1518. do {
  1519. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
  1520. // Rest.
  1521. if (pattern->rest_used) {
  1522. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  1523. } else {
  1524. PatternNode *sub_pattern = alloc_node<PatternNode>();
  1525. sub_pattern->pattern_type = PatternNode::PT_REST;
  1526. pattern->dictionary.push_back({ nullptr, sub_pattern });
  1527. pattern->rest_used = true;
  1528. }
  1529. } else {
  1530. ExpressionNode *key = parse_expression(false);
  1531. if (key == nullptr) {
  1532. push_error(R"(Expected expression as key for dictionary pattern.)");
  1533. }
  1534. if (match(GDScriptTokenizer::Token::COLON)) {
  1535. // Value pattern.
  1536. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  1537. if (sub_pattern == nullptr) {
  1538. continue;
  1539. }
  1540. if (pattern->rest_used) {
  1541. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  1542. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  1543. push_error(R"(The ".." pattern cannot be used as a value.)");
  1544. } else {
  1545. pattern->dictionary.push_back({ key, sub_pattern });
  1546. }
  1547. } else {
  1548. // Key match only.
  1549. pattern->dictionary.push_back({ key, nullptr });
  1550. }
  1551. }
  1552. } while (match(GDScriptTokenizer::Token::COMMA));
  1553. }
  1554. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
  1555. break;
  1556. }
  1557. default: {
  1558. // Expression.
  1559. ExpressionNode *expression = parse_expression(false);
  1560. if (expression == nullptr) {
  1561. push_error(R"(Expected expression for match pattern.)");
  1562. } else {
  1563. pattern->pattern_type = PatternNode::PT_EXPRESSION;
  1564. pattern->expression = expression;
  1565. }
  1566. break;
  1567. }
  1568. }
  1569. return pattern;
  1570. }
  1571. bool GDScriptParser::PatternNode::has_bind(const StringName &p_name) {
  1572. return binds.has(p_name);
  1573. }
  1574. GDScriptParser::IdentifierNode *GDScriptParser::PatternNode::get_bind(const StringName &p_name) {
  1575. return binds[p_name];
  1576. }
  1577. GDScriptParser::WhileNode *GDScriptParser::parse_while() {
  1578. WhileNode *n_while = alloc_node<WhileNode>();
  1579. n_while->condition = parse_expression(false);
  1580. if (n_while->condition == nullptr) {
  1581. push_error(R"(Expected conditional expression after "while".)");
  1582. }
  1583. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "while" condition.)");
  1584. // Save break/continue state.
  1585. bool could_break = can_break;
  1586. bool could_continue = can_continue;
  1587. bool was_continue_match = is_continue_match;
  1588. // Allow break/continue.
  1589. can_break = true;
  1590. can_continue = true;
  1591. is_continue_match = false;
  1592. n_while->loop = parse_suite(R"("while" block)");
  1593. // Reset break/continue state.
  1594. can_break = could_break;
  1595. can_continue = could_continue;
  1596. is_continue_match = was_continue_match;
  1597. return n_while;
  1598. }
  1599. GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign) {
  1600. // Switch multiline mode on for grouping tokens.
  1601. // Do this early to avoid the tokenizer generating whitespace tokens.
  1602. switch (current.type) {
  1603. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  1604. case GDScriptTokenizer::Token::BRACE_OPEN:
  1605. case GDScriptTokenizer::Token::BRACKET_OPEN:
  1606. push_multiline(true);
  1607. break;
  1608. default:
  1609. break; // Nothing to do.
  1610. }
  1611. // Completion can appear whenever an expression is expected.
  1612. make_completion_context(COMPLETION_IDENTIFIER, nullptr);
  1613. GDScriptTokenizer::Token token = advance();
  1614. ParseFunction prefix_rule = get_rule(token.type)->prefix;
  1615. if (prefix_rule == nullptr) {
  1616. // Expected expression. Let the caller give the proper error message.
  1617. return nullptr;
  1618. }
  1619. ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign);
  1620. while (p_precedence <= get_rule(current.type)->precedence) {
  1621. if (p_stop_on_assign && current.type == GDScriptTokenizer::Token::EQUAL) {
  1622. return previous_operand;
  1623. }
  1624. // Also switch multiline mode on here for infix operators.
  1625. switch (current.type) {
  1626. // case GDScriptTokenizer::Token::BRACE_OPEN: // Not an infix operator.
  1627. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  1628. case GDScriptTokenizer::Token::BRACKET_OPEN:
  1629. push_multiline(true);
  1630. break;
  1631. default:
  1632. break; // Nothing to do.
  1633. }
  1634. token = advance();
  1635. ParseFunction infix_rule = get_rule(token.type)->infix;
  1636. previous_operand = (this->*infix_rule)(previous_operand, p_can_assign);
  1637. }
  1638. return previous_operand;
  1639. }
  1640. GDScriptParser::ExpressionNode *GDScriptParser::parse_expression(bool p_can_assign, bool p_stop_on_assign) {
  1641. return parse_precedence(PREC_ASSIGNMENT, p_can_assign, p_stop_on_assign);
  1642. }
  1643. GDScriptParser::IdentifierNode *GDScriptParser::parse_identifier() {
  1644. return static_cast<IdentifierNode *>(parse_identifier(nullptr, false));
  1645. }
  1646. GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1647. if (!previous.is_identifier()) {
  1648. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
  1649. }
  1650. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  1651. identifier->name = previous.get_identifier();
  1652. if (current_suite != nullptr && current_suite->has_local(identifier->name)) {
  1653. const SuiteNode::Local &declaration = current_suite->get_local(identifier->name);
  1654. switch (declaration.type) {
  1655. case SuiteNode::Local::CONSTANT:
  1656. identifier->source = IdentifierNode::LOCAL_CONSTANT;
  1657. identifier->constant_source = declaration.constant;
  1658. declaration.constant->usages++;
  1659. break;
  1660. case SuiteNode::Local::VARIABLE:
  1661. identifier->source = IdentifierNode::LOCAL_VARIABLE;
  1662. identifier->variable_source = declaration.variable;
  1663. declaration.variable->usages++;
  1664. break;
  1665. case SuiteNode::Local::PARAMETER:
  1666. identifier->source = IdentifierNode::FUNCTION_PARAMETER;
  1667. identifier->parameter_source = declaration.parameter;
  1668. declaration.parameter->usages++;
  1669. break;
  1670. case SuiteNode::Local::FOR_VARIABLE:
  1671. identifier->source = IdentifierNode::LOCAL_ITERATOR;
  1672. identifier->bind_source = declaration.bind;
  1673. declaration.bind->usages++;
  1674. break;
  1675. case SuiteNode::Local::PATTERN_BIND:
  1676. identifier->source = IdentifierNode::LOCAL_BIND;
  1677. identifier->bind_source = declaration.bind;
  1678. declaration.bind->usages++;
  1679. break;
  1680. case SuiteNode::Local::UNDEFINED:
  1681. ERR_FAIL_V_MSG(nullptr, "Undefined local found.");
  1682. }
  1683. }
  1684. return identifier;
  1685. }
  1686. GDScriptParser::LiteralNode *GDScriptParser::parse_literal() {
  1687. return static_cast<LiteralNode *>(parse_literal(nullptr, false));
  1688. }
  1689. GDScriptParser::ExpressionNode *GDScriptParser::parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1690. if (previous.type != GDScriptTokenizer::Token::LITERAL) {
  1691. push_error("Parser bug: parsing literal node without literal token.");
  1692. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
  1693. }
  1694. LiteralNode *literal = alloc_node<LiteralNode>();
  1695. literal->value = previous.literal;
  1696. return literal;
  1697. }
  1698. GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1699. if (current_function && current_function->is_static) {
  1700. push_error(R"(Cannot use "self" inside a static function.)");
  1701. }
  1702. SelfNode *self = alloc_node<SelfNode>();
  1703. self->current_class = current_class;
  1704. return self;
  1705. }
  1706. GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1707. GDScriptTokenizer::Token::Type op_type = previous.type;
  1708. LiteralNode *constant = alloc_node<LiteralNode>();
  1709. switch (op_type) {
  1710. case GDScriptTokenizer::Token::CONST_PI:
  1711. constant->value = Math_PI;
  1712. break;
  1713. case GDScriptTokenizer::Token::CONST_TAU:
  1714. constant->value = Math_TAU;
  1715. break;
  1716. case GDScriptTokenizer::Token::CONST_INF:
  1717. constant->value = Math_INF;
  1718. break;
  1719. case GDScriptTokenizer::Token::CONST_NAN:
  1720. constant->value = Math_NAN;
  1721. break;
  1722. default:
  1723. return nullptr; // Unreachable.
  1724. }
  1725. return constant;
  1726. }
  1727. GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1728. GDScriptTokenizer::Token::Type op_type = previous.type;
  1729. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  1730. switch (op_type) {
  1731. case GDScriptTokenizer::Token::MINUS:
  1732. operation->operation = UnaryOpNode::OP_NEGATIVE;
  1733. operation->variant_op = Variant::OP_NEGATE;
  1734. operation->operand = parse_precedence(PREC_SIGN, false);
  1735. break;
  1736. case GDScriptTokenizer::Token::PLUS:
  1737. operation->operation = UnaryOpNode::OP_POSITIVE;
  1738. operation->variant_op = Variant::OP_POSITIVE;
  1739. operation->operand = parse_precedence(PREC_SIGN, false);
  1740. break;
  1741. case GDScriptTokenizer::Token::TILDE:
  1742. operation->operation = UnaryOpNode::OP_COMPLEMENT;
  1743. operation->variant_op = Variant::OP_BIT_NEGATE;
  1744. operation->operand = parse_precedence(PREC_BIT_NOT, false);
  1745. break;
  1746. case GDScriptTokenizer::Token::NOT:
  1747. case GDScriptTokenizer::Token::BANG:
  1748. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  1749. operation->variant_op = Variant::OP_NOT;
  1750. operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
  1751. break;
  1752. default:
  1753. return nullptr; // Unreachable.
  1754. }
  1755. return operation;
  1756. }
  1757. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1758. GDScriptTokenizer::Token op = previous;
  1759. BinaryOpNode *operation = alloc_node<BinaryOpNode>();
  1760. Precedence precedence = (Precedence)(get_rule(op.type)->precedence + 1);
  1761. operation->left_operand = p_previous_operand;
  1762. operation->right_operand = parse_precedence(precedence, false);
  1763. if (operation->right_operand == nullptr) {
  1764. push_error(vformat(R"(Expected expression after "%s" operator.")", op.get_name()));
  1765. }
  1766. // TODO: Also for unary, ternary, and assignment.
  1767. switch (op.type) {
  1768. case GDScriptTokenizer::Token::PLUS:
  1769. operation->operation = BinaryOpNode::OP_ADDITION;
  1770. operation->variant_op = Variant::OP_ADD;
  1771. break;
  1772. case GDScriptTokenizer::Token::MINUS:
  1773. operation->operation = BinaryOpNode::OP_SUBTRACTION;
  1774. operation->variant_op = Variant::OP_SUBTRACT;
  1775. break;
  1776. case GDScriptTokenizer::Token::STAR:
  1777. operation->operation = BinaryOpNode::OP_MULTIPLICATION;
  1778. operation->variant_op = Variant::OP_MULTIPLY;
  1779. break;
  1780. case GDScriptTokenizer::Token::SLASH:
  1781. operation->operation = BinaryOpNode::OP_DIVISION;
  1782. operation->variant_op = Variant::OP_DIVIDE;
  1783. break;
  1784. case GDScriptTokenizer::Token::PERCENT:
  1785. operation->operation = BinaryOpNode::OP_MODULO;
  1786. operation->variant_op = Variant::OP_MODULE;
  1787. break;
  1788. case GDScriptTokenizer::Token::LESS_LESS:
  1789. operation->operation = BinaryOpNode::OP_BIT_LEFT_SHIFT;
  1790. operation->variant_op = Variant::OP_SHIFT_LEFT;
  1791. break;
  1792. case GDScriptTokenizer::Token::GREATER_GREATER:
  1793. operation->operation = BinaryOpNode::OP_BIT_RIGHT_SHIFT;
  1794. operation->variant_op = Variant::OP_SHIFT_RIGHT;
  1795. break;
  1796. case GDScriptTokenizer::Token::AMPERSAND:
  1797. operation->operation = BinaryOpNode::OP_BIT_AND;
  1798. operation->variant_op = Variant::OP_BIT_AND;
  1799. break;
  1800. case GDScriptTokenizer::Token::PIPE:
  1801. operation->operation = BinaryOpNode::OP_BIT_OR;
  1802. operation->variant_op = Variant::OP_BIT_OR;
  1803. break;
  1804. case GDScriptTokenizer::Token::CARET:
  1805. operation->operation = BinaryOpNode::OP_BIT_XOR;
  1806. operation->variant_op = Variant::OP_BIT_XOR;
  1807. break;
  1808. case GDScriptTokenizer::Token::AND:
  1809. case GDScriptTokenizer::Token::AMPERSAND_AMPERSAND:
  1810. operation->operation = BinaryOpNode::OP_LOGIC_AND;
  1811. operation->variant_op = Variant::OP_AND;
  1812. break;
  1813. case GDScriptTokenizer::Token::OR:
  1814. case GDScriptTokenizer::Token::PIPE_PIPE:
  1815. operation->operation = BinaryOpNode::OP_LOGIC_OR;
  1816. operation->variant_op = Variant::OP_OR;
  1817. break;
  1818. case GDScriptTokenizer::Token::IS:
  1819. operation->operation = BinaryOpNode::OP_TYPE_TEST;
  1820. break;
  1821. case GDScriptTokenizer::Token::IN:
  1822. operation->operation = BinaryOpNode::OP_CONTENT_TEST;
  1823. operation->variant_op = Variant::OP_IN;
  1824. break;
  1825. case GDScriptTokenizer::Token::EQUAL_EQUAL:
  1826. operation->operation = BinaryOpNode::OP_COMP_EQUAL;
  1827. operation->variant_op = Variant::OP_EQUAL;
  1828. break;
  1829. case GDScriptTokenizer::Token::BANG_EQUAL:
  1830. operation->operation = BinaryOpNode::OP_COMP_NOT_EQUAL;
  1831. operation->variant_op = Variant::OP_NOT_EQUAL;
  1832. break;
  1833. case GDScriptTokenizer::Token::LESS:
  1834. operation->operation = BinaryOpNode::OP_COMP_LESS;
  1835. operation->variant_op = Variant::OP_LESS;
  1836. break;
  1837. case GDScriptTokenizer::Token::LESS_EQUAL:
  1838. operation->operation = BinaryOpNode::OP_COMP_LESS_EQUAL;
  1839. operation->variant_op = Variant::OP_LESS_EQUAL;
  1840. break;
  1841. case GDScriptTokenizer::Token::GREATER:
  1842. operation->operation = BinaryOpNode::OP_COMP_GREATER;
  1843. operation->variant_op = Variant::OP_GREATER;
  1844. break;
  1845. case GDScriptTokenizer::Token::GREATER_EQUAL:
  1846. operation->operation = BinaryOpNode::OP_COMP_GREATER_EQUAL;
  1847. operation->variant_op = Variant::OP_GREATER_EQUAL;
  1848. break;
  1849. default:
  1850. return nullptr; // Unreachable.
  1851. }
  1852. return operation;
  1853. }
  1854. GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1855. // Only one ternary operation exists, so no abstraction here.
  1856. TernaryOpNode *operation = alloc_node<TernaryOpNode>();
  1857. operation->true_expr = p_previous_operand;
  1858. operation->condition = parse_precedence(PREC_TERNARY, false);
  1859. if (operation->condition == nullptr) {
  1860. push_error(R"(Expected expression as ternary condition after "if".)");
  1861. }
  1862. consume(GDScriptTokenizer::Token::ELSE, R"(Expected "else" after ternary operator condition.)");
  1863. operation->false_expr = parse_precedence(PREC_TERNARY, false);
  1864. return operation;
  1865. }
  1866. GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1867. if (!p_can_assign) {
  1868. push_error("Assignment is not allowed inside an expression.");
  1869. return parse_expression(false); // Return the following expression.
  1870. }
  1871. #ifdef DEBUG_ENABLED
  1872. VariableNode *source_variable = nullptr;
  1873. #endif
  1874. switch (p_previous_operand->type) {
  1875. case Node::IDENTIFIER: {
  1876. #ifdef DEBUG_ENABLED
  1877. // Get source to store assignment count.
  1878. // Also remove one usage since assignment isn't usage.
  1879. IdentifierNode *id = static_cast<IdentifierNode *>(p_previous_operand);
  1880. switch (id->source) {
  1881. case IdentifierNode::LOCAL_VARIABLE:
  1882. source_variable = id->variable_source;
  1883. id->variable_source->usages--;
  1884. break;
  1885. case IdentifierNode::LOCAL_CONSTANT:
  1886. id->constant_source->usages--;
  1887. break;
  1888. case IdentifierNode::FUNCTION_PARAMETER:
  1889. id->parameter_source->usages--;
  1890. break;
  1891. case IdentifierNode::LOCAL_ITERATOR:
  1892. case IdentifierNode::LOCAL_BIND:
  1893. id->bind_source->usages--;
  1894. break;
  1895. default:
  1896. break;
  1897. }
  1898. #endif
  1899. } break;
  1900. case Node::SUBSCRIPT:
  1901. // Okay.
  1902. break;
  1903. default:
  1904. push_error(R"(Only identifier, attribute access, and subscription access can be used as assignment target.)");
  1905. return parse_expression(false); // Return the following expression.
  1906. }
  1907. AssignmentNode *assignment = alloc_node<AssignmentNode>();
  1908. make_completion_context(COMPLETION_ASSIGN, assignment);
  1909. #ifdef DEBUG_ENABLED
  1910. bool has_operator = true;
  1911. #endif
  1912. switch (previous.type) {
  1913. case GDScriptTokenizer::Token::EQUAL:
  1914. assignment->operation = AssignmentNode::OP_NONE;
  1915. assignment->variant_op = Variant::OP_MAX;
  1916. #ifdef DEBUG_ENABLED
  1917. has_operator = false;
  1918. #endif
  1919. break;
  1920. case GDScriptTokenizer::Token::PLUS_EQUAL:
  1921. assignment->operation = AssignmentNode::OP_ADDITION;
  1922. assignment->variant_op = Variant::OP_ADD;
  1923. break;
  1924. case GDScriptTokenizer::Token::MINUS_EQUAL:
  1925. assignment->operation = AssignmentNode::OP_SUBTRACTION;
  1926. assignment->variant_op = Variant::OP_SUBTRACT;
  1927. break;
  1928. case GDScriptTokenizer::Token::STAR_EQUAL:
  1929. assignment->operation = AssignmentNode::OP_MULTIPLICATION;
  1930. assignment->variant_op = Variant::OP_MULTIPLY;
  1931. break;
  1932. case GDScriptTokenizer::Token::SLASH_EQUAL:
  1933. assignment->operation = AssignmentNode::OP_DIVISION;
  1934. assignment->variant_op = Variant::OP_DIVIDE;
  1935. break;
  1936. case GDScriptTokenizer::Token::PERCENT_EQUAL:
  1937. assignment->operation = AssignmentNode::OP_MODULO;
  1938. assignment->variant_op = Variant::OP_MODULE;
  1939. break;
  1940. case GDScriptTokenizer::Token::LESS_LESS_EQUAL:
  1941. assignment->operation = AssignmentNode::OP_BIT_SHIFT_LEFT;
  1942. assignment->variant_op = Variant::OP_SHIFT_LEFT;
  1943. break;
  1944. case GDScriptTokenizer::Token::GREATER_GREATER_EQUAL:
  1945. assignment->operation = AssignmentNode::OP_BIT_SHIFT_RIGHT;
  1946. assignment->variant_op = Variant::OP_SHIFT_RIGHT;
  1947. break;
  1948. case GDScriptTokenizer::Token::AMPERSAND_EQUAL:
  1949. assignment->operation = AssignmentNode::OP_BIT_AND;
  1950. assignment->variant_op = Variant::OP_BIT_AND;
  1951. break;
  1952. case GDScriptTokenizer::Token::PIPE_EQUAL:
  1953. assignment->operation = AssignmentNode::OP_BIT_OR;
  1954. assignment->variant_op = Variant::OP_BIT_OR;
  1955. break;
  1956. case GDScriptTokenizer::Token::CARET_EQUAL:
  1957. assignment->operation = AssignmentNode::OP_BIT_XOR;
  1958. assignment->variant_op = Variant::OP_BIT_XOR;
  1959. break;
  1960. default:
  1961. break; // Unreachable.
  1962. }
  1963. assignment->assignee = p_previous_operand;
  1964. assignment->assigned_value = parse_expression(false);
  1965. #ifdef DEBUG_ENABLED
  1966. if (has_operator && source_variable != nullptr && source_variable->assignments == 0) {
  1967. push_warning(assignment, GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, source_variable->identifier->name);
  1968. }
  1969. #endif
  1970. return assignment;
  1971. }
  1972. GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1973. AwaitNode *await = alloc_node<AwaitNode>();
  1974. await->to_await = parse_precedence(PREC_AWAIT, false);
  1975. current_function->is_coroutine = true;
  1976. return await;
  1977. }
  1978. GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1979. ArrayNode *array = alloc_node<ArrayNode>();
  1980. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  1981. do {
  1982. if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  1983. // Allow for trailing comma.
  1984. break;
  1985. }
  1986. ExpressionNode *element = parse_expression(false);
  1987. if (element == nullptr) {
  1988. push_error(R"(Expected expression as array element.)");
  1989. } else {
  1990. array->elements.push_back(element);
  1991. }
  1992. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  1993. }
  1994. pop_multiline();
  1995. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
  1996. return array;
  1997. }
  1998. GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1999. DictionaryNode *dictionary = alloc_node<DictionaryNode>();
  2000. bool decided_style = false;
  2001. if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2002. do {
  2003. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2004. // Allow for trailing comma.
  2005. break;
  2006. }
  2007. // Key.
  2008. ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
  2009. if (key == nullptr) {
  2010. push_error(R"(Expected expression as dictionary key.)");
  2011. }
  2012. if (!decided_style) {
  2013. switch (current.type) {
  2014. case GDScriptTokenizer::Token::COLON:
  2015. dictionary->style = DictionaryNode::PYTHON_DICT;
  2016. break;
  2017. case GDScriptTokenizer::Token::EQUAL:
  2018. dictionary->style = DictionaryNode::LUA_TABLE;
  2019. break;
  2020. default:
  2021. push_error(R"(Expected ":" or "=" after dictionary key.)");
  2022. break;
  2023. }
  2024. decided_style = true;
  2025. }
  2026. switch (dictionary->style) {
  2027. case DictionaryNode::LUA_TABLE:
  2028. if (key != nullptr && key->type != Node::IDENTIFIER) {
  2029. push_error("Expected identifier as dictionary key.");
  2030. }
  2031. if (!match(GDScriptTokenizer::Token::EQUAL)) {
  2032. if (match(GDScriptTokenizer::Token::COLON)) {
  2033. push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
  2034. advance(); // Consume wrong separator anyway.
  2035. } else {
  2036. push_error(R"(Expected "=" after dictionary key.)");
  2037. }
  2038. }
  2039. break;
  2040. case DictionaryNode::PYTHON_DICT:
  2041. if (!match(GDScriptTokenizer::Token::COLON)) {
  2042. if (match(GDScriptTokenizer::Token::EQUAL)) {
  2043. push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
  2044. advance(); // Consume wrong separator anyway.
  2045. } else {
  2046. push_error(R"(Expected ":" after dictionary key.)");
  2047. }
  2048. }
  2049. break;
  2050. }
  2051. // Value.
  2052. ExpressionNode *value = parse_expression(false);
  2053. if (value == nullptr) {
  2054. push_error(R"(Expected expression as dictionary value.)");
  2055. }
  2056. if (key != nullptr && value != nullptr) {
  2057. dictionary->elements.push_back({ key, value });
  2058. }
  2059. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2060. }
  2061. pop_multiline();
  2062. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
  2063. return dictionary;
  2064. }
  2065. GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2066. ExpressionNode *grouped = parse_expression(false);
  2067. pop_multiline();
  2068. if (grouped == nullptr) {
  2069. push_error(R"(Expected grouping expression.)");
  2070. } else {
  2071. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
  2072. }
  2073. return grouped;
  2074. }
  2075. GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2076. SubscriptNode *attribute = alloc_node<SubscriptNode>();
  2077. if (for_completion) {
  2078. bool is_builtin = false;
  2079. if (p_previous_operand->type == Node::IDENTIFIER) {
  2080. const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
  2081. Variant::Type builtin_type = get_builtin_type(id->name);
  2082. if (builtin_type < Variant::VARIANT_MAX) {
  2083. make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT, builtin_type, true);
  2084. is_builtin = true;
  2085. }
  2086. }
  2087. if (!is_builtin) {
  2088. make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1, true);
  2089. }
  2090. }
  2091. attribute->is_attribute = true;
  2092. attribute->base = p_previous_operand;
  2093. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
  2094. return attribute;
  2095. }
  2096. attribute->attribute = parse_identifier();
  2097. return attribute;
  2098. }
  2099. GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2100. SubscriptNode *subscript = alloc_node<SubscriptNode>();
  2101. make_completion_context(COMPLETION_SUBSCRIPT, subscript);
  2102. subscript->base = p_previous_operand;
  2103. subscript->index = parse_expression(false);
  2104. pop_multiline();
  2105. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
  2106. return subscript;
  2107. }
  2108. GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2109. CastNode *cast = alloc_node<CastNode>();
  2110. cast->operand = p_previous_operand;
  2111. cast->cast_type = parse_type();
  2112. if (cast->cast_type == nullptr) {
  2113. push_error(R"(Expected type specifier after "as".)");
  2114. return p_previous_operand;
  2115. }
  2116. return cast;
  2117. }
  2118. GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2119. CallNode *call = alloc_node<CallNode>();
  2120. if (previous.type == GDScriptTokenizer::Token::SUPER) {
  2121. // Super call.
  2122. call->is_super = true;
  2123. push_multiline(true);
  2124. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  2125. // Implicit call to the parent method of the same name.
  2126. if (current_function == nullptr) {
  2127. push_error(R"(Cannot use implicit "super" call outside of a function.)");
  2128. pop_multiline();
  2129. return nullptr;
  2130. }
  2131. call->function_name = current_function->identifier->name;
  2132. } else {
  2133. consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
  2134. make_completion_context(COMPLETION_SUPER_METHOD, call, true);
  2135. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
  2136. pop_multiline();
  2137. return nullptr;
  2138. }
  2139. IdentifierNode *identifier = parse_identifier();
  2140. call->callee = identifier;
  2141. call->function_name = identifier->name;
  2142. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)");
  2143. }
  2144. } else {
  2145. call->callee = p_previous_operand;
  2146. if (call->callee == nullptr) {
  2147. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2148. } else if (call->callee->type == Node::IDENTIFIER) {
  2149. call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
  2150. make_completion_context(COMPLETION_METHOD, call->callee);
  2151. } else if (call->callee->type == Node::SUBSCRIPT) {
  2152. SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
  2153. if (attribute->is_attribute) {
  2154. if (attribute->attribute) {
  2155. call->function_name = attribute->attribute->name;
  2156. }
  2157. make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
  2158. } else {
  2159. // TODO: The analyzer can see if this is actually a Callable and give better error message.
  2160. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2161. }
  2162. } else {
  2163. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2164. }
  2165. }
  2166. // Arguments.
  2167. CompletionType ct = COMPLETION_CALL_ARGUMENTS;
  2168. if (get_builtin_function(call->function_name) == GDScriptFunctions::RESOURCE_LOAD) {
  2169. ct = COMPLETION_RESOURCE_PATH;
  2170. }
  2171. push_completion_call(call);
  2172. int argument_index = 0;
  2173. do {
  2174. make_completion_context(ct, call, argument_index++, true);
  2175. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  2176. // Allow for trailing comma.
  2177. break;
  2178. }
  2179. ExpressionNode *argument = parse_expression(false);
  2180. if (argument == nullptr) {
  2181. push_error(R"(Expected expression as the function argument.)");
  2182. } else {
  2183. call->arguments.push_back(argument);
  2184. }
  2185. ct = COMPLETION_CALL_ARGUMENTS;
  2186. } while (match(GDScriptTokenizer::Token::COMMA));
  2187. pop_completion_call();
  2188. pop_multiline();
  2189. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
  2190. return call;
  2191. }
  2192. GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2193. if (match(GDScriptTokenizer::Token::LITERAL)) {
  2194. if (previous.literal.get_type() != Variant::STRING) {
  2195. push_error(R"(Expect node path as string or identifier after "$".)");
  2196. return nullptr;
  2197. }
  2198. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  2199. make_completion_context(COMPLETION_GET_NODE, get_node);
  2200. get_node->string = parse_literal();
  2201. return get_node;
  2202. } else if (current.is_node_name()) {
  2203. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  2204. int chain_position = 0;
  2205. do {
  2206. make_completion_context(COMPLETION_GET_NODE, get_node, chain_position++);
  2207. if (!current.is_node_name()) {
  2208. push_error(R"(Expect node path after "/".)");
  2209. return nullptr;
  2210. }
  2211. advance();
  2212. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  2213. identifier->name = previous.get_identifier();
  2214. get_node->chain.push_back(identifier);
  2215. } while (match(GDScriptTokenizer::Token::SLASH));
  2216. return get_node;
  2217. } else {
  2218. push_error(R"(Expect node path as string or identifier after "$".)");
  2219. return nullptr;
  2220. }
  2221. }
  2222. GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2223. PreloadNode *preload = alloc_node<PreloadNode>();
  2224. preload->resolved_path = "<missing path>";
  2225. push_multiline(true);
  2226. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
  2227. make_completion_context(COMPLETION_RESOURCE_PATH, preload);
  2228. push_completion_call(preload);
  2229. preload->path = parse_expression(false);
  2230. if (preload->path == nullptr) {
  2231. push_error(R"(Expected resource path after "(".)");
  2232. }
  2233. pop_completion_call();
  2234. pop_multiline();
  2235. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
  2236. return preload;
  2237. }
  2238. GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2239. // Just for better error messages.
  2240. GDScriptTokenizer::Token::Type invalid = previous.type;
  2241. switch (invalid) {
  2242. case GDScriptTokenizer::Token::QUESTION_MARK:
  2243. push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
  2244. break;
  2245. default:
  2246. return nullptr; // Unreachable.
  2247. }
  2248. // Return the previous expression.
  2249. return p_previous_operand;
  2250. }
  2251. GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
  2252. TypeNode *type = alloc_node<TypeNode>();
  2253. make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
  2254. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2255. if (match(GDScriptTokenizer::Token::VOID)) {
  2256. if (p_allow_void) {
  2257. TypeNode *void_type = alloc_node<TypeNode>();
  2258. return void_type;
  2259. } else {
  2260. push_error(R"("void" is only allowed for a function return type.)");
  2261. }
  2262. }
  2263. // Leave error message to the caller who knows the context.
  2264. return nullptr;
  2265. }
  2266. IdentifierNode *type_element = parse_identifier();
  2267. type->type_chain.push_back(type_element);
  2268. int chain_index = 1;
  2269. while (match(GDScriptTokenizer::Token::PERIOD)) {
  2270. make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
  2271. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
  2272. type_element = parse_identifier();
  2273. type->type_chain.push_back(type_element);
  2274. }
  2275. }
  2276. return type;
  2277. }
  2278. GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
  2279. // Function table for expression parsing.
  2280. // clang-format destroys the alignment here, so turn off for the table.
  2281. /* clang-format off */
  2282. static ParseRule rules[] = {
  2283. // PREFIX INFIX PRECEDENCE (for infix)
  2284. { nullptr, nullptr, PREC_NONE }, // EMPTY,
  2285. // Basic
  2286. { nullptr, nullptr, PREC_NONE }, // ANNOTATION,
  2287. { &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
  2288. { &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
  2289. // Comparison
  2290. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
  2291. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
  2292. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
  2293. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
  2294. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
  2295. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
  2296. // Logical
  2297. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
  2298. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
  2299. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // NOT,
  2300. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
  2301. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
  2302. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
  2303. // Bitwise
  2304. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
  2305. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
  2306. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
  2307. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
  2308. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
  2309. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
  2310. // Math
  2311. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION }, // PLUS,
  2312. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_SUBTRACTION }, // MINUS,
  2313. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
  2314. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
  2315. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
  2316. // Assignment
  2317. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
  2318. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
  2319. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
  2320. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
  2321. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
  2322. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
  2323. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
  2324. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
  2325. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
  2326. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
  2327. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
  2328. // Control flow
  2329. { nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
  2330. { nullptr, nullptr, PREC_NONE }, // ELIF,
  2331. { nullptr, nullptr, PREC_NONE }, // ELSE,
  2332. { nullptr, nullptr, PREC_NONE }, // FOR,
  2333. { nullptr, nullptr, PREC_NONE }, // WHILE,
  2334. { nullptr, nullptr, PREC_NONE }, // BREAK,
  2335. { nullptr, nullptr, PREC_NONE }, // CONTINUE,
  2336. { nullptr, nullptr, PREC_NONE }, // PASS,
  2337. { nullptr, nullptr, PREC_NONE }, // RETURN,
  2338. { nullptr, nullptr, PREC_NONE }, // MATCH,
  2339. // Keywords
  2340. { nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
  2341. { nullptr, nullptr, PREC_NONE }, // ASSERT,
  2342. { &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
  2343. { nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
  2344. { nullptr, nullptr, PREC_NONE }, // CLASS,
  2345. { nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
  2346. { nullptr, nullptr, PREC_NONE }, // CONST,
  2347. { nullptr, nullptr, PREC_NONE }, // ENUM,
  2348. { nullptr, nullptr, PREC_NONE }, // EXTENDS,
  2349. { nullptr, nullptr, PREC_NONE }, // FUNC,
  2350. { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // IN,
  2351. { nullptr, &GDScriptParser::parse_binary_operator, PREC_TYPE_TEST }, // IS,
  2352. { nullptr, nullptr, PREC_NONE }, // NAMESPACE,
  2353. { &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
  2354. { &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
  2355. { nullptr, nullptr, PREC_NONE }, // SIGNAL,
  2356. { nullptr, nullptr, PREC_NONE }, // STATIC,
  2357. { &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
  2358. { nullptr, nullptr, PREC_NONE }, // TRAIT,
  2359. { nullptr, nullptr, PREC_NONE }, // VAR,
  2360. { nullptr, nullptr, PREC_NONE }, // VOID,
  2361. { nullptr, nullptr, PREC_NONE }, // YIELD,
  2362. // Punctuation
  2363. { &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
  2364. { nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
  2365. { &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
  2366. { nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
  2367. { &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
  2368. { nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
  2369. { nullptr, nullptr, PREC_NONE }, // COMMA,
  2370. { nullptr, nullptr, PREC_NONE }, // SEMICOLON,
  2371. { nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
  2372. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
  2373. { nullptr, nullptr, PREC_NONE }, // COLON,
  2374. { &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
  2375. { nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
  2376. { nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
  2377. // Whitespace
  2378. { nullptr, nullptr, PREC_NONE }, // NEWLINE,
  2379. { nullptr, nullptr, PREC_NONE }, // INDENT,
  2380. { nullptr, nullptr, PREC_NONE }, // DEDENT,
  2381. // Constants
  2382. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
  2383. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
  2384. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
  2385. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
  2386. // Error message improvement
  2387. { nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
  2388. { nullptr, nullptr, PREC_NONE }, // BACKTICK,
  2389. { nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
  2390. // Special
  2391. { nullptr, nullptr, PREC_NONE }, // ERROR,
  2392. { nullptr, nullptr, PREC_NONE }, // TK_EOF,
  2393. };
  2394. /* clang-format on */
  2395. // Avoid desync.
  2396. static_assert(sizeof(rules) / sizeof(rules[0]) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
  2397. // Let's assume this this never invalid, since nothing generates a TK_MAX.
  2398. return &rules[p_token_type];
  2399. }
  2400. bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
  2401. if (locals_indices.has(p_name)) {
  2402. return true;
  2403. }
  2404. if (parent_block != nullptr) {
  2405. return parent_block->has_local(p_name);
  2406. }
  2407. return false;
  2408. }
  2409. const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
  2410. if (locals_indices.has(p_name)) {
  2411. return locals[locals_indices[p_name]];
  2412. }
  2413. if (parent_block != nullptr) {
  2414. return parent_block->get_local(p_name);
  2415. }
  2416. return empty;
  2417. }
  2418. bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target) const {
  2419. return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target);
  2420. }
  2421. bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
  2422. return (info->target_kind & p_target_kinds) > 0;
  2423. }
  2424. bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
  2425. ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  2426. const MethodInfo &info = valid_annotations[p_annotation->name].info;
  2427. if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
  2428. 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()));
  2429. return false;
  2430. }
  2431. if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  2432. 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()));
  2433. return false;
  2434. }
  2435. const List<PropertyInfo>::Element *E = info.arguments.front();
  2436. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  2437. ExpressionNode *argument = p_annotation->arguments[i];
  2438. const PropertyInfo &parameter = E->get();
  2439. if (E->next() != nullptr) {
  2440. E = E->next();
  2441. }
  2442. switch (parameter.type) {
  2443. case Variant::STRING:
  2444. case Variant::STRING_NAME:
  2445. case Variant::NODE_PATH:
  2446. // Allow "quote-less strings", as long as they are recognized as identifiers.
  2447. if (argument->type == Node::IDENTIFIER) {
  2448. IdentifierNode *string = static_cast<IdentifierNode *>(argument);
  2449. Callable::CallError error;
  2450. Vector<Variant> args = varray(string->name);
  2451. const Variant *name = args.ptr();
  2452. Variant r;
  2453. Variant::construct(parameter.type, r, &(name), 1, error);
  2454. p_annotation->resolved_arguments.push_back(r);
  2455. if (error.error != Callable::CallError::CALL_OK) {
  2456. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2457. p_annotation->resolved_arguments.remove(p_annotation->resolved_arguments.size() - 1);
  2458. return false;
  2459. }
  2460. break;
  2461. }
  2462. [[fallthrough]];
  2463. default: {
  2464. if (argument->type != Node::LITERAL) {
  2465. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2466. return false;
  2467. }
  2468. Variant value = static_cast<LiteralNode *>(argument)->value;
  2469. if (!Variant::can_convert_strict(value.get_type(), parameter.type)) {
  2470. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2471. return false;
  2472. }
  2473. Callable::CallError error;
  2474. const Variant *args = &value;
  2475. Variant r;
  2476. Variant::construct(parameter.type, r, &(args), 1, error);
  2477. p_annotation->resolved_arguments.push_back(r);
  2478. if (error.error != Callable::CallError::CALL_OK) {
  2479. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2480. p_annotation->resolved_arguments.remove(p_annotation->resolved_arguments.size() - 1);
  2481. return false;
  2482. }
  2483. break;
  2484. }
  2485. }
  2486. }
  2487. return true;
  2488. }
  2489. bool GDScriptParser::tool_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  2490. this->_is_tool = true;
  2491. return true;
  2492. }
  2493. bool GDScriptParser::icon_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  2494. ERR_FAIL_COND_V_MSG(p_node->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
  2495. ClassNode *p_class = static_cast<ClassNode *>(p_node);
  2496. p_class->icon_path = p_annotation->resolved_arguments[0];
  2497. return true;
  2498. }
  2499. bool GDScriptParser::onready_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  2500. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
  2501. VariableNode *variable = static_cast<VariableNode *>(p_node);
  2502. if (variable->onready) {
  2503. push_error(R"("@onready" annotation can only be used once per variable.)");
  2504. return false;
  2505. }
  2506. variable->onready = true;
  2507. current_class->onready_used = true;
  2508. return true;
  2509. }
  2510. template <PropertyHint t_hint, Variant::Type t_type>
  2511. bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  2512. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  2513. VariableNode *variable = static_cast<VariableNode *>(p_node);
  2514. if (variable->exported) {
  2515. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  2516. return false;
  2517. }
  2518. variable->exported = true;
  2519. // TODO: Improving setting type, especially for range hints, which can be int or float.
  2520. variable->export_info.type = t_type;
  2521. variable->export_info.hint = t_hint;
  2522. if (p_annotation->name == "@export") {
  2523. if (variable->datatype_specifier == nullptr) {
  2524. if (variable->initializer == nullptr) {
  2525. push_error(R"(Cannot use "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
  2526. return false;
  2527. }
  2528. if (variable->initializer->type != Node::LITERAL) {
  2529. push_error(R"(To use "@export" annotation with type-less variable, the default value must be a literal.)", p_annotation);
  2530. return false;
  2531. }
  2532. variable->export_info.type = static_cast<LiteralNode *>(variable->initializer)->value.get_type();
  2533. } // else: Actual type will be set by the analyzer, which can infer the proper type.
  2534. }
  2535. String hint_string;
  2536. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  2537. if (i > 0) {
  2538. hint_string += ",";
  2539. }
  2540. hint_string += String(p_annotation->resolved_arguments[i]);
  2541. }
  2542. variable->export_info.hint_string = hint_string;
  2543. return true;
  2544. }
  2545. bool GDScriptParser::warning_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  2546. ERR_FAIL_V_MSG(false, "Not implemented.");
  2547. }
  2548. template <MultiplayerAPI::RPCMode t_mode>
  2549. bool GDScriptParser::network_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  2550. 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));
  2551. switch (p_node->type) {
  2552. case Node::VARIABLE: {
  2553. VariableNode *variable = static_cast<VariableNode *>(p_node);
  2554. if (variable->rpc_mode != MultiplayerAPI::RPC_MODE_DISABLED) {
  2555. push_error(R"(RPC annotations can only be used once per variable.)", p_annotation);
  2556. }
  2557. variable->rpc_mode = t_mode;
  2558. break;
  2559. }
  2560. case Node::FUNCTION: {
  2561. FunctionNode *function = static_cast<FunctionNode *>(p_node);
  2562. if (function->rpc_mode != MultiplayerAPI::RPC_MODE_DISABLED) {
  2563. push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
  2564. }
  2565. function->rpc_mode = t_mode;
  2566. break;
  2567. }
  2568. default:
  2569. return false; // Unreachable.
  2570. }
  2571. return true;
  2572. }
  2573. GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
  2574. switch (type) {
  2575. case CONSTANT:
  2576. return constant->get_datatype();
  2577. case VARIABLE:
  2578. return variable->get_datatype();
  2579. case PARAMETER:
  2580. return parameter->get_datatype();
  2581. case FOR_VARIABLE:
  2582. case PATTERN_BIND:
  2583. return bind->get_datatype();
  2584. case UNDEFINED:
  2585. return DataType();
  2586. }
  2587. return DataType();
  2588. }
  2589. String GDScriptParser::SuiteNode::Local::get_name() const {
  2590. String name;
  2591. switch (type) {
  2592. case SuiteNode::Local::PARAMETER:
  2593. name = "parameter";
  2594. break;
  2595. case SuiteNode::Local::CONSTANT:
  2596. name = "constant";
  2597. break;
  2598. case SuiteNode::Local::VARIABLE:
  2599. name = "variable";
  2600. break;
  2601. case SuiteNode::Local::FOR_VARIABLE:
  2602. name = "for loop iterator";
  2603. break;
  2604. case SuiteNode::Local::PATTERN_BIND:
  2605. name = "pattern_bind";
  2606. break;
  2607. case SuiteNode::Local::UNDEFINED:
  2608. name = "<undefined>";
  2609. break;
  2610. }
  2611. return name;
  2612. }
  2613. String GDScriptParser::DataType::to_string() const {
  2614. switch (kind) {
  2615. case VARIANT:
  2616. return "Variant";
  2617. case BUILTIN:
  2618. if (builtin_type == Variant::NIL) {
  2619. return "null";
  2620. }
  2621. return Variant::get_type_name(builtin_type);
  2622. case NATIVE:
  2623. if (is_meta_type) {
  2624. return GDScriptNativeClass::get_class_static();
  2625. }
  2626. return native_type.operator String();
  2627. case CLASS:
  2628. if (is_meta_type) {
  2629. return GDScript::get_class_static();
  2630. }
  2631. if (class_type->identifier != nullptr) {
  2632. return class_type->identifier->name.operator String();
  2633. }
  2634. return class_type->fqcn;
  2635. case SCRIPT: {
  2636. if (is_meta_type) {
  2637. return script_type->get_class_name().operator String();
  2638. }
  2639. String name = script_type->get_name();
  2640. if (!name.empty()) {
  2641. return name;
  2642. }
  2643. name = script_path;
  2644. if (!name.empty()) {
  2645. return name;
  2646. }
  2647. return native_type.operator String();
  2648. }
  2649. case ENUM:
  2650. return enum_type.operator String() + " (enum)";
  2651. case ENUM_VALUE:
  2652. return enum_type.operator String() + " (enum value)";
  2653. case UNRESOLVED:
  2654. return "<unresolved type>";
  2655. }
  2656. ERR_FAIL_V_MSG("<unresolved type", "Kind set outside the enum range.");
  2657. }
  2658. /*---------- PRETTY PRINT FOR DEBUG ----------*/
  2659. #ifdef DEBUG_ENABLED
  2660. void GDScriptParser::TreePrinter::increase_indent() {
  2661. indent_level++;
  2662. indent = "";
  2663. for (int i = 0; i < indent_level * 4; i++) {
  2664. if (i % 4 == 0) {
  2665. indent += "|";
  2666. } else {
  2667. indent += " ";
  2668. }
  2669. }
  2670. }
  2671. void GDScriptParser::TreePrinter::decrease_indent() {
  2672. indent_level--;
  2673. indent = "";
  2674. for (int i = 0; i < indent_level * 4; i++) {
  2675. if (i % 4 == 0) {
  2676. indent += "|";
  2677. } else {
  2678. indent += " ";
  2679. }
  2680. }
  2681. }
  2682. void GDScriptParser::TreePrinter::push_line(const String &p_line) {
  2683. if (!p_line.empty()) {
  2684. push_text(p_line);
  2685. }
  2686. printed += "\n";
  2687. pending_indent = true;
  2688. }
  2689. void GDScriptParser::TreePrinter::push_text(const String &p_text) {
  2690. if (pending_indent) {
  2691. printed += indent;
  2692. pending_indent = false;
  2693. }
  2694. printed += p_text;
  2695. }
  2696. void GDScriptParser::TreePrinter::print_annotation(AnnotationNode *p_annotation) {
  2697. push_text(p_annotation->name);
  2698. push_text(" (");
  2699. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  2700. if (i > 0) {
  2701. push_text(" , ");
  2702. }
  2703. print_expression(p_annotation->arguments[i]);
  2704. }
  2705. push_line(")");
  2706. }
  2707. void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
  2708. push_text("[ ");
  2709. for (int i = 0; i < p_array->elements.size(); i++) {
  2710. if (i > 0) {
  2711. push_text(" , ");
  2712. }
  2713. print_expression(p_array->elements[i]);
  2714. }
  2715. push_text(" ]");
  2716. }
  2717. void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
  2718. push_text("Assert ( ");
  2719. print_expression(p_assert->condition);
  2720. push_line(" )");
  2721. }
  2722. void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
  2723. switch (p_assignment->assignee->type) {
  2724. case Node::IDENTIFIER:
  2725. print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
  2726. break;
  2727. case Node::SUBSCRIPT:
  2728. print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
  2729. break;
  2730. default:
  2731. break; // Unreachable.
  2732. }
  2733. push_text(" ");
  2734. switch (p_assignment->operation) {
  2735. case AssignmentNode::OP_ADDITION:
  2736. push_text("+");
  2737. break;
  2738. case AssignmentNode::OP_SUBTRACTION:
  2739. push_text("-");
  2740. break;
  2741. case AssignmentNode::OP_MULTIPLICATION:
  2742. push_text("*");
  2743. break;
  2744. case AssignmentNode::OP_DIVISION:
  2745. push_text("/");
  2746. break;
  2747. case AssignmentNode::OP_MODULO:
  2748. push_text("%");
  2749. break;
  2750. case AssignmentNode::OP_BIT_SHIFT_LEFT:
  2751. push_text("<<");
  2752. break;
  2753. case AssignmentNode::OP_BIT_SHIFT_RIGHT:
  2754. push_text(">>");
  2755. break;
  2756. case AssignmentNode::OP_BIT_AND:
  2757. push_text("&");
  2758. break;
  2759. case AssignmentNode::OP_BIT_OR:
  2760. push_text("|");
  2761. break;
  2762. case AssignmentNode::OP_BIT_XOR:
  2763. push_text("^");
  2764. break;
  2765. case AssignmentNode::OP_NONE:
  2766. break;
  2767. }
  2768. push_text("= ");
  2769. print_expression(p_assignment->assigned_value);
  2770. push_line();
  2771. }
  2772. void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
  2773. push_text("Await ");
  2774. print_expression(p_await->to_await);
  2775. }
  2776. void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
  2777. // Surround in parenthesis for disambiguation.
  2778. push_text("(");
  2779. print_expression(p_binary_op->left_operand);
  2780. switch (p_binary_op->operation) {
  2781. case BinaryOpNode::OP_ADDITION:
  2782. push_text(" + ");
  2783. break;
  2784. case BinaryOpNode::OP_SUBTRACTION:
  2785. push_text(" - ");
  2786. break;
  2787. case BinaryOpNode::OP_MULTIPLICATION:
  2788. push_text(" * ");
  2789. break;
  2790. case BinaryOpNode::OP_DIVISION:
  2791. push_text(" / ");
  2792. break;
  2793. case BinaryOpNode::OP_MODULO:
  2794. push_text(" % ");
  2795. break;
  2796. case BinaryOpNode::OP_BIT_LEFT_SHIFT:
  2797. push_text(" << ");
  2798. break;
  2799. case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
  2800. push_text(" >> ");
  2801. break;
  2802. case BinaryOpNode::OP_BIT_AND:
  2803. push_text(" & ");
  2804. break;
  2805. case BinaryOpNode::OP_BIT_OR:
  2806. push_text(" | ");
  2807. break;
  2808. case BinaryOpNode::OP_BIT_XOR:
  2809. push_text(" ^ ");
  2810. break;
  2811. case BinaryOpNode::OP_LOGIC_AND:
  2812. push_text(" AND ");
  2813. break;
  2814. case BinaryOpNode::OP_LOGIC_OR:
  2815. push_text(" OR ");
  2816. break;
  2817. case BinaryOpNode::OP_TYPE_TEST:
  2818. push_text(" IS ");
  2819. break;
  2820. case BinaryOpNode::OP_CONTENT_TEST:
  2821. push_text(" IN ");
  2822. break;
  2823. case BinaryOpNode::OP_COMP_EQUAL:
  2824. push_text(" == ");
  2825. break;
  2826. case BinaryOpNode::OP_COMP_NOT_EQUAL:
  2827. push_text(" != ");
  2828. break;
  2829. case BinaryOpNode::OP_COMP_LESS:
  2830. push_text(" < ");
  2831. break;
  2832. case BinaryOpNode::OP_COMP_LESS_EQUAL:
  2833. push_text(" <= ");
  2834. break;
  2835. case BinaryOpNode::OP_COMP_GREATER:
  2836. push_text(" > ");
  2837. break;
  2838. case BinaryOpNode::OP_COMP_GREATER_EQUAL:
  2839. push_text(" >= ");
  2840. break;
  2841. }
  2842. print_expression(p_binary_op->right_operand);
  2843. // Surround in parenthesis for disambiguation.
  2844. push_text(")");
  2845. }
  2846. void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
  2847. if (p_call->is_super) {
  2848. push_text("super");
  2849. if (p_call->callee != nullptr) {
  2850. push_text(".");
  2851. print_expression(p_call->callee);
  2852. }
  2853. } else {
  2854. print_expression(p_call->callee);
  2855. }
  2856. push_text("( ");
  2857. for (int i = 0; i < p_call->arguments.size(); i++) {
  2858. if (i > 0) {
  2859. push_text(" , ");
  2860. }
  2861. print_expression(p_call->arguments[i]);
  2862. }
  2863. push_text(" )");
  2864. }
  2865. void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
  2866. print_expression(p_cast->operand);
  2867. push_text(" AS ");
  2868. print_type(p_cast->cast_type);
  2869. }
  2870. void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
  2871. push_text("Class ");
  2872. if (p_class->identifier == nullptr) {
  2873. push_text("<unnamed>");
  2874. } else {
  2875. print_identifier(p_class->identifier);
  2876. }
  2877. if (p_class->extends_used) {
  2878. bool first = true;
  2879. push_text(" Extends ");
  2880. if (!p_class->extends_path.empty()) {
  2881. push_text(vformat(R"("%s")", p_class->extends_path));
  2882. first = false;
  2883. }
  2884. for (int i = 0; i < p_class->extends.size(); i++) {
  2885. if (!first) {
  2886. push_text(".");
  2887. } else {
  2888. first = false;
  2889. }
  2890. push_text(p_class->extends[i]);
  2891. }
  2892. }
  2893. push_line(" :");
  2894. increase_indent();
  2895. for (int i = 0; i < p_class->members.size(); i++) {
  2896. const ClassNode::Member &m = p_class->members[i];
  2897. switch (m.type) {
  2898. case ClassNode::Member::CLASS:
  2899. print_class(m.m_class);
  2900. break;
  2901. case ClassNode::Member::VARIABLE:
  2902. print_variable(m.variable);
  2903. break;
  2904. case ClassNode::Member::CONSTANT:
  2905. print_constant(m.constant);
  2906. break;
  2907. case ClassNode::Member::SIGNAL:
  2908. print_signal(m.signal);
  2909. break;
  2910. case ClassNode::Member::FUNCTION:
  2911. print_function(m.function);
  2912. break;
  2913. case ClassNode::Member::ENUM:
  2914. print_enum(m.m_enum);
  2915. break;
  2916. case ClassNode::Member::ENUM_VALUE:
  2917. break; // Nothing. Will be printed by enum.
  2918. case ClassNode::Member::UNDEFINED:
  2919. push_line("<unknown member>");
  2920. break;
  2921. }
  2922. }
  2923. decrease_indent();
  2924. }
  2925. void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
  2926. push_text("Constant ");
  2927. print_identifier(p_constant->identifier);
  2928. increase_indent();
  2929. push_line();
  2930. push_text("= ");
  2931. if (p_constant->initializer == nullptr) {
  2932. push_text("<missing value>");
  2933. } else {
  2934. print_expression(p_constant->initializer);
  2935. }
  2936. decrease_indent();
  2937. push_line();
  2938. }
  2939. void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
  2940. push_line("{");
  2941. increase_indent();
  2942. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  2943. print_expression(p_dictionary->elements[i].key);
  2944. if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
  2945. push_text(" : ");
  2946. } else {
  2947. push_text(" = ");
  2948. }
  2949. print_expression(p_dictionary->elements[i].value);
  2950. push_line(" ,");
  2951. }
  2952. decrease_indent();
  2953. push_text("}");
  2954. }
  2955. void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
  2956. switch (p_expression->type) {
  2957. case Node::ARRAY:
  2958. print_array(static_cast<ArrayNode *>(p_expression));
  2959. break;
  2960. case Node::ASSIGNMENT:
  2961. print_assignment(static_cast<AssignmentNode *>(p_expression));
  2962. break;
  2963. case Node::AWAIT:
  2964. print_await(static_cast<AwaitNode *>(p_expression));
  2965. break;
  2966. case Node::BINARY_OPERATOR:
  2967. print_binary_op(static_cast<BinaryOpNode *>(p_expression));
  2968. break;
  2969. case Node::CALL:
  2970. print_call(static_cast<CallNode *>(p_expression));
  2971. break;
  2972. case Node::CAST:
  2973. print_cast(static_cast<CastNode *>(p_expression));
  2974. break;
  2975. case Node::DICTIONARY:
  2976. print_dictionary(static_cast<DictionaryNode *>(p_expression));
  2977. break;
  2978. case Node::GET_NODE:
  2979. print_get_node(static_cast<GetNodeNode *>(p_expression));
  2980. break;
  2981. case Node::IDENTIFIER:
  2982. print_identifier(static_cast<IdentifierNode *>(p_expression));
  2983. break;
  2984. case Node::LITERAL:
  2985. print_literal(static_cast<LiteralNode *>(p_expression));
  2986. break;
  2987. case Node::PRELOAD:
  2988. print_preload(static_cast<PreloadNode *>(p_expression));
  2989. break;
  2990. case Node::SELF:
  2991. print_self(static_cast<SelfNode *>(p_expression));
  2992. break;
  2993. case Node::SUBSCRIPT:
  2994. print_subscript(static_cast<SubscriptNode *>(p_expression));
  2995. break;
  2996. case Node::TERNARY_OPERATOR:
  2997. print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
  2998. break;
  2999. case Node::UNARY_OPERATOR:
  3000. print_unary_op(static_cast<UnaryOpNode *>(p_expression));
  3001. break;
  3002. default:
  3003. push_text(vformat("<unknown expression %d>", p_expression->type));
  3004. break;
  3005. }
  3006. }
  3007. void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
  3008. push_text("Enum ");
  3009. if (p_enum->identifier != nullptr) {
  3010. print_identifier(p_enum->identifier);
  3011. } else {
  3012. push_text("<unnamed>");
  3013. }
  3014. push_line(" {");
  3015. increase_indent();
  3016. for (int i = 0; i < p_enum->values.size(); i++) {
  3017. const EnumNode::Value &item = p_enum->values[i];
  3018. print_identifier(item.identifier);
  3019. push_text(" = ");
  3020. push_text(itos(item.value));
  3021. push_line(" ,");
  3022. }
  3023. decrease_indent();
  3024. push_line("}");
  3025. }
  3026. void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
  3027. push_text("For ");
  3028. print_identifier(p_for->variable);
  3029. push_text(" IN ");
  3030. print_expression(p_for->list);
  3031. push_line(" :");
  3032. increase_indent();
  3033. print_suite(p_for->loop);
  3034. decrease_indent();
  3035. }
  3036. void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function) {
  3037. for (const List<AnnotationNode *>::Element *E = p_function->annotations.front(); E != nullptr; E = E->next()) {
  3038. print_annotation(E->get());
  3039. }
  3040. push_text("Function ");
  3041. print_identifier(p_function->identifier);
  3042. push_text("( ");
  3043. for (int i = 0; i < p_function->parameters.size(); i++) {
  3044. if (i > 0) {
  3045. push_text(" , ");
  3046. }
  3047. print_parameter(p_function->parameters[i]);
  3048. }
  3049. push_line(" ) :");
  3050. increase_indent();
  3051. print_suite(p_function->body);
  3052. decrease_indent();
  3053. }
  3054. void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
  3055. push_text("$");
  3056. if (p_get_node->string != nullptr) {
  3057. print_literal(p_get_node->string);
  3058. } else {
  3059. for (int i = 0; i < p_get_node->chain.size(); i++) {
  3060. if (i > 0) {
  3061. push_text("/");
  3062. }
  3063. print_identifier(p_get_node->chain[i]);
  3064. }
  3065. }
  3066. }
  3067. void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
  3068. push_text(p_identifier->name);
  3069. }
  3070. void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
  3071. if (p_is_elif) {
  3072. push_text("Elif ");
  3073. } else {
  3074. push_text("If ");
  3075. }
  3076. print_expression(p_if->condition);
  3077. push_line(" :");
  3078. increase_indent();
  3079. print_suite(p_if->true_block);
  3080. decrease_indent();
  3081. // FIXME: Properly detect "elif" blocks.
  3082. if (p_if->false_block != nullptr) {
  3083. push_line("Else :");
  3084. increase_indent();
  3085. print_suite(p_if->false_block);
  3086. decrease_indent();
  3087. }
  3088. }
  3089. void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
  3090. // Prefix for string types.
  3091. switch (p_literal->value.get_type()) {
  3092. case Variant::NODE_PATH:
  3093. push_text("^\"");
  3094. break;
  3095. case Variant::STRING:
  3096. push_text("\"");
  3097. break;
  3098. case Variant::STRING_NAME:
  3099. push_text("&\"");
  3100. break;
  3101. default:
  3102. break;
  3103. }
  3104. push_text(p_literal->value);
  3105. // Suffix for string types.
  3106. switch (p_literal->value.get_type()) {
  3107. case Variant::NODE_PATH:
  3108. case Variant::STRING:
  3109. case Variant::STRING_NAME:
  3110. push_text("\"");
  3111. break;
  3112. default:
  3113. break;
  3114. }
  3115. }
  3116. void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
  3117. push_text("Match ");
  3118. print_expression(p_match->test);
  3119. push_line(" :");
  3120. increase_indent();
  3121. for (int i = 0; i < p_match->branches.size(); i++) {
  3122. print_match_branch(p_match->branches[i]);
  3123. }
  3124. decrease_indent();
  3125. }
  3126. void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
  3127. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  3128. if (i > 0) {
  3129. push_text(" , ");
  3130. }
  3131. print_match_pattern(p_match_branch->patterns[i]);
  3132. }
  3133. push_line(" :");
  3134. increase_indent();
  3135. print_suite(p_match_branch->block);
  3136. decrease_indent();
  3137. }
  3138. void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
  3139. switch (p_match_pattern->pattern_type) {
  3140. case PatternNode::PT_LITERAL:
  3141. print_literal(p_match_pattern->literal);
  3142. break;
  3143. case PatternNode::PT_WILDCARD:
  3144. push_text("_");
  3145. break;
  3146. case PatternNode::PT_REST:
  3147. push_text("..");
  3148. break;
  3149. case PatternNode::PT_BIND:
  3150. push_text("Var ");
  3151. print_identifier(p_match_pattern->bind);
  3152. break;
  3153. case PatternNode::PT_EXPRESSION:
  3154. print_expression(p_match_pattern->expression);
  3155. break;
  3156. case PatternNode::PT_ARRAY:
  3157. push_text("[ ");
  3158. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  3159. if (i > 0) {
  3160. push_text(" , ");
  3161. }
  3162. print_match_pattern(p_match_pattern->array[i]);
  3163. }
  3164. push_text(" ]");
  3165. break;
  3166. case PatternNode::PT_DICTIONARY:
  3167. push_text("{ ");
  3168. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  3169. if (i > 0) {
  3170. push_text(" , ");
  3171. }
  3172. if (p_match_pattern->dictionary[i].key != nullptr) {
  3173. // Key can be null for rest pattern.
  3174. print_expression(p_match_pattern->dictionary[i].key);
  3175. push_text(" : ");
  3176. }
  3177. print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
  3178. }
  3179. push_text(" }");
  3180. break;
  3181. }
  3182. }
  3183. void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
  3184. print_identifier(p_parameter->identifier);
  3185. if (p_parameter->datatype_specifier != nullptr) {
  3186. push_text(" : ");
  3187. print_type(p_parameter->datatype_specifier);
  3188. }
  3189. if (p_parameter->default_value != nullptr) {
  3190. push_text(" = ");
  3191. print_expression(p_parameter->default_value);
  3192. }
  3193. }
  3194. void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
  3195. push_text(R"(Preload ( ")");
  3196. push_text(p_preload->resolved_path);
  3197. push_text(R"(" )");
  3198. }
  3199. void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
  3200. push_text("Return");
  3201. if (p_return->return_value != nullptr) {
  3202. push_text(" ");
  3203. print_expression(p_return->return_value);
  3204. }
  3205. push_line();
  3206. }
  3207. void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
  3208. push_text("Self(");
  3209. if (p_self->current_class->identifier != nullptr) {
  3210. print_identifier(p_self->current_class->identifier);
  3211. } else {
  3212. push_text("<main class>");
  3213. }
  3214. push_text(")");
  3215. }
  3216. void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
  3217. push_text("Signal ");
  3218. print_identifier(p_signal->identifier);
  3219. push_text("( ");
  3220. for (int i = 0; i < p_signal->parameters.size(); i++) {
  3221. print_parameter(p_signal->parameters[i]);
  3222. }
  3223. push_line(" )");
  3224. }
  3225. void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
  3226. print_expression(p_subscript->base);
  3227. if (p_subscript->is_attribute) {
  3228. push_text(".");
  3229. print_identifier(p_subscript->attribute);
  3230. } else {
  3231. push_text("[ ");
  3232. print_expression(p_subscript->index);
  3233. push_text(" ]");
  3234. }
  3235. }
  3236. void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
  3237. switch (p_statement->type) {
  3238. case Node::ASSERT:
  3239. print_assert(static_cast<AssertNode *>(p_statement));
  3240. break;
  3241. case Node::VARIABLE:
  3242. print_variable(static_cast<VariableNode *>(p_statement));
  3243. break;
  3244. case Node::CONSTANT:
  3245. print_constant(static_cast<ConstantNode *>(p_statement));
  3246. break;
  3247. case Node::IF:
  3248. print_if(static_cast<IfNode *>(p_statement));
  3249. break;
  3250. case Node::FOR:
  3251. print_for(static_cast<ForNode *>(p_statement));
  3252. break;
  3253. case Node::WHILE:
  3254. print_while(static_cast<WhileNode *>(p_statement));
  3255. break;
  3256. case Node::MATCH:
  3257. print_match(static_cast<MatchNode *>(p_statement));
  3258. break;
  3259. case Node::RETURN:
  3260. print_return(static_cast<ReturnNode *>(p_statement));
  3261. break;
  3262. case Node::BREAK:
  3263. push_line("Break");
  3264. break;
  3265. case Node::CONTINUE:
  3266. push_line("Continue");
  3267. break;
  3268. case Node::PASS:
  3269. push_line("Pass");
  3270. break;
  3271. case Node::BREAKPOINT:
  3272. push_line("Breakpoint");
  3273. break;
  3274. case Node::ASSIGNMENT:
  3275. print_assignment(static_cast<AssignmentNode *>(p_statement));
  3276. break;
  3277. default:
  3278. if (p_statement->is_expression()) {
  3279. print_expression(static_cast<ExpressionNode *>(p_statement));
  3280. push_line();
  3281. } else {
  3282. push_line(vformat("<unknown statement %d>", p_statement->type));
  3283. }
  3284. break;
  3285. }
  3286. }
  3287. void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
  3288. for (int i = 0; i < p_suite->statements.size(); i++) {
  3289. print_statement(p_suite->statements[i]);
  3290. }
  3291. }
  3292. void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
  3293. // Surround in parenthesis for disambiguation.
  3294. push_text("(");
  3295. print_expression(p_ternary_op->true_expr);
  3296. push_text(") IF (");
  3297. print_expression(p_ternary_op->condition);
  3298. push_text(") ELSE (");
  3299. print_expression(p_ternary_op->false_expr);
  3300. push_text(")");
  3301. }
  3302. void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
  3303. if (p_type->type_chain.empty()) {
  3304. push_text("Void");
  3305. } else {
  3306. for (int i = 0; i < p_type->type_chain.size(); i++) {
  3307. if (i > 0) {
  3308. push_text(".");
  3309. }
  3310. print_identifier(p_type->type_chain[i]);
  3311. }
  3312. }
  3313. }
  3314. void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
  3315. // Surround in parenthesis for disambiguation.
  3316. push_text("(");
  3317. switch (p_unary_op->operation) {
  3318. case UnaryOpNode::OP_POSITIVE:
  3319. push_text("+");
  3320. break;
  3321. case UnaryOpNode::OP_NEGATIVE:
  3322. push_text("-");
  3323. break;
  3324. case UnaryOpNode::OP_LOGIC_NOT:
  3325. push_text("NOT");
  3326. break;
  3327. case UnaryOpNode::OP_COMPLEMENT:
  3328. push_text("~");
  3329. break;
  3330. }
  3331. print_expression(p_unary_op->operand);
  3332. // Surround in parenthesis for disambiguation.
  3333. push_text(")");
  3334. }
  3335. void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
  3336. for (const List<AnnotationNode *>::Element *E = p_variable->annotations.front(); E != nullptr; E = E->next()) {
  3337. print_annotation(E->get());
  3338. }
  3339. push_text("Variable ");
  3340. print_identifier(p_variable->identifier);
  3341. push_text(" : ");
  3342. if (p_variable->datatype_specifier != nullptr) {
  3343. print_type(p_variable->datatype_specifier);
  3344. } else if (p_variable->infer_datatype) {
  3345. push_text("<inferred type>");
  3346. } else {
  3347. push_text("Variant");
  3348. }
  3349. increase_indent();
  3350. push_line();
  3351. push_text("= ");
  3352. if (p_variable->initializer == nullptr) {
  3353. push_text("<default value>");
  3354. } else {
  3355. print_expression(p_variable->initializer);
  3356. }
  3357. push_line();
  3358. if (p_variable->property != VariableNode::PROP_NONE) {
  3359. if (p_variable->getter != nullptr) {
  3360. push_text("Get");
  3361. if (p_variable->property == VariableNode::PROP_INLINE) {
  3362. push_line(":");
  3363. increase_indent();
  3364. print_suite(p_variable->getter);
  3365. decrease_indent();
  3366. } else {
  3367. push_line(" =");
  3368. increase_indent();
  3369. print_identifier(p_variable->getter_pointer);
  3370. push_line();
  3371. decrease_indent();
  3372. }
  3373. }
  3374. if (p_variable->setter != nullptr) {
  3375. push_text("Set (");
  3376. if (p_variable->property == VariableNode::PROP_INLINE) {
  3377. if (p_variable->setter_parameter != nullptr) {
  3378. print_identifier(p_variable->setter_parameter);
  3379. } else {
  3380. push_text("<missing>");
  3381. }
  3382. push_line("):");
  3383. increase_indent();
  3384. print_suite(p_variable->setter);
  3385. decrease_indent();
  3386. } else {
  3387. push_line(" =");
  3388. increase_indent();
  3389. print_identifier(p_variable->setter_pointer);
  3390. push_line();
  3391. decrease_indent();
  3392. }
  3393. }
  3394. }
  3395. decrease_indent();
  3396. push_line();
  3397. }
  3398. void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
  3399. push_text("While ");
  3400. print_expression(p_while->condition);
  3401. push_line(" :");
  3402. increase_indent();
  3403. print_suite(p_while->loop);
  3404. decrease_indent();
  3405. }
  3406. void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
  3407. ERR_FAIL_COND_MSG(p_parser.get_tree() == nullptr, "Parse the code before printing the parse tree.");
  3408. if (p_parser.is_tool()) {
  3409. push_line("@tool");
  3410. }
  3411. if (!p_parser.get_tree()->icon_path.empty()) {
  3412. push_text(R"(@icon (")");
  3413. push_text(p_parser.get_tree()->icon_path);
  3414. push_line("\")");
  3415. }
  3416. print_class(p_parser.get_tree());
  3417. print_line(printed);
  3418. }
  3419. #endif // DEBUG_ENABLED