gdscript_parser.cpp 130 KB

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