gdscript_parser.cpp 161 KB

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