gdscript_parser.cpp 167 KB

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