gdscript_parser.cpp 185 KB

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