gdscript_parser.cpp 170 KB

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