2
0

gdscript_parser.cpp 139 KB

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