gdscript_parser.cpp 182 KB

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