gdscript_parser.cpp 167 KB

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