gdscript_parser.cpp 129 KB

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