gdscript_parser.cpp 146 KB

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