gdscript_parser.cpp 179 KB

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