gdscript_parser.cpp 187 KB

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