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