gdscript_parser.cpp 130 KB

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