gdscript_parser.cpp 130 KB

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