gdscript_parser.cpp 221 KB

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