gdscript_parser.cpp 138 KB

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