gdscript_parser.cpp 158 KB

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