gdscript_parser.cpp 189 KB

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