2
0

gdscript_parser.cpp 173 KB

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