gdscript_parser.cpp 147 KB

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