gdscript_parser.cpp 150 KB

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