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