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