gdscript_parser.cpp 188 KB

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