gdscript_parser.cpp 130 KB

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