gdscript_parser.cpp 129 KB

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