gdscript_parser.cpp 178 KB

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