gdscript_parser.cpp 170 KB

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