gdscript_parser.cpp 138 KB

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