gdscript_parser.cpp 156 KB

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