Parser.cpp 346 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, the SerenityOS developers.
  4. * Copyright (c) 2021-2024, Sam Atkins <sam@ladybird.org>
  5. * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
  6. * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
  7. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  8. * Copyright (c) 2024, Tommy van der Vorst <tommy@pixelspark.nl>
  9. * Copyright (c) 2024, Matthew Olsson <mattco@serenityos.org>
  10. *
  11. * SPDX-License-Identifier: BSD-2-Clause
  12. */
  13. #include <AK/CharacterTypes.h>
  14. #include <AK/Debug.h>
  15. #include <AK/GenericLexer.h>
  16. #include <AK/SourceLocation.h>
  17. #include <AK/TemporaryChange.h>
  18. #include <LibWeb/CSS/CSSFontFaceRule.h>
  19. #include <LibWeb/CSS/CSSImportRule.h>
  20. #include <LibWeb/CSS/CSSKeyframeRule.h>
  21. #include <LibWeb/CSS/CSSKeyframesRule.h>
  22. #include <LibWeb/CSS/CSSMediaRule.h>
  23. #include <LibWeb/CSS/CSSNamespaceRule.h>
  24. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  25. #include <LibWeb/CSS/CSSStyleRule.h>
  26. #include <LibWeb/CSS/CSSStyleSheet.h>
  27. #include <LibWeb/CSS/CSSStyleValue.h>
  28. #include <LibWeb/CSS/CSSSupportsRule.h>
  29. #include <LibWeb/CSS/CalculatedOr.h>
  30. #include <LibWeb/CSS/EdgeRect.h>
  31. #include <LibWeb/CSS/MediaList.h>
  32. #include <LibWeb/CSS/Parser/Block.h>
  33. #include <LibWeb/CSS/Parser/ComponentValue.h>
  34. #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
  35. #include <LibWeb/CSS/Parser/Function.h>
  36. #include <LibWeb/CSS/Parser/Parser.h>
  37. #include <LibWeb/CSS/Parser/Rule.h>
  38. #include <LibWeb/CSS/Selector.h>
  39. #include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
  40. #include <LibWeb/CSS/StyleValues/BackgroundRepeatStyleValue.h>
  41. #include <LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h>
  42. #include <LibWeb/CSS/StyleValues/BasicShapeStyleValue.h>
  43. #include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h>
  44. #include <LibWeb/CSS/StyleValues/CSSColorValue.h>
  45. #include <LibWeb/CSS/StyleValues/CSSHSL.h>
  46. #include <LibWeb/CSS/StyleValues/CSSHWB.h>
  47. #include <LibWeb/CSS/StyleValues/CSSKeywordValue.h>
  48. #include <LibWeb/CSS/StyleValues/CSSOKLCH.h>
  49. #include <LibWeb/CSS/StyleValues/CSSOKLab.h>
  50. #include <LibWeb/CSS/StyleValues/CSSRGB.h>
  51. #include <LibWeb/CSS/StyleValues/ContentStyleValue.h>
  52. #include <LibWeb/CSS/StyleValues/CounterDefinitionsStyleValue.h>
  53. #include <LibWeb/CSS/StyleValues/CounterStyleValue.h>
  54. #include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
  55. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  56. #include <LibWeb/CSS/StyleValues/EasingStyleValue.h>
  57. #include <LibWeb/CSS/StyleValues/EdgeStyleValue.h>
  58. #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h>
  59. #include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
  60. #include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
  61. #include <LibWeb/CSS/StyleValues/GridAutoFlowStyleValue.h>
  62. #include <LibWeb/CSS/StyleValues/GridTemplateAreaStyleValue.h>
  63. #include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
  64. #include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
  65. #include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
  66. #include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
  67. #include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
  68. #include <LibWeb/CSS/StyleValues/MathDepthStyleValue.h>
  69. #include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
  70. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  71. #include <LibWeb/CSS/StyleValues/PositionStyleValue.h>
  72. #include <LibWeb/CSS/StyleValues/RatioStyleValue.h>
  73. #include <LibWeb/CSS/StyleValues/RectStyleValue.h>
  74. #include <LibWeb/CSS/StyleValues/ResolutionStyleValue.h>
  75. #include <LibWeb/CSS/StyleValues/ScrollbarGutterStyleValue.h>
  76. #include <LibWeb/CSS/StyleValues/ShadowStyleValue.h>
  77. #include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>
  78. #include <LibWeb/CSS/StyleValues/StringStyleValue.h>
  79. #include <LibWeb/CSS/StyleValues/StyleValueList.h>
  80. #include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
  81. #include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
  82. #include <LibWeb/CSS/StyleValues/TransitionStyleValue.h>
  83. #include <LibWeb/CSS/StyleValues/URLStyleValue.h>
  84. #include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
  85. #include <LibWeb/Dump.h>
  86. #include <LibWeb/Infra/CharacterTypes.h>
  87. #include <LibWeb/Infra/Strings.h>
  88. static void log_parse_error(SourceLocation const& location = SourceLocation::current())
  89. {
  90. dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
  91. }
  92. namespace Web::CSS::Parser {
  93. Parser Parser::create(ParsingContext const& context, StringView input, StringView encoding)
  94. {
  95. auto tokens = Tokenizer::tokenize(input, encoding);
  96. return Parser { context, move(tokens) };
  97. }
  98. Parser::Parser(ParsingContext const& context, Vector<Token> tokens)
  99. : m_context(context)
  100. , m_tokens(move(tokens))
  101. , m_token_stream(m_tokens)
  102. {
  103. }
  104. Parser::Parser(Parser&& other)
  105. : m_context(other.m_context)
  106. , m_tokens(move(other.m_tokens))
  107. , m_token_stream(m_tokens)
  108. {
  109. // Moving the TokenStream directly from `other` would break it, because TokenStream holds
  110. // a reference to the Vector<Token>, so it would be pointing at the old Parser's tokens.
  111. // So instead, we create a new TokenStream from this Parser's tokens, and then tell it to
  112. // copy the other TokenStream's state. This is quite hacky.
  113. m_token_stream.copy_state({}, other.m_token_stream);
  114. }
  115. // 5.3.3. Parse a stylesheet
  116. // https://www.w3.org/TR/css-syntax-3/#parse-stylesheet
  117. template<typename T>
  118. Parser::ParsedStyleSheet Parser::parse_a_stylesheet(TokenStream<T>& tokens, Optional<URL::URL> location)
  119. {
  120. // To parse a stylesheet from an input given an optional url location:
  121. // 1. If input is a byte stream for stylesheet, decode bytes from input, and set input to the result.
  122. // 2. Normalize input, and set input to the result.
  123. // NOTE: These are done automatically when creating the Parser.
  124. // 3. Create a new stylesheet, with its location set to location (or null, if location was not passed).
  125. ParsedStyleSheet style_sheet;
  126. style_sheet.location = move(location);
  127. // 4. Consume a list of rules from input, with the top-level flag set, and set the stylesheet’s value to the result.
  128. style_sheet.rules = consume_a_list_of_rules(tokens, TopLevel::Yes);
  129. // 5. Return the stylesheet.
  130. return style_sheet;
  131. }
  132. // https://www.w3.org/TR/css-syntax-3/#parse-a-css-stylesheet
  133. CSSStyleSheet* Parser::parse_as_css_stylesheet(Optional<URL::URL> location)
  134. {
  135. // To parse a CSS stylesheet, first parse a stylesheet.
  136. auto style_sheet = parse_a_stylesheet(m_token_stream, {});
  137. // Interpret all of the resulting top-level qualified rules as style rules, defined below.
  138. JS::MarkedVector<CSSRule*> rules(m_context.realm().heap());
  139. for (auto& raw_rule : style_sheet.rules) {
  140. auto rule = convert_to_rule(raw_rule);
  141. // If any style rule is invalid, or any at-rule is not recognized or is invalid according to its grammar or context, it’s a parse error. Discard that rule.
  142. if (rule)
  143. rules.append(rule);
  144. }
  145. auto rule_list = CSSRuleList::create(m_context.realm(), rules);
  146. auto media_list = MediaList::create(m_context.realm(), {});
  147. return CSSStyleSheet::create(m_context.realm(), rule_list, media_list, move(location));
  148. }
  149. RefPtr<Supports> Parser::parse_as_supports()
  150. {
  151. return parse_a_supports(m_token_stream);
  152. }
  153. template<typename T>
  154. RefPtr<Supports> Parser::parse_a_supports(TokenStream<T>& tokens)
  155. {
  156. auto component_values = parse_a_list_of_component_values(tokens);
  157. TokenStream<ComponentValue> token_stream { component_values };
  158. auto maybe_condition = parse_supports_condition(token_stream);
  159. token_stream.skip_whitespace();
  160. if (maybe_condition && !token_stream.has_next_token())
  161. return Supports::create(m_context.realm(), maybe_condition.release_nonnull());
  162. return {};
  163. }
  164. OwnPtr<Supports::Condition> Parser::parse_supports_condition(TokenStream<ComponentValue>& tokens)
  165. {
  166. auto transaction = tokens.begin_transaction();
  167. tokens.skip_whitespace();
  168. auto const& peeked_token = tokens.peek_token();
  169. // `not <supports-in-parens>`
  170. if (peeked_token.is_ident("not"sv)) {
  171. tokens.next_token();
  172. tokens.skip_whitespace();
  173. auto child = parse_supports_in_parens(tokens);
  174. if (!child.has_value())
  175. return {};
  176. transaction.commit();
  177. auto condition = make<Supports::Condition>();
  178. condition->type = Supports::Condition::Type::Not;
  179. condition->children.append(child.release_value());
  180. return condition;
  181. }
  182. // ` <supports-in-parens> [ and <supports-in-parens> ]*
  183. // | <supports-in-parens> [ or <supports-in-parens> ]*`
  184. Vector<Supports::InParens> children;
  185. Optional<Supports::Condition::Type> condition_type {};
  186. auto as_condition_type = [](auto& token) -> Optional<Supports::Condition::Type> {
  187. if (!token.is(Token::Type::Ident))
  188. return {};
  189. auto ident = token.token().ident();
  190. if (ident.equals_ignoring_ascii_case("and"sv))
  191. return Supports::Condition::Type::And;
  192. if (ident.equals_ignoring_ascii_case("or"sv))
  193. return Supports::Condition::Type::Or;
  194. return {};
  195. };
  196. while (tokens.has_next_token()) {
  197. if (!children.is_empty()) {
  198. // Expect `and` or `or` here
  199. auto maybe_combination = as_condition_type(tokens.next_token());
  200. if (!maybe_combination.has_value())
  201. return {};
  202. if (!condition_type.has_value()) {
  203. condition_type = maybe_combination.value();
  204. } else if (maybe_combination != condition_type) {
  205. return {};
  206. }
  207. }
  208. tokens.skip_whitespace();
  209. if (auto in_parens = parse_supports_in_parens(tokens); in_parens.has_value()) {
  210. children.append(in_parens.release_value());
  211. } else {
  212. return {};
  213. }
  214. tokens.skip_whitespace();
  215. }
  216. if (children.is_empty())
  217. return {};
  218. transaction.commit();
  219. auto condition = make<Supports::Condition>();
  220. condition->type = condition_type.value_or(Supports::Condition::Type::Or);
  221. condition->children = move(children);
  222. return condition;
  223. }
  224. Optional<Supports::InParens> Parser::parse_supports_in_parens(TokenStream<ComponentValue>& tokens)
  225. {
  226. // `( <supports-condition> )`
  227. auto const& first_token = tokens.peek_token();
  228. if (first_token.is_block() && first_token.block().is_paren()) {
  229. auto transaction = tokens.begin_transaction();
  230. tokens.next_token();
  231. tokens.skip_whitespace();
  232. TokenStream child_tokens { first_token.block().values() };
  233. if (auto condition = parse_supports_condition(child_tokens)) {
  234. if (child_tokens.has_next_token())
  235. return {};
  236. transaction.commit();
  237. return Supports::InParens {
  238. .value = { condition.release_nonnull() }
  239. };
  240. }
  241. }
  242. // `<supports-feature>`
  243. if (auto feature = parse_supports_feature(tokens); feature.has_value()) {
  244. return Supports::InParens {
  245. .value = { feature.release_value() }
  246. };
  247. }
  248. // `<general-enclosed>`
  249. if (auto general_enclosed = parse_general_enclosed(tokens); general_enclosed.has_value()) {
  250. return Supports::InParens {
  251. .value = general_enclosed.release_value()
  252. };
  253. }
  254. return {};
  255. }
  256. Optional<Supports::Feature> Parser::parse_supports_feature(TokenStream<ComponentValue>& tokens)
  257. {
  258. auto transaction = tokens.begin_transaction();
  259. tokens.skip_whitespace();
  260. auto const& first_token = tokens.next_token();
  261. // `<supports-decl>`
  262. if (first_token.is_block() && first_token.block().is_paren()) {
  263. TokenStream block_tokens { first_token.block().values() };
  264. // FIXME: Parsing and then converting back to a string is weird.
  265. if (auto declaration = consume_a_declaration(block_tokens); declaration.has_value()) {
  266. transaction.commit();
  267. return Supports::Feature {
  268. Supports::Declaration { declaration->to_string() }
  269. };
  270. }
  271. }
  272. // `<supports-selector-fn>`
  273. if (first_token.is_function("selector"sv)) {
  274. // FIXME: Parsing and then converting back to a string is weird.
  275. StringBuilder builder;
  276. for (auto const& item : first_token.function().values())
  277. builder.append(item.to_string());
  278. transaction.commit();
  279. return Supports::Feature {
  280. Supports::Selector { builder.to_string().release_value_but_fixme_should_propagate_errors() }
  281. };
  282. }
  283. return {};
  284. }
  285. // https://www.w3.org/TR/mediaqueries-4/#typedef-general-enclosed
  286. Optional<GeneralEnclosed> Parser::parse_general_enclosed(TokenStream<ComponentValue>& tokens)
  287. {
  288. auto transaction = tokens.begin_transaction();
  289. tokens.skip_whitespace();
  290. auto const& first_token = tokens.next_token();
  291. // `[ <function-token> <any-value>? ) ]`
  292. if (first_token.is_function()) {
  293. transaction.commit();
  294. return GeneralEnclosed { first_token.to_string() };
  295. }
  296. // `( <any-value>? )`
  297. if (first_token.is_block() && first_token.block().is_paren()) {
  298. transaction.commit();
  299. return GeneralEnclosed { first_token.to_string() };
  300. }
  301. return {};
  302. }
  303. // 5.4.1. Consume a list of rules
  304. // https://www.w3.org/TR/css-syntax-3/#consume-list-of-rules
  305. template<typename T>
  306. Vector<NonnullRefPtr<Rule>> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, TopLevel top_level)
  307. {
  308. // To consume a list of rules, given a top-level flag:
  309. // Create an initially empty list of rules.
  310. Vector<NonnullRefPtr<Rule>> rules;
  311. // Repeatedly consume the next input token:
  312. for (;;) {
  313. auto& token = tokens.next_token();
  314. // <whitespace-token>
  315. if (token.is(Token::Type::Whitespace)) {
  316. // Do nothing.
  317. continue;
  318. }
  319. // <EOF-token>
  320. if (token.is(Token::Type::EndOfFile)) {
  321. // Return the list of rules.
  322. return rules;
  323. }
  324. // <CDO-token>
  325. // <CDC-token>
  326. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  327. // If the top-level flag is set, do nothing.
  328. if (top_level == TopLevel::Yes)
  329. continue;
  330. // Otherwise, reconsume the current input token.
  331. tokens.reconsume_current_input_token();
  332. // Consume a qualified rule. If anything is returned, append it to the list of rules.
  333. if (auto maybe_qualified = consume_a_qualified_rule(tokens))
  334. rules.append(maybe_qualified.release_nonnull());
  335. continue;
  336. }
  337. // <at-keyword-token>
  338. if (token.is(Token::Type::AtKeyword)) {
  339. // Reconsume the current input token.
  340. tokens.reconsume_current_input_token();
  341. // Consume an at-rule, and append the returned value to the list of rules.
  342. rules.append(consume_an_at_rule(tokens));
  343. continue;
  344. }
  345. // anything else
  346. {
  347. // Reconsume the current input token.
  348. tokens.reconsume_current_input_token();
  349. // Consume a qualified rule. If anything is returned, append it to the list of rules.
  350. if (auto maybe_qualified = consume_a_qualified_rule(tokens))
  351. rules.append(maybe_qualified.release_nonnull());
  352. continue;
  353. }
  354. }
  355. }
  356. // 5.4.2. Consume an at-rule
  357. // https://www.w3.org/TR/css-syntax-3/#consume-at-rule
  358. template<typename T>
  359. NonnullRefPtr<Rule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  360. {
  361. // To consume an at-rule:
  362. // Consume the next input token.
  363. auto& name_ident = tokens.next_token();
  364. VERIFY(name_ident.is(Token::Type::AtKeyword));
  365. // Create a new at-rule with its name set to the value of the current input token, its prelude initially set to an empty list, and its value initially set to nothing.
  366. // NOTE: We create the Rule fully initialized when we return it instead.
  367. auto at_rule_name = ((Token)name_ident).at_keyword();
  368. Vector<ComponentValue> prelude;
  369. RefPtr<Block> block;
  370. // Repeatedly consume the next input token:
  371. for (;;) {
  372. auto& token = tokens.next_token();
  373. // <semicolon-token>
  374. if (token.is(Token::Type::Semicolon)) {
  375. // Return the at-rule.
  376. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  377. }
  378. // <EOF-token>
  379. if (token.is(Token::Type::EndOfFile)) {
  380. // This is a parse error. Return the at-rule.
  381. log_parse_error();
  382. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  383. }
  384. // <{-token>
  385. if (token.is(Token::Type::OpenCurly)) {
  386. // Consume a simple block and assign it to the at-rule’s block. Return the at-rule.
  387. block = consume_a_simple_block(tokens);
  388. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  389. }
  390. // simple block with an associated token of <{-token>
  391. if constexpr (IsSame<T, ComponentValue>) {
  392. ComponentValue const& component_value = token;
  393. if (component_value.is_block() && component_value.block().is_curly()) {
  394. // Assign the block to the at-rule’s block. Return the at-rule.
  395. block = component_value.block();
  396. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  397. }
  398. }
  399. // anything else
  400. {
  401. // Reconsume the current input token.
  402. tokens.reconsume_current_input_token();
  403. // Consume a component value. Append the returned value to the at-rule’s prelude.
  404. prelude.append(consume_a_component_value(tokens));
  405. }
  406. }
  407. }
  408. // 5.4.3. Consume a qualified rule
  409. // https://www.w3.org/TR/css-syntax-3/#consume-qualified-rule
  410. template<typename T>
  411. RefPtr<Rule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  412. {
  413. // To consume a qualified rule:
  414. // Create a new qualified rule with its prelude initially set to an empty list, and its value initially set to nothing.
  415. // NOTE: We create the Rule fully initialized when we return it instead.
  416. Vector<ComponentValue> prelude;
  417. RefPtr<Block> block;
  418. // Repeatedly consume the next input token:
  419. for (;;) {
  420. auto& token = tokens.next_token();
  421. // <EOF-token>
  422. if (token.is(Token::Type::EndOfFile)) {
  423. // This is a parse error. Return nothing.
  424. log_parse_error();
  425. return {};
  426. }
  427. // <{-token>
  428. if (token.is(Token::Type::OpenCurly)) {
  429. // Consume a simple block and assign it to the qualified rule’s block. Return the qualified rule.
  430. block = consume_a_simple_block(tokens);
  431. return Rule::make_qualified_rule(move(prelude), move(block));
  432. }
  433. // simple block with an associated token of <{-token>
  434. if constexpr (IsSame<T, ComponentValue>) {
  435. ComponentValue const& component_value = token;
  436. if (component_value.is_block() && component_value.block().is_curly()) {
  437. // Assign the block to the qualified rule’s block. Return the qualified rule.
  438. block = component_value.block();
  439. return Rule::make_qualified_rule(move(prelude), move(block));
  440. }
  441. }
  442. // anything else
  443. {
  444. // Reconsume the current input token.
  445. tokens.reconsume_current_input_token();
  446. // Consume a component value. Append the returned value to the qualified rule’s prelude.
  447. prelude.append(consume_a_component_value(tokens));
  448. }
  449. }
  450. }
  451. // 5.4.4. Consume a style block’s contents
  452. // https://www.w3.org/TR/css-syntax-3/#consume-a-style-blocks-contents
  453. template<typename T>
  454. Vector<DeclarationOrAtRule> Parser::consume_a_style_blocks_contents(TokenStream<T>& tokens)
  455. {
  456. // To consume a style block’s contents:
  457. // Create an initially empty list of declarations decls, and an initially empty list of rules rules.
  458. Vector<DeclarationOrAtRule> declarations;
  459. Vector<DeclarationOrAtRule> rules;
  460. // Repeatedly consume the next input token:
  461. for (;;) {
  462. auto& token = tokens.next_token();
  463. // <whitespace-token>
  464. // <semicolon-token>
  465. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  466. // Do nothing.
  467. continue;
  468. }
  469. // <EOF-token>
  470. if (token.is(Token::Type::EndOfFile)) {
  471. // Extend decls with rules, then return decls.
  472. declarations.extend(move(rules));
  473. return declarations;
  474. }
  475. // <at-keyword-token>
  476. if (token.is(Token::Type::AtKeyword)) {
  477. // Reconsume the current input token.
  478. tokens.reconsume_current_input_token();
  479. // Consume an at-rule, and append the result to rules.
  480. rules.empend(consume_an_at_rule(tokens));
  481. continue;
  482. }
  483. // <ident-token>
  484. if (token.is(Token::Type::Ident)) {
  485. // Initialize a temporary list initially filled with the current input token.
  486. Vector<ComponentValue> temporary_list;
  487. temporary_list.append(token);
  488. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  489. // consume a component value and append it to the temporary list.
  490. for (;;) {
  491. auto& next_input_token = tokens.peek_token();
  492. if (next_input_token.is(Token::Type::Semicolon) || next_input_token.is(Token::Type::EndOfFile))
  493. break;
  494. temporary_list.append(consume_a_component_value(tokens));
  495. }
  496. // Consume a declaration from the temporary list. If anything was returned, append it to decls.
  497. auto token_stream = TokenStream(temporary_list);
  498. if (auto maybe_declaration = consume_a_declaration(token_stream); maybe_declaration.has_value())
  499. declarations.empend(maybe_declaration.release_value());
  500. continue;
  501. }
  502. // <delim-token> with a value of "&" (U+0026 AMPERSAND)
  503. if (token.is_delim('&')) {
  504. // Reconsume the current input token.
  505. tokens.reconsume_current_input_token();
  506. // Consume a qualified rule. If anything was returned, append it to rules.
  507. if (auto qualified_rule = consume_a_qualified_rule(tokens))
  508. rules.empend(qualified_rule);
  509. continue;
  510. }
  511. // anything else
  512. {
  513. // This is a parse error.
  514. log_parse_error();
  515. // Reconsume the current input token.
  516. tokens.reconsume_current_input_token();
  517. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  518. // consume a component value and throw away the returned value.
  519. for (;;) {
  520. auto& peek = tokens.peek_token();
  521. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  522. break;
  523. (void)consume_a_component_value(tokens);
  524. }
  525. }
  526. }
  527. }
  528. template<>
  529. ComponentValue Parser::consume_a_component_value(TokenStream<ComponentValue>& tokens)
  530. {
  531. // Note: This overload is called once tokens have already been converted into component values,
  532. // so we do not need to do the work in the more general overload.
  533. return tokens.next_token();
  534. }
  535. // 5.4.7. Consume a component value
  536. // https://www.w3.org/TR/css-syntax-3/#consume-component-value
  537. template<typename T>
  538. ComponentValue Parser::consume_a_component_value(TokenStream<T>& tokens)
  539. {
  540. // To consume a component value:
  541. // Consume the next input token.
  542. auto& token = tokens.next_token();
  543. // If the current input token is a <{-token>, <[-token>, or <(-token>, consume a simple block and return it.
  544. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  545. return ComponentValue(consume_a_simple_block(tokens));
  546. // Otherwise, if the current input token is a <function-token>, consume a function and return it.
  547. if (token.is(Token::Type::Function))
  548. return ComponentValue(consume_a_function(tokens));
  549. // Otherwise, return the current input token.
  550. return ComponentValue(token);
  551. }
  552. // 5.4.8. Consume a simple block
  553. // https://www.w3.org/TR/css-syntax-3/#consume-simple-block
  554. template<typename T>
  555. NonnullRefPtr<Block> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  556. {
  557. // Note: This algorithm assumes that the current input token has already been checked
  558. // to be an <{-token>, <[-token>, or <(-token>.
  559. // To consume a simple block:
  560. // The ending token is the mirror variant of the current input token.
  561. // (E.g. if it was called with <[-token>, the ending token is <]-token>.)
  562. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  563. // Create a simple block with its associated token set to the current input token
  564. // and with its value initially set to an empty list.
  565. // NOTE: We create the Block fully initialized when we return it instead.
  566. Token block_token = tokens.current_token();
  567. Vector<ComponentValue> block_values;
  568. // Repeatedly consume the next input token and process it as follows:
  569. for (;;) {
  570. auto& token = tokens.next_token();
  571. // ending token
  572. if (token.is(ending_token)) {
  573. // Return the block.
  574. return Block::create(move(block_token), move(block_values));
  575. }
  576. // <EOF-token>
  577. if (token.is(Token::Type::EndOfFile)) {
  578. // This is a parse error. Return the block.
  579. log_parse_error();
  580. return Block::create(move(block_token), move(block_values));
  581. }
  582. // anything else
  583. {
  584. // Reconsume the current input token.
  585. tokens.reconsume_current_input_token();
  586. // Consume a component value and append it to the value of the block.
  587. block_values.empend(consume_a_component_value(tokens));
  588. }
  589. }
  590. }
  591. // 5.4.9. Consume a function
  592. // https://www.w3.org/TR/css-syntax-3/#consume-function
  593. template<typename T>
  594. NonnullRefPtr<Function> Parser::consume_a_function(TokenStream<T>& tokens)
  595. {
  596. // Note: This algorithm assumes that the current input token has already been checked to be a <function-token>.
  597. auto name_ident = tokens.current_token();
  598. VERIFY(name_ident.is(Token::Type::Function));
  599. // To consume a function:
  600. // Create a function with its name equal to the value of the current input token
  601. // and with its value initially set to an empty list.
  602. // NOTE: We create the Function fully initialized when we return it instead.
  603. auto function_name = ((Token)name_ident).function();
  604. Vector<ComponentValue> function_values;
  605. // Repeatedly consume the next input token and process it as follows:
  606. for (;;) {
  607. auto& token = tokens.next_token();
  608. // <)-token>
  609. if (token.is(Token::Type::CloseParen)) {
  610. // Return the function.
  611. return Function::create(move(function_name), move(function_values));
  612. }
  613. // <EOF-token>
  614. if (token.is(Token::Type::EndOfFile)) {
  615. // This is a parse error. Return the function.
  616. log_parse_error();
  617. return Function::create(move(function_name), move(function_values));
  618. }
  619. // anything else
  620. {
  621. // Reconsume the current input token.
  622. tokens.reconsume_current_input_token();
  623. // Consume a component value and append the returned value to the function’s value.
  624. function_values.append(consume_a_component_value(tokens));
  625. }
  626. }
  627. }
  628. // 5.4.6. Consume a declaration
  629. // https://www.w3.org/TR/css-syntax-3/#consume-declaration
  630. template<typename T>
  631. Optional<Declaration> Parser::consume_a_declaration(TokenStream<T>& tokens)
  632. {
  633. // Note: This algorithm assumes that the next input token has already been checked to
  634. // be an <ident-token>.
  635. // NOTE: This is not true in our implementation! For convenience, we both skip whitespace
  636. // and gracefully handle the first token not being an <ident-token>.
  637. // To consume a declaration:
  638. // Consume the next input token.
  639. auto transaction = tokens.begin_transaction();
  640. tokens.skip_whitespace();
  641. auto& token = tokens.next_token();
  642. // NOTE: Not to spec, handle the case where the input token *isn't* an <ident-token>.
  643. if (!token.is(Token::Type::Ident))
  644. return {};
  645. // Create a new declaration with its name set to the value of the current input token
  646. // and its value initially set to the empty list.
  647. // NOTE: We create a fully-initialized Declaration just before returning it instead.
  648. auto declaration_name = ((Token)token).ident();
  649. Vector<ComponentValue> declaration_values;
  650. Important declaration_important = Important::No;
  651. // 1. While the next input token is a <whitespace-token>, consume the next input token.
  652. tokens.skip_whitespace();
  653. // 2. If the next input token is anything other than a <colon-token>, this is a parse error.
  654. // Return nothing.
  655. auto& maybe_colon = tokens.peek_token();
  656. if (!maybe_colon.is(Token::Type::Colon)) {
  657. log_parse_error();
  658. return {};
  659. }
  660. // Otherwise, consume the next input token.
  661. tokens.next_token();
  662. // 3. While the next input token is a <whitespace-token>, consume the next input token.
  663. tokens.skip_whitespace();
  664. // 4. As long as the next input token is anything other than an <EOF-token>, consume a
  665. // component value and append it to the declaration’s value.
  666. for (;;) {
  667. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  668. break;
  669. }
  670. declaration_values.append(consume_a_component_value(tokens));
  671. }
  672. // 5. If the last two non-<whitespace-token>s in the declaration’s value are a <delim-token>
  673. // with the value "!" followed by an <ident-token> with a value that is an ASCII case-insensitive
  674. // match for "important", remove them from the declaration’s value and set the declaration’s
  675. // important flag to true.
  676. if (declaration_values.size() >= 2) {
  677. // Walk backwards from the end until we find "important"
  678. Optional<size_t> important_index;
  679. for (size_t i = declaration_values.size() - 1; i > 0; i--) {
  680. auto value = declaration_values[i];
  681. if (value.is_ident("important"sv)) {
  682. important_index = i;
  683. break;
  684. }
  685. if (value.is(Token::Type::Whitespace))
  686. continue;
  687. break;
  688. }
  689. // Walk backwards from important until we find "!"
  690. if (important_index.has_value()) {
  691. Optional<size_t> bang_index;
  692. for (size_t i = important_index.value() - 1; i > 0; i--) {
  693. auto value = declaration_values[i];
  694. if (value.is_delim('!')) {
  695. bang_index = i;
  696. break;
  697. }
  698. if (value.is(Token::Type::Whitespace))
  699. continue;
  700. break;
  701. }
  702. if (bang_index.has_value()) {
  703. declaration_values.remove(important_index.value());
  704. declaration_values.remove(bang_index.value());
  705. declaration_important = Important::Yes;
  706. }
  707. }
  708. }
  709. // 6. While the last token in the declaration’s value is a <whitespace-token>, remove that token.
  710. while (!declaration_values.is_empty()) {
  711. auto maybe_whitespace = declaration_values.last();
  712. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  713. break;
  714. }
  715. declaration_values.take_last();
  716. }
  717. // 7. Return the declaration.
  718. transaction.commit();
  719. return Declaration { move(declaration_name), move(declaration_values), declaration_important };
  720. }
  721. // 5.4.5. Consume a list of declarations
  722. // https://www.w3.org/TR/css-syntax-3/#consume-list-of-declarations
  723. template<typename T>
  724. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  725. {
  726. // To consume a list of declarations:
  727. // Create an initially empty list of declarations.
  728. Vector<DeclarationOrAtRule> list_of_declarations;
  729. // Repeatedly consume the next input token:
  730. for (;;) {
  731. auto& token = tokens.next_token();
  732. // <whitespace-token>
  733. // <semicolon-token>
  734. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  735. // Do nothing.
  736. continue;
  737. }
  738. // <EOF-token>
  739. if (token.is(Token::Type::EndOfFile)) {
  740. // Return the list of declarations.
  741. return list_of_declarations;
  742. }
  743. // <at-keyword-token>
  744. if (token.is(Token::Type::AtKeyword)) {
  745. // Reconsume the current input token.
  746. tokens.reconsume_current_input_token();
  747. // Consume an at-rule. Append the returned rule to the list of declarations.
  748. list_of_declarations.empend(consume_an_at_rule(tokens));
  749. continue;
  750. }
  751. // <ident-token>
  752. if (token.is(Token::Type::Ident)) {
  753. // Initialize a temporary list initially filled with the current input token.
  754. Vector<ComponentValue> temporary_list;
  755. temporary_list.append(token);
  756. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  757. // consume a component value and append it to the temporary list.
  758. for (;;) {
  759. auto& peek = tokens.peek_token();
  760. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  761. break;
  762. temporary_list.append(consume_a_component_value(tokens));
  763. }
  764. // Consume a declaration from the temporary list. If anything was returned, append it to the list of declarations.
  765. auto token_stream = TokenStream(temporary_list);
  766. if (auto maybe_declaration = consume_a_declaration(token_stream); maybe_declaration.has_value())
  767. list_of_declarations.empend(maybe_declaration.value());
  768. continue;
  769. }
  770. // anything else
  771. {
  772. // This is a parse error.
  773. log_parse_error();
  774. // Reconsume the current input token.
  775. tokens.reconsume_current_input_token();
  776. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  777. // consume a component value and throw away the returned value.
  778. for (;;) {
  779. auto& peek = tokens.peek_token();
  780. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  781. break;
  782. dbgln_if(CSS_PARSER_DEBUG, "Discarding token: '{}'", peek.to_debug_string());
  783. (void)consume_a_component_value(tokens);
  784. }
  785. }
  786. }
  787. }
  788. CSSRule* Parser::parse_as_css_rule()
  789. {
  790. auto maybe_rule = parse_a_rule(m_token_stream);
  791. if (maybe_rule)
  792. return convert_to_rule(maybe_rule.release_nonnull());
  793. return {};
  794. }
  795. // 5.3.5. Parse a rule
  796. // https://www.w3.org/TR/css-syntax-3/#parse-rule
  797. template<typename T>
  798. RefPtr<Rule> Parser::parse_a_rule(TokenStream<T>& tokens)
  799. {
  800. // To parse a rule from input:
  801. RefPtr<Rule> rule;
  802. // 1. Normalize input, and set input to the result.
  803. // Note: This is done when initializing the Parser.
  804. // 2. While the next input token from input is a <whitespace-token>, consume the next input token from input.
  805. tokens.skip_whitespace();
  806. // 3. If the next input token from input is an <EOF-token>, return a syntax error.
  807. auto& token = tokens.peek_token();
  808. if (token.is(Token::Type::EndOfFile)) {
  809. return {};
  810. }
  811. // Otherwise, if the next input token from input is an <at-keyword-token>, consume an at-rule from input, and let rule be the return value.
  812. else if (token.is(Token::Type::AtKeyword)) {
  813. rule = consume_an_at_rule(m_token_stream);
  814. }
  815. // Otherwise, consume a qualified rule from input and let rule be the return value. If nothing was returned, return a syntax error.
  816. else {
  817. auto qualified_rule = consume_a_qualified_rule(tokens);
  818. if (!qualified_rule)
  819. return {};
  820. rule = qualified_rule;
  821. }
  822. // 4. While the next input token from input is a <whitespace-token>, consume the next input token from input.
  823. tokens.skip_whitespace();
  824. // 5. If the next input token from input is an <EOF-token>, return rule. Otherwise, return a syntax error.
  825. if (tokens.peek_token().is(Token::Type::EndOfFile))
  826. return rule;
  827. return {};
  828. }
  829. // 5.3.4. Parse a list of rules
  830. // https://www.w3.org/TR/css-syntax-3/#parse-list-of-rules
  831. template<typename T>
  832. Vector<NonnullRefPtr<Rule>> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
  833. {
  834. // To parse a list of rules from input:
  835. // 1. Normalize input, and set input to the result.
  836. // Note: This is done when initializing the Parser.
  837. // 2. Consume a list of rules from the input, with the top-level flag unset.
  838. auto list_of_rules = consume_a_list_of_rules(tokens, TopLevel::No);
  839. // 3. Return the returned list.
  840. return list_of_rules;
  841. }
  842. template Vector<NonnullRefPtr<Rule>> Parser::parse_a_list_of_rules(TokenStream<Token>& tokens);
  843. template Vector<NonnullRefPtr<Rule>> Parser::parse_a_list_of_rules(TokenStream<ComponentValue>& tokens);
  844. Optional<StyleProperty> Parser::parse_as_supports_condition()
  845. {
  846. auto maybe_declaration = parse_a_declaration(m_token_stream);
  847. if (maybe_declaration.has_value())
  848. return convert_to_style_property(maybe_declaration.release_value());
  849. return {};
  850. }
  851. // 5.3.6. Parse a declaration
  852. // https://www.w3.org/TR/css-syntax-3/#parse-a-declaration
  853. template<typename T>
  854. Optional<Declaration> Parser::parse_a_declaration(TokenStream<T>& tokens)
  855. {
  856. // To parse a declaration from input:
  857. // 1. Normalize input, and set input to the result.
  858. // Note: This is done when initializing the Parser.
  859. // 2. While the next input token from input is a <whitespace-token>, consume the next input token.
  860. tokens.skip_whitespace();
  861. // 3. If the next input token from input is not an <ident-token>, return a syntax error.
  862. auto& token = tokens.peek_token();
  863. if (!token.is(Token::Type::Ident)) {
  864. return {};
  865. }
  866. // 4. Consume a declaration from input. If anything was returned, return it. Otherwise, return a syntax error.
  867. if (auto declaration = consume_a_declaration(tokens); declaration.has_value())
  868. return declaration.release_value();
  869. return {};
  870. }
  871. // 5.3.7. Parse a style block’s contents
  872. // https://www.w3.org/TR/css-syntax-3/#parse-style-blocks-contents
  873. template<typename T>
  874. Vector<DeclarationOrAtRule> Parser::parse_a_style_blocks_contents(TokenStream<T>& tokens)
  875. {
  876. // To parse a style block’s contents from input:
  877. // 1. Normalize input, and set input to the result.
  878. // Note: This is done when initializing the Parser.
  879. // 2. Consume a style block’s contents from input, and return the result.
  880. return consume_a_style_blocks_contents(tokens);
  881. }
  882. // 5.3.8. Parse a list of declarations
  883. // https://www.w3.org/TR/css-syntax-3/#parse-list-of-declarations
  884. template<typename T>
  885. Vector<DeclarationOrAtRule> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
  886. {
  887. // To parse a list of declarations from input:
  888. // 1. Normalize input, and set input to the result.
  889. // Note: This is done when initializing the Parser.
  890. // 2. Consume a list of declarations from input, and return the result.
  891. return consume_a_list_of_declarations(tokens);
  892. }
  893. Optional<ComponentValue> Parser::parse_as_component_value()
  894. {
  895. return parse_a_component_value(m_token_stream);
  896. }
  897. // 5.3.9. Parse a component value
  898. // https://www.w3.org/TR/css-syntax-3/#parse-component-value
  899. template<typename T>
  900. Optional<ComponentValue> Parser::parse_a_component_value(TokenStream<T>& tokens)
  901. {
  902. // To parse a component value from input:
  903. // 1. Normalize input, and set input to the result.
  904. // Note: This is done when initializing the Parser.
  905. // 2. While the next input token from input is a <whitespace-token>, consume the next input token from input.
  906. tokens.skip_whitespace();
  907. // 3. If the next input token from input is an <EOF-token>, return a syntax error.
  908. if (tokens.peek_token().is(Token::Type::EndOfFile))
  909. return {};
  910. // 4. Consume a component value from input and let value be the return value.
  911. auto value = consume_a_component_value(tokens);
  912. // 5. While the next input token from input is a <whitespace-token>, consume the next input token.
  913. tokens.skip_whitespace();
  914. // 6. If the next input token from input is an <EOF-token>, return value. Otherwise, return a syntax error.
  915. if (tokens.peek_token().is(Token::Type::EndOfFile))
  916. return value;
  917. return {};
  918. }
  919. // 5.3.10. Parse a list of component values
  920. // https://www.w3.org/TR/css-syntax-3/#parse-list-of-component-values
  921. template<typename T>
  922. Vector<ComponentValue> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
  923. {
  924. // To parse a list of component values from input:
  925. // 1. Normalize input, and set input to the result.
  926. // Note: This is done when initializing the Parser.
  927. // 2. Repeatedly consume a component value from input until an <EOF-token> is returned, appending the returned values (except the final <EOF-token>) into a list. Return the list.
  928. Vector<ComponentValue> component_values;
  929. for (;;) {
  930. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  931. break;
  932. }
  933. component_values.append(consume_a_component_value(tokens));
  934. }
  935. return component_values;
  936. }
  937. // 5.3.11. Parse a comma-separated list of component values
  938. // https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values
  939. template<typename T>
  940. Vector<Vector<ComponentValue>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  941. {
  942. // To parse a comma-separated list of component values from input:
  943. // 1. Normalize input, and set input to the result.
  944. // Note: This is done when initializing the Parser.
  945. // 2. Let list of cvls be an initially empty list of component value lists.
  946. Vector<Vector<ComponentValue>> list_of_component_value_lists;
  947. // 3. Repeatedly consume a component value from input until an <EOF-token> or <comma-token> is returned,
  948. // appending the returned values (except the final <EOF-token> or <comma-token>) into a list.
  949. // Append the list to list of cvls.
  950. // If it was a <comma-token> that was returned, repeat this step.
  951. Vector<ComponentValue> current_list;
  952. for (;;) {
  953. auto component_value = consume_a_component_value(tokens);
  954. if (component_value.is(Token::Type::EndOfFile)) {
  955. list_of_component_value_lists.append(move(current_list));
  956. break;
  957. }
  958. if (component_value.is(Token::Type::Comma)) {
  959. list_of_component_value_lists.append(move(current_list));
  960. current_list = {};
  961. continue;
  962. }
  963. current_list.append(component_value);
  964. }
  965. // 4. Return list of cvls.
  966. return list_of_component_value_lists;
  967. }
  968. template Vector<Vector<ComponentValue>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<ComponentValue>&);
  969. template Vector<Vector<ComponentValue>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<Token>&);
  970. ElementInlineCSSStyleDeclaration* Parser::parse_as_style_attribute(DOM::Element& element)
  971. {
  972. auto declarations_and_at_rules = parse_a_list_of_declarations(m_token_stream);
  973. auto [properties, custom_properties] = extract_properties(declarations_and_at_rules);
  974. return ElementInlineCSSStyleDeclaration::create(element, move(properties), move(custom_properties));
  975. }
  976. Optional<URL::URL> Parser::parse_url_function(TokenStream<ComponentValue>& tokens)
  977. {
  978. auto transaction = tokens.begin_transaction();
  979. auto& component_value = tokens.next_token();
  980. auto convert_string_to_url = [&](StringView url_string) -> Optional<URL::URL> {
  981. auto url = m_context.complete_url(url_string);
  982. if (url.is_valid()) {
  983. transaction.commit();
  984. return url;
  985. }
  986. return {};
  987. };
  988. if (component_value.is(Token::Type::Url)) {
  989. auto url_string = component_value.token().url();
  990. return convert_string_to_url(url_string);
  991. }
  992. if (component_value.is_function("url"sv)) {
  993. auto const& function_values = component_value.function().values();
  994. // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
  995. for (size_t i = 0; i < function_values.size(); ++i) {
  996. auto const& value = function_values[i];
  997. if (value.is(Token::Type::Whitespace))
  998. continue;
  999. if (value.is(Token::Type::String)) {
  1000. auto url_string = value.token().string();
  1001. return convert_string_to_url(url_string);
  1002. }
  1003. break;
  1004. }
  1005. }
  1006. return {};
  1007. }
  1008. RefPtr<CSSStyleValue> Parser::parse_url_value(TokenStream<ComponentValue>& tokens)
  1009. {
  1010. auto url = parse_url_function(tokens);
  1011. if (!url.has_value())
  1012. return nullptr;
  1013. return URLStyleValue::create(*url);
  1014. }
  1015. RefPtr<CSSStyleValue> Parser::parse_basic_shape_value(TokenStream<ComponentValue>& tokens)
  1016. {
  1017. auto transaction = tokens.begin_transaction();
  1018. auto& component_value = tokens.next_token();
  1019. if (!component_value.is_function())
  1020. return nullptr;
  1021. auto function_name = component_value.function().name().bytes_as_string_view();
  1022. // FIXME: Implement other shapes. See: https://www.w3.org/TR/css-shapes-1/#basic-shape-functions
  1023. if (!function_name.equals_ignoring_ascii_case("polygon"sv))
  1024. return nullptr;
  1025. // polygon() = polygon( <'fill-rule'>? , [<length-percentage> <length-percentage>]# )
  1026. // FIXME: Parse the fill-rule.
  1027. auto arguments_tokens = TokenStream { component_value.function().values() };
  1028. auto arguments = parse_a_comma_separated_list_of_component_values(arguments_tokens);
  1029. Vector<Polygon::Point> points;
  1030. for (auto& argument : arguments) {
  1031. TokenStream argument_tokens { argument };
  1032. argument_tokens.skip_whitespace();
  1033. auto x_pos = parse_length_percentage(argument_tokens);
  1034. if (!x_pos.has_value())
  1035. return nullptr;
  1036. argument_tokens.skip_whitespace();
  1037. auto y_pos = parse_length_percentage(argument_tokens);
  1038. if (!y_pos.has_value())
  1039. return nullptr;
  1040. argument_tokens.skip_whitespace();
  1041. if (argument_tokens.has_next_token())
  1042. return nullptr;
  1043. points.append(Polygon::Point { *x_pos, *y_pos });
  1044. }
  1045. transaction.commit();
  1046. return BasicShapeStyleValue::create(Polygon { FillRule::Nonzero, move(points) });
  1047. }
  1048. JS::GCPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<Rule> rule)
  1049. {
  1050. if (rule->is_at_rule()) {
  1051. if (has_ignored_vendor_prefix(rule->at_rule_name()))
  1052. return {};
  1053. if (rule->at_rule_name().equals_ignoring_ascii_case("font-face"sv)) {
  1054. if (!rule->block() || !rule->block()->is_curly()) {
  1055. dbgln_if(CSS_PARSER_DEBUG, "@font-face rule is malformed.");
  1056. return {};
  1057. }
  1058. TokenStream tokens { rule->block()->values() };
  1059. return parse_font_face_rule(tokens);
  1060. }
  1061. if (rule->at_rule_name().equals_ignoring_ascii_case("import"sv))
  1062. return convert_to_import_rule(rule);
  1063. if (rule->at_rule_name().equals_ignoring_ascii_case("keyframes"sv))
  1064. return convert_to_keyframes_rule(rule);
  1065. if (rule->at_rule_name().equals_ignoring_ascii_case("media"sv))
  1066. return convert_to_media_rule(rule);
  1067. if (rule->at_rule_name().equals_ignoring_ascii_case("namespace"sv))
  1068. return convert_to_namespace_rule(rule);
  1069. if (rule->at_rule_name().equals_ignoring_ascii_case("supports"sv))
  1070. return convert_to_supports_rule(rule);
  1071. // FIXME: More at rules!
  1072. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS at-rule: @{}", rule->at_rule_name());
  1073. return {};
  1074. }
  1075. auto prelude_stream = TokenStream(rule->prelude());
  1076. auto selectors = parse_a_selector_list(prelude_stream, SelectorType::Standalone);
  1077. if (selectors.is_error()) {
  1078. if (selectors.error() == ParseError::SyntaxError) {
  1079. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule selectors invalid; discarding.");
  1080. if constexpr (CSS_PARSER_DEBUG) {
  1081. prelude_stream.dump_all_tokens();
  1082. }
  1083. }
  1084. return {};
  1085. }
  1086. if (selectors.value().is_empty()) {
  1087. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: empty selector; discarding.");
  1088. return {};
  1089. }
  1090. if (!rule->block()->is_curly())
  1091. return {};
  1092. auto stream = TokenStream(rule->block()->values());
  1093. auto declarations_and_at_rules = parse_a_style_blocks_contents(stream);
  1094. auto* declaration = convert_to_style_declaration(declarations_and_at_rules);
  1095. if (!declaration) {
  1096. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule declaration invalid; discarding.");
  1097. return {};
  1098. }
  1099. return CSSStyleRule::create(m_context.realm(), move(selectors.value()), *declaration);
  1100. }
  1101. JS::GCPtr<CSSImportRule> Parser::convert_to_import_rule(Rule& rule)
  1102. {
  1103. // https://drafts.csswg.org/css-cascade-5/#at-import
  1104. // @import [ <url> | <string> ]
  1105. // [ layer | layer(<layer-name>) ]?
  1106. // <import-conditions> ;
  1107. //
  1108. // <import-conditions> = [ supports( [ <supports-condition> | <declaration> ] ) ]?
  1109. // <media-query-list>?
  1110. if (rule.prelude().is_empty()) {
  1111. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse @import rule: Empty prelude.");
  1112. return {};
  1113. }
  1114. if (rule.block()) {
  1115. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse @import rule: Block is not allowed.");
  1116. return {};
  1117. }
  1118. TokenStream tokens { rule.prelude() };
  1119. tokens.skip_whitespace();
  1120. Optional<URL::URL> url = parse_url_function(tokens);
  1121. if (!url.has_value() && tokens.peek_token().is(Token::Type::String))
  1122. url = m_context.complete_url(tokens.next_token().token().string());
  1123. if (!url.has_value()) {
  1124. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse @import rule: Unable to parse `{}` as URL.", tokens.peek_token().to_debug_string());
  1125. return {};
  1126. }
  1127. tokens.skip_whitespace();
  1128. // TODO: Support layers and import-conditions
  1129. if (tokens.has_next_token()) {
  1130. if constexpr (CSS_PARSER_DEBUG) {
  1131. dbgln("Failed to parse @import rule: Trailing tokens after URL are not yet supported.");
  1132. tokens.dump_all_tokens();
  1133. }
  1134. return {};
  1135. }
  1136. return CSSImportRule::create(url.value(), const_cast<DOM::Document&>(*m_context.document()));
  1137. }
  1138. JS::GCPtr<CSSKeyframesRule> Parser::convert_to_keyframes_rule(Rule& rule)
  1139. {
  1140. // https://www.w3.org/TR/css-animations-1/#keyframes
  1141. if (rule.prelude().is_empty()) {
  1142. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse @keyframes rule: Empty prelude.");
  1143. return {};
  1144. }
  1145. if (!rule.block()) {
  1146. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse @keyframes rule: No block.");
  1147. return {};
  1148. }
  1149. auto prelude_stream = TokenStream { rule.prelude() };
  1150. prelude_stream.skip_whitespace();
  1151. auto& token = prelude_stream.next_token();
  1152. if (!token.is_token()) {
  1153. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes has invalid prelude, prelude = {}; discarding.", rule.prelude());
  1154. return {};
  1155. }
  1156. auto name_token = token.token();
  1157. prelude_stream.skip_whitespace();
  1158. if (prelude_stream.has_next_token()) {
  1159. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes has invalid prelude, prelude = {}; discarding.", rule.prelude());
  1160. return {};
  1161. }
  1162. if (name_token.is(Token::Type::Ident) && (is_css_wide_keyword(name_token.ident()) || name_token.ident().equals_ignoring_ascii_case("none"sv))) {
  1163. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule name is invalid: {}; discarding.", name_token.ident());
  1164. return {};
  1165. }
  1166. if (!name_token.is(Token::Type::String) && !name_token.is(Token::Type::Ident)) {
  1167. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule name is invalid: {}; discarding.", name_token.to_debug_string());
  1168. return {};
  1169. }
  1170. auto name = name_token.to_string();
  1171. auto child_tokens = TokenStream { rule.block()->values() };
  1172. JS::MarkedVector<CSSRule*> keyframes(m_context.realm().heap());
  1173. while (child_tokens.has_next_token()) {
  1174. child_tokens.skip_whitespace();
  1175. // keyframe-selector = <keyframe-keyword> | <percentage>
  1176. // keyframe-keyword = "from" | "to"
  1177. // selector = <keyframe-selector>#
  1178. // keyframes-block = "{" <declaration-list>? "}"
  1179. // keyframe-rule = <selector> <keyframes-block>
  1180. auto selectors = Vector<CSS::Percentage> {};
  1181. while (child_tokens.has_next_token()) {
  1182. child_tokens.skip_whitespace();
  1183. if (!child_tokens.has_next_token())
  1184. break;
  1185. auto tok = child_tokens.next_token();
  1186. if (!tok.is_token()) {
  1187. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule has invalid selector: {}; discarding.", tok.to_debug_string());
  1188. child_tokens.reconsume_current_input_token();
  1189. break;
  1190. }
  1191. auto token = tok.token();
  1192. auto read_a_selector = false;
  1193. if (token.is(Token::Type::Ident)) {
  1194. if (token.ident().equals_ignoring_ascii_case("from"sv)) {
  1195. selectors.append(CSS::Percentage(0));
  1196. read_a_selector = true;
  1197. }
  1198. if (token.ident().equals_ignoring_ascii_case("to"sv)) {
  1199. selectors.append(CSS::Percentage(100));
  1200. read_a_selector = true;
  1201. }
  1202. } else if (token.is(Token::Type::Percentage)) {
  1203. selectors.append(CSS::Percentage(token.percentage()));
  1204. read_a_selector = true;
  1205. }
  1206. if (read_a_selector) {
  1207. child_tokens.skip_whitespace();
  1208. if (child_tokens.next_token().is(Token::Type::Comma))
  1209. continue;
  1210. }
  1211. child_tokens.reconsume_current_input_token();
  1212. break;
  1213. }
  1214. if (!child_tokens.has_next_token())
  1215. break;
  1216. child_tokens.skip_whitespace();
  1217. auto token = child_tokens.next_token();
  1218. if (token.is_block()) {
  1219. auto block_tokens = token.block().values();
  1220. auto block_stream = TokenStream { block_tokens };
  1221. auto block_declarations = parse_a_list_of_declarations(block_stream);
  1222. auto style = convert_to_style_declaration(block_declarations);
  1223. for (auto& selector : selectors) {
  1224. auto keyframe_rule = CSSKeyframeRule::create(m_context.realm(), selector, *style);
  1225. keyframes.append(keyframe_rule);
  1226. }
  1227. } else {
  1228. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule has invalid block: {}; discarding.", token.to_debug_string());
  1229. }
  1230. }
  1231. return CSSKeyframesRule::create(m_context.realm(), name, CSSRuleList::create(m_context.realm(), move(keyframes)));
  1232. }
  1233. JS::GCPtr<CSSNamespaceRule> Parser::convert_to_namespace_rule(Rule& rule)
  1234. {
  1235. // https://drafts.csswg.org/css-namespaces/#syntax
  1236. // @namespace <namespace-prefix>? [ <string> | <url> ] ;
  1237. // <namespace-prefix> = <ident>
  1238. if (rule.prelude().is_empty()) {
  1239. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse @namespace rule: Empty prelude.");
  1240. return {};
  1241. }
  1242. if (rule.block()) {
  1243. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse @namespace rule: Block is not allowed.");
  1244. return {};
  1245. }
  1246. auto tokens = TokenStream { rule.prelude() };
  1247. tokens.skip_whitespace();
  1248. Optional<FlyString> prefix = {};
  1249. if (tokens.peek_token().is(Token::Type::Ident)) {
  1250. prefix = tokens.next_token().token().ident();
  1251. tokens.skip_whitespace();
  1252. }
  1253. FlyString namespace_uri;
  1254. if (auto url = parse_url_function(tokens); url.has_value()) {
  1255. namespace_uri = MUST(url.value().to_string());
  1256. } else if (auto& url_token = tokens.next_token(); url_token.is(Token::Type::String)) {
  1257. namespace_uri = url_token.token().string();
  1258. } else {
  1259. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse @namespace rule: Unable to parse `{}` as URL.", tokens.peek_token().to_debug_string());
  1260. return {};
  1261. }
  1262. tokens.skip_whitespace();
  1263. if (tokens.has_next_token()) {
  1264. if constexpr (CSS_PARSER_DEBUG) {
  1265. dbgln("Failed to parse @namespace rule: Trailing tokens after URL.");
  1266. tokens.dump_all_tokens();
  1267. }
  1268. return {};
  1269. }
  1270. return CSSNamespaceRule::create(m_context.realm(), prefix, namespace_uri);
  1271. }
  1272. JS::GCPtr<CSSSupportsRule> Parser::convert_to_supports_rule(Rule& rule)
  1273. {
  1274. // https://drafts.csswg.org/css-conditional-3/#at-supports
  1275. // @supports <supports-condition> {
  1276. // <rule-list>
  1277. // }
  1278. if (rule.prelude().is_empty()) {
  1279. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse @supports rule: Empty prelude.");
  1280. return {};
  1281. }
  1282. if (!rule.block()) {
  1283. dbgln_if(CSS_PARSER_DEBUG, "Failed to parse @supports rule: No block.");
  1284. return {};
  1285. }
  1286. auto supports_tokens = TokenStream { rule.prelude() };
  1287. auto supports = parse_a_supports(supports_tokens);
  1288. if (!supports) {
  1289. if constexpr (CSS_PARSER_DEBUG) {
  1290. dbgln("Failed to parse @supports rule: supports clause invalid.");
  1291. supports_tokens.dump_all_tokens();
  1292. }
  1293. return {};
  1294. }
  1295. auto child_tokens = TokenStream { rule.block()->values() };
  1296. auto parser_rules = parse_a_list_of_rules(child_tokens);
  1297. JS::MarkedVector<CSSRule*> child_rules { m_context.realm().heap() };
  1298. for (auto& raw_rule : parser_rules) {
  1299. if (auto child_rule = convert_to_rule(raw_rule))
  1300. child_rules.append(child_rule);
  1301. }
  1302. auto rule_list = CSSRuleList::create(m_context.realm(), child_rules);
  1303. return CSSSupportsRule::create(m_context.realm(), supports.release_nonnull(), rule_list);
  1304. }
  1305. auto Parser::extract_properties(Vector<DeclarationOrAtRule> const& declarations_and_at_rules) -> PropertiesAndCustomProperties
  1306. {
  1307. PropertiesAndCustomProperties result;
  1308. for (auto const& declaration_or_at_rule : declarations_and_at_rules) {
  1309. if (declaration_or_at_rule.is_at_rule()) {
  1310. dbgln_if(CSS_PARSER_DEBUG, "!!! CSS at-rule is not allowed here!");
  1311. continue;
  1312. }
  1313. auto const& declaration = declaration_or_at_rule.declaration();
  1314. if (auto maybe_property = convert_to_style_property(declaration); maybe_property.has_value()) {
  1315. auto property = maybe_property.release_value();
  1316. if (property.property_id == PropertyID::Custom) {
  1317. result.custom_properties.set(property.custom_name, property);
  1318. } else {
  1319. result.properties.append(move(property));
  1320. }
  1321. }
  1322. }
  1323. return result;
  1324. }
  1325. PropertyOwningCSSStyleDeclaration* Parser::convert_to_style_declaration(Vector<DeclarationOrAtRule> const& declarations_and_at_rules)
  1326. {
  1327. auto [properties, custom_properties] = extract_properties(declarations_and_at_rules);
  1328. return PropertyOwningCSSStyleDeclaration::create(m_context.realm(), move(properties), move(custom_properties));
  1329. }
  1330. Optional<StyleProperty> Parser::convert_to_style_property(Declaration const& declaration)
  1331. {
  1332. auto const& property_name = declaration.name();
  1333. auto property_id = property_id_from_string(property_name);
  1334. if (!property_id.has_value()) {
  1335. if (property_name.bytes_as_string_view().starts_with("--"sv)) {
  1336. property_id = PropertyID::Custom;
  1337. } else if (has_ignored_vendor_prefix(property_name)) {
  1338. return {};
  1339. } else if (!property_name.bytes_as_string_view().starts_with('-')) {
  1340. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS property '{}'", property_name);
  1341. return {};
  1342. }
  1343. }
  1344. auto value_token_stream = TokenStream(declaration.values());
  1345. auto value = parse_css_value(property_id.value(), value_token_stream);
  1346. if (value.is_error()) {
  1347. if (value.error() == ParseError::SyntaxError) {
  1348. dbgln_if(CSS_PARSER_DEBUG, "Unable to parse value for CSS property '{}'.", property_name);
  1349. if constexpr (CSS_PARSER_DEBUG) {
  1350. value_token_stream.dump_all_tokens();
  1351. }
  1352. }
  1353. return {};
  1354. }
  1355. if (property_id.value() == PropertyID::Custom)
  1356. return StyleProperty { declaration.importance(), property_id.value(), value.release_value(), declaration.name() };
  1357. return StyleProperty { declaration.importance(), property_id.value(), value.release_value(), {} };
  1358. }
  1359. RefPtr<CSSStyleValue> Parser::parse_builtin_value(TokenStream<ComponentValue>& tokens)
  1360. {
  1361. auto transaction = tokens.begin_transaction();
  1362. auto& component_value = tokens.next_token();
  1363. if (component_value.is(Token::Type::Ident)) {
  1364. auto ident = component_value.token().ident();
  1365. if (ident.equals_ignoring_ascii_case("inherit"sv)) {
  1366. transaction.commit();
  1367. return CSSKeywordValue::create(Keyword::Inherit);
  1368. }
  1369. if (ident.equals_ignoring_ascii_case("initial"sv)) {
  1370. transaction.commit();
  1371. return CSSKeywordValue::create(Keyword::Initial);
  1372. }
  1373. if (ident.equals_ignoring_ascii_case("unset"sv)) {
  1374. transaction.commit();
  1375. return CSSKeywordValue::create(Keyword::Unset);
  1376. }
  1377. if (ident.equals_ignoring_ascii_case("revert"sv)) {
  1378. transaction.commit();
  1379. return CSSKeywordValue::create(Keyword::Revert);
  1380. }
  1381. // FIXME: Implement `revert-layer` from CSS-CASCADE-5.
  1382. }
  1383. return nullptr;
  1384. }
  1385. // https://www.w3.org/TR/css-values-4/#custom-idents
  1386. RefPtr<CustomIdentStyleValue> Parser::parse_custom_ident_value(TokenStream<ComponentValue>& tokens, std::initializer_list<StringView> blacklist)
  1387. {
  1388. auto transaction = tokens.begin_transaction();
  1389. tokens.skip_whitespace();
  1390. auto token = tokens.next_token();
  1391. if (!token.is(Token::Type::Ident))
  1392. return nullptr;
  1393. auto custom_ident = token.token().ident();
  1394. // The CSS-wide keywords are not valid <custom-ident>s.
  1395. if (is_css_wide_keyword(custom_ident))
  1396. return nullptr;
  1397. // The default keyword is reserved and is also not a valid <custom-ident>.
  1398. if (custom_ident.equals_ignoring_ascii_case("default"sv))
  1399. return nullptr;
  1400. // Specifications using <custom-ident> must specify clearly what other keywords are excluded from <custom-ident>,
  1401. // if any—for example by saying that any pre-defined keywords in that property’s value definition are excluded.
  1402. // Excluded keywords are excluded in all ASCII case permutations.
  1403. for (auto& value : blacklist) {
  1404. if (custom_ident.equals_ignoring_ascii_case(value))
  1405. return nullptr;
  1406. }
  1407. transaction.commit();
  1408. return CustomIdentStyleValue::create(custom_ident);
  1409. }
  1410. RefPtr<CalculatedStyleValue> Parser::parse_calculated_value(ComponentValue const& component_value)
  1411. {
  1412. if (!component_value.is_function())
  1413. return nullptr;
  1414. auto const& function = component_value.function();
  1415. auto function_node = parse_a_calc_function_node(function);
  1416. if (!function_node)
  1417. return nullptr;
  1418. auto function_type = function_node->determine_type(m_context.current_property_id());
  1419. if (!function_type.has_value())
  1420. return nullptr;
  1421. return CalculatedStyleValue::create(function_node.release_nonnull(), function_type.release_value());
  1422. }
  1423. OwnPtr<CalculationNode> Parser::parse_a_calc_function_node(Function const& function)
  1424. {
  1425. if (function.name().equals_ignoring_ascii_case("calc"sv))
  1426. return parse_a_calculation(function.values());
  1427. if (auto maybe_function = parse_math_function(m_context.current_property_id(), function))
  1428. return maybe_function;
  1429. return nullptr;
  1430. }
  1431. Optional<Dimension> Parser::parse_dimension(ComponentValue const& component_value)
  1432. {
  1433. if (component_value.is(Token::Type::Dimension)) {
  1434. auto numeric_value = component_value.token().dimension_value();
  1435. auto unit_string = component_value.token().dimension_unit();
  1436. if (auto length_type = Length::unit_from_name(unit_string); length_type.has_value())
  1437. return Length { numeric_value, length_type.release_value() };
  1438. if (auto angle_type = Angle::unit_from_name(unit_string); angle_type.has_value())
  1439. return Angle { numeric_value, angle_type.release_value() };
  1440. if (auto flex_type = Flex::unit_from_name(unit_string); flex_type.has_value())
  1441. return Flex { numeric_value, flex_type.release_value() };
  1442. if (auto frequency_type = Frequency::unit_from_name(unit_string); frequency_type.has_value())
  1443. return Frequency { numeric_value, frequency_type.release_value() };
  1444. if (auto resolution_type = Resolution::unit_from_name(unit_string); resolution_type.has_value())
  1445. return Resolution { numeric_value, resolution_type.release_value() };
  1446. if (auto time_type = Time::unit_from_name(unit_string); time_type.has_value())
  1447. return Time { numeric_value, time_type.release_value() };
  1448. }
  1449. if (component_value.is(Token::Type::Percentage))
  1450. return Percentage { component_value.token().percentage() };
  1451. if (component_value.is(Token::Type::Number)) {
  1452. auto numeric_value = component_value.token().number_value();
  1453. if (numeric_value == 0)
  1454. return Length::make_px(0);
  1455. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
  1456. // https://quirks.spec.whatwg.org/#quirky-length-value
  1457. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  1458. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  1459. // expression, and must not be supported in the supports() static method of the CSS interface."
  1460. return Length::make_px(CSSPixels::nearest_value_for(numeric_value));
  1461. }
  1462. }
  1463. return {};
  1464. }
  1465. Optional<AngleOrCalculated> Parser::parse_angle(TokenStream<ComponentValue>& tokens)
  1466. {
  1467. auto transaction = tokens.begin_transaction();
  1468. auto& token = tokens.next_token();
  1469. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1470. if (dimension->is_angle()) {
  1471. transaction.commit();
  1472. return dimension->angle();
  1473. }
  1474. return {};
  1475. }
  1476. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_angle()) {
  1477. transaction.commit();
  1478. return calc.release_nonnull();
  1479. }
  1480. return {};
  1481. }
  1482. Optional<AnglePercentage> Parser::parse_angle_percentage(TokenStream<ComponentValue>& tokens)
  1483. {
  1484. auto transaction = tokens.begin_transaction();
  1485. auto& token = tokens.next_token();
  1486. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1487. if (dimension->is_angle_percentage()) {
  1488. transaction.commit();
  1489. return dimension->angle_percentage();
  1490. }
  1491. return {};
  1492. }
  1493. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_angle_percentage()) {
  1494. transaction.commit();
  1495. return calc.release_nonnull();
  1496. }
  1497. return {};
  1498. }
  1499. Optional<FlexOrCalculated> Parser::parse_flex(TokenStream<ComponentValue>& tokens)
  1500. {
  1501. auto transaction = tokens.begin_transaction();
  1502. auto& token = tokens.next_token();
  1503. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1504. if (dimension->is_flex()) {
  1505. transaction.commit();
  1506. return dimension->flex();
  1507. }
  1508. return {};
  1509. }
  1510. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_flex()) {
  1511. transaction.commit();
  1512. return calc.release_nonnull();
  1513. }
  1514. return {};
  1515. }
  1516. Optional<FrequencyOrCalculated> Parser::parse_frequency(TokenStream<ComponentValue>& tokens)
  1517. {
  1518. auto transaction = tokens.begin_transaction();
  1519. auto& token = tokens.next_token();
  1520. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1521. if (dimension->is_frequency()) {
  1522. transaction.commit();
  1523. return dimension->frequency();
  1524. }
  1525. return {};
  1526. }
  1527. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_frequency()) {
  1528. transaction.commit();
  1529. return calc.release_nonnull();
  1530. }
  1531. return {};
  1532. }
  1533. Optional<FrequencyPercentage> Parser::parse_frequency_percentage(TokenStream<ComponentValue>& tokens)
  1534. {
  1535. auto transaction = tokens.begin_transaction();
  1536. auto& token = tokens.next_token();
  1537. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1538. if (dimension->is_frequency_percentage()) {
  1539. transaction.commit();
  1540. return dimension->frequency_percentage();
  1541. }
  1542. return {};
  1543. }
  1544. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_frequency_percentage()) {
  1545. transaction.commit();
  1546. return calc.release_nonnull();
  1547. }
  1548. return {};
  1549. }
  1550. Optional<IntegerOrCalculated> Parser::parse_integer(TokenStream<ComponentValue>& tokens)
  1551. {
  1552. auto transaction = tokens.begin_transaction();
  1553. auto& token = tokens.next_token();
  1554. if (token.is(Token::Type::Number) && token.token().number().is_integer()) {
  1555. transaction.commit();
  1556. return token.token().to_integer();
  1557. }
  1558. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_number()) {
  1559. transaction.commit();
  1560. return calc.release_nonnull();
  1561. }
  1562. return {};
  1563. }
  1564. Optional<LengthOrCalculated> Parser::parse_length(TokenStream<ComponentValue>& tokens)
  1565. {
  1566. auto transaction = tokens.begin_transaction();
  1567. auto& token = tokens.next_token();
  1568. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1569. if (dimension->is_length()) {
  1570. transaction.commit();
  1571. return dimension->length();
  1572. }
  1573. return {};
  1574. }
  1575. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_length()) {
  1576. transaction.commit();
  1577. return calc.release_nonnull();
  1578. }
  1579. return {};
  1580. }
  1581. Optional<LengthPercentage> Parser::parse_length_percentage(TokenStream<ComponentValue>& tokens)
  1582. {
  1583. auto transaction = tokens.begin_transaction();
  1584. auto& token = tokens.next_token();
  1585. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1586. if (dimension->is_length_percentage()) {
  1587. transaction.commit();
  1588. return dimension->length_percentage();
  1589. }
  1590. return {};
  1591. }
  1592. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_length_percentage()) {
  1593. transaction.commit();
  1594. return calc.release_nonnull();
  1595. }
  1596. return {};
  1597. }
  1598. Optional<NumberOrCalculated> Parser::parse_number(TokenStream<ComponentValue>& tokens)
  1599. {
  1600. auto transaction = tokens.begin_transaction();
  1601. auto& token = tokens.next_token();
  1602. if (token.is(Token::Type::Number)) {
  1603. transaction.commit();
  1604. return token.token().number_value();
  1605. }
  1606. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_number()) {
  1607. transaction.commit();
  1608. return calc.release_nonnull();
  1609. }
  1610. return {};
  1611. }
  1612. Optional<ResolutionOrCalculated> Parser::parse_resolution(TokenStream<ComponentValue>& tokens)
  1613. {
  1614. auto transaction = tokens.begin_transaction();
  1615. auto& token = tokens.next_token();
  1616. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1617. if (dimension->is_resolution()) {
  1618. transaction.commit();
  1619. return dimension->resolution();
  1620. }
  1621. return {};
  1622. }
  1623. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_resolution()) {
  1624. transaction.commit();
  1625. return calc.release_nonnull();
  1626. }
  1627. return {};
  1628. }
  1629. Optional<TimeOrCalculated> Parser::parse_time(TokenStream<ComponentValue>& tokens)
  1630. {
  1631. auto transaction = tokens.begin_transaction();
  1632. auto& token = tokens.next_token();
  1633. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1634. if (dimension->is_time()) {
  1635. transaction.commit();
  1636. return dimension->time();
  1637. }
  1638. return {};
  1639. }
  1640. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_time()) {
  1641. transaction.commit();
  1642. return calc.release_nonnull();
  1643. }
  1644. return {};
  1645. }
  1646. Optional<TimePercentage> Parser::parse_time_percentage(TokenStream<ComponentValue>& tokens)
  1647. {
  1648. auto transaction = tokens.begin_transaction();
  1649. auto& token = tokens.next_token();
  1650. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1651. if (dimension->is_time_percentage()) {
  1652. transaction.commit();
  1653. return dimension->time_percentage();
  1654. }
  1655. return {};
  1656. }
  1657. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_time_percentage()) {
  1658. transaction.commit();
  1659. return calc.release_nonnull();
  1660. }
  1661. return {};
  1662. }
  1663. Optional<LengthOrCalculated> Parser::parse_source_size_value(TokenStream<ComponentValue>& tokens)
  1664. {
  1665. if (tokens.peek_token().is_ident("auto"sv)) {
  1666. (void)tokens.next_token(); // auto
  1667. return LengthOrCalculated { Length::make_auto() };
  1668. }
  1669. return parse_length(tokens);
  1670. }
  1671. Optional<Ratio> Parser::parse_ratio(TokenStream<ComponentValue>& tokens)
  1672. {
  1673. auto transaction = tokens.begin_transaction();
  1674. tokens.skip_whitespace();
  1675. auto read_number_value = [this](ComponentValue const& component_value) -> Optional<double> {
  1676. if (component_value.is(Token::Type::Number)) {
  1677. return component_value.token().number_value();
  1678. } else if (component_value.is_function()) {
  1679. auto maybe_calc = parse_calculated_value(component_value);
  1680. if (!maybe_calc || !maybe_calc->resolves_to_number())
  1681. return {};
  1682. if (auto resolved_number = maybe_calc->resolve_number(); resolved_number.has_value() && resolved_number.value() >= 0) {
  1683. return resolved_number.value();
  1684. }
  1685. }
  1686. return {};
  1687. };
  1688. // `<ratio> = <number [0,∞]> [ / <number [0,∞]> ]?`
  1689. auto maybe_numerator = read_number_value(tokens.next_token());
  1690. if (!maybe_numerator.has_value() || maybe_numerator.value() < 0)
  1691. return {};
  1692. auto numerator = maybe_numerator.value();
  1693. {
  1694. auto two_value_transaction = tokens.begin_transaction();
  1695. tokens.skip_whitespace();
  1696. auto solidus = tokens.next_token();
  1697. tokens.skip_whitespace();
  1698. auto maybe_denominator = read_number_value(tokens.next_token());
  1699. if (solidus.is_delim('/') && maybe_denominator.has_value() && maybe_denominator.value() >= 0) {
  1700. auto denominator = maybe_denominator.value();
  1701. // Two-value ratio
  1702. two_value_transaction.commit();
  1703. transaction.commit();
  1704. return Ratio { numerator, denominator };
  1705. }
  1706. }
  1707. // Single-value ratio
  1708. transaction.commit();
  1709. return Ratio { numerator };
  1710. }
  1711. // https://www.w3.org/TR/css-syntax-3/#urange-syntax
  1712. Optional<Gfx::UnicodeRange> Parser::parse_unicode_range(TokenStream<ComponentValue>& tokens)
  1713. {
  1714. auto transaction = tokens.begin_transaction();
  1715. tokens.skip_whitespace();
  1716. // <urange> =
  1717. // u '+' <ident-token> '?'* |
  1718. // u <dimension-token> '?'* |
  1719. // u <number-token> '?'* |
  1720. // u <number-token> <dimension-token> |
  1721. // u <number-token> <number-token> |
  1722. // u '+' '?'+
  1723. // (All with no whitespace in between tokens.)
  1724. // NOTE: Parsing this is different from usual. We take these steps:
  1725. // 1. Match the grammar above against the tokens, concatenating them into a string using their original representation.
  1726. // 2. Then, parse that string according to the spec algorithm.
  1727. // Step 2 is performed by calling the other parse_unicode_range() overload.
  1728. auto is_ending_token = [](ComponentValue const& component_value) {
  1729. return component_value.is(Token::Type::EndOfFile)
  1730. || component_value.is(Token::Type::Comma)
  1731. || component_value.is(Token::Type::Semicolon)
  1732. || component_value.is(Token::Type::Whitespace);
  1733. };
  1734. auto create_unicode_range = [&](StringView text, auto& local_transaction) -> Optional<Gfx::UnicodeRange> {
  1735. auto maybe_unicode_range = parse_unicode_range(text);
  1736. if (maybe_unicode_range.has_value()) {
  1737. local_transaction.commit();
  1738. transaction.commit();
  1739. }
  1740. return maybe_unicode_range;
  1741. };
  1742. // All options start with 'u'/'U'.
  1743. auto const& u = tokens.next_token();
  1744. if (!u.is_ident("u"sv)) {
  1745. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> does not start with 'u'");
  1746. return {};
  1747. }
  1748. auto const& second_token = tokens.next_token();
  1749. // u '+' <ident-token> '?'* |
  1750. // u '+' '?'+
  1751. if (second_token.is_delim('+')) {
  1752. auto local_transaction = tokens.begin_transaction();
  1753. StringBuilder string_builder;
  1754. string_builder.append(second_token.token().representation());
  1755. auto const& third_token = tokens.next_token();
  1756. if (third_token.is(Token::Type::Ident) || third_token.is_delim('?')) {
  1757. string_builder.append(third_token.token().representation());
  1758. while (tokens.peek_token().is_delim('?'))
  1759. string_builder.append(tokens.next_token().token().representation());
  1760. if (is_ending_token(tokens.peek_token()))
  1761. return create_unicode_range(string_builder.string_view(), local_transaction);
  1762. }
  1763. }
  1764. // u <dimension-token> '?'*
  1765. if (second_token.is(Token::Type::Dimension)) {
  1766. auto local_transaction = tokens.begin_transaction();
  1767. StringBuilder string_builder;
  1768. string_builder.append(second_token.token().representation());
  1769. while (tokens.peek_token().is_delim('?'))
  1770. string_builder.append(tokens.next_token().token().representation());
  1771. if (is_ending_token(tokens.peek_token()))
  1772. return create_unicode_range(string_builder.string_view(), local_transaction);
  1773. }
  1774. // u <number-token> '?'* |
  1775. // u <number-token> <dimension-token> |
  1776. // u <number-token> <number-token>
  1777. if (second_token.is(Token::Type::Number)) {
  1778. auto local_transaction = tokens.begin_transaction();
  1779. StringBuilder string_builder;
  1780. string_builder.append(second_token.token().representation());
  1781. if (is_ending_token(tokens.peek_token()))
  1782. return create_unicode_range(string_builder.string_view(), local_transaction);
  1783. auto const& third_token = tokens.next_token();
  1784. if (third_token.is_delim('?')) {
  1785. string_builder.append(third_token.token().representation());
  1786. while (tokens.peek_token().is_delim('?'))
  1787. string_builder.append(tokens.next_token().token().representation());
  1788. if (is_ending_token(tokens.peek_token()))
  1789. return create_unicode_range(string_builder.string_view(), local_transaction);
  1790. } else if (third_token.is(Token::Type::Dimension)) {
  1791. string_builder.append(third_token.token().representation());
  1792. if (is_ending_token(tokens.peek_token()))
  1793. return create_unicode_range(string_builder.string_view(), local_transaction);
  1794. } else if (third_token.is(Token::Type::Number)) {
  1795. string_builder.append(third_token.token().representation());
  1796. if (is_ending_token(tokens.peek_token()))
  1797. return create_unicode_range(string_builder.string_view(), local_transaction);
  1798. }
  1799. }
  1800. if constexpr (CSS_PARSER_DEBUG) {
  1801. dbgln("CSSParser: Tokens did not match <urange> grammar.");
  1802. tokens.dump_all_tokens();
  1803. }
  1804. return {};
  1805. }
  1806. Optional<Gfx::UnicodeRange> Parser::parse_unicode_range(StringView text)
  1807. {
  1808. auto make_valid_unicode_range = [&](u32 start_value, u32 end_value) -> Optional<Gfx::UnicodeRange> {
  1809. // https://www.w3.org/TR/css-syntax-3/#maximum-allowed-code-point
  1810. constexpr u32 maximum_allowed_code_point = 0x10FFFF;
  1811. // To determine what codepoints the <urange> represents:
  1812. // 1. If end value is greater than the maximum allowed code point,
  1813. // the <urange> is invalid and a syntax error.
  1814. if (end_value > maximum_allowed_code_point) {
  1815. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: end_value ({}) > maximum ({})", end_value, maximum_allowed_code_point);
  1816. return {};
  1817. }
  1818. // 2. If start value is greater than end value, the <urange> is invalid and a syntax error.
  1819. if (start_value > end_value) {
  1820. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: start_value ({}) > end_value ({})", start_value, end_value);
  1821. return {};
  1822. }
  1823. // 3. Otherwise, the <urange> represents a contiguous range of codepoints from start value to end value, inclusive.
  1824. return Gfx::UnicodeRange { start_value, end_value };
  1825. };
  1826. // 1. Skipping the first u token, concatenate the representations of all the tokens in the production together.
  1827. // Let this be text.
  1828. // NOTE: The concatenation is already done by the caller.
  1829. GenericLexer lexer { text };
  1830. // 2. If the first character of text is U+002B PLUS SIGN, consume it.
  1831. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  1832. if (lexer.next_is('+')) {
  1833. lexer.consume();
  1834. } else {
  1835. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Second character of <urange> was not '+'; got: '{}'", lexer.consume());
  1836. return {};
  1837. }
  1838. // 3. Consume as many hex digits from text as possible.
  1839. // then consume as many U+003F QUESTION MARK (?) code points as possible.
  1840. auto hex_digits = lexer.consume_while(is_ascii_hex_digit);
  1841. auto question_marks = lexer.consume_while([](auto it) { return it == '?'; });
  1842. // If zero code points were consumed, or more than six code points were consumed,
  1843. // this is an invalid <urange>, and this algorithm must exit.
  1844. size_t consumed_code_points = hex_digits.length() + question_marks.length();
  1845. if (consumed_code_points == 0 || consumed_code_points > 6) {
  1846. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value had {} digits/?s, expected between 1 and 6.", consumed_code_points);
  1847. return {};
  1848. }
  1849. StringView start_value_code_points { hex_digits.characters_without_null_termination(), consumed_code_points };
  1850. // If any U+003F QUESTION MARK (?) code points were consumed, then:
  1851. if (question_marks.length() > 0) {
  1852. // 1. If there are any code points left in text, this is an invalid <urange>,
  1853. // and this algorithm must exit.
  1854. if (lexer.tell_remaining() != 0) {
  1855. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  1856. return {};
  1857. }
  1858. // 2. Interpret the consumed code points as a hexadecimal number,
  1859. // with the U+003F QUESTION MARK (?) code points replaced by U+0030 DIGIT ZERO (0) code points.
  1860. // This is the start value.
  1861. auto start_value_string = start_value_code_points.replace("?"sv, "0"sv, ReplaceMode::All);
  1862. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_string);
  1863. if (!maybe_start_value.has_value()) {
  1864. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted start value did not parse as hex number.");
  1865. return {};
  1866. }
  1867. u32 start_value = maybe_start_value.release_value();
  1868. // 3. Interpret the consumed code points as a hexadecimal number again,
  1869. // with the U+003F QUESTION MARK (?) code points replaced by U+0046 LATIN CAPITAL LETTER F (F) code points.
  1870. // This is the end value.
  1871. auto end_value_string = start_value_code_points.replace("?"sv, "F"sv, ReplaceMode::All);
  1872. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_value_string);
  1873. if (!maybe_end_value.has_value()) {
  1874. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted end value did not parse as hex number.");
  1875. return {};
  1876. }
  1877. u32 end_value = maybe_end_value.release_value();
  1878. // 4. Exit this algorithm.
  1879. return make_valid_unicode_range(start_value, end_value);
  1880. }
  1881. // Otherwise, interpret the consumed code points as a hexadecimal number. This is the start value.
  1882. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_code_points);
  1883. if (!maybe_start_value.has_value()) {
  1884. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value did not parse as hex number.");
  1885. return {};
  1886. }
  1887. u32 start_value = maybe_start_value.release_value();
  1888. // 4. If there are no code points left in text, The end value is the same as the start value.
  1889. // Exit this algorithm.
  1890. if (lexer.tell_remaining() == 0)
  1891. return make_valid_unicode_range(start_value, start_value);
  1892. // 5. If the next code point in text is U+002D HYPHEN-MINUS (-), consume it.
  1893. if (lexer.next_is('-')) {
  1894. lexer.consume();
  1895. }
  1896. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  1897. else {
  1898. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start and end values not separated by '-'.");
  1899. return {};
  1900. }
  1901. // 6. Consume as many hex digits as possible from text.
  1902. auto end_hex_digits = lexer.consume_while(is_ascii_hex_digit);
  1903. // If zero hex digits were consumed, or more than 6 hex digits were consumed,
  1904. // this is an invalid <urange>, and this algorithm must exit.
  1905. if (end_hex_digits.length() == 0 || end_hex_digits.length() > 6) {
  1906. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value had {} digits, expected between 1 and 6.", end_hex_digits.length());
  1907. return {};
  1908. }
  1909. // If there are any code points left in text, this is an invalid <urange>, and this algorithm must exit.
  1910. if (lexer.tell_remaining() != 0) {
  1911. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  1912. return {};
  1913. }
  1914. // 7. Interpret the consumed code points as a hexadecimal number. This is the end value.
  1915. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_hex_digits);
  1916. if (!maybe_end_value.has_value()) {
  1917. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value did not parse as hex number.");
  1918. return {};
  1919. }
  1920. u32 end_value = maybe_end_value.release_value();
  1921. return make_valid_unicode_range(start_value, end_value);
  1922. }
  1923. Vector<Gfx::UnicodeRange> Parser::parse_unicode_ranges(TokenStream<ComponentValue>& tokens)
  1924. {
  1925. Vector<Gfx::UnicodeRange> unicode_ranges;
  1926. auto range_token_lists = parse_a_comma_separated_list_of_component_values(tokens);
  1927. for (auto& range_tokens : range_token_lists) {
  1928. TokenStream range_token_stream { range_tokens };
  1929. auto maybe_unicode_range = parse_unicode_range(range_token_stream);
  1930. if (!maybe_unicode_range.has_value()) {
  1931. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: unicode-range format invalid; discarding.");
  1932. return {};
  1933. }
  1934. unicode_ranges.append(maybe_unicode_range.release_value());
  1935. }
  1936. return unicode_ranges;
  1937. }
  1938. RefPtr<CSSStyleValue> Parser::parse_dimension_value(TokenStream<ComponentValue>& tokens)
  1939. {
  1940. if (auto dimension = parse_dimension(tokens.peek_token()); dimension.has_value()) {
  1941. (void)tokens.next_token(); // dimension
  1942. if (dimension->is_angle())
  1943. return AngleStyleValue::create(dimension->angle());
  1944. if (dimension->is_frequency())
  1945. return FrequencyStyleValue::create(dimension->frequency());
  1946. if (dimension->is_length())
  1947. return LengthStyleValue::create(dimension->length());
  1948. if (dimension->is_percentage())
  1949. return PercentageStyleValue::create(dimension->percentage());
  1950. if (dimension->is_resolution())
  1951. return ResolutionStyleValue::create(dimension->resolution());
  1952. if (dimension->is_time())
  1953. return TimeStyleValue::create(dimension->time());
  1954. VERIFY_NOT_REACHED();
  1955. }
  1956. if (auto calc = parse_calculated_value(tokens.peek_token()); calc && calc->resolves_to_dimension()) {
  1957. (void)tokens.next_token(); // calc
  1958. return calc;
  1959. }
  1960. return nullptr;
  1961. }
  1962. RefPtr<CSSStyleValue> Parser::parse_integer_value(TokenStream<ComponentValue>& tokens)
  1963. {
  1964. auto peek_token = tokens.peek_token();
  1965. if (peek_token.is(Token::Type::Number) && peek_token.token().number().is_integer()) {
  1966. (void)tokens.next_token(); // integer
  1967. return IntegerStyleValue::create(peek_token.token().number().integer_value());
  1968. }
  1969. if (auto calc = parse_calculated_value(peek_token); calc && calc->resolves_to_number()) {
  1970. (void)tokens.next_token(); // calc
  1971. return calc;
  1972. }
  1973. return nullptr;
  1974. }
  1975. RefPtr<CSSStyleValue> Parser::parse_number_value(TokenStream<ComponentValue>& tokens)
  1976. {
  1977. auto peek_token = tokens.peek_token();
  1978. if (peek_token.is(Token::Type::Number)) {
  1979. (void)tokens.next_token(); // number
  1980. return NumberStyleValue::create(peek_token.token().number().value());
  1981. }
  1982. if (auto calc = parse_calculated_value(peek_token); calc && calc->resolves_to_number()) {
  1983. (void)tokens.next_token(); // calc
  1984. return calc;
  1985. }
  1986. return nullptr;
  1987. }
  1988. RefPtr<CSSStyleValue> Parser::parse_number_percentage_value(TokenStream<ComponentValue>& tokens)
  1989. {
  1990. auto peek_token = tokens.peek_token();
  1991. if (peek_token.is(Token::Type::Number)) {
  1992. (void)tokens.next_token(); // number
  1993. return NumberStyleValue::create(peek_token.token().number().value());
  1994. }
  1995. if (peek_token.is(Token::Type::Percentage)) {
  1996. (void)tokens.next_token(); // percentage
  1997. return PercentageStyleValue::create(Percentage(peek_token.token().percentage()));
  1998. }
  1999. if (auto calc = parse_calculated_value(peek_token); calc && calc->resolves_to_number_percentage()) {
  2000. (void)tokens.next_token(); // calc
  2001. return calc;
  2002. }
  2003. return nullptr;
  2004. }
  2005. RefPtr<CSSStyleValue> Parser::parse_percentage_value(TokenStream<ComponentValue>& tokens)
  2006. {
  2007. auto peek_token = tokens.peek_token();
  2008. if (peek_token.is(Token::Type::Percentage)) {
  2009. (void)tokens.next_token(); // percentage
  2010. return PercentageStyleValue::create(Percentage(peek_token.token().percentage()));
  2011. }
  2012. if (auto calc = parse_calculated_value(peek_token); calc && calc->resolves_to_percentage()) {
  2013. (void)tokens.next_token(); // calc
  2014. return calc;
  2015. }
  2016. return nullptr;
  2017. }
  2018. RefPtr<CSSStyleValue> Parser::parse_angle_value(TokenStream<ComponentValue>& tokens)
  2019. {
  2020. auto transaction = tokens.begin_transaction();
  2021. if (auto dimension_value = parse_dimension_value(tokens)) {
  2022. if (dimension_value->is_angle()
  2023. || (dimension_value->is_calculated() && dimension_value->as_calculated().resolves_to_angle())) {
  2024. transaction.commit();
  2025. return dimension_value;
  2026. }
  2027. }
  2028. return nullptr;
  2029. }
  2030. RefPtr<CSSStyleValue> Parser::parse_angle_percentage_value(TokenStream<ComponentValue>& tokens)
  2031. {
  2032. auto transaction = tokens.begin_transaction();
  2033. if (auto dimension_value = parse_dimension_value(tokens)) {
  2034. if (dimension_value->is_angle() || dimension_value->is_percentage()
  2035. || (dimension_value->is_calculated() && dimension_value->as_calculated().resolves_to_angle_percentage())) {
  2036. transaction.commit();
  2037. return dimension_value;
  2038. }
  2039. }
  2040. return nullptr;
  2041. }
  2042. RefPtr<CSSStyleValue> Parser::parse_flex_value(TokenStream<ComponentValue>& tokens)
  2043. {
  2044. auto transaction = tokens.begin_transaction();
  2045. if (auto dimension_value = parse_dimension_value(tokens)) {
  2046. if (dimension_value->is_flex()
  2047. || (dimension_value->is_calculated() && dimension_value->as_calculated().resolves_to_flex())) {
  2048. transaction.commit();
  2049. return dimension_value;
  2050. }
  2051. }
  2052. return nullptr;
  2053. }
  2054. RefPtr<CSSStyleValue> Parser::parse_frequency_value(TokenStream<ComponentValue>& tokens)
  2055. {
  2056. auto transaction = tokens.begin_transaction();
  2057. if (auto dimension_value = parse_dimension_value(tokens)) {
  2058. if (dimension_value->is_frequency()
  2059. || (dimension_value->is_calculated() && dimension_value->as_calculated().resolves_to_frequency())) {
  2060. transaction.commit();
  2061. return dimension_value;
  2062. }
  2063. }
  2064. return nullptr;
  2065. }
  2066. RefPtr<CSSStyleValue> Parser::parse_frequency_percentage_value(TokenStream<ComponentValue>& tokens)
  2067. {
  2068. auto transaction = tokens.begin_transaction();
  2069. if (auto dimension_value = parse_dimension_value(tokens)) {
  2070. if (dimension_value->is_frequency() || dimension_value->is_percentage()
  2071. || (dimension_value->is_calculated() && dimension_value->as_calculated().resolves_to_frequency_percentage())) {
  2072. transaction.commit();
  2073. return dimension_value;
  2074. }
  2075. }
  2076. return nullptr;
  2077. }
  2078. RefPtr<CSSStyleValue> Parser::parse_length_value(TokenStream<ComponentValue>& tokens)
  2079. {
  2080. auto transaction = tokens.begin_transaction();
  2081. if (auto dimension_value = parse_dimension_value(tokens)) {
  2082. if (dimension_value->is_length()
  2083. || (dimension_value->is_calculated() && dimension_value->as_calculated().resolves_to_length())) {
  2084. transaction.commit();
  2085. return dimension_value;
  2086. }
  2087. }
  2088. return nullptr;
  2089. }
  2090. RefPtr<CSSStyleValue> Parser::parse_length_percentage_value(TokenStream<ComponentValue>& tokens)
  2091. {
  2092. auto transaction = tokens.begin_transaction();
  2093. if (auto dimension_value = parse_dimension_value(tokens)) {
  2094. if (dimension_value->is_length() || dimension_value->is_percentage()
  2095. || (dimension_value->is_calculated() && dimension_value->as_calculated().resolves_to_length_percentage())) {
  2096. transaction.commit();
  2097. return dimension_value;
  2098. }
  2099. }
  2100. return nullptr;
  2101. }
  2102. RefPtr<CSSStyleValue> Parser::parse_resolution_value(TokenStream<ComponentValue>& tokens)
  2103. {
  2104. auto transaction = tokens.begin_transaction();
  2105. if (auto dimension_value = parse_dimension_value(tokens)) {
  2106. if (dimension_value->is_resolution()
  2107. || (dimension_value->is_calculated() && dimension_value->as_calculated().resolves_to_resolution())) {
  2108. transaction.commit();
  2109. return dimension_value;
  2110. }
  2111. }
  2112. return nullptr;
  2113. }
  2114. RefPtr<CSSStyleValue> Parser::parse_time_value(TokenStream<ComponentValue>& tokens)
  2115. {
  2116. auto transaction = tokens.begin_transaction();
  2117. if (auto dimension_value = parse_dimension_value(tokens)) {
  2118. if (dimension_value->is_time()
  2119. || (dimension_value->is_calculated() && dimension_value->as_calculated().resolves_to_time())) {
  2120. transaction.commit();
  2121. return dimension_value;
  2122. }
  2123. }
  2124. return nullptr;
  2125. }
  2126. RefPtr<CSSStyleValue> Parser::parse_time_percentage_value(TokenStream<ComponentValue>& tokens)
  2127. {
  2128. auto transaction = tokens.begin_transaction();
  2129. if (auto dimension_value = parse_dimension_value(tokens)) {
  2130. if (dimension_value->is_time() || dimension_value->is_percentage()
  2131. || (dimension_value->is_calculated() && dimension_value->as_calculated().resolves_to_time_percentage())) {
  2132. transaction.commit();
  2133. return dimension_value;
  2134. }
  2135. }
  2136. return nullptr;
  2137. }
  2138. RefPtr<CSSStyleValue> Parser::parse_keyword_value(TokenStream<ComponentValue>& tokens)
  2139. {
  2140. auto peek_token = tokens.peek_token();
  2141. if (peek_token.is(Token::Type::Ident)) {
  2142. auto keyword = keyword_from_string(peek_token.token().ident());
  2143. if (keyword.has_value()) {
  2144. (void)tokens.next_token(); // ident
  2145. return CSSKeywordValue::create(keyword.value());
  2146. }
  2147. }
  2148. return nullptr;
  2149. }
  2150. // https://www.w3.org/TR/CSS2/visufx.html#value-def-shape
  2151. RefPtr<CSSStyleValue> Parser::parse_rect_value(TokenStream<ComponentValue>& tokens)
  2152. {
  2153. auto transaction = tokens.begin_transaction();
  2154. auto function_token = tokens.next_token();
  2155. if (!function_token.is_function("rect"sv))
  2156. return nullptr;
  2157. Vector<Length, 4> params;
  2158. auto argument_tokens = TokenStream { function_token.function().values() };
  2159. enum class CommaRequirement {
  2160. Unknown,
  2161. RequiresCommas,
  2162. RequiresNoCommas
  2163. };
  2164. enum class Side {
  2165. Top = 0,
  2166. Right = 1,
  2167. Bottom = 2,
  2168. Left = 3
  2169. };
  2170. auto comma_requirement = CommaRequirement::Unknown;
  2171. // In CSS 2.1, the only valid <shape> value is: rect(<top>, <right>, <bottom>, <left>) where
  2172. // <top> and <bottom> specify offsets from the top border edge of the box, and <right>, and
  2173. // <left> specify offsets from the left border edge of the box.
  2174. for (size_t side = 0; side < 4; side++) {
  2175. argument_tokens.skip_whitespace();
  2176. // <top>, <right>, <bottom>, and <left> may either have a <length> value or 'auto'.
  2177. // Negative lengths are permitted.
  2178. if (argument_tokens.peek_token().is_ident("auto"sv)) {
  2179. (void)argument_tokens.next_token(); // `auto`
  2180. params.append(Length::make_auto());
  2181. } else {
  2182. auto maybe_length = parse_length(argument_tokens);
  2183. if (!maybe_length.has_value())
  2184. return nullptr;
  2185. // FIXME: Support calculated lengths
  2186. params.append(maybe_length.value().value());
  2187. }
  2188. argument_tokens.skip_whitespace();
  2189. // The last side, should be no more tokens following it.
  2190. if (static_cast<Side>(side) == Side::Left) {
  2191. if (argument_tokens.has_next_token())
  2192. return nullptr;
  2193. break;
  2194. }
  2195. bool next_is_comma = argument_tokens.peek_token().is(Token::Type::Comma);
  2196. // Authors should separate offset values with commas. User agents must support separation
  2197. // with commas, but may also support separation without commas (but not a combination),
  2198. // because a previous revision of this specification was ambiguous in this respect.
  2199. if (comma_requirement == CommaRequirement::Unknown)
  2200. comma_requirement = next_is_comma ? CommaRequirement::RequiresCommas : CommaRequirement::RequiresNoCommas;
  2201. if (comma_requirement == CommaRequirement::RequiresCommas) {
  2202. if (next_is_comma)
  2203. argument_tokens.next_token();
  2204. else
  2205. return nullptr;
  2206. } else if (comma_requirement == CommaRequirement::RequiresNoCommas) {
  2207. if (next_is_comma)
  2208. return nullptr;
  2209. } else {
  2210. VERIFY_NOT_REACHED();
  2211. }
  2212. }
  2213. transaction.commit();
  2214. return RectStyleValue::create(EdgeRect { params[0], params[1], params[2], params[3] });
  2215. }
  2216. // https://www.w3.org/TR/css-color-4/#typedef-hue
  2217. RefPtr<CSSStyleValue> Parser::parse_hue_value(TokenStream<ComponentValue>& tokens)
  2218. {
  2219. // <hue> = <number> | <angle>
  2220. if (auto number = parse_number_value(tokens))
  2221. return number;
  2222. if (auto angle = parse_angle_value(tokens))
  2223. return angle;
  2224. return nullptr;
  2225. }
  2226. RefPtr<CSSStyleValue> Parser::parse_solidus_and_alpha_value(TokenStream<ComponentValue>& tokens)
  2227. {
  2228. // [ / [<alpha-value> | none] ]?
  2229. // Common to the modern-syntax color functions.
  2230. // TODO: Parse `none`
  2231. auto transaction = tokens.begin_transaction();
  2232. tokens.skip_whitespace();
  2233. if (!tokens.next_token().is_delim('/'))
  2234. return {};
  2235. tokens.skip_whitespace();
  2236. auto alpha = parse_number_percentage_value(tokens);
  2237. if (!alpha)
  2238. return {};
  2239. tokens.skip_whitespace();
  2240. transaction.commit();
  2241. return alpha;
  2242. }
  2243. // https://www.w3.org/TR/css-color-4/#funcdef-rgb
  2244. RefPtr<CSSStyleValue> Parser::parse_rgb_color_value(TokenStream<ComponentValue>& outer_tokens)
  2245. {
  2246. // rgb() = [ <legacy-rgb-syntax> | <modern-rgb-syntax> ]
  2247. // rgba() = [ <legacy-rgba-syntax> | <modern-rgba-syntax> ]
  2248. // <legacy-rgb-syntax> = rgb( <percentage>#{3} , <alpha-value>? ) |
  2249. // rgb( <number>#{3} , <alpha-value>? )
  2250. // <legacy-rgba-syntax> = rgba( <percentage>#{3} , <alpha-value>? ) |
  2251. // rgba( <number>#{3} , <alpha-value>? )
  2252. // <modern-rgb-syntax> = rgb(
  2253. // [ <number> | <percentage> | none]{3}
  2254. // [ / [<alpha-value> | none] ]? )
  2255. // <modern-rgba-syntax> = rgba(
  2256. // [ <number> | <percentage> | none]{3}
  2257. // [ / [<alpha-value> | none] ]? )
  2258. // TODO: Handle none values
  2259. auto transaction = outer_tokens.begin_transaction();
  2260. outer_tokens.skip_whitespace();
  2261. auto& function_token = outer_tokens.next_token();
  2262. if (!function_token.is_function("rgb"sv) && !function_token.is_function("rgba"sv))
  2263. return {};
  2264. RefPtr<CSSStyleValue> red;
  2265. RefPtr<CSSStyleValue> green;
  2266. RefPtr<CSSStyleValue> blue;
  2267. RefPtr<CSSStyleValue> alpha;
  2268. auto inner_tokens = TokenStream { function_token.function().values() };
  2269. inner_tokens.skip_whitespace();
  2270. red = parse_number_percentage_value(inner_tokens);
  2271. if (!red)
  2272. return {};
  2273. inner_tokens.skip_whitespace();
  2274. bool legacy_syntax = inner_tokens.peek_token().is(Token::Type::Comma);
  2275. if (legacy_syntax) {
  2276. // Legacy syntax
  2277. // <percentage>#{3} , <alpha-value>?
  2278. // | <number>#{3} , <alpha-value>?
  2279. // So, r/g/b can be numbers or percentages, as long as they're all the same type.
  2280. inner_tokens.next_token(); // comma
  2281. inner_tokens.skip_whitespace();
  2282. green = parse_number_percentage_value(inner_tokens);
  2283. if (!green)
  2284. return {};
  2285. inner_tokens.skip_whitespace();
  2286. if (!inner_tokens.next_token().is(Token::Type::Comma))
  2287. return {};
  2288. inner_tokens.skip_whitespace();
  2289. blue = parse_number_percentage_value(inner_tokens);
  2290. if (!blue)
  2291. return {};
  2292. inner_tokens.skip_whitespace();
  2293. if (inner_tokens.has_next_token()) {
  2294. // Try and read comma and alpha
  2295. if (!inner_tokens.next_token().is(Token::Type::Comma))
  2296. return {};
  2297. inner_tokens.skip_whitespace();
  2298. alpha = parse_number_percentage_value(inner_tokens);
  2299. inner_tokens.skip_whitespace();
  2300. if (inner_tokens.has_next_token())
  2301. return {};
  2302. }
  2303. // Verify we're all percentages or all numbers
  2304. auto is_percentage = [](CSSStyleValue const& style_value) {
  2305. return style_value.is_percentage()
  2306. || (style_value.is_calculated() && style_value.as_calculated().resolves_to_percentage());
  2307. };
  2308. bool red_is_percentage = is_percentage(*red);
  2309. bool green_is_percentage = is_percentage(*green);
  2310. bool blue_is_percentage = is_percentage(*blue);
  2311. if (red_is_percentage != green_is_percentage || red_is_percentage != blue_is_percentage)
  2312. return {};
  2313. } else {
  2314. // Modern syntax
  2315. // [ <number> | <percentage> | none]{3} [ / [<alpha-value> | none] ]?
  2316. green = parse_number_percentage_value(inner_tokens);
  2317. if (!green)
  2318. return {};
  2319. inner_tokens.skip_whitespace();
  2320. blue = parse_number_percentage_value(inner_tokens);
  2321. if (!blue)
  2322. return {};
  2323. inner_tokens.skip_whitespace();
  2324. if (inner_tokens.has_next_token()) {
  2325. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2326. if (!alpha || inner_tokens.has_next_token())
  2327. return {};
  2328. }
  2329. }
  2330. if (!alpha)
  2331. alpha = NumberStyleValue::create(1);
  2332. transaction.commit();
  2333. return CSSRGB::create(red.release_nonnull(), green.release_nonnull(), blue.release_nonnull(), alpha.release_nonnull());
  2334. }
  2335. // https://www.w3.org/TR/css-color-4/#funcdef-hsl
  2336. RefPtr<CSSStyleValue> Parser::parse_hsl_color_value(TokenStream<ComponentValue>& outer_tokens)
  2337. {
  2338. // hsl() = [ <legacy-hsl-syntax> | <modern-hsl-syntax> ]
  2339. // hsla() = [ <legacy-hsla-syntax> | <modern-hsla-syntax> ]
  2340. // <modern-hsl-syntax> = hsl(
  2341. // [<hue> | none]
  2342. // [<percentage> | <number> | none]
  2343. // [<percentage> | <number> | none]
  2344. // [ / [<alpha-value> | none] ]? )
  2345. // <modern-hsla-syntax> = hsla(
  2346. // [<hue> | none]
  2347. // [<percentage> | <number> | none]
  2348. // [<percentage> | <number> | none]
  2349. // [ / [<alpha-value> | none] ]? )
  2350. // <legacy-hsl-syntax> = hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )
  2351. // <legacy-hsla-syntax> = hsla( <hue>, <percentage>, <percentage>, <alpha-value>? )
  2352. // TODO: Handle none values
  2353. auto transaction = outer_tokens.begin_transaction();
  2354. outer_tokens.skip_whitespace();
  2355. auto& function_token = outer_tokens.next_token();
  2356. if (!function_token.is_function("hsl"sv) && !function_token.is_function("hsla"sv))
  2357. return {};
  2358. RefPtr<CSSStyleValue> h;
  2359. RefPtr<CSSStyleValue> s;
  2360. RefPtr<CSSStyleValue> l;
  2361. RefPtr<CSSStyleValue> alpha;
  2362. auto inner_tokens = TokenStream { function_token.function().values() };
  2363. inner_tokens.skip_whitespace();
  2364. h = parse_hue_value(inner_tokens);
  2365. if (!h)
  2366. return {};
  2367. inner_tokens.skip_whitespace();
  2368. bool legacy_syntax = inner_tokens.peek_token().is(Token::Type::Comma);
  2369. if (legacy_syntax) {
  2370. // Legacy syntax
  2371. // <hue>, <percentage>, <percentage>, <alpha-value>?
  2372. (void)inner_tokens.next_token(); // comma
  2373. inner_tokens.skip_whitespace();
  2374. s = parse_percentage_value(inner_tokens);
  2375. if (!s)
  2376. return {};
  2377. inner_tokens.skip_whitespace();
  2378. if (!inner_tokens.next_token().is(Token::Type::Comma))
  2379. return {};
  2380. inner_tokens.skip_whitespace();
  2381. l = parse_percentage_value(inner_tokens);
  2382. if (!l)
  2383. return {};
  2384. inner_tokens.skip_whitespace();
  2385. if (inner_tokens.has_next_token()) {
  2386. // Try and read comma and alpha
  2387. if (!inner_tokens.next_token().is(Token::Type::Comma))
  2388. return {};
  2389. inner_tokens.skip_whitespace();
  2390. alpha = parse_number_percentage_value(inner_tokens);
  2391. inner_tokens.skip_whitespace();
  2392. if (inner_tokens.has_next_token())
  2393. return {};
  2394. }
  2395. } else {
  2396. // Modern syntax
  2397. // [<hue> | none]
  2398. // [<percentage> | <number> | none]
  2399. // [<percentage> | <number> | none]
  2400. // [ / [<alpha-value> | none] ]?
  2401. s = parse_number_percentage_value(inner_tokens);
  2402. if (!s)
  2403. return {};
  2404. inner_tokens.skip_whitespace();
  2405. l = parse_number_percentage_value(inner_tokens);
  2406. if (!l)
  2407. return {};
  2408. inner_tokens.skip_whitespace();
  2409. if (inner_tokens.has_next_token()) {
  2410. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2411. if (!alpha || inner_tokens.has_next_token())
  2412. return {};
  2413. }
  2414. }
  2415. if (!alpha)
  2416. alpha = NumberStyleValue::create(1);
  2417. transaction.commit();
  2418. return CSSHSL::create(h.release_nonnull(), s.release_nonnull(), l.release_nonnull(), alpha.release_nonnull());
  2419. }
  2420. // https://www.w3.org/TR/css-color-4/#funcdef-hwb
  2421. RefPtr<CSSStyleValue> Parser::parse_hwb_color_value(TokenStream<ComponentValue>& outer_tokens)
  2422. {
  2423. // hwb() = hwb(
  2424. // [<hue> | none]
  2425. // [<percentage> | <number> | none]
  2426. // [<percentage> | <number> | none]
  2427. // [ / [<alpha-value> | none] ]? )
  2428. auto transaction = outer_tokens.begin_transaction();
  2429. outer_tokens.skip_whitespace();
  2430. auto& function_token = outer_tokens.next_token();
  2431. if (!function_token.is_function("hwb"sv))
  2432. return {};
  2433. RefPtr<CSSStyleValue> h;
  2434. RefPtr<CSSStyleValue> w;
  2435. RefPtr<CSSStyleValue> b;
  2436. RefPtr<CSSStyleValue> alpha;
  2437. auto inner_tokens = TokenStream { function_token.function().values() };
  2438. inner_tokens.skip_whitespace();
  2439. h = parse_hue_value(inner_tokens);
  2440. if (!h)
  2441. return {};
  2442. inner_tokens.skip_whitespace();
  2443. w = parse_number_percentage_value(inner_tokens);
  2444. if (!w)
  2445. return {};
  2446. inner_tokens.skip_whitespace();
  2447. b = parse_number_percentage_value(inner_tokens);
  2448. if (!b)
  2449. return {};
  2450. inner_tokens.skip_whitespace();
  2451. if (inner_tokens.has_next_token()) {
  2452. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2453. if (!alpha || inner_tokens.has_next_token())
  2454. return {};
  2455. }
  2456. if (!alpha)
  2457. alpha = NumberStyleValue::create(1);
  2458. transaction.commit();
  2459. return CSSHWB::create(h.release_nonnull(), w.release_nonnull(), b.release_nonnull(), alpha.release_nonnull());
  2460. }
  2461. // https://www.w3.org/TR/css-color-4/#funcdef-oklab
  2462. RefPtr<CSSStyleValue> Parser::parse_oklab_color_value(TokenStream<ComponentValue>& outer_tokens)
  2463. {
  2464. // oklab() = oklab( [ <percentage> | <number> | none]
  2465. // [ <percentage> | <number> | none]
  2466. // [ <percentage> | <number> | none]
  2467. // [ / [<alpha-value> | none] ]? )
  2468. auto transaction = outer_tokens.begin_transaction();
  2469. outer_tokens.skip_whitespace();
  2470. auto& function_token = outer_tokens.next_token();
  2471. if (!function_token.is_function("oklab"sv))
  2472. return {};
  2473. RefPtr<CSSStyleValue> l;
  2474. RefPtr<CSSStyleValue> a;
  2475. RefPtr<CSSStyleValue> b;
  2476. RefPtr<CSSStyleValue> alpha;
  2477. auto inner_tokens = TokenStream { function_token.function().values() };
  2478. inner_tokens.skip_whitespace();
  2479. l = parse_number_percentage_value(inner_tokens);
  2480. if (!l)
  2481. return {};
  2482. inner_tokens.skip_whitespace();
  2483. a = parse_number_percentage_value(inner_tokens);
  2484. if (!a)
  2485. return {};
  2486. inner_tokens.skip_whitespace();
  2487. b = parse_number_percentage_value(inner_tokens);
  2488. if (!b)
  2489. return {};
  2490. inner_tokens.skip_whitespace();
  2491. if (inner_tokens.has_next_token()) {
  2492. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2493. if (!alpha || inner_tokens.has_next_token())
  2494. return {};
  2495. }
  2496. if (!alpha)
  2497. alpha = NumberStyleValue::create(1);
  2498. transaction.commit();
  2499. return CSSOKLab::create(l.release_nonnull(), a.release_nonnull(), b.release_nonnull(), alpha.release_nonnull());
  2500. }
  2501. // https://www.w3.org/TR/css-color-4/#funcdef-oklch
  2502. RefPtr<CSSStyleValue> Parser::parse_oklch_color_value(TokenStream<ComponentValue>& outer_tokens)
  2503. {
  2504. // oklch() = oklch( [ <percentage> | <number> | none]
  2505. // [ <percentage> | <number> | none]
  2506. // [ <hue> | none]
  2507. // [ / [<alpha-value> | none] ]? )
  2508. auto transaction = outer_tokens.begin_transaction();
  2509. outer_tokens.skip_whitespace();
  2510. auto& function_token = outer_tokens.next_token();
  2511. if (!function_token.is_function("oklch"sv))
  2512. return {};
  2513. RefPtr<CSSStyleValue> l;
  2514. RefPtr<CSSStyleValue> c;
  2515. RefPtr<CSSStyleValue> h;
  2516. RefPtr<CSSStyleValue> alpha;
  2517. auto inner_tokens = TokenStream { function_token.function().values() };
  2518. inner_tokens.skip_whitespace();
  2519. l = parse_number_percentage_value(inner_tokens);
  2520. if (!l)
  2521. return {};
  2522. inner_tokens.skip_whitespace();
  2523. c = parse_number_percentage_value(inner_tokens);
  2524. if (!c)
  2525. return {};
  2526. inner_tokens.skip_whitespace();
  2527. h = parse_hue_value(inner_tokens);
  2528. if (!h)
  2529. return {};
  2530. inner_tokens.skip_whitespace();
  2531. if (inner_tokens.has_next_token()) {
  2532. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2533. if (!alpha || inner_tokens.has_next_token())
  2534. return {};
  2535. }
  2536. if (!alpha)
  2537. alpha = NumberStyleValue::create(1);
  2538. transaction.commit();
  2539. return CSSOKLCH::create(l.release_nonnull(), c.release_nonnull(), h.release_nonnull(), alpha.release_nonnull());
  2540. }
  2541. // https://www.w3.org/TR/css-color-4/#color-syntax
  2542. RefPtr<CSSStyleValue> Parser::parse_color_value(TokenStream<ComponentValue>& tokens)
  2543. {
  2544. // Keywords: <system-color> | <deprecated-color> | currentColor
  2545. {
  2546. auto transaction = tokens.begin_transaction();
  2547. if (auto keyword = parse_keyword_value(tokens); keyword && keyword->has_color()) {
  2548. transaction.commit();
  2549. return keyword;
  2550. }
  2551. }
  2552. // Functions
  2553. if (auto rgb = parse_rgb_color_value(tokens))
  2554. return rgb;
  2555. if (auto hsl = parse_hsl_color_value(tokens))
  2556. return hsl;
  2557. if (auto hwb = parse_hwb_color_value(tokens))
  2558. return hwb;
  2559. if (auto oklab = parse_oklab_color_value(tokens))
  2560. return oklab;
  2561. if (auto oklch = parse_oklch_color_value(tokens))
  2562. return oklch;
  2563. auto transaction = tokens.begin_transaction();
  2564. tokens.skip_whitespace();
  2565. auto component_value = tokens.next_token();
  2566. if (component_value.is(Token::Type::Ident)) {
  2567. auto ident = component_value.token().ident();
  2568. auto color = Color::from_string(ident);
  2569. if (color.has_value()) {
  2570. transaction.commit();
  2571. return CSSColorValue::create_from_color(color.release_value());
  2572. }
  2573. // Otherwise, fall through to the hashless-hex-color case
  2574. }
  2575. if (component_value.is(Token::Type::Hash)) {
  2576. auto color = Color::from_string(MUST(String::formatted("#{}", component_value.token().hash_value())));
  2577. if (color.has_value()) {
  2578. transaction.commit();
  2579. return CSSColorValue::create_from_color(color.release_value());
  2580. }
  2581. return {};
  2582. }
  2583. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  2584. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  2585. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  2586. // aborting on the first step that returns a value:
  2587. // 1. Let cv be the component value.
  2588. auto const& cv = component_value;
  2589. String serialization;
  2590. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  2591. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  2592. // 1. If cv’s type flag is not "integer", return an error.
  2593. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  2594. if (!cv.token().number().is_integer())
  2595. return {};
  2596. // 2. If cv’s value is less than zero, return an error.
  2597. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  2598. if (value < 0)
  2599. return {};
  2600. // 3. Let serialization be the serialization of cv’s value, as a base-ten integer using digits 0-9 (U+0030 to U+0039) in the shortest form possible.
  2601. StringBuilder serialization_builder;
  2602. serialization_builder.appendff("{}", value);
  2603. // 4. If cv is a <dimension-token>, append the unit to serialization.
  2604. if (cv.is(Token::Type::Dimension))
  2605. serialization_builder.append(cv.token().dimension_unit());
  2606. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  2607. serialization = MUST(serialization_builder.to_string());
  2608. if (serialization_builder.length() < 6) {
  2609. StringBuilder builder;
  2610. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  2611. builder.append('0');
  2612. builder.append(serialization_builder.string_view());
  2613. serialization = MUST(builder.to_string());
  2614. }
  2615. }
  2616. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  2617. else {
  2618. if (!cv.is(Token::Type::Ident))
  2619. return {};
  2620. serialization = cv.token().ident().to_string();
  2621. }
  2622. // 4. If serialization does not consist of three or six characters, return an error.
  2623. if (serialization.bytes().size() != 3 && serialization.bytes().size() != 6)
  2624. return {};
  2625. // 5. If serialization contains any characters not in the range [0-9A-Fa-f] (U+0030 to U+0039, U+0041 to U+0046, U+0061 to U+0066), return an error.
  2626. for (auto c : serialization.bytes_as_string_view()) {
  2627. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  2628. return {};
  2629. }
  2630. // 6. Return the concatenation of "#" (U+0023) and serialization.
  2631. auto color = Color::from_string(MUST(String::formatted("#{}", serialization)));
  2632. if (color.has_value()) {
  2633. transaction.commit();
  2634. return CSSColorValue::create_from_color(color.release_value());
  2635. }
  2636. }
  2637. return {};
  2638. }
  2639. // https://drafts.csswg.org/css-lists-3/#counter-functions
  2640. RefPtr<CSSStyleValue> Parser::parse_counter_value(TokenStream<ComponentValue>& tokens)
  2641. {
  2642. auto parse_counter_name = [this](TokenStream<ComponentValue>& tokens) -> Optional<FlyString> {
  2643. // https://drafts.csswg.org/css-lists-3/#typedef-counter-name
  2644. // Counters are referred to in CSS syntax using the <counter-name> type, which represents
  2645. // their name as a <custom-ident>. A <counter-name> name cannot match the keyword none;
  2646. // such an identifier is invalid as a <counter-name>.
  2647. auto transaction = tokens.begin_transaction();
  2648. tokens.skip_whitespace();
  2649. auto counter_name = parse_custom_ident_value(tokens, { "none"sv });
  2650. if (!counter_name)
  2651. return {};
  2652. tokens.skip_whitespace();
  2653. if (tokens.has_next_token())
  2654. return {};
  2655. transaction.commit();
  2656. return counter_name->custom_ident();
  2657. };
  2658. auto parse_counter_style = [this](TokenStream<ComponentValue>& tokens) -> RefPtr<CSSStyleValue> {
  2659. // https://drafts.csswg.org/css-counter-styles-3/#typedef-counter-style
  2660. // <counter-style> = <counter-style-name> | <symbols()>
  2661. // For now we just support <counter-style-name>, found here:
  2662. // https://drafts.csswg.org/css-counter-styles-3/#typedef-counter-style-name
  2663. // <counter-style-name> is a <custom-ident> that is not an ASCII case-insensitive match for none.
  2664. auto transaction = tokens.begin_transaction();
  2665. tokens.skip_whitespace();
  2666. auto counter_style_name = parse_custom_ident_value(tokens, { "none"sv });
  2667. if (!counter_style_name)
  2668. return {};
  2669. tokens.skip_whitespace();
  2670. if (tokens.has_next_token())
  2671. return {};
  2672. transaction.commit();
  2673. return counter_style_name.release_nonnull();
  2674. };
  2675. auto transaction = tokens.begin_transaction();
  2676. auto token = tokens.next_token();
  2677. if (token.is_function("counter"sv)) {
  2678. // counter() = counter( <counter-name>, <counter-style>? )
  2679. auto& function = token.function();
  2680. TokenStream function_tokens { function.values() };
  2681. auto function_values = parse_a_comma_separated_list_of_component_values(function_tokens);
  2682. if (function_values.is_empty() || function_values.size() > 2)
  2683. return nullptr;
  2684. TokenStream name_tokens { function_values[0] };
  2685. auto counter_name = parse_counter_name(name_tokens);
  2686. if (!counter_name.has_value())
  2687. return nullptr;
  2688. RefPtr<CSSStyleValue> counter_style;
  2689. if (function_values.size() > 1) {
  2690. TokenStream counter_style_tokens { function_values[1] };
  2691. counter_style = parse_counter_style(counter_style_tokens);
  2692. if (!counter_style)
  2693. return nullptr;
  2694. } else {
  2695. // In both cases, if the <counter-style> argument is omitted it defaults to `decimal`.
  2696. counter_style = CustomIdentStyleValue::create("decimal"_fly_string);
  2697. }
  2698. transaction.commit();
  2699. return CounterStyleValue::create_counter(counter_name.release_value(), counter_style.release_nonnull());
  2700. }
  2701. if (token.is_function("counters"sv)) {
  2702. // counters() = counters( <counter-name>, <string>, <counter-style>? )
  2703. auto& function = token.function();
  2704. TokenStream function_tokens { function.values() };
  2705. auto function_values = parse_a_comma_separated_list_of_component_values(function_tokens);
  2706. if (function_values.size() < 2 || function_values.size() > 3)
  2707. return nullptr;
  2708. TokenStream name_tokens { function_values[0] };
  2709. auto counter_name = parse_counter_name(name_tokens);
  2710. if (!counter_name.has_value())
  2711. return nullptr;
  2712. TokenStream string_tokens { function_values[1] };
  2713. string_tokens.skip_whitespace();
  2714. RefPtr<CSSStyleValue> join_string = parse_string_value(string_tokens);
  2715. string_tokens.skip_whitespace();
  2716. if (!join_string || string_tokens.has_next_token())
  2717. return nullptr;
  2718. RefPtr<CSSStyleValue> counter_style;
  2719. if (function_values.size() > 2) {
  2720. TokenStream counter_style_tokens { function_values[2] };
  2721. counter_style = parse_counter_style(counter_style_tokens);
  2722. if (!counter_style)
  2723. return nullptr;
  2724. } else {
  2725. // In both cases, if the <counter-style> argument is omitted it defaults to `decimal`.
  2726. counter_style = CustomIdentStyleValue::create("decimal"_fly_string);
  2727. }
  2728. transaction.commit();
  2729. return CounterStyleValue::create_counters(counter_name.release_value(), join_string->as_string().string_value(), counter_style.release_nonnull());
  2730. }
  2731. return nullptr;
  2732. }
  2733. RefPtr<CSSStyleValue> Parser::parse_counter_definitions_value(TokenStream<ComponentValue>& tokens, AllowReversed allow_reversed, i32 default_value_if_not_reversed)
  2734. {
  2735. // If AllowReversed is Yes, parses:
  2736. // [ <counter-name> <integer>? | <reversed-counter-name> <integer>? ]+
  2737. // Otherwise parses:
  2738. // [ <counter-name> <integer>? ]+
  2739. // FIXME: This disabled parsing of `reversed()` counters. Remove this line once they're supported.
  2740. allow_reversed = AllowReversed::No;
  2741. auto transaction = tokens.begin_transaction();
  2742. tokens.skip_whitespace();
  2743. Vector<CounterDefinition> counter_definitions;
  2744. while (tokens.has_next_token()) {
  2745. auto per_item_transaction = tokens.begin_transaction();
  2746. CounterDefinition definition {};
  2747. // <counter-name> | <reversed-counter-name>
  2748. auto& token = tokens.next_token();
  2749. if (token.is(Token::Type::Ident)) {
  2750. definition.name = token.token().ident();
  2751. definition.is_reversed = false;
  2752. } else if (allow_reversed == AllowReversed::Yes && token.is_function("reversed"sv)) {
  2753. TokenStream function_tokens { token.function().values() };
  2754. function_tokens.skip_whitespace();
  2755. auto& name_token = function_tokens.next_token();
  2756. if (!name_token.is(Token::Type::Ident))
  2757. break;
  2758. function_tokens.skip_whitespace();
  2759. if (function_tokens.has_next_token())
  2760. break;
  2761. definition.name = name_token.token().ident();
  2762. definition.is_reversed = true;
  2763. } else {
  2764. break;
  2765. }
  2766. tokens.skip_whitespace();
  2767. // <integer>?
  2768. definition.value = parse_integer_value(tokens);
  2769. if (!definition.value && !definition.is_reversed)
  2770. definition.value = IntegerStyleValue::create(default_value_if_not_reversed);
  2771. counter_definitions.append(move(definition));
  2772. tokens.skip_whitespace();
  2773. per_item_transaction.commit();
  2774. }
  2775. if (counter_definitions.is_empty())
  2776. return {};
  2777. transaction.commit();
  2778. return CounterDefinitionsStyleValue::create(move(counter_definitions));
  2779. }
  2780. RefPtr<CSSStyleValue> Parser::parse_ratio_value(TokenStream<ComponentValue>& tokens)
  2781. {
  2782. if (auto ratio = parse_ratio(tokens); ratio.has_value())
  2783. return RatioStyleValue::create(ratio.release_value());
  2784. return nullptr;
  2785. }
  2786. RefPtr<CSSStyleValue> Parser::parse_string_value(TokenStream<ComponentValue>& tokens)
  2787. {
  2788. auto peek = tokens.peek_token();
  2789. if (peek.is(Token::Type::String)) {
  2790. (void)tokens.next_token();
  2791. return StringStyleValue::create(peek.token().string());
  2792. }
  2793. return nullptr;
  2794. }
  2795. RefPtr<CSSStyleValue> Parser::parse_image_value(TokenStream<ComponentValue>& tokens)
  2796. {
  2797. if (auto url = parse_url_function(tokens); url.has_value())
  2798. return ImageStyleValue::create(url.value());
  2799. if (auto linear_gradient = parse_linear_gradient_function(tokens))
  2800. return linear_gradient;
  2801. if (auto conic_gradient = parse_conic_gradient_function(tokens))
  2802. return conic_gradient;
  2803. if (auto radial_gradient = parse_radial_gradient_function(tokens))
  2804. return radial_gradient;
  2805. return nullptr;
  2806. }
  2807. // https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint
  2808. RefPtr<CSSStyleValue> Parser::parse_paint_value(TokenStream<ComponentValue>& tokens)
  2809. {
  2810. // `<paint> = none | <color> | <url> [none | <color>]? | context-fill | context-stroke`
  2811. auto parse_color_or_none = [&]() -> Optional<RefPtr<CSSStyleValue>> {
  2812. if (auto color = parse_color_value(tokens))
  2813. return color;
  2814. // NOTE: <color> also accepts identifiers, so we do this identifier check last.
  2815. if (tokens.peek_token().is(Token::Type::Ident)) {
  2816. auto maybe_keyword = keyword_from_string(tokens.peek_token().token().ident());
  2817. if (maybe_keyword.has_value()) {
  2818. // FIXME: Accept `context-fill` and `context-stroke`
  2819. switch (*maybe_keyword) {
  2820. case Keyword::None:
  2821. (void)tokens.next_token();
  2822. return CSSKeywordValue::create(*maybe_keyword);
  2823. default:
  2824. return nullptr;
  2825. }
  2826. }
  2827. }
  2828. return OptionalNone {};
  2829. };
  2830. // FIMXE: Allow context-fill/context-stroke here
  2831. if (auto color_or_none = parse_color_or_none(); color_or_none.has_value())
  2832. return *color_or_none;
  2833. if (auto url = parse_url_value(tokens)) {
  2834. tokens.skip_whitespace();
  2835. if (auto color_or_none = parse_color_or_none(); color_or_none == nullptr) {
  2836. // Fail to parse if the fallback is invalid, but otherwise ignore it.
  2837. // FIXME: Use fallback color
  2838. return nullptr;
  2839. }
  2840. return url;
  2841. }
  2842. return nullptr;
  2843. }
  2844. // https://www.w3.org/TR/css-values-4/#position
  2845. RefPtr<PositionStyleValue> Parser::parse_position_value(TokenStream<ComponentValue>& tokens, PositionParsingMode position_parsing_mode)
  2846. {
  2847. auto parse_position_edge = [](ComponentValue const& token) -> Optional<PositionEdge> {
  2848. if (!token.is(Token::Type::Ident))
  2849. return {};
  2850. auto keyword = keyword_from_string(token.token().ident());
  2851. if (!keyword.has_value())
  2852. return {};
  2853. return keyword_to_position_edge(*keyword);
  2854. };
  2855. auto parse_length_percentage = [&](ComponentValue const& token) -> Optional<LengthPercentage> {
  2856. if (token.is(Token::Type::EndOfFile))
  2857. return {};
  2858. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  2859. if (dimension->is_length_percentage())
  2860. return dimension->length_percentage();
  2861. return {};
  2862. }
  2863. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_length_percentage())
  2864. return LengthPercentage { calc.release_nonnull() };
  2865. return {};
  2866. };
  2867. auto is_horizontal = [](PositionEdge edge, bool accept_center) -> bool {
  2868. switch (edge) {
  2869. case PositionEdge::Left:
  2870. case PositionEdge::Right:
  2871. return true;
  2872. case PositionEdge::Center:
  2873. return accept_center;
  2874. default:
  2875. return false;
  2876. }
  2877. };
  2878. auto is_vertical = [](PositionEdge edge, bool accept_center) -> bool {
  2879. switch (edge) {
  2880. case PositionEdge::Top:
  2881. case PositionEdge::Bottom:
  2882. return true;
  2883. case PositionEdge::Center:
  2884. return accept_center;
  2885. default:
  2886. return false;
  2887. }
  2888. };
  2889. auto make_edge_style_value = [](PositionEdge position_edge, bool is_horizontal) -> NonnullRefPtr<EdgeStyleValue> {
  2890. if (position_edge == PositionEdge::Center)
  2891. return EdgeStyleValue::create(is_horizontal ? PositionEdge::Left : PositionEdge::Top, Percentage { 50 });
  2892. return EdgeStyleValue::create(position_edge, Length::make_px(0));
  2893. };
  2894. // <position> = [
  2895. // [ left | center | right | top | bottom | <length-percentage> ]
  2896. // |
  2897. // [ left | center | right ] && [ top | center | bottom ]
  2898. // |
  2899. // [ left | center | right | <length-percentage> ]
  2900. // [ top | center | bottom | <length-percentage> ]
  2901. // |
  2902. // [ [ left | right ] <length-percentage> ] &&
  2903. // [ [ top | bottom ] <length-percentage> ]
  2904. // ]
  2905. // [ left | center | right | top | bottom | <length-percentage> ]
  2906. auto alternative_1 = [&]() -> RefPtr<PositionStyleValue> {
  2907. auto transaction = tokens.begin_transaction();
  2908. tokens.skip_whitespace();
  2909. auto const& token = tokens.next_token();
  2910. // [ left | center | right | top | bottom ]
  2911. if (auto maybe_edge = parse_position_edge(token); maybe_edge.has_value()) {
  2912. auto edge = maybe_edge.release_value();
  2913. transaction.commit();
  2914. // [ left | right ]
  2915. if (is_horizontal(edge, false))
  2916. return PositionStyleValue::create(make_edge_style_value(edge, true), make_edge_style_value(PositionEdge::Center, false));
  2917. // [ top | bottom ]
  2918. if (is_vertical(edge, false))
  2919. return PositionStyleValue::create(make_edge_style_value(PositionEdge::Center, true), make_edge_style_value(edge, false));
  2920. // [ center ]
  2921. VERIFY(edge == PositionEdge::Center);
  2922. return PositionStyleValue::create(make_edge_style_value(PositionEdge::Center, true), make_edge_style_value(PositionEdge::Center, false));
  2923. }
  2924. // [ <length-percentage> ]
  2925. if (auto maybe_percentage = parse_length_percentage(token); maybe_percentage.has_value()) {
  2926. transaction.commit();
  2927. return PositionStyleValue::create(EdgeStyleValue::create(PositionEdge::Left, *maybe_percentage), make_edge_style_value(PositionEdge::Center, false));
  2928. }
  2929. return nullptr;
  2930. };
  2931. // [ left | center | right ] && [ top | center | bottom ]
  2932. auto alternative_2 = [&]() -> RefPtr<PositionStyleValue> {
  2933. auto transaction = tokens.begin_transaction();
  2934. tokens.skip_whitespace();
  2935. // Parse out two position edges
  2936. auto maybe_first_edge = parse_position_edge(tokens.next_token());
  2937. if (!maybe_first_edge.has_value())
  2938. return nullptr;
  2939. auto first_edge = maybe_first_edge.release_value();
  2940. tokens.skip_whitespace();
  2941. auto maybe_second_edge = parse_position_edge(tokens.next_token());
  2942. if (!maybe_second_edge.has_value())
  2943. return nullptr;
  2944. auto second_edge = maybe_second_edge.release_value();
  2945. // If 'left' or 'right' is given, that position is X and the other is Y.
  2946. // Conversely -
  2947. // If 'top' or 'bottom' is given, that position is Y and the other is X.
  2948. if (is_vertical(first_edge, false) || is_horizontal(second_edge, false))
  2949. swap(first_edge, second_edge);
  2950. // [ left | center | right ] [ top | bottom | center ]
  2951. if (is_horizontal(first_edge, true) && is_vertical(second_edge, true)) {
  2952. transaction.commit();
  2953. return PositionStyleValue::create(make_edge_style_value(first_edge, true), make_edge_style_value(second_edge, false));
  2954. }
  2955. return nullptr;
  2956. };
  2957. // [ left | center | right | <length-percentage> ]
  2958. // [ top | center | bottom | <length-percentage> ]
  2959. auto alternative_3 = [&]() -> RefPtr<PositionStyleValue> {
  2960. auto transaction = tokens.begin_transaction();
  2961. auto parse_position_or_length = [&](bool as_horizontal) -> RefPtr<EdgeStyleValue> {
  2962. tokens.skip_whitespace();
  2963. auto const& token = tokens.next_token();
  2964. if (auto maybe_position = parse_position_edge(token); maybe_position.has_value()) {
  2965. auto position = maybe_position.release_value();
  2966. bool valid = as_horizontal ? is_horizontal(position, true) : is_vertical(position, true);
  2967. if (!valid)
  2968. return nullptr;
  2969. return make_edge_style_value(position, as_horizontal);
  2970. }
  2971. auto maybe_length = parse_length_percentage(token);
  2972. if (!maybe_length.has_value())
  2973. return nullptr;
  2974. return EdgeStyleValue::create(as_horizontal ? PositionEdge::Left : PositionEdge::Top, maybe_length.release_value());
  2975. };
  2976. // [ left | center | right | <length-percentage> ]
  2977. auto horizontal_edge = parse_position_or_length(true);
  2978. if (!horizontal_edge)
  2979. return nullptr;
  2980. // [ top | center | bottom | <length-percentage> ]
  2981. auto vertical_edge = parse_position_or_length(false);
  2982. if (!vertical_edge)
  2983. return nullptr;
  2984. transaction.commit();
  2985. return PositionStyleValue::create(horizontal_edge.release_nonnull(), vertical_edge.release_nonnull());
  2986. };
  2987. // [ [ left | right ] <length-percentage> ] &&
  2988. // [ [ top | bottom ] <length-percentage> ]
  2989. auto alternative_4 = [&]() -> RefPtr<PositionStyleValue> {
  2990. struct PositionAndLength {
  2991. PositionEdge position;
  2992. LengthPercentage length;
  2993. };
  2994. auto parse_position_and_length = [&]() -> Optional<PositionAndLength> {
  2995. tokens.skip_whitespace();
  2996. auto maybe_position = parse_position_edge(tokens.next_token());
  2997. if (!maybe_position.has_value())
  2998. return {};
  2999. tokens.skip_whitespace();
  3000. auto maybe_length = parse_length_percentage(tokens.next_token());
  3001. if (!maybe_length.has_value())
  3002. return {};
  3003. return PositionAndLength {
  3004. .position = maybe_position.release_value(),
  3005. .length = maybe_length.release_value(),
  3006. };
  3007. };
  3008. auto transaction = tokens.begin_transaction();
  3009. auto maybe_group1 = parse_position_and_length();
  3010. if (!maybe_group1.has_value())
  3011. return nullptr;
  3012. auto maybe_group2 = parse_position_and_length();
  3013. if (!maybe_group2.has_value())
  3014. return nullptr;
  3015. auto group1 = maybe_group1.release_value();
  3016. auto group2 = maybe_group2.release_value();
  3017. // [ [ left | right ] <length-percentage> ] [ [ top | bottom ] <length-percentage> ]
  3018. if (is_horizontal(group1.position, false) && is_vertical(group2.position, false)) {
  3019. transaction.commit();
  3020. return PositionStyleValue::create(EdgeStyleValue::create(group1.position, group1.length), EdgeStyleValue::create(group2.position, group2.length));
  3021. }
  3022. // [ [ top | bottom ] <length-percentage> ] [ [ left | right ] <length-percentage> ]
  3023. if (is_vertical(group1.position, false) && is_horizontal(group2.position, false)) {
  3024. transaction.commit();
  3025. return PositionStyleValue::create(EdgeStyleValue::create(group2.position, group2.length), EdgeStyleValue::create(group1.position, group1.length));
  3026. }
  3027. return nullptr;
  3028. };
  3029. // The extra 3-value syntax that's allowed for background-position:
  3030. // [ center | [ left | right ] <length-percentage>? ] &&
  3031. // [ center | [ top | bottom ] <length-percentage>? ]
  3032. auto alternative_5_for_background_position = [&]() -> RefPtr<PositionStyleValue> {
  3033. auto transaction = tokens.begin_transaction();
  3034. struct PositionAndMaybeLength {
  3035. PositionEdge position;
  3036. Optional<LengthPercentage> length;
  3037. };
  3038. // [ <position> <length-percentage>? ]
  3039. auto parse_position_and_maybe_length = [&]() -> Optional<PositionAndMaybeLength> {
  3040. tokens.skip_whitespace();
  3041. auto maybe_position = parse_position_edge(tokens.next_token());
  3042. if (!maybe_position.has_value())
  3043. return {};
  3044. tokens.skip_whitespace();
  3045. auto maybe_length = parse_length_percentage(tokens.peek_token());
  3046. if (maybe_length.has_value()) {
  3047. // 'center' cannot be followed by a <length-percentage>
  3048. if (maybe_position.value() == PositionEdge::Center && maybe_length.has_value())
  3049. return {};
  3050. tokens.next_token();
  3051. }
  3052. return PositionAndMaybeLength {
  3053. .position = maybe_position.release_value(),
  3054. .length = move(maybe_length),
  3055. };
  3056. };
  3057. auto maybe_group1 = parse_position_and_maybe_length();
  3058. if (!maybe_group1.has_value())
  3059. return nullptr;
  3060. auto maybe_group2 = parse_position_and_maybe_length();
  3061. if (!maybe_group2.has_value())
  3062. return nullptr;
  3063. auto group1 = maybe_group1.release_value();
  3064. auto group2 = maybe_group2.release_value();
  3065. // 2-value or 4-value if both <length-percentage>s are present or missing.
  3066. if (group1.length.has_value() == group2.length.has_value())
  3067. return nullptr;
  3068. // If 'left' or 'right' is given, that position is X and the other is Y.
  3069. // Conversely -
  3070. // If 'top' or 'bottom' is given, that position is Y and the other is X.
  3071. if (is_vertical(group1.position, false) || is_horizontal(group2.position, false))
  3072. swap(group1, group2);
  3073. // [ center | [ left | right ] ]
  3074. if (!is_horizontal(group1.position, true))
  3075. return nullptr;
  3076. // [ center | [ top | bottom ] ]
  3077. if (!is_vertical(group2.position, true))
  3078. return nullptr;
  3079. auto to_style_value = [&](PositionAndMaybeLength const& group, bool is_horizontal) -> NonnullRefPtr<EdgeStyleValue> {
  3080. if (group.position == PositionEdge::Center)
  3081. return EdgeStyleValue::create(is_horizontal ? PositionEdge::Left : PositionEdge::Top, Percentage { 50 });
  3082. return EdgeStyleValue::create(group.position, group.length.value_or(Length::make_px(0)));
  3083. };
  3084. transaction.commit();
  3085. return PositionStyleValue::create(to_style_value(group1, true), to_style_value(group2, false));
  3086. };
  3087. // Note: The alternatives must be attempted in this order since shorter alternatives can match a prefix of longer ones.
  3088. if (auto position = alternative_4())
  3089. return position;
  3090. if (position_parsing_mode == PositionParsingMode::BackgroundPosition) {
  3091. if (auto position = alternative_5_for_background_position())
  3092. return position;
  3093. }
  3094. if (auto position = alternative_3())
  3095. return position;
  3096. if (auto position = alternative_2())
  3097. return position;
  3098. if (auto position = alternative_1())
  3099. return position;
  3100. return nullptr;
  3101. }
  3102. template<typename ParseFunction>
  3103. RefPtr<CSSStyleValue> Parser::parse_comma_separated_value_list(TokenStream<ComponentValue>& tokens, ParseFunction parse_one_value)
  3104. {
  3105. auto first = parse_one_value(tokens);
  3106. if (!first || !tokens.has_next_token())
  3107. return first;
  3108. StyleValueVector values;
  3109. values.append(first.release_nonnull());
  3110. while (tokens.has_next_token()) {
  3111. if (!tokens.next_token().is(Token::Type::Comma))
  3112. return nullptr;
  3113. if (auto maybe_value = parse_one_value(tokens)) {
  3114. values.append(maybe_value.release_nonnull());
  3115. continue;
  3116. }
  3117. return nullptr;
  3118. }
  3119. return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
  3120. }
  3121. RefPtr<CSSStyleValue> Parser::parse_simple_comma_separated_value_list(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  3122. {
  3123. return parse_comma_separated_value_list(tokens, [this, property_id](auto& tokens) -> RefPtr<CSSStyleValue> {
  3124. if (auto value = parse_css_value_for_property(property_id, tokens))
  3125. return value;
  3126. tokens.reconsume_current_input_token();
  3127. return nullptr;
  3128. });
  3129. }
  3130. RefPtr<CSSStyleValue> Parser::parse_all_as_single_none_value(TokenStream<ComponentValue>& tokens)
  3131. {
  3132. auto transaction = tokens.begin_transaction();
  3133. tokens.skip_whitespace();
  3134. auto maybe_none = tokens.next_token();
  3135. tokens.skip_whitespace();
  3136. if (tokens.has_next_token() || !maybe_none.is_ident("none"sv))
  3137. return {};
  3138. transaction.commit();
  3139. return CSSKeywordValue::create(Keyword::None);
  3140. }
  3141. static void remove_property(Vector<PropertyID>& properties, PropertyID property_to_remove)
  3142. {
  3143. properties.remove_first_matching([&](auto it) { return it == property_to_remove; });
  3144. }
  3145. // https://www.w3.org/TR/css-sizing-4/#aspect-ratio
  3146. RefPtr<CSSStyleValue> Parser::parse_aspect_ratio_value(TokenStream<ComponentValue>& tokens)
  3147. {
  3148. // `auto || <ratio>`
  3149. RefPtr<CSSStyleValue> auto_value;
  3150. RefPtr<CSSStyleValue> ratio_value;
  3151. auto transaction = tokens.begin_transaction();
  3152. while (tokens.has_next_token()) {
  3153. auto maybe_value = parse_css_value_for_property(PropertyID::AspectRatio, tokens);
  3154. if (!maybe_value)
  3155. return nullptr;
  3156. if (maybe_value->is_ratio()) {
  3157. if (ratio_value)
  3158. return nullptr;
  3159. ratio_value = maybe_value.release_nonnull();
  3160. continue;
  3161. }
  3162. if (maybe_value->is_keyword() && maybe_value->as_keyword().keyword() == Keyword::Auto) {
  3163. if (auto_value)
  3164. return nullptr;
  3165. auto_value = maybe_value.release_nonnull();
  3166. continue;
  3167. }
  3168. return nullptr;
  3169. }
  3170. if (auto_value && ratio_value) {
  3171. transaction.commit();
  3172. return StyleValueList::create(
  3173. StyleValueVector { auto_value.release_nonnull(), ratio_value.release_nonnull() },
  3174. StyleValueList::Separator::Space);
  3175. }
  3176. if (ratio_value) {
  3177. transaction.commit();
  3178. return ratio_value.release_nonnull();
  3179. }
  3180. if (auto_value) {
  3181. transaction.commit();
  3182. return auto_value.release_nonnull();
  3183. }
  3184. return nullptr;
  3185. }
  3186. RefPtr<CSSStyleValue> Parser::parse_background_value(TokenStream<ComponentValue>& tokens)
  3187. {
  3188. auto transaction = tokens.begin_transaction();
  3189. auto make_background_shorthand = [&](auto background_color, auto background_image, auto background_position, auto background_size, auto background_repeat, auto background_attachment, auto background_origin, auto background_clip) {
  3190. return ShorthandStyleValue::create(PropertyID::Background,
  3191. { PropertyID::BackgroundColor, PropertyID::BackgroundImage, PropertyID::BackgroundPosition, PropertyID::BackgroundSize, PropertyID::BackgroundRepeat, PropertyID::BackgroundAttachment, PropertyID::BackgroundOrigin, PropertyID::BackgroundClip },
  3192. { move(background_color), move(background_image), move(background_position), move(background_size), move(background_repeat), move(background_attachment), move(background_origin), move(background_clip) });
  3193. };
  3194. StyleValueVector background_images;
  3195. StyleValueVector background_positions;
  3196. StyleValueVector background_sizes;
  3197. StyleValueVector background_repeats;
  3198. StyleValueVector background_attachments;
  3199. StyleValueVector background_clips;
  3200. StyleValueVector background_origins;
  3201. RefPtr<CSSStyleValue> background_color;
  3202. auto initial_background_image = property_initial_value(m_context.realm(), PropertyID::BackgroundImage);
  3203. auto initial_background_position = property_initial_value(m_context.realm(), PropertyID::BackgroundPosition);
  3204. auto initial_background_size = property_initial_value(m_context.realm(), PropertyID::BackgroundSize);
  3205. auto initial_background_repeat = property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat);
  3206. auto initial_background_attachment = property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment);
  3207. auto initial_background_clip = property_initial_value(m_context.realm(), PropertyID::BackgroundClip);
  3208. auto initial_background_origin = property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin);
  3209. auto initial_background_color = property_initial_value(m_context.realm(), PropertyID::BackgroundColor);
  3210. // Per-layer values
  3211. RefPtr<CSSStyleValue> background_image;
  3212. RefPtr<CSSStyleValue> background_position;
  3213. RefPtr<CSSStyleValue> background_size;
  3214. RefPtr<CSSStyleValue> background_repeat;
  3215. RefPtr<CSSStyleValue> background_attachment;
  3216. RefPtr<CSSStyleValue> background_clip;
  3217. RefPtr<CSSStyleValue> background_origin;
  3218. bool has_multiple_layers = false;
  3219. // BackgroundSize is always parsed as part of BackgroundPosition, so we don't include it here.
  3220. Vector<PropertyID> remaining_layer_properties {
  3221. PropertyID::BackgroundAttachment,
  3222. PropertyID::BackgroundClip,
  3223. PropertyID::BackgroundColor,
  3224. PropertyID::BackgroundImage,
  3225. PropertyID::BackgroundOrigin,
  3226. PropertyID::BackgroundPosition,
  3227. PropertyID::BackgroundRepeat,
  3228. };
  3229. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  3230. if (allow_background_color) {
  3231. if (background_color)
  3232. return true;
  3233. } else {
  3234. if (background_color)
  3235. return false;
  3236. }
  3237. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  3238. };
  3239. auto complete_background_layer = [&]() {
  3240. background_images.append(background_image ? background_image.release_nonnull() : initial_background_image);
  3241. background_positions.append(background_position ? background_position.release_nonnull() : initial_background_position);
  3242. background_sizes.append(background_size ? background_size.release_nonnull() : initial_background_size);
  3243. background_repeats.append(background_repeat ? background_repeat.release_nonnull() : initial_background_repeat);
  3244. background_attachments.append(background_attachment ? background_attachment.release_nonnull() : initial_background_attachment);
  3245. if (!background_origin && !background_clip) {
  3246. background_origin = initial_background_origin;
  3247. background_clip = initial_background_clip;
  3248. } else if (!background_clip) {
  3249. background_clip = background_origin;
  3250. }
  3251. background_origins.append(background_origin.release_nonnull());
  3252. background_clips.append(background_clip.release_nonnull());
  3253. background_image = nullptr;
  3254. background_position = nullptr;
  3255. background_size = nullptr;
  3256. background_repeat = nullptr;
  3257. background_attachment = nullptr;
  3258. background_clip = nullptr;
  3259. background_origin = nullptr;
  3260. remaining_layer_properties.clear_with_capacity();
  3261. remaining_layer_properties.unchecked_append(PropertyID::BackgroundAttachment);
  3262. remaining_layer_properties.unchecked_append(PropertyID::BackgroundClip);
  3263. remaining_layer_properties.unchecked_append(PropertyID::BackgroundColor);
  3264. remaining_layer_properties.unchecked_append(PropertyID::BackgroundImage);
  3265. remaining_layer_properties.unchecked_append(PropertyID::BackgroundOrigin);
  3266. remaining_layer_properties.unchecked_append(PropertyID::BackgroundPosition);
  3267. remaining_layer_properties.unchecked_append(PropertyID::BackgroundRepeat);
  3268. };
  3269. while (tokens.has_next_token()) {
  3270. if (tokens.peek_token().is(Token::Type::Comma)) {
  3271. has_multiple_layers = true;
  3272. if (!background_layer_is_valid(false))
  3273. return nullptr;
  3274. complete_background_layer();
  3275. (void)tokens.next_token();
  3276. continue;
  3277. }
  3278. auto value_and_property = parse_css_value_for_properties(remaining_layer_properties, tokens);
  3279. if (!value_and_property.has_value())
  3280. return nullptr;
  3281. auto& value = value_and_property->style_value;
  3282. remove_property(remaining_layer_properties, value_and_property->property);
  3283. switch (value_and_property->property) {
  3284. case PropertyID::BackgroundAttachment:
  3285. VERIFY(!background_attachment);
  3286. background_attachment = value.release_nonnull();
  3287. continue;
  3288. case PropertyID::BackgroundColor:
  3289. VERIFY(!background_color);
  3290. background_color = value.release_nonnull();
  3291. continue;
  3292. case PropertyID::BackgroundImage:
  3293. VERIFY(!background_image);
  3294. background_image = value.release_nonnull();
  3295. continue;
  3296. case PropertyID::BackgroundClip:
  3297. case PropertyID::BackgroundOrigin: {
  3298. // background-origin and background-clip accept the same values. From the spec:
  3299. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  3300. // If two values are present, then the first sets background-origin and the second background-clip."
  3301. // - https://www.w3.org/TR/css-backgrounds-3/#background
  3302. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  3303. // If we only get one, we copy the value before creating the ShorthandStyleValue.
  3304. if (!background_origin) {
  3305. background_origin = value.release_nonnull();
  3306. } else if (!background_clip) {
  3307. background_clip = value.release_nonnull();
  3308. } else {
  3309. VERIFY_NOT_REACHED();
  3310. }
  3311. continue;
  3312. }
  3313. case PropertyID::BackgroundPosition: {
  3314. VERIFY(!background_position);
  3315. background_position = value.release_nonnull();
  3316. // Attempt to parse `/ <background-size>`
  3317. auto background_size_transaction = tokens.begin_transaction();
  3318. auto& maybe_slash = tokens.next_token();
  3319. if (maybe_slash.is_delim('/')) {
  3320. if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
  3321. background_size_transaction.commit();
  3322. background_size = maybe_background_size.release_nonnull();
  3323. continue;
  3324. }
  3325. return nullptr;
  3326. }
  3327. continue;
  3328. }
  3329. case PropertyID::BackgroundRepeat: {
  3330. VERIFY(!background_repeat);
  3331. tokens.reconsume_current_input_token();
  3332. if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
  3333. background_repeat = maybe_repeat.release_nonnull();
  3334. continue;
  3335. }
  3336. return nullptr;
  3337. }
  3338. default:
  3339. VERIFY_NOT_REACHED();
  3340. }
  3341. return nullptr;
  3342. }
  3343. if (!background_layer_is_valid(true))
  3344. return nullptr;
  3345. // We only need to create StyleValueLists if there are multiple layers.
  3346. // Otherwise, we can pass the single StyleValues directly.
  3347. if (has_multiple_layers) {
  3348. complete_background_layer();
  3349. if (!background_color)
  3350. background_color = initial_background_color;
  3351. transaction.commit();
  3352. return make_background_shorthand(
  3353. background_color.release_nonnull(),
  3354. StyleValueList::create(move(background_images), StyleValueList::Separator::Comma),
  3355. StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma),
  3356. StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma),
  3357. StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma),
  3358. StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma),
  3359. StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma),
  3360. StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma));
  3361. }
  3362. if (!background_color)
  3363. background_color = initial_background_color;
  3364. if (!background_image)
  3365. background_image = initial_background_image;
  3366. if (!background_position)
  3367. background_position = initial_background_position;
  3368. if (!background_size)
  3369. background_size = initial_background_size;
  3370. if (!background_repeat)
  3371. background_repeat = initial_background_repeat;
  3372. if (!background_attachment)
  3373. background_attachment = initial_background_attachment;
  3374. if (!background_origin && !background_clip) {
  3375. background_origin = initial_background_origin;
  3376. background_clip = initial_background_clip;
  3377. } else if (!background_clip) {
  3378. background_clip = background_origin;
  3379. }
  3380. transaction.commit();
  3381. return make_background_shorthand(
  3382. background_color.release_nonnull(),
  3383. background_image.release_nonnull(),
  3384. background_position.release_nonnull(),
  3385. background_size.release_nonnull(),
  3386. background_repeat.release_nonnull(),
  3387. background_attachment.release_nonnull(),
  3388. background_origin.release_nonnull(),
  3389. background_clip.release_nonnull());
  3390. }
  3391. static Optional<LengthPercentage> style_value_to_length_percentage(auto value)
  3392. {
  3393. if (value->is_percentage())
  3394. return LengthPercentage { value->as_percentage().percentage() };
  3395. if (value->is_length())
  3396. return LengthPercentage { value->as_length().length() };
  3397. if (value->is_calculated())
  3398. return LengthPercentage { value->as_calculated() };
  3399. return {};
  3400. }
  3401. RefPtr<CSSStyleValue> Parser::parse_single_background_position_x_or_y_value(TokenStream<ComponentValue>& tokens, PropertyID property)
  3402. {
  3403. PositionEdge relative_edge {};
  3404. if (property == PropertyID::BackgroundPositionX) {
  3405. // [ center | [ [ left | right | x-start | x-end ]? <length-percentage>? ]! ]#
  3406. relative_edge = PositionEdge::Left;
  3407. } else if (property == PropertyID::BackgroundPositionY) {
  3408. // [ center | [ [ top | bottom | y-start | y-end ]? <length-percentage>? ]! ]#
  3409. relative_edge = PositionEdge::Top;
  3410. } else {
  3411. VERIFY_NOT_REACHED();
  3412. }
  3413. auto transaction = tokens.begin_transaction();
  3414. if (!tokens.has_next_token())
  3415. return nullptr;
  3416. auto value = parse_css_value_for_property(property, tokens);
  3417. if (!value)
  3418. return nullptr;
  3419. if (value->is_keyword()) {
  3420. auto keyword = value->to_keyword();
  3421. if (keyword == Keyword::Center) {
  3422. transaction.commit();
  3423. return EdgeStyleValue::create(relative_edge, Percentage { 50 });
  3424. }
  3425. if (auto edge = keyword_to_position_edge(keyword); edge.has_value()) {
  3426. relative_edge = *edge;
  3427. } else {
  3428. return nullptr;
  3429. }
  3430. if (tokens.has_next_token()) {
  3431. value = parse_css_value_for_property(property, tokens);
  3432. if (!value) {
  3433. transaction.commit();
  3434. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  3435. }
  3436. }
  3437. }
  3438. auto offset = style_value_to_length_percentage(value);
  3439. if (offset.has_value()) {
  3440. transaction.commit();
  3441. return EdgeStyleValue::create(relative_edge, *offset);
  3442. }
  3443. // If no offset is provided create this element but with an offset of default value of zero
  3444. transaction.commit();
  3445. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  3446. }
  3447. RefPtr<CSSStyleValue> Parser::parse_single_background_repeat_value(TokenStream<ComponentValue>& tokens)
  3448. {
  3449. auto transaction = tokens.begin_transaction();
  3450. auto is_directional_repeat = [](CSSStyleValue const& value) -> bool {
  3451. auto keyword = value.to_keyword();
  3452. return keyword == Keyword::RepeatX || keyword == Keyword::RepeatY;
  3453. };
  3454. auto as_repeat = [](Keyword keyword) -> Optional<Repeat> {
  3455. switch (keyword) {
  3456. case Keyword::NoRepeat:
  3457. return Repeat::NoRepeat;
  3458. case Keyword::Repeat:
  3459. return Repeat::Repeat;
  3460. case Keyword::Round:
  3461. return Repeat::Round;
  3462. case Keyword::Space:
  3463. return Repeat::Space;
  3464. default:
  3465. return {};
  3466. }
  3467. };
  3468. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  3469. if (!maybe_x_value)
  3470. return nullptr;
  3471. auto x_value = maybe_x_value.release_nonnull();
  3472. if (is_directional_repeat(*x_value)) {
  3473. auto keyword = x_value->to_keyword();
  3474. transaction.commit();
  3475. return BackgroundRepeatStyleValue::create(
  3476. keyword == Keyword::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  3477. keyword == Keyword::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  3478. }
  3479. auto x_repeat = as_repeat(x_value->to_keyword());
  3480. if (!x_repeat.has_value())
  3481. return nullptr;
  3482. // See if we have a second value for Y
  3483. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  3484. if (!maybe_y_value) {
  3485. // We don't have a second value, so use x for both
  3486. transaction.commit();
  3487. return BackgroundRepeatStyleValue::create(x_repeat.value(), x_repeat.value());
  3488. }
  3489. auto y_value = maybe_y_value.release_nonnull();
  3490. if (is_directional_repeat(*y_value))
  3491. return nullptr;
  3492. auto y_repeat = as_repeat(y_value->to_keyword());
  3493. if (!y_repeat.has_value())
  3494. return nullptr;
  3495. transaction.commit();
  3496. return BackgroundRepeatStyleValue::create(x_repeat.value(), y_repeat.value());
  3497. }
  3498. RefPtr<CSSStyleValue> Parser::parse_single_background_size_value(TokenStream<ComponentValue>& tokens)
  3499. {
  3500. auto transaction = tokens.begin_transaction();
  3501. auto get_length_percentage = [](CSSStyleValue& style_value) -> Optional<LengthPercentage> {
  3502. if (style_value.has_auto())
  3503. return LengthPercentage { Length::make_auto() };
  3504. if (style_value.is_percentage())
  3505. return LengthPercentage { style_value.as_percentage().percentage() };
  3506. if (style_value.is_length())
  3507. return LengthPercentage { style_value.as_length().length() };
  3508. if (style_value.is_calculated())
  3509. return LengthPercentage { style_value.as_calculated() };
  3510. return {};
  3511. };
  3512. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  3513. if (!maybe_x_value)
  3514. return nullptr;
  3515. auto x_value = maybe_x_value.release_nonnull();
  3516. if (x_value->to_keyword() == Keyword::Cover || x_value->to_keyword() == Keyword::Contain) {
  3517. transaction.commit();
  3518. return x_value;
  3519. }
  3520. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  3521. if (!maybe_y_value) {
  3522. auto y_value = LengthPercentage { Length::make_auto() };
  3523. auto x_size = get_length_percentage(*x_value);
  3524. if (!x_size.has_value())
  3525. return nullptr;
  3526. transaction.commit();
  3527. return BackgroundSizeStyleValue::create(x_size.value(), y_value);
  3528. }
  3529. auto y_value = maybe_y_value.release_nonnull();
  3530. auto x_size = get_length_percentage(*x_value);
  3531. auto y_size = get_length_percentage(*y_value);
  3532. if (!x_size.has_value() || !y_size.has_value())
  3533. return nullptr;
  3534. transaction.commit();
  3535. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  3536. }
  3537. RefPtr<CSSStyleValue> Parser::parse_border_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  3538. {
  3539. RefPtr<CSSStyleValue> border_width;
  3540. RefPtr<CSSStyleValue> border_color;
  3541. RefPtr<CSSStyleValue> border_style;
  3542. auto color_property = PropertyID::Invalid;
  3543. auto style_property = PropertyID::Invalid;
  3544. auto width_property = PropertyID::Invalid;
  3545. switch (property_id) {
  3546. case PropertyID::Border:
  3547. color_property = PropertyID::BorderColor;
  3548. style_property = PropertyID::BorderStyle;
  3549. width_property = PropertyID::BorderWidth;
  3550. break;
  3551. case PropertyID::BorderBottom:
  3552. color_property = PropertyID::BorderBottomColor;
  3553. style_property = PropertyID::BorderBottomStyle;
  3554. width_property = PropertyID::BorderBottomWidth;
  3555. break;
  3556. case PropertyID::BorderLeft:
  3557. color_property = PropertyID::BorderLeftColor;
  3558. style_property = PropertyID::BorderLeftStyle;
  3559. width_property = PropertyID::BorderLeftWidth;
  3560. break;
  3561. case PropertyID::BorderRight:
  3562. color_property = PropertyID::BorderRightColor;
  3563. style_property = PropertyID::BorderRightStyle;
  3564. width_property = PropertyID::BorderRightWidth;
  3565. break;
  3566. case PropertyID::BorderTop:
  3567. color_property = PropertyID::BorderTopColor;
  3568. style_property = PropertyID::BorderTopStyle;
  3569. width_property = PropertyID::BorderTopWidth;
  3570. break;
  3571. default:
  3572. VERIFY_NOT_REACHED();
  3573. }
  3574. auto remaining_longhands = Vector { width_property, color_property, style_property };
  3575. auto transaction = tokens.begin_transaction();
  3576. while (tokens.has_next_token()) {
  3577. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3578. if (!property_and_value.has_value())
  3579. return nullptr;
  3580. auto& value = property_and_value->style_value;
  3581. remove_property(remaining_longhands, property_and_value->property);
  3582. if (property_and_value->property == width_property) {
  3583. VERIFY(!border_width);
  3584. border_width = value.release_nonnull();
  3585. } else if (property_and_value->property == color_property) {
  3586. VERIFY(!border_color);
  3587. border_color = value.release_nonnull();
  3588. } else if (property_and_value->property == style_property) {
  3589. VERIFY(!border_style);
  3590. border_style = value.release_nonnull();
  3591. } else {
  3592. VERIFY_NOT_REACHED();
  3593. }
  3594. }
  3595. if (!border_width)
  3596. border_width = property_initial_value(m_context.realm(), width_property);
  3597. if (!border_style)
  3598. border_style = property_initial_value(m_context.realm(), style_property);
  3599. if (!border_color)
  3600. border_color = property_initial_value(m_context.realm(), color_property);
  3601. transaction.commit();
  3602. return ShorthandStyleValue::create(property_id,
  3603. { width_property, style_property, color_property },
  3604. { border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull() });
  3605. }
  3606. RefPtr<CSSStyleValue> Parser::parse_border_radius_value(TokenStream<ComponentValue>& tokens)
  3607. {
  3608. if (tokens.remaining_token_count() == 2) {
  3609. auto transaction = tokens.begin_transaction();
  3610. auto horizontal = parse_length_percentage(tokens);
  3611. auto vertical = parse_length_percentage(tokens);
  3612. if (horizontal.has_value() && vertical.has_value()) {
  3613. transaction.commit();
  3614. return BorderRadiusStyleValue::create(horizontal.release_value(), vertical.release_value());
  3615. }
  3616. }
  3617. if (tokens.remaining_token_count() == 1) {
  3618. auto transaction = tokens.begin_transaction();
  3619. auto radius = parse_length_percentage(tokens);
  3620. if (radius.has_value()) {
  3621. transaction.commit();
  3622. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  3623. }
  3624. }
  3625. return nullptr;
  3626. }
  3627. RefPtr<CSSStyleValue> Parser::parse_border_radius_shorthand_value(TokenStream<ComponentValue>& tokens)
  3628. {
  3629. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  3630. auto top_right = [&](Vector<LengthPercentage>& radii) {
  3631. switch (radii.size()) {
  3632. case 4:
  3633. case 3:
  3634. case 2:
  3635. return radii[1];
  3636. case 1:
  3637. return radii[0];
  3638. default:
  3639. VERIFY_NOT_REACHED();
  3640. }
  3641. };
  3642. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  3643. switch (radii.size()) {
  3644. case 4:
  3645. case 3:
  3646. return radii[2];
  3647. case 2:
  3648. case 1:
  3649. return radii[0];
  3650. default:
  3651. VERIFY_NOT_REACHED();
  3652. }
  3653. };
  3654. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  3655. switch (radii.size()) {
  3656. case 4:
  3657. return radii[3];
  3658. case 3:
  3659. case 2:
  3660. return radii[1];
  3661. case 1:
  3662. return radii[0];
  3663. default:
  3664. VERIFY_NOT_REACHED();
  3665. }
  3666. };
  3667. Vector<LengthPercentage> horizontal_radii;
  3668. Vector<LengthPercentage> vertical_radii;
  3669. bool reading_vertical = false;
  3670. auto transaction = tokens.begin_transaction();
  3671. while (tokens.has_next_token()) {
  3672. if (tokens.peek_token().is_delim('/')) {
  3673. if (reading_vertical || horizontal_radii.is_empty())
  3674. return nullptr;
  3675. reading_vertical = true;
  3676. (void)tokens.next_token(); // `/`
  3677. continue;
  3678. }
  3679. auto maybe_dimension = parse_length_percentage(tokens);
  3680. if (!maybe_dimension.has_value())
  3681. return nullptr;
  3682. if (reading_vertical) {
  3683. vertical_radii.append(maybe_dimension.release_value());
  3684. } else {
  3685. horizontal_radii.append(maybe_dimension.release_value());
  3686. }
  3687. }
  3688. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  3689. || horizontal_radii.is_empty()
  3690. || (reading_vertical && vertical_radii.is_empty()))
  3691. return nullptr;
  3692. auto top_left_radius = BorderRadiusStyleValue::create(top_left(horizontal_radii),
  3693. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii));
  3694. auto top_right_radius = BorderRadiusStyleValue::create(top_right(horizontal_radii),
  3695. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii));
  3696. auto bottom_right_radius = BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  3697. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii));
  3698. auto bottom_left_radius = BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  3699. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii));
  3700. transaction.commit();
  3701. return ShorthandStyleValue::create(PropertyID::BorderRadius,
  3702. { PropertyID::BorderTopLeftRadius, PropertyID::BorderTopRightRadius, PropertyID::BorderBottomRightRadius, PropertyID::BorderBottomLeftRadius },
  3703. { move(top_left_radius), move(top_right_radius), move(bottom_right_radius), move(bottom_left_radius) });
  3704. }
  3705. RefPtr<CSSStyleValue> Parser::parse_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  3706. {
  3707. // "none"
  3708. if (auto none = parse_all_as_single_none_value(tokens))
  3709. return none;
  3710. return parse_comma_separated_value_list(tokens, [this, allow_inset_keyword](auto& tokens) {
  3711. return parse_single_shadow_value(tokens, allow_inset_keyword);
  3712. });
  3713. }
  3714. RefPtr<CSSStyleValue> Parser::parse_single_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  3715. {
  3716. auto transaction = tokens.begin_transaction();
  3717. RefPtr<CSSStyleValue> color;
  3718. RefPtr<CSSStyleValue> offset_x;
  3719. RefPtr<CSSStyleValue> offset_y;
  3720. RefPtr<CSSStyleValue> blur_radius;
  3721. RefPtr<CSSStyleValue> spread_distance;
  3722. Optional<ShadowPlacement> placement;
  3723. auto possibly_dynamic_length = [&](ComponentValue const& token) -> RefPtr<CSSStyleValue> {
  3724. auto tokens = TokenStream<ComponentValue>::of_single_token(token);
  3725. auto maybe_length = parse_length(tokens);
  3726. if (!maybe_length.has_value())
  3727. return nullptr;
  3728. return maybe_length->as_style_value();
  3729. };
  3730. while (tokens.has_next_token()) {
  3731. if (auto maybe_color = parse_color_value(tokens); maybe_color) {
  3732. if (color)
  3733. return nullptr;
  3734. color = maybe_color.release_nonnull();
  3735. continue;
  3736. }
  3737. auto const& token = tokens.peek_token();
  3738. if (auto maybe_offset_x = possibly_dynamic_length(token); maybe_offset_x) {
  3739. // horizontal offset
  3740. if (offset_x)
  3741. return nullptr;
  3742. offset_x = maybe_offset_x;
  3743. tokens.next_token();
  3744. // vertical offset
  3745. if (!tokens.has_next_token())
  3746. return nullptr;
  3747. auto maybe_offset_y = possibly_dynamic_length(tokens.peek_token());
  3748. if (!maybe_offset_y)
  3749. return nullptr;
  3750. offset_y = maybe_offset_y;
  3751. tokens.next_token();
  3752. // blur radius (optional)
  3753. if (!tokens.has_next_token())
  3754. break;
  3755. auto maybe_blur_radius = possibly_dynamic_length(tokens.peek_token());
  3756. if (!maybe_blur_radius)
  3757. continue;
  3758. blur_radius = maybe_blur_radius;
  3759. tokens.next_token();
  3760. // spread distance (optional)
  3761. if (!tokens.has_next_token())
  3762. break;
  3763. auto maybe_spread_distance = possibly_dynamic_length(tokens.peek_token());
  3764. if (!maybe_spread_distance)
  3765. continue;
  3766. spread_distance = maybe_spread_distance;
  3767. tokens.next_token();
  3768. continue;
  3769. }
  3770. if (allow_inset_keyword == AllowInsetKeyword::Yes && token.is_ident("inset"sv)) {
  3771. if (placement.has_value())
  3772. return nullptr;
  3773. placement = ShadowPlacement::Inner;
  3774. tokens.next_token();
  3775. continue;
  3776. }
  3777. if (token.is(Token::Type::Comma))
  3778. break;
  3779. return nullptr;
  3780. }
  3781. // If color is absent, default to `currentColor`
  3782. if (!color)
  3783. color = CSSKeywordValue::create(Keyword::Currentcolor);
  3784. // x/y offsets are required
  3785. if (!offset_x || !offset_y)
  3786. return nullptr;
  3787. // Other lengths default to 0
  3788. if (!blur_radius)
  3789. blur_radius = LengthStyleValue::create(Length::make_px(0));
  3790. if (!spread_distance)
  3791. spread_distance = LengthStyleValue::create(Length::make_px(0));
  3792. // Placement is outer by default
  3793. if (!placement.has_value())
  3794. placement = ShadowPlacement::Outer;
  3795. transaction.commit();
  3796. return ShadowStyleValue::create(color.release_nonnull(), offset_x.release_nonnull(), offset_y.release_nonnull(), blur_radius.release_nonnull(), spread_distance.release_nonnull(), placement.release_value());
  3797. }
  3798. RefPtr<CSSStyleValue> Parser::parse_content_value(TokenStream<ComponentValue>& tokens)
  3799. {
  3800. // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.
  3801. auto is_single_value_keyword = [](Keyword keyword) -> bool {
  3802. switch (keyword) {
  3803. case Keyword::None:
  3804. case Keyword::Normal:
  3805. return true;
  3806. default:
  3807. return false;
  3808. }
  3809. };
  3810. if (tokens.remaining_token_count() == 1) {
  3811. auto transaction = tokens.begin_transaction();
  3812. if (auto keyword = parse_keyword_value(tokens)) {
  3813. if (is_single_value_keyword(keyword->to_keyword())) {
  3814. transaction.commit();
  3815. return keyword;
  3816. }
  3817. }
  3818. }
  3819. auto transaction = tokens.begin_transaction();
  3820. StyleValueVector content_values;
  3821. StyleValueVector alt_text_values;
  3822. bool in_alt_text = false;
  3823. while (tokens.has_next_token()) {
  3824. auto& next = tokens.peek_token();
  3825. if (next.is_delim('/')) {
  3826. if (in_alt_text || content_values.is_empty())
  3827. return nullptr;
  3828. in_alt_text = true;
  3829. (void)tokens.next_token();
  3830. continue;
  3831. }
  3832. if (auto style_value = parse_css_value_for_property(PropertyID::Content, tokens)) {
  3833. if (is_single_value_keyword(style_value->to_keyword()))
  3834. return nullptr;
  3835. if (in_alt_text) {
  3836. alt_text_values.append(style_value.release_nonnull());
  3837. } else {
  3838. content_values.append(style_value.release_nonnull());
  3839. }
  3840. continue;
  3841. }
  3842. return nullptr;
  3843. }
  3844. if (content_values.is_empty())
  3845. return nullptr;
  3846. if (in_alt_text && alt_text_values.is_empty())
  3847. return nullptr;
  3848. RefPtr<StyleValueList> alt_text;
  3849. if (!alt_text_values.is_empty())
  3850. alt_text = StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space);
  3851. transaction.commit();
  3852. return ContentStyleValue::create(StyleValueList::create(move(content_values), StyleValueList::Separator::Space), move(alt_text));
  3853. }
  3854. // https://drafts.csswg.org/css-lists-3/#propdef-counter-increment
  3855. RefPtr<CSSStyleValue> Parser::parse_counter_increment_value(TokenStream<ComponentValue>& tokens)
  3856. {
  3857. // [ <counter-name> <integer>? ]+ | none
  3858. if (auto none = parse_all_as_single_none_value(tokens))
  3859. return none;
  3860. return parse_counter_definitions_value(tokens, AllowReversed::No, 1);
  3861. }
  3862. // https://drafts.csswg.org/css-lists-3/#propdef-counter-reset
  3863. RefPtr<CSSStyleValue> Parser::parse_counter_reset_value(TokenStream<ComponentValue>& tokens)
  3864. {
  3865. // [ <counter-name> <integer>? | <reversed-counter-name> <integer>? ]+ | none
  3866. if (auto none = parse_all_as_single_none_value(tokens))
  3867. return none;
  3868. return parse_counter_definitions_value(tokens, AllowReversed::Yes, 0);
  3869. }
  3870. // https://drafts.csswg.org/css-lists-3/#propdef-counter-set
  3871. RefPtr<CSSStyleValue> Parser::parse_counter_set_value(TokenStream<ComponentValue>& tokens)
  3872. {
  3873. // [ <counter-name> <integer>? ]+ | none
  3874. if (auto none = parse_all_as_single_none_value(tokens))
  3875. return none;
  3876. return parse_counter_definitions_value(tokens, AllowReversed::No, 0);
  3877. }
  3878. // https://www.w3.org/TR/css-display-3/#the-display-properties
  3879. RefPtr<CSSStyleValue> Parser::parse_display_value(TokenStream<ComponentValue>& tokens)
  3880. {
  3881. auto parse_single_component_display = [this](TokenStream<ComponentValue>& tokens) -> Optional<Display> {
  3882. auto transaction = tokens.begin_transaction();
  3883. if (auto keyword_value = parse_keyword_value(tokens)) {
  3884. auto keyword = keyword_value->to_keyword();
  3885. if (keyword == Keyword::ListItem) {
  3886. transaction.commit();
  3887. return Display::from_short(Display::Short::ListItem);
  3888. }
  3889. if (auto display_outside = keyword_to_display_outside(keyword); display_outside.has_value()) {
  3890. transaction.commit();
  3891. switch (display_outside.value()) {
  3892. case DisplayOutside::Block:
  3893. return Display::from_short(Display::Short::Block);
  3894. case DisplayOutside::Inline:
  3895. return Display::from_short(Display::Short::Inline);
  3896. case DisplayOutside::RunIn:
  3897. return Display::from_short(Display::Short::RunIn);
  3898. }
  3899. }
  3900. if (auto display_inside = keyword_to_display_inside(keyword); display_inside.has_value()) {
  3901. transaction.commit();
  3902. switch (display_inside.value()) {
  3903. case DisplayInside::Flow:
  3904. return Display::from_short(Display::Short::Flow);
  3905. case DisplayInside::FlowRoot:
  3906. return Display::from_short(Display::Short::FlowRoot);
  3907. case DisplayInside::Table:
  3908. return Display::from_short(Display::Short::Table);
  3909. case DisplayInside::Flex:
  3910. return Display::from_short(Display::Short::Flex);
  3911. case DisplayInside::Grid:
  3912. return Display::from_short(Display::Short::Grid);
  3913. case DisplayInside::Ruby:
  3914. return Display::from_short(Display::Short::Ruby);
  3915. case DisplayInside::Math:
  3916. return Display::from_short(Display::Short::Math);
  3917. }
  3918. }
  3919. if (auto display_internal = keyword_to_display_internal(keyword); display_internal.has_value()) {
  3920. transaction.commit();
  3921. return Display { display_internal.value() };
  3922. }
  3923. if (auto display_box = keyword_to_display_box(keyword); display_box.has_value()) {
  3924. transaction.commit();
  3925. switch (display_box.value()) {
  3926. case DisplayBox::Contents:
  3927. return Display::from_short(Display::Short::Contents);
  3928. case DisplayBox::None:
  3929. return Display::from_short(Display::Short::None);
  3930. }
  3931. }
  3932. if (auto display_legacy = keyword_to_display_legacy(keyword); display_legacy.has_value()) {
  3933. transaction.commit();
  3934. switch (display_legacy.value()) {
  3935. case DisplayLegacy::InlineBlock:
  3936. return Display::from_short(Display::Short::InlineBlock);
  3937. case DisplayLegacy::InlineTable:
  3938. return Display::from_short(Display::Short::InlineTable);
  3939. case DisplayLegacy::InlineFlex:
  3940. return Display::from_short(Display::Short::InlineFlex);
  3941. case DisplayLegacy::InlineGrid:
  3942. return Display::from_short(Display::Short::InlineGrid);
  3943. }
  3944. }
  3945. }
  3946. return OptionalNone {};
  3947. };
  3948. auto parse_multi_component_display = [this](TokenStream<ComponentValue>& tokens) -> Optional<Display> {
  3949. auto list_item = Display::ListItem::No;
  3950. Optional<DisplayInside> inside;
  3951. Optional<DisplayOutside> outside;
  3952. auto transaction = tokens.begin_transaction();
  3953. while (tokens.has_next_token()) {
  3954. if (auto value = parse_keyword_value(tokens)) {
  3955. auto keyword = value->to_keyword();
  3956. if (keyword == Keyword::ListItem) {
  3957. if (list_item == Display::ListItem::Yes)
  3958. return {};
  3959. list_item = Display::ListItem::Yes;
  3960. continue;
  3961. }
  3962. if (auto inside_value = keyword_to_display_inside(keyword); inside_value.has_value()) {
  3963. if (inside.has_value())
  3964. return {};
  3965. inside = inside_value.value();
  3966. continue;
  3967. }
  3968. if (auto outside_value = keyword_to_display_outside(keyword); outside_value.has_value()) {
  3969. if (outside.has_value())
  3970. return {};
  3971. outside = outside_value.value();
  3972. continue;
  3973. }
  3974. }
  3975. // Not a display value, abort.
  3976. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized display value: `{}`", tokens.peek_token().to_string());
  3977. return {};
  3978. }
  3979. // The spec does not allow any other inside values to be combined with list-item
  3980. // <display-outside>? && [ flow | flow-root ]? && list-item
  3981. if (list_item == Display::ListItem::Yes && inside.has_value() && inside != DisplayInside::Flow && inside != DisplayInside::FlowRoot)
  3982. return {};
  3983. transaction.commit();
  3984. return Display { outside.value_or(DisplayOutside::Block), inside.value_or(DisplayInside::Flow), list_item };
  3985. };
  3986. Optional<Display> display;
  3987. if (tokens.remaining_token_count() == 1)
  3988. display = parse_single_component_display(tokens);
  3989. else
  3990. display = parse_multi_component_display(tokens);
  3991. if (display.has_value())
  3992. return DisplayStyleValue::create(display.value());
  3993. return nullptr;
  3994. }
  3995. RefPtr<CSSStyleValue> Parser::parse_filter_value_list_value(TokenStream<ComponentValue>& tokens)
  3996. {
  3997. if (auto none = parse_all_as_single_none_value(tokens))
  3998. return none;
  3999. auto transaction = tokens.begin_transaction();
  4000. // FIXME: <url>s are ignored for now
  4001. // <filter-value-list> = [ <filter-function> | <url> ]+
  4002. enum class FilterToken {
  4003. // Color filters:
  4004. Brightness,
  4005. Contrast,
  4006. Grayscale,
  4007. Invert,
  4008. Opacity,
  4009. Saturate,
  4010. Sepia,
  4011. // Special filters:
  4012. Blur,
  4013. DropShadow,
  4014. HueRotate
  4015. };
  4016. auto filter_token_to_operation = [&](auto filter) {
  4017. VERIFY(to_underlying(filter) < to_underlying(FilterToken::Blur));
  4018. return static_cast<Filter::Color::Operation>(filter);
  4019. };
  4020. auto parse_number_percentage = [&](auto& token) -> Optional<NumberPercentage> {
  4021. if (token.is(Token::Type::Percentage))
  4022. return NumberPercentage(Percentage(token.token().percentage()));
  4023. if (token.is(Token::Type::Number))
  4024. return NumberPercentage(Number(Number::Type::Number, token.token().number_value()));
  4025. return {};
  4026. };
  4027. auto parse_filter_function_name = [&](auto name) -> Optional<FilterToken> {
  4028. if (name.equals_ignoring_ascii_case("blur"sv))
  4029. return FilterToken::Blur;
  4030. if (name.equals_ignoring_ascii_case("brightness"sv))
  4031. return FilterToken::Brightness;
  4032. if (name.equals_ignoring_ascii_case("contrast"sv))
  4033. return FilterToken::Contrast;
  4034. if (name.equals_ignoring_ascii_case("drop-shadow"sv))
  4035. return FilterToken::DropShadow;
  4036. if (name.equals_ignoring_ascii_case("grayscale"sv))
  4037. return FilterToken::Grayscale;
  4038. if (name.equals_ignoring_ascii_case("hue-rotate"sv))
  4039. return FilterToken::HueRotate;
  4040. if (name.equals_ignoring_ascii_case("invert"sv))
  4041. return FilterToken::Invert;
  4042. if (name.equals_ignoring_ascii_case("opacity"sv))
  4043. return FilterToken::Opacity;
  4044. if (name.equals_ignoring_ascii_case("saturate"sv))
  4045. return FilterToken::Saturate;
  4046. if (name.equals_ignoring_ascii_case("sepia"sv))
  4047. return FilterToken::Sepia;
  4048. return {};
  4049. };
  4050. auto parse_filter_function = [&](auto filter_token, auto function_values) -> Optional<FilterFunction> {
  4051. TokenStream tokens { function_values };
  4052. tokens.skip_whitespace();
  4053. auto if_no_more_tokens_return = [&](auto filter) -> Optional<FilterFunction> {
  4054. tokens.skip_whitespace();
  4055. if (tokens.has_next_token())
  4056. return {};
  4057. return filter;
  4058. };
  4059. if (filter_token == FilterToken::Blur) {
  4060. // blur( <length>? )
  4061. if (!tokens.has_next_token())
  4062. return Filter::Blur {};
  4063. auto blur_radius = parse_length(tokens);
  4064. tokens.skip_whitespace();
  4065. if (!blur_radius.has_value())
  4066. return {};
  4067. // FIXME: Support calculated radius
  4068. return if_no_more_tokens_return(Filter::Blur { blur_radius->value() });
  4069. } else if (filter_token == FilterToken::DropShadow) {
  4070. if (!tokens.has_next_token())
  4071. return {};
  4072. // drop-shadow( [ <color>? && <length>{2,3} ] )
  4073. // Note: The following code is a little awkward to allow the color to be before or after the lengths.
  4074. Optional<LengthOrCalculated> maybe_radius = {};
  4075. auto maybe_color = parse_color_value(tokens);
  4076. auto x_offset = parse_length(tokens);
  4077. tokens.skip_whitespace();
  4078. if (!x_offset.has_value() || !tokens.has_next_token()) {
  4079. return {};
  4080. }
  4081. auto y_offset = parse_length(tokens);
  4082. if (!y_offset.has_value()) {
  4083. return {};
  4084. }
  4085. if (tokens.has_next_token()) {
  4086. maybe_radius = parse_length(tokens);
  4087. if (!maybe_color && (!maybe_radius.has_value() || tokens.has_next_token())) {
  4088. maybe_color = parse_color_value(tokens);
  4089. tokens.skip_whitespace();
  4090. if (!maybe_color)
  4091. return {};
  4092. } else if (!maybe_radius.has_value()) {
  4093. return {};
  4094. }
  4095. }
  4096. // FIXME: Support calculated offsets and radius
  4097. return if_no_more_tokens_return(Filter::DropShadow { x_offset->value(), y_offset->value(), maybe_radius.map([](auto& it) { return it.value(); }), maybe_color->to_color({}) });
  4098. } else if (filter_token == FilterToken::HueRotate) {
  4099. // hue-rotate( [ <angle> | <zero> ]? )
  4100. if (!tokens.has_next_token())
  4101. return Filter::HueRotate {};
  4102. auto& token = tokens.next_token();
  4103. if (token.is(Token::Type::Number)) {
  4104. // hue-rotate(0)
  4105. auto number = token.token().number();
  4106. if (number.is_integer() && number.integer_value() == 0)
  4107. return if_no_more_tokens_return(Filter::HueRotate { Filter::HueRotate::Zero {} });
  4108. return {};
  4109. }
  4110. if (!token.is(Token::Type::Dimension))
  4111. return {};
  4112. auto angle_value = token.token().dimension_value();
  4113. auto angle_unit_name = token.token().dimension_unit();
  4114. auto angle_unit = Angle::unit_from_name(angle_unit_name);
  4115. if (!angle_unit.has_value())
  4116. return {};
  4117. Angle angle { angle_value, angle_unit.release_value() };
  4118. return if_no_more_tokens_return(Filter::HueRotate { angle });
  4119. } else {
  4120. // Simple filters:
  4121. // brightness( <number-percentage>? )
  4122. // contrast( <number-percentage>? )
  4123. // grayscale( <number-percentage>? )
  4124. // invert( <number-percentage>? )
  4125. // opacity( <number-percentage>? )
  4126. // sepia( <number-percentage>? )
  4127. // saturate( <number-percentage>? )
  4128. if (!tokens.has_next_token())
  4129. return Filter::Color { filter_token_to_operation(filter_token) };
  4130. auto amount = parse_number_percentage(tokens.next_token());
  4131. if (!amount.has_value())
  4132. return {};
  4133. return if_no_more_tokens_return(Filter::Color { filter_token_to_operation(filter_token), *amount });
  4134. }
  4135. };
  4136. Vector<FilterFunction> filter_value_list {};
  4137. while (tokens.has_next_token()) {
  4138. tokens.skip_whitespace();
  4139. if (!tokens.has_next_token())
  4140. break;
  4141. auto& token = tokens.next_token();
  4142. if (!token.is_function())
  4143. return nullptr;
  4144. auto filter_token = parse_filter_function_name(token.function().name());
  4145. if (!filter_token.has_value())
  4146. return nullptr;
  4147. auto filter_function = parse_filter_function(*filter_token, token.function().values());
  4148. if (!filter_function.has_value())
  4149. return nullptr;
  4150. filter_value_list.append(*filter_function);
  4151. }
  4152. if (filter_value_list.is_empty())
  4153. return nullptr;
  4154. transaction.commit();
  4155. return FilterValueListStyleValue::create(move(filter_value_list));
  4156. }
  4157. RefPtr<CSSStyleValue> Parser::parse_flex_shorthand_value(TokenStream<ComponentValue>& tokens)
  4158. {
  4159. auto transaction = tokens.begin_transaction();
  4160. auto make_flex_shorthand = [&](NonnullRefPtr<CSSStyleValue> flex_grow, NonnullRefPtr<CSSStyleValue> flex_shrink, NonnullRefPtr<CSSStyleValue> flex_basis) {
  4161. transaction.commit();
  4162. return ShorthandStyleValue::create(PropertyID::Flex,
  4163. { PropertyID::FlexGrow, PropertyID::FlexShrink, PropertyID::FlexBasis },
  4164. { move(flex_grow), move(flex_shrink), move(flex_basis) });
  4165. };
  4166. if (tokens.remaining_token_count() == 1) {
  4167. // One-value syntax: <flex-grow> | <flex-basis> | none
  4168. auto properties = Array { PropertyID::FlexGrow, PropertyID::FlexBasis, PropertyID::Flex };
  4169. auto property_and_value = parse_css_value_for_properties(properties, tokens);
  4170. if (!property_and_value.has_value())
  4171. return nullptr;
  4172. auto& value = property_and_value->style_value;
  4173. switch (property_and_value->property) {
  4174. case PropertyID::FlexGrow: {
  4175. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  4176. // https://github.com/w3c/csswg-drafts/issues/5742
  4177. auto flex_basis = PercentageStyleValue::create(Percentage(0));
  4178. auto one = NumberStyleValue::create(1);
  4179. return make_flex_shorthand(*value, one, flex_basis);
  4180. }
  4181. case PropertyID::FlexBasis: {
  4182. auto one = NumberStyleValue::create(1);
  4183. return make_flex_shorthand(one, one, *value);
  4184. }
  4185. case PropertyID::Flex: {
  4186. if (value->is_keyword() && value->to_keyword() == Keyword::None) {
  4187. auto zero = NumberStyleValue::create(0);
  4188. return make_flex_shorthand(zero, zero, CSSKeywordValue::create(Keyword::Auto));
  4189. }
  4190. break;
  4191. }
  4192. default:
  4193. VERIFY_NOT_REACHED();
  4194. }
  4195. return nullptr;
  4196. }
  4197. RefPtr<CSSStyleValue> flex_grow;
  4198. RefPtr<CSSStyleValue> flex_shrink;
  4199. RefPtr<CSSStyleValue> flex_basis;
  4200. // NOTE: FlexGrow has to be before FlexBasis. `0` is a valid FlexBasis, but only
  4201. // if FlexGrow (along with optional FlexShrink) have already been specified.
  4202. auto remaining_longhands = Vector { PropertyID::FlexGrow, PropertyID::FlexBasis };
  4203. while (tokens.has_next_token()) {
  4204. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4205. if (!property_and_value.has_value())
  4206. return nullptr;
  4207. auto& value = property_and_value->style_value;
  4208. remove_property(remaining_longhands, property_and_value->property);
  4209. switch (property_and_value->property) {
  4210. case PropertyID::FlexGrow: {
  4211. VERIFY(!flex_grow);
  4212. flex_grow = value.release_nonnull();
  4213. // Flex-shrink may optionally follow directly after.
  4214. auto maybe_flex_shrink = parse_css_value_for_property(PropertyID::FlexShrink, tokens);
  4215. if (maybe_flex_shrink)
  4216. flex_shrink = maybe_flex_shrink.release_nonnull();
  4217. continue;
  4218. }
  4219. case PropertyID::FlexBasis: {
  4220. VERIFY(!flex_basis);
  4221. flex_basis = value.release_nonnull();
  4222. continue;
  4223. }
  4224. default:
  4225. VERIFY_NOT_REACHED();
  4226. }
  4227. }
  4228. if (!flex_grow)
  4229. flex_grow = property_initial_value(m_context.realm(), PropertyID::FlexGrow);
  4230. if (!flex_shrink)
  4231. flex_shrink = property_initial_value(m_context.realm(), PropertyID::FlexShrink);
  4232. if (!flex_basis) {
  4233. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  4234. // https://github.com/w3c/csswg-drafts/issues/5742
  4235. flex_basis = PercentageStyleValue::create(Percentage(0));
  4236. }
  4237. return make_flex_shorthand(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  4238. }
  4239. RefPtr<CSSStyleValue> Parser::parse_flex_flow_value(TokenStream<ComponentValue>& tokens)
  4240. {
  4241. RefPtr<CSSStyleValue> flex_direction;
  4242. RefPtr<CSSStyleValue> flex_wrap;
  4243. auto remaining_longhands = Vector { PropertyID::FlexDirection, PropertyID::FlexWrap };
  4244. auto transaction = tokens.begin_transaction();
  4245. while (tokens.has_next_token()) {
  4246. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4247. if (!property_and_value.has_value())
  4248. return nullptr;
  4249. auto& value = property_and_value->style_value;
  4250. remove_property(remaining_longhands, property_and_value->property);
  4251. switch (property_and_value->property) {
  4252. case PropertyID::FlexDirection:
  4253. VERIFY(!flex_direction);
  4254. flex_direction = value.release_nonnull();
  4255. continue;
  4256. case PropertyID::FlexWrap:
  4257. VERIFY(!flex_wrap);
  4258. flex_wrap = value.release_nonnull();
  4259. continue;
  4260. default:
  4261. VERIFY_NOT_REACHED();
  4262. }
  4263. }
  4264. if (!flex_direction)
  4265. flex_direction = property_initial_value(m_context.realm(), PropertyID::FlexDirection);
  4266. if (!flex_wrap)
  4267. flex_wrap = property_initial_value(m_context.realm(), PropertyID::FlexWrap);
  4268. transaction.commit();
  4269. return ShorthandStyleValue::create(PropertyID::FlexFlow,
  4270. { PropertyID::FlexDirection, PropertyID::FlexWrap },
  4271. { flex_direction.release_nonnull(), flex_wrap.release_nonnull() });
  4272. }
  4273. static bool is_generic_font_family(Keyword keyword)
  4274. {
  4275. switch (keyword) {
  4276. case Keyword::Cursive:
  4277. case Keyword::Fantasy:
  4278. case Keyword::Monospace:
  4279. case Keyword::Serif:
  4280. case Keyword::SansSerif:
  4281. case Keyword::UiMonospace:
  4282. case Keyword::UiRounded:
  4283. case Keyword::UiSerif:
  4284. case Keyword::UiSansSerif:
  4285. return true;
  4286. default:
  4287. return false;
  4288. }
  4289. }
  4290. RefPtr<CSSStyleValue> Parser::parse_font_value(TokenStream<ComponentValue>& tokens)
  4291. {
  4292. RefPtr<CSSStyleValue> font_stretch;
  4293. RefPtr<CSSStyleValue> font_style;
  4294. RefPtr<CSSStyleValue> font_weight;
  4295. RefPtr<CSSStyleValue> font_size;
  4296. RefPtr<CSSStyleValue> line_height;
  4297. RefPtr<CSSStyleValue> font_families;
  4298. RefPtr<CSSStyleValue> font_variant;
  4299. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  4300. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  4301. // So, we have to handle that separately.
  4302. int normal_count = 0;
  4303. auto remaining_longhands = Vector { PropertyID::FontSize, PropertyID::FontStretch, PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight };
  4304. auto transaction = tokens.begin_transaction();
  4305. while (tokens.has_next_token()) {
  4306. auto& peek_token = tokens.peek_token();
  4307. if (peek_token.is_ident("normal"sv)) {
  4308. normal_count++;
  4309. (void)tokens.next_token();
  4310. continue;
  4311. }
  4312. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4313. if (!property_and_value.has_value())
  4314. return nullptr;
  4315. auto& value = property_and_value->style_value;
  4316. remove_property(remaining_longhands, property_and_value->property);
  4317. switch (property_and_value->property) {
  4318. case PropertyID::FontSize: {
  4319. VERIFY(!font_size);
  4320. font_size = value.release_nonnull();
  4321. // Consume `/ line-height` if present
  4322. if (tokens.peek_token().is_delim('/')) {
  4323. (void)tokens.next_token();
  4324. auto maybe_line_height = parse_css_value_for_property(PropertyID::LineHeight, tokens);
  4325. if (!maybe_line_height)
  4326. return nullptr;
  4327. line_height = maybe_line_height.release_nonnull();
  4328. }
  4329. // Consume font-families
  4330. auto maybe_font_families = parse_font_family_value(tokens);
  4331. // font-family comes last, so we must not have any tokens left over.
  4332. if (!maybe_font_families || tokens.has_next_token())
  4333. return nullptr;
  4334. font_families = maybe_font_families.release_nonnull();
  4335. continue;
  4336. }
  4337. case PropertyID::FontStretch: {
  4338. VERIFY(!font_stretch);
  4339. font_stretch = value.release_nonnull();
  4340. continue;
  4341. }
  4342. case PropertyID::FontStyle: {
  4343. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  4344. VERIFY(!font_style);
  4345. font_style = value.release_nonnull();
  4346. continue;
  4347. }
  4348. case PropertyID::FontVariant: {
  4349. VERIFY(!font_variant);
  4350. font_variant = value.release_nonnull();
  4351. continue;
  4352. }
  4353. case PropertyID::FontWeight: {
  4354. VERIFY(!font_weight);
  4355. font_weight = value.release_nonnull();
  4356. continue;
  4357. }
  4358. default:
  4359. VERIFY_NOT_REACHED();
  4360. }
  4361. return nullptr;
  4362. }
  4363. // Since normal is the default value for all the properties that can have it, we don't have to actually
  4364. // set anything to normal here. It'll be set when we create the ShorthandStyleValue below.
  4365. // We just need to make sure we were not given more normals than will fit.
  4366. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1) + (font_variant ? 0 : 1) + (font_stretch ? 0 : 1);
  4367. if (unset_value_count < normal_count)
  4368. return nullptr;
  4369. if (!font_size || !font_families)
  4370. return nullptr;
  4371. if (!font_style)
  4372. font_style = property_initial_value(m_context.realm(), PropertyID::FontStyle);
  4373. if (!font_variant)
  4374. font_variant = property_initial_value(m_context.realm(), PropertyID::FontVariant);
  4375. if (!font_weight)
  4376. font_weight = property_initial_value(m_context.realm(), PropertyID::FontWeight);
  4377. if (!font_stretch)
  4378. font_stretch = property_initial_value(m_context.realm(), PropertyID::FontStretch);
  4379. if (!line_height)
  4380. line_height = property_initial_value(m_context.realm(), PropertyID::LineHeight);
  4381. transaction.commit();
  4382. return ShorthandStyleValue::create(PropertyID::Font,
  4383. { PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight, PropertyID::FontStretch, PropertyID::FontSize, PropertyID::LineHeight, PropertyID::FontFamily },
  4384. { font_style.release_nonnull(), font_variant.release_nonnull(), font_weight.release_nonnull(), font_stretch.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull() });
  4385. }
  4386. RefPtr<CSSStyleValue> Parser::parse_font_family_value(TokenStream<ComponentValue>& tokens)
  4387. {
  4388. auto next_is_comma_or_eof = [&]() -> bool {
  4389. return !tokens.has_next_token() || tokens.peek_token().is(Token::Type::Comma);
  4390. };
  4391. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  4392. // eg, these are equivalent:
  4393. // font-family: my cool font\!, serif;
  4394. // font-family: "my cool font!", serif;
  4395. StyleValueVector font_families;
  4396. Vector<String> current_name_parts;
  4397. while (tokens.has_next_token()) {
  4398. auto const& peek = tokens.peek_token();
  4399. if (peek.is(Token::Type::String)) {
  4400. // `font-family: my cool "font";` is invalid.
  4401. if (!current_name_parts.is_empty())
  4402. return nullptr;
  4403. (void)tokens.next_token(); // String
  4404. if (!next_is_comma_or_eof())
  4405. return nullptr;
  4406. font_families.append(StringStyleValue::create(peek.token().string()));
  4407. (void)tokens.next_token(); // Comma
  4408. continue;
  4409. }
  4410. if (peek.is(Token::Type::Ident)) {
  4411. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  4412. // CSS-wide keywords are not allowed
  4413. if (auto builtin = parse_builtin_value(tokens))
  4414. return nullptr;
  4415. auto maybe_keyword = keyword_from_string(peek.token().ident());
  4416. // Can't have a generic-font-name as a token in an unquoted font name.
  4417. if (maybe_keyword.has_value() && is_generic_font_family(maybe_keyword.value())) {
  4418. if (!current_name_parts.is_empty())
  4419. return nullptr;
  4420. (void)tokens.next_token(); // Ident
  4421. if (!next_is_comma_or_eof())
  4422. return nullptr;
  4423. font_families.append(CSSKeywordValue::create(maybe_keyword.value()));
  4424. (void)tokens.next_token(); // Comma
  4425. continue;
  4426. }
  4427. current_name_parts.append(tokens.next_token().token().ident().to_string());
  4428. continue;
  4429. }
  4430. if (peek.is(Token::Type::Comma)) {
  4431. if (current_name_parts.is_empty())
  4432. return nullptr;
  4433. (void)tokens.next_token(); // Comma
  4434. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  4435. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  4436. current_name_parts.clear();
  4437. // Can't have a trailing comma
  4438. if (!tokens.has_next_token())
  4439. return nullptr;
  4440. continue;
  4441. }
  4442. return nullptr;
  4443. }
  4444. if (!current_name_parts.is_empty()) {
  4445. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  4446. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  4447. current_name_parts.clear();
  4448. }
  4449. if (font_families.is_empty())
  4450. return nullptr;
  4451. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  4452. }
  4453. JS::GCPtr<CSSFontFaceRule> Parser::parse_font_face_rule(TokenStream<ComponentValue>& tokens)
  4454. {
  4455. auto declarations_and_at_rules = parse_a_list_of_declarations(tokens);
  4456. Optional<FlyString> font_family;
  4457. Vector<ParsedFontFace::Source> src;
  4458. Vector<Gfx::UnicodeRange> unicode_range;
  4459. Optional<int> weight;
  4460. Optional<int> slope;
  4461. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  4462. if (declaration_or_at_rule.is_at_rule()) {
  4463. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: CSS at-rules are not allowed in @font-face; discarding.");
  4464. continue;
  4465. }
  4466. auto const& declaration = declaration_or_at_rule.declaration();
  4467. if (declaration.name().equals_ignoring_ascii_case("font-weight"sv)) {
  4468. TokenStream token_stream { declaration.values() };
  4469. if (auto value = parse_css_value(CSS::PropertyID::FontWeight, token_stream); !value.is_error()) {
  4470. weight = value.value()->to_font_weight();
  4471. }
  4472. continue;
  4473. }
  4474. if (declaration.name().equals_ignoring_ascii_case("font-style"sv)) {
  4475. TokenStream token_stream { declaration.values() };
  4476. if (auto value = parse_css_value(CSS::PropertyID::FontStyle, token_stream); !value.is_error()) {
  4477. slope = value.value()->to_font_slope();
  4478. }
  4479. continue;
  4480. }
  4481. if (declaration.name().equals_ignoring_ascii_case("font-family"sv)) {
  4482. // FIXME: This is very similar to, but different from, the logic in parse_font_family_value().
  4483. // Ideally they could share code.
  4484. Vector<FlyString> font_family_parts;
  4485. bool had_syntax_error = false;
  4486. for (size_t i = 0; i < declaration.values().size(); ++i) {
  4487. auto const& part = declaration.values()[i];
  4488. if (part.is(Token::Type::Whitespace))
  4489. continue;
  4490. if (part.is(Token::Type::String)) {
  4491. if (!font_family_parts.is_empty()) {
  4492. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  4493. had_syntax_error = true;
  4494. break;
  4495. }
  4496. font_family_parts.append(part.token().string());
  4497. continue;
  4498. }
  4499. if (part.is(Token::Type::Ident)) {
  4500. if (is_css_wide_keyword(part.token().ident())) {
  4501. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  4502. had_syntax_error = true;
  4503. break;
  4504. }
  4505. auto keyword = keyword_from_string(part.token().ident());
  4506. if (keyword.has_value() && is_generic_font_family(keyword.value())) {
  4507. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  4508. had_syntax_error = true;
  4509. break;
  4510. }
  4511. font_family_parts.append(part.token().ident());
  4512. continue;
  4513. }
  4514. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  4515. had_syntax_error = true;
  4516. break;
  4517. }
  4518. if (had_syntax_error || font_family_parts.is_empty())
  4519. continue;
  4520. font_family = String::join(' ', font_family_parts).release_value_but_fixme_should_propagate_errors();
  4521. continue;
  4522. }
  4523. if (declaration.name().equals_ignoring_ascii_case("src"sv)) {
  4524. TokenStream token_stream { declaration.values() };
  4525. Vector<ParsedFontFace::Source> supported_sources = parse_font_face_src(token_stream);
  4526. if (!supported_sources.is_empty())
  4527. src = move(supported_sources);
  4528. continue;
  4529. }
  4530. if (declaration.name().equals_ignoring_ascii_case("unicode-range"sv)) {
  4531. TokenStream token_stream { declaration.values() };
  4532. auto unicode_ranges = parse_unicode_ranges(token_stream);
  4533. if (unicode_ranges.is_empty())
  4534. continue;
  4535. unicode_range = move(unicode_ranges);
  4536. continue;
  4537. }
  4538. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unrecognized descriptor '{}' in @font-face; discarding.", declaration.name());
  4539. }
  4540. if (!font_family.has_value()) {
  4541. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face: no font-family!");
  4542. return {};
  4543. }
  4544. if (unicode_range.is_empty()) {
  4545. unicode_range.empend(0x0u, 0x10FFFFu);
  4546. }
  4547. return CSSFontFaceRule::create(m_context.realm(), ParsedFontFace { font_family.release_value(), weight, slope, move(src), move(unicode_range) });
  4548. }
  4549. Vector<ParsedFontFace::Source> Parser::parse_as_font_face_src()
  4550. {
  4551. return parse_font_face_src(m_token_stream);
  4552. }
  4553. template<typename T>
  4554. Vector<ParsedFontFace::Source> Parser::parse_font_face_src(TokenStream<T>& component_values)
  4555. {
  4556. // FIXME: Get this information from the system somehow?
  4557. // Format-name table: https://www.w3.org/TR/css-fonts-4/#font-format-definitions
  4558. auto font_format_is_supported = [](StringView name) {
  4559. // The spec requires us to treat opentype and truetype as synonymous.
  4560. if (name.is_one_of_ignoring_ascii_case("opentype"sv, "truetype"sv, "woff"sv, "woff2"sv))
  4561. return true;
  4562. return false;
  4563. };
  4564. Vector<ParsedFontFace::Source> supported_sources;
  4565. auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(component_values);
  4566. for (auto const& source_token_list : list_of_source_token_lists) {
  4567. TokenStream source_tokens { source_token_list };
  4568. source_tokens.skip_whitespace();
  4569. // <url> [ format(<font-format>)]?
  4570. // FIXME: Implement optional tech() function from CSS-Fonts-4.
  4571. if (auto maybe_url = parse_url_function(source_tokens); maybe_url.has_value()) {
  4572. auto url = maybe_url.release_value();
  4573. if (!url.is_valid()) {
  4574. continue;
  4575. }
  4576. Optional<FlyString> format;
  4577. source_tokens.skip_whitespace();
  4578. if (!source_tokens.has_next_token()) {
  4579. supported_sources.empend(move(url), format);
  4580. continue;
  4581. }
  4582. auto maybe_function = source_tokens.next_token();
  4583. if (!maybe_function.is_function()) {
  4584. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (token after `url()` that isn't a function: {}); discarding.", maybe_function.to_debug_string());
  4585. return {};
  4586. }
  4587. auto const& function = maybe_function.function();
  4588. if (function.name().equals_ignoring_ascii_case("format"sv)) {
  4589. TokenStream format_tokens { function.values() };
  4590. format_tokens.skip_whitespace();
  4591. auto const& format_name_token = format_tokens.next_token();
  4592. StringView format_name;
  4593. if (format_name_token.is(Token::Type::Ident)) {
  4594. format_name = format_name_token.token().ident();
  4595. } else if (format_name_token.is(Token::Type::String)) {
  4596. format_name = format_name_token.token().string();
  4597. } else {
  4598. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (`format()` parameter not an ident or string; is: {}); discarding.", format_name_token.to_debug_string());
  4599. return {};
  4600. }
  4601. if (!font_format_is_supported(format_name)) {
  4602. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format({}) not supported; skipping.", format_name);
  4603. continue;
  4604. }
  4605. format = FlyString::from_utf8(format_name).release_value_but_fixme_should_propagate_errors();
  4606. } else {
  4607. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (unrecognized function token `{}`); discarding.", function.name());
  4608. return {};
  4609. }
  4610. source_tokens.skip_whitespace();
  4611. if (source_tokens.has_next_token()) {
  4612. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (extra token `{}`); discarding.", source_tokens.peek_token().to_debug_string());
  4613. return {};
  4614. }
  4615. supported_sources.empend(move(url), format);
  4616. continue;
  4617. }
  4618. auto const& first = source_tokens.next_token();
  4619. if (first.is_function("local"sv)) {
  4620. if (first.function().values().is_empty()) {
  4621. continue;
  4622. }
  4623. supported_sources.empend(first.function().values().first().to_string(), Optional<FlyString> {});
  4624. continue;
  4625. }
  4626. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (failed to parse url from: {}); discarding.", first.to_debug_string());
  4627. return {};
  4628. }
  4629. return supported_sources;
  4630. }
  4631. RefPtr<CSSStyleValue> Parser::parse_list_style_value(TokenStream<ComponentValue>& tokens)
  4632. {
  4633. RefPtr<CSSStyleValue> list_position;
  4634. RefPtr<CSSStyleValue> list_image;
  4635. RefPtr<CSSStyleValue> list_type;
  4636. int found_nones = 0;
  4637. Vector<PropertyID> remaining_longhands { PropertyID::ListStyleImage, PropertyID::ListStylePosition, PropertyID::ListStyleType };
  4638. auto transaction = tokens.begin_transaction();
  4639. while (tokens.has_next_token()) {
  4640. if (auto peek = tokens.peek_token(); peek.is_ident("none"sv)) {
  4641. (void)tokens.next_token();
  4642. found_nones++;
  4643. continue;
  4644. }
  4645. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4646. if (!property_and_value.has_value())
  4647. return nullptr;
  4648. auto& value = property_and_value->style_value;
  4649. remove_property(remaining_longhands, property_and_value->property);
  4650. switch (property_and_value->property) {
  4651. case PropertyID::ListStylePosition: {
  4652. VERIFY(!list_position);
  4653. list_position = value.release_nonnull();
  4654. continue;
  4655. }
  4656. case PropertyID::ListStyleImage: {
  4657. VERIFY(!list_image);
  4658. list_image = value.release_nonnull();
  4659. continue;
  4660. }
  4661. case PropertyID::ListStyleType: {
  4662. VERIFY(!list_type);
  4663. list_type = value.release_nonnull();
  4664. continue;
  4665. }
  4666. default:
  4667. VERIFY_NOT_REACHED();
  4668. }
  4669. }
  4670. if (found_nones > 2)
  4671. return nullptr;
  4672. if (found_nones == 2) {
  4673. if (list_image || list_type)
  4674. return nullptr;
  4675. auto none = CSSKeywordValue::create(Keyword::None);
  4676. list_image = none;
  4677. list_type = none;
  4678. } else if (found_nones == 1) {
  4679. if (list_image && list_type)
  4680. return nullptr;
  4681. auto none = CSSKeywordValue::create(Keyword::None);
  4682. if (!list_image)
  4683. list_image = none;
  4684. if (!list_type)
  4685. list_type = none;
  4686. }
  4687. if (!list_position)
  4688. list_position = property_initial_value(m_context.realm(), PropertyID::ListStylePosition);
  4689. if (!list_image)
  4690. list_image = property_initial_value(m_context.realm(), PropertyID::ListStyleImage);
  4691. if (!list_type)
  4692. list_type = property_initial_value(m_context.realm(), PropertyID::ListStyleType);
  4693. transaction.commit();
  4694. return ShorthandStyleValue::create(PropertyID::ListStyle,
  4695. { PropertyID::ListStylePosition, PropertyID::ListStyleImage, PropertyID::ListStyleType },
  4696. { list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull() });
  4697. }
  4698. RefPtr<CSSStyleValue> Parser::parse_math_depth_value(TokenStream<ComponentValue>& tokens)
  4699. {
  4700. // https://w3c.github.io/mathml-core/#propdef-math-depth
  4701. // auto-add | add(<integer>) | <integer>
  4702. auto transaction = tokens.begin_transaction();
  4703. auto token = tokens.next_token();
  4704. if (tokens.has_next_token())
  4705. return nullptr;
  4706. // auto-add
  4707. if (token.is_ident("auto-add"sv)) {
  4708. transaction.commit();
  4709. return MathDepthStyleValue::create_auto_add();
  4710. }
  4711. // FIXME: Make it easier to parse "thing that might be <bar> or literally anything that resolves to it" and get rid of this
  4712. auto parse_something_that_resolves_to_integer = [this](ComponentValue& token) -> RefPtr<CSSStyleValue> {
  4713. if (token.is(Token::Type::Number) && token.token().number().is_integer())
  4714. return IntegerStyleValue::create(token.token().to_integer());
  4715. if (auto value = parse_calculated_value(token); value && value->resolves_to_number())
  4716. return value;
  4717. return nullptr;
  4718. };
  4719. // add(<integer>)
  4720. if (token.is_function("add"sv)) {
  4721. auto add_tokens = TokenStream { token.function().values() };
  4722. add_tokens.skip_whitespace();
  4723. auto integer_token = add_tokens.next_token();
  4724. add_tokens.skip_whitespace();
  4725. if (add_tokens.has_next_token())
  4726. return nullptr;
  4727. if (auto integer_value = parse_something_that_resolves_to_integer(integer_token)) {
  4728. transaction.commit();
  4729. return MathDepthStyleValue::create_add(integer_value.release_nonnull());
  4730. }
  4731. return nullptr;
  4732. }
  4733. // <integer>
  4734. if (auto integer_value = parse_something_that_resolves_to_integer(token)) {
  4735. transaction.commit();
  4736. return MathDepthStyleValue::create_integer(integer_value.release_nonnull());
  4737. }
  4738. return nullptr;
  4739. }
  4740. RefPtr<CSSStyleValue> Parser::parse_overflow_value(TokenStream<ComponentValue>& tokens)
  4741. {
  4742. auto transaction = tokens.begin_transaction();
  4743. auto maybe_x_value = parse_css_value_for_property(PropertyID::OverflowX, tokens);
  4744. if (!maybe_x_value)
  4745. return nullptr;
  4746. auto maybe_y_value = parse_css_value_for_property(PropertyID::OverflowY, tokens);
  4747. transaction.commit();
  4748. if (maybe_y_value) {
  4749. return ShorthandStyleValue::create(PropertyID::Overflow,
  4750. { PropertyID::OverflowX, PropertyID::OverflowY },
  4751. { maybe_x_value.release_nonnull(), maybe_y_value.release_nonnull() });
  4752. }
  4753. return ShorthandStyleValue::create(PropertyID::Overflow,
  4754. { PropertyID::OverflowX, PropertyID::OverflowY },
  4755. { *maybe_x_value, *maybe_x_value });
  4756. }
  4757. RefPtr<CSSStyleValue> Parser::parse_place_content_value(TokenStream<ComponentValue>& tokens)
  4758. {
  4759. auto transaction = tokens.begin_transaction();
  4760. auto maybe_align_content_value = parse_css_value_for_property(PropertyID::AlignContent, tokens);
  4761. if (!maybe_align_content_value)
  4762. return nullptr;
  4763. if (!tokens.has_next_token()) {
  4764. if (!property_accepts_keyword(PropertyID::JustifyContent, maybe_align_content_value->to_keyword()))
  4765. return nullptr;
  4766. transaction.commit();
  4767. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  4768. { PropertyID::AlignContent, PropertyID::JustifyContent },
  4769. { *maybe_align_content_value, *maybe_align_content_value });
  4770. }
  4771. auto maybe_justify_content_value = parse_css_value_for_property(PropertyID::JustifyContent, tokens);
  4772. if (!maybe_justify_content_value)
  4773. return nullptr;
  4774. transaction.commit();
  4775. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  4776. { PropertyID::AlignContent, PropertyID::JustifyContent },
  4777. { maybe_align_content_value.release_nonnull(), maybe_justify_content_value.release_nonnull() });
  4778. }
  4779. RefPtr<CSSStyleValue> Parser::parse_place_items_value(TokenStream<ComponentValue>& tokens)
  4780. {
  4781. auto transaction = tokens.begin_transaction();
  4782. auto maybe_align_items_value = parse_css_value_for_property(PropertyID::AlignItems, tokens);
  4783. if (!maybe_align_items_value)
  4784. return nullptr;
  4785. if (!tokens.has_next_token()) {
  4786. if (!property_accepts_keyword(PropertyID::JustifyItems, maybe_align_items_value->to_keyword()))
  4787. return nullptr;
  4788. transaction.commit();
  4789. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  4790. { PropertyID::AlignItems, PropertyID::JustifyItems },
  4791. { *maybe_align_items_value, *maybe_align_items_value });
  4792. }
  4793. auto maybe_justify_items_value = parse_css_value_for_property(PropertyID::JustifyItems, tokens);
  4794. if (!maybe_justify_items_value)
  4795. return nullptr;
  4796. transaction.commit();
  4797. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  4798. { PropertyID::AlignItems, PropertyID::JustifyItems },
  4799. { *maybe_align_items_value, *maybe_justify_items_value });
  4800. }
  4801. RefPtr<CSSStyleValue> Parser::parse_place_self_value(TokenStream<ComponentValue>& tokens)
  4802. {
  4803. auto transaction = tokens.begin_transaction();
  4804. auto maybe_align_self_value = parse_css_value_for_property(PropertyID::AlignSelf, tokens);
  4805. if (!maybe_align_self_value)
  4806. return nullptr;
  4807. if (!tokens.has_next_token()) {
  4808. if (!property_accepts_keyword(PropertyID::JustifySelf, maybe_align_self_value->to_keyword()))
  4809. return nullptr;
  4810. transaction.commit();
  4811. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  4812. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  4813. { *maybe_align_self_value, *maybe_align_self_value });
  4814. }
  4815. auto maybe_justify_self_value = parse_css_value_for_property(PropertyID::JustifySelf, tokens);
  4816. if (!maybe_justify_self_value)
  4817. return nullptr;
  4818. transaction.commit();
  4819. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  4820. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  4821. { *maybe_align_self_value, *maybe_justify_self_value });
  4822. }
  4823. RefPtr<CSSStyleValue> Parser::parse_quotes_value(TokenStream<ComponentValue>& tokens)
  4824. {
  4825. // https://www.w3.org/TR/css-content-3/#quotes-property
  4826. // auto | none | [ <string> <string> ]+
  4827. auto transaction = tokens.begin_transaction();
  4828. if (tokens.remaining_token_count() == 1) {
  4829. auto keyword = parse_keyword_value(tokens);
  4830. if (keyword && property_accepts_keyword(PropertyID::Quotes, keyword->to_keyword())) {
  4831. transaction.commit();
  4832. return keyword;
  4833. }
  4834. return nullptr;
  4835. }
  4836. // Parse an even number of <string> values.
  4837. if (tokens.remaining_token_count() % 2 != 0)
  4838. return nullptr;
  4839. StyleValueVector string_values;
  4840. while (tokens.has_next_token()) {
  4841. auto maybe_string = parse_string_value(tokens);
  4842. if (!maybe_string)
  4843. return nullptr;
  4844. string_values.append(maybe_string.release_nonnull());
  4845. }
  4846. transaction.commit();
  4847. return StyleValueList::create(move(string_values), StyleValueList::Separator::Space);
  4848. }
  4849. RefPtr<CSSStyleValue> Parser::parse_text_decoration_value(TokenStream<ComponentValue>& tokens)
  4850. {
  4851. RefPtr<CSSStyleValue> decoration_line;
  4852. RefPtr<CSSStyleValue> decoration_thickness;
  4853. RefPtr<CSSStyleValue> decoration_style;
  4854. RefPtr<CSSStyleValue> decoration_color;
  4855. auto remaining_longhands = Vector { PropertyID::TextDecorationColor, PropertyID::TextDecorationLine, PropertyID::TextDecorationStyle, PropertyID::TextDecorationThickness };
  4856. auto transaction = tokens.begin_transaction();
  4857. while (tokens.has_next_token()) {
  4858. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4859. if (!property_and_value.has_value())
  4860. return nullptr;
  4861. auto& value = property_and_value->style_value;
  4862. remove_property(remaining_longhands, property_and_value->property);
  4863. switch (property_and_value->property) {
  4864. case PropertyID::TextDecorationColor: {
  4865. VERIFY(!decoration_color);
  4866. decoration_color = value.release_nonnull();
  4867. continue;
  4868. }
  4869. case PropertyID::TextDecorationLine: {
  4870. VERIFY(!decoration_line);
  4871. tokens.reconsume_current_input_token();
  4872. auto parsed_decoration_line = parse_text_decoration_line_value(tokens);
  4873. if (!parsed_decoration_line)
  4874. return nullptr;
  4875. decoration_line = parsed_decoration_line.release_nonnull();
  4876. continue;
  4877. }
  4878. case PropertyID::TextDecorationThickness: {
  4879. VERIFY(!decoration_thickness);
  4880. decoration_thickness = value.release_nonnull();
  4881. continue;
  4882. }
  4883. case PropertyID::TextDecorationStyle: {
  4884. VERIFY(!decoration_style);
  4885. decoration_style = value.release_nonnull();
  4886. continue;
  4887. }
  4888. default:
  4889. VERIFY_NOT_REACHED();
  4890. }
  4891. }
  4892. if (!decoration_line)
  4893. decoration_line = property_initial_value(m_context.realm(), PropertyID::TextDecorationLine);
  4894. if (!decoration_thickness)
  4895. decoration_thickness = property_initial_value(m_context.realm(), PropertyID::TextDecorationThickness);
  4896. if (!decoration_style)
  4897. decoration_style = property_initial_value(m_context.realm(), PropertyID::TextDecorationStyle);
  4898. if (!decoration_color)
  4899. decoration_color = property_initial_value(m_context.realm(), PropertyID::TextDecorationColor);
  4900. transaction.commit();
  4901. return ShorthandStyleValue::create(PropertyID::TextDecoration,
  4902. { PropertyID::TextDecorationLine, PropertyID::TextDecorationThickness, PropertyID::TextDecorationStyle, PropertyID::TextDecorationColor },
  4903. { decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull() });
  4904. }
  4905. RefPtr<CSSStyleValue> Parser::parse_text_decoration_line_value(TokenStream<ComponentValue>& tokens)
  4906. {
  4907. StyleValueVector style_values;
  4908. while (tokens.has_next_token()) {
  4909. auto maybe_value = parse_css_value_for_property(PropertyID::TextDecorationLine, tokens);
  4910. if (!maybe_value)
  4911. break;
  4912. auto value = maybe_value.release_nonnull();
  4913. if (auto maybe_line = keyword_to_text_decoration_line(value->to_keyword()); maybe_line.has_value()) {
  4914. if (maybe_line == TextDecorationLine::None) {
  4915. if (!style_values.is_empty())
  4916. break;
  4917. return value;
  4918. }
  4919. if (style_values.contains_slow(value))
  4920. break;
  4921. style_values.append(move(value));
  4922. continue;
  4923. }
  4924. break;
  4925. }
  4926. if (style_values.is_empty())
  4927. return nullptr;
  4928. return StyleValueList::create(move(style_values), StyleValueList::Separator::Space);
  4929. }
  4930. RefPtr<CSSStyleValue> Parser::parse_easing_value(TokenStream<ComponentValue>& tokens)
  4931. {
  4932. auto transaction = tokens.begin_transaction();
  4933. tokens.skip_whitespace();
  4934. auto const& part = tokens.next_token();
  4935. if (part.is(Token::Type::Ident)) {
  4936. auto name = part.token().ident();
  4937. auto maybe_simple_easing = [&] -> RefPtr<EasingStyleValue> {
  4938. if (name == "linear"sv)
  4939. return EasingStyleValue::create(EasingStyleValue::Linear {});
  4940. if (name == "ease"sv)
  4941. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease());
  4942. if (name == "ease-in"sv)
  4943. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease_in());
  4944. if (name == "ease-out"sv)
  4945. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease_out());
  4946. if (name == "ease-in-out"sv)
  4947. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease_in_out());
  4948. if (name == "step-start"sv)
  4949. return EasingStyleValue::create(EasingStyleValue::Steps::step_start());
  4950. if (name == "step-end"sv)
  4951. return EasingStyleValue::create(EasingStyleValue::Steps::step_end());
  4952. return {};
  4953. }();
  4954. if (!maybe_simple_easing)
  4955. return nullptr;
  4956. transaction.commit();
  4957. return maybe_simple_easing;
  4958. }
  4959. if (!part.is_function())
  4960. return nullptr;
  4961. TokenStream argument_tokens { part.function().values() };
  4962. auto comma_separated_arguments = parse_a_comma_separated_list_of_component_values(argument_tokens);
  4963. // Remove whitespace
  4964. for (auto& argument : comma_separated_arguments)
  4965. argument.remove_all_matching([](auto& value) { return value.is(Token::Type::Whitespace); });
  4966. auto name = part.function().name();
  4967. if (name == "linear"sv) {
  4968. Vector<EasingStyleValue::Linear::Stop> stops;
  4969. for (auto const& argument : comma_separated_arguments) {
  4970. if (argument.is_empty() || argument.size() > 2)
  4971. return nullptr;
  4972. Optional<double> offset;
  4973. Optional<double> position;
  4974. for (auto const& part : argument) {
  4975. if (part.is(Token::Type::Number)) {
  4976. if (offset.has_value())
  4977. return nullptr;
  4978. offset = part.token().number_value();
  4979. } else if (part.is(Token::Type::Percentage)) {
  4980. if (position.has_value())
  4981. return nullptr;
  4982. position = part.token().percentage();
  4983. } else {
  4984. return nullptr;
  4985. };
  4986. }
  4987. if (!offset.has_value())
  4988. return nullptr;
  4989. stops.append({ offset.value(), move(position) });
  4990. }
  4991. if (stops.is_empty())
  4992. return nullptr;
  4993. transaction.commit();
  4994. return EasingStyleValue::create(EasingStyleValue::Linear { move(stops) });
  4995. }
  4996. if (name == "cubic-bezier") {
  4997. if (comma_separated_arguments.size() != 4)
  4998. return nullptr;
  4999. for (auto const& argument : comma_separated_arguments) {
  5000. if (argument.size() != 1)
  5001. return nullptr;
  5002. if (!argument[0].is(Token::Type::Number))
  5003. return nullptr;
  5004. }
  5005. EasingStyleValue::CubicBezier bezier {
  5006. comma_separated_arguments[0][0].token().number_value(),
  5007. comma_separated_arguments[1][0].token().number_value(),
  5008. comma_separated_arguments[2][0].token().number_value(),
  5009. comma_separated_arguments[3][0].token().number_value(),
  5010. };
  5011. if (bezier.x1 < 0.0 || bezier.x1 > 1.0 || bezier.x2 < 0.0 || bezier.x2 > 1.0)
  5012. return nullptr;
  5013. transaction.commit();
  5014. return EasingStyleValue::create(bezier);
  5015. }
  5016. if (name == "steps") {
  5017. if (comma_separated_arguments.is_empty() || comma_separated_arguments.size() > 2)
  5018. return nullptr;
  5019. for (auto const& argument : comma_separated_arguments) {
  5020. if (argument.size() != 1)
  5021. return nullptr;
  5022. }
  5023. EasingStyleValue::Steps steps;
  5024. auto intervals_argument = comma_separated_arguments[0][0];
  5025. if (!intervals_argument.is(Token::Type::Number))
  5026. return nullptr;
  5027. if (!intervals_argument.token().number().is_integer())
  5028. return nullptr;
  5029. auto intervals = intervals_argument.token().to_integer();
  5030. if (comma_separated_arguments.size() == 2) {
  5031. TokenStream identifier_stream { comma_separated_arguments[1] };
  5032. auto keyword_value = parse_keyword_value(identifier_stream);
  5033. if (!keyword_value)
  5034. return nullptr;
  5035. switch (keyword_value->to_keyword()) {
  5036. case Keyword::JumpStart:
  5037. steps.position = EasingStyleValue::Steps::Position::JumpStart;
  5038. break;
  5039. case Keyword::JumpEnd:
  5040. steps.position = EasingStyleValue::Steps::Position::JumpEnd;
  5041. break;
  5042. case Keyword::JumpBoth:
  5043. steps.position = EasingStyleValue::Steps::Position::JumpBoth;
  5044. break;
  5045. case Keyword::JumpNone:
  5046. steps.position = EasingStyleValue::Steps::Position::JumpNone;
  5047. break;
  5048. case Keyword::Start:
  5049. steps.position = EasingStyleValue::Steps::Position::Start;
  5050. break;
  5051. case Keyword::End:
  5052. steps.position = EasingStyleValue::Steps::Position::End;
  5053. break;
  5054. default:
  5055. return nullptr;
  5056. }
  5057. }
  5058. // Perform extra validation
  5059. // https://drafts.csswg.org/css-easing/#funcdef-step-easing-function-steps
  5060. // The first parameter specifies the number of intervals in the function. It must be a positive integer greater than 0
  5061. // unless the second parameter is jump-none in which case it must be a positive integer greater than 1.
  5062. if (steps.position == EasingStyleValue::Steps::Position::JumpNone) {
  5063. if (intervals < 1)
  5064. return nullptr;
  5065. } else if (intervals < 0) {
  5066. return nullptr;
  5067. }
  5068. steps.number_of_intervals = intervals;
  5069. transaction.commit();
  5070. return EasingStyleValue::create(steps);
  5071. }
  5072. return nullptr;
  5073. }
  5074. // https://www.w3.org/TR/css-transforms-1/#transform-property
  5075. RefPtr<CSSStyleValue> Parser::parse_transform_value(TokenStream<ComponentValue>& tokens)
  5076. {
  5077. // <transform> = none | <transform-list>
  5078. // <transform-list> = <transform-function>+
  5079. if (auto none = parse_all_as_single_none_value(tokens))
  5080. return none;
  5081. StyleValueVector transformations;
  5082. auto transaction = tokens.begin_transaction();
  5083. while (tokens.has_next_token()) {
  5084. auto const& part = tokens.next_token();
  5085. if (!part.is_function())
  5086. return nullptr;
  5087. auto maybe_function = transform_function_from_string(part.function().name());
  5088. if (!maybe_function.has_value())
  5089. return nullptr;
  5090. auto function = maybe_function.release_value();
  5091. auto function_metadata = transform_function_metadata(function);
  5092. auto function_tokens = TokenStream { part.function().values() };
  5093. auto arguments = parse_a_comma_separated_list_of_component_values(function_tokens);
  5094. if (arguments.size() > function_metadata.parameters.size()) {
  5095. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", part.function().name(), function_metadata.parameters.size());
  5096. return nullptr;
  5097. }
  5098. if (arguments.size() < function_metadata.parameters.size() && function_metadata.parameters[arguments.size()].required) {
  5099. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", arguments.size());
  5100. return nullptr;
  5101. }
  5102. StyleValueVector values;
  5103. for (auto argument_index = 0u; argument_index < arguments.size(); ++argument_index) {
  5104. TokenStream argument_tokens { arguments[argument_index] };
  5105. argument_tokens.skip_whitespace();
  5106. auto const& value = argument_tokens.next_token();
  5107. RefPtr<CalculatedStyleValue> maybe_calc_value = parse_calculated_value(value);
  5108. switch (function_metadata.parameters[argument_index].type) {
  5109. case TransformFunctionParameterType::Angle: {
  5110. // These are `<angle> | <zero>` in the spec, so we have to check for both kinds.
  5111. if (maybe_calc_value && maybe_calc_value->resolves_to_angle()) {
  5112. values.append(maybe_calc_value.release_nonnull());
  5113. } else if (value.is(Token::Type::Number) && value.token().number_value() == 0) {
  5114. values.append(AngleStyleValue::create(Angle::make_degrees(0)));
  5115. } else {
  5116. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5117. argument_tokens.reconsume_current_input_token();
  5118. auto dimension_value = parse_dimension_value(argument_tokens);
  5119. if (!dimension_value || !dimension_value->is_angle())
  5120. return nullptr;
  5121. values.append(dimension_value.release_nonnull());
  5122. }
  5123. break;
  5124. }
  5125. case TransformFunctionParameterType::Length:
  5126. case TransformFunctionParameterType::LengthNone: {
  5127. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  5128. (void)argument_tokens.next_token(); // calc()
  5129. values.append(maybe_calc_value.release_nonnull());
  5130. } else {
  5131. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5132. argument_tokens.reconsume_current_input_token();
  5133. if (function_metadata.parameters[argument_index].type == TransformFunctionParameterType::LengthNone) {
  5134. auto keyword_transaction = argument_tokens.begin_transaction();
  5135. auto keyword_value = parse_keyword_value(argument_tokens);
  5136. if (keyword_value && keyword_value->to_keyword() == Keyword::None) {
  5137. values.append(keyword_value.release_nonnull());
  5138. keyword_transaction.commit();
  5139. break;
  5140. }
  5141. }
  5142. auto dimension_value = parse_dimension_value(argument_tokens);
  5143. if (!dimension_value || !dimension_value->is_length())
  5144. return nullptr;
  5145. values.append(dimension_value.release_nonnull());
  5146. }
  5147. break;
  5148. }
  5149. case TransformFunctionParameterType::LengthPercentage: {
  5150. if (maybe_calc_value && maybe_calc_value->resolves_to_length_percentage()) {
  5151. values.append(maybe_calc_value.release_nonnull());
  5152. } else {
  5153. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5154. argument_tokens.reconsume_current_input_token();
  5155. auto dimension_value = parse_dimension_value(argument_tokens);
  5156. if (!dimension_value)
  5157. return nullptr;
  5158. if (dimension_value->is_percentage() || dimension_value->is_length())
  5159. values.append(dimension_value.release_nonnull());
  5160. else
  5161. return nullptr;
  5162. }
  5163. break;
  5164. }
  5165. case TransformFunctionParameterType::Number: {
  5166. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  5167. values.append(maybe_calc_value.release_nonnull());
  5168. } else {
  5169. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5170. argument_tokens.reconsume_current_input_token();
  5171. auto number = parse_number_value(argument_tokens);
  5172. if (!number)
  5173. return nullptr;
  5174. values.append(number.release_nonnull());
  5175. }
  5176. break;
  5177. }
  5178. case TransformFunctionParameterType::NumberPercentage: {
  5179. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  5180. values.append(maybe_calc_value.release_nonnull());
  5181. } else {
  5182. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5183. argument_tokens.reconsume_current_input_token();
  5184. auto number_or_percentage = parse_number_percentage_value(argument_tokens);
  5185. if (!number_or_percentage)
  5186. return nullptr;
  5187. values.append(number_or_percentage.release_nonnull());
  5188. }
  5189. break;
  5190. }
  5191. }
  5192. argument_tokens.skip_whitespace();
  5193. if (argument_tokens.has_next_token())
  5194. return nullptr;
  5195. }
  5196. transformations.append(TransformationStyleValue::create(function, move(values)));
  5197. }
  5198. transaction.commit();
  5199. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  5200. }
  5201. // https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
  5202. // FIXME: This only supports a 2D position
  5203. RefPtr<CSSStyleValue> Parser::parse_transform_origin_value(TokenStream<ComponentValue>& tokens)
  5204. {
  5205. enum class Axis {
  5206. None,
  5207. X,
  5208. Y,
  5209. };
  5210. struct AxisOffset {
  5211. Axis axis;
  5212. NonnullRefPtr<CSSStyleValue> offset;
  5213. };
  5214. auto to_axis_offset = [](RefPtr<CSSStyleValue> value) -> Optional<AxisOffset> {
  5215. if (!value)
  5216. return OptionalNone {};
  5217. if (value->is_percentage())
  5218. return AxisOffset { Axis::None, value->as_percentage() };
  5219. if (value->is_length())
  5220. return AxisOffset { Axis::None, value->as_length() };
  5221. if (value->is_keyword()) {
  5222. switch (value->to_keyword()) {
  5223. case Keyword::Top:
  5224. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(0)) };
  5225. case Keyword::Left:
  5226. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(0)) };
  5227. case Keyword::Center:
  5228. return AxisOffset { Axis::None, PercentageStyleValue::create(Percentage(50)) };
  5229. case Keyword::Bottom:
  5230. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(100)) };
  5231. case Keyword::Right:
  5232. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(100)) };
  5233. default:
  5234. return OptionalNone {};
  5235. }
  5236. }
  5237. return OptionalNone {};
  5238. };
  5239. auto transaction = tokens.begin_transaction();
  5240. auto make_list = [&transaction](NonnullRefPtr<CSSStyleValue> const& x_value, NonnullRefPtr<CSSStyleValue> const& y_value) -> NonnullRefPtr<StyleValueList> {
  5241. transaction.commit();
  5242. return StyleValueList::create(StyleValueVector { x_value, y_value }, StyleValueList::Separator::Space);
  5243. };
  5244. switch (tokens.remaining_token_count()) {
  5245. case 1: {
  5246. auto single_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  5247. if (!single_value.has_value())
  5248. return nullptr;
  5249. // If only one value is specified, the second value is assumed to be center.
  5250. // FIXME: If one or two values are specified, the third value is assumed to be 0px.
  5251. switch (single_value->axis) {
  5252. case Axis::None:
  5253. case Axis::X:
  5254. return make_list(single_value->offset, PercentageStyleValue::create(Percentage(50)));
  5255. case Axis::Y:
  5256. return make_list(PercentageStyleValue::create(Percentage(50)), single_value->offset);
  5257. }
  5258. VERIFY_NOT_REACHED();
  5259. }
  5260. case 2: {
  5261. auto first_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  5262. auto second_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  5263. if (!first_value.has_value() || !second_value.has_value())
  5264. return nullptr;
  5265. RefPtr<CSSStyleValue> x_value;
  5266. RefPtr<CSSStyleValue> y_value;
  5267. if (first_value->axis == Axis::X) {
  5268. x_value = first_value->offset;
  5269. } else if (first_value->axis == Axis::Y) {
  5270. y_value = first_value->offset;
  5271. }
  5272. if (second_value->axis == Axis::X) {
  5273. if (x_value)
  5274. return nullptr;
  5275. x_value = second_value->offset;
  5276. // Put the other in Y since its axis can't have been X
  5277. y_value = first_value->offset;
  5278. } else if (second_value->axis == Axis::Y) {
  5279. if (y_value)
  5280. return nullptr;
  5281. y_value = second_value->offset;
  5282. // Put the other in X since its axis can't have been Y
  5283. x_value = first_value->offset;
  5284. } else {
  5285. if (x_value) {
  5286. VERIFY(!y_value);
  5287. y_value = second_value->offset;
  5288. } else {
  5289. VERIFY(!x_value);
  5290. x_value = second_value->offset;
  5291. }
  5292. }
  5293. // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
  5294. // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
  5295. // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
  5296. if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
  5297. x_value = first_value->offset;
  5298. y_value = second_value->offset;
  5299. }
  5300. return make_list(x_value.release_nonnull(), y_value.release_nonnull());
  5301. }
  5302. }
  5303. return nullptr;
  5304. }
  5305. RefPtr<CSSStyleValue> Parser::parse_transition_value(TokenStream<ComponentValue>& tokens)
  5306. {
  5307. if (auto none = parse_all_as_single_none_value(tokens))
  5308. return none;
  5309. Vector<TransitionStyleValue::Transition> transitions;
  5310. auto transaction = tokens.begin_transaction();
  5311. while (tokens.has_next_token()) {
  5312. TransitionStyleValue::Transition transition;
  5313. auto time_value_count = 0;
  5314. while (tokens.has_next_token() && !tokens.peek_token().is(Token::Type::Comma)) {
  5315. if (auto time = parse_time(tokens); time.has_value()) {
  5316. switch (time_value_count) {
  5317. case 0:
  5318. transition.duration = time.release_value();
  5319. break;
  5320. case 1:
  5321. transition.delay = time.release_value();
  5322. break;
  5323. default:
  5324. dbgln_if(CSS_PARSER_DEBUG, "Transition property has more than two time values");
  5325. return {};
  5326. }
  5327. time_value_count++;
  5328. continue;
  5329. }
  5330. if (auto easing = parse_easing_value(tokens)) {
  5331. if (transition.easing) {
  5332. dbgln_if(CSS_PARSER_DEBUG, "Transition property has multiple easing values");
  5333. return {};
  5334. }
  5335. transition.easing = easing->as_easing();
  5336. continue;
  5337. }
  5338. if (tokens.peek_token().is(Token::Type::Ident)) {
  5339. if (transition.property_name) {
  5340. dbgln_if(CSS_PARSER_DEBUG, "Transition property has multiple property identifiers");
  5341. return {};
  5342. }
  5343. auto ident = tokens.next_token().token().ident();
  5344. if (auto property = property_id_from_string(ident); property.has_value())
  5345. transition.property_name = CustomIdentStyleValue::create(ident);
  5346. continue;
  5347. }
  5348. dbgln_if(CSS_PARSER_DEBUG, "Transition property has unexpected token \"{}\"", tokens.peek_token().to_string());
  5349. return {};
  5350. }
  5351. if (!transition.property_name)
  5352. transition.property_name = CustomIdentStyleValue::create("all"_fly_string);
  5353. if (!transition.easing)
  5354. transition.easing = EasingStyleValue::create(EasingStyleValue::CubicBezier::ease());
  5355. transitions.append(move(transition));
  5356. if (!tokens.peek_token().is(Token::Type::Comma))
  5357. break;
  5358. tokens.next_token();
  5359. }
  5360. transaction.commit();
  5361. return TransitionStyleValue::create(move(transitions));
  5362. }
  5363. RefPtr<CSSStyleValue> Parser::parse_as_css_value(PropertyID property_id)
  5364. {
  5365. auto component_values = parse_a_list_of_component_values(m_token_stream);
  5366. auto tokens = TokenStream(component_values);
  5367. auto parsed_value = parse_css_value(property_id, tokens);
  5368. if (parsed_value.is_error())
  5369. return nullptr;
  5370. return parsed_value.release_value();
  5371. }
  5372. Optional<CSS::GridSize> Parser::parse_grid_size(ComponentValue const& component_value)
  5373. {
  5374. if (component_value.is_function()) {
  5375. if (auto maybe_calculated = parse_calculated_value(component_value)) {
  5376. if (maybe_calculated->resolves_to_length_percentage())
  5377. return GridSize(LengthPercentage(maybe_calculated.release_nonnull()));
  5378. // FIXME: Support calculated <flex>
  5379. }
  5380. return {};
  5381. }
  5382. if (component_value.is_ident("auto"sv))
  5383. return GridSize::make_auto();
  5384. if (component_value.is_ident("max-content"sv))
  5385. return GridSize(GridSize::Type::MaxContent);
  5386. if (component_value.is_ident("min-content"sv))
  5387. return GridSize(GridSize::Type::MinContent);
  5388. auto dimension = parse_dimension(component_value);
  5389. if (!dimension.has_value())
  5390. return {};
  5391. if (dimension->is_length())
  5392. return GridSize(dimension->length());
  5393. else if (dimension->is_percentage())
  5394. return GridSize(dimension->percentage());
  5395. else if (dimension->is_flex())
  5396. return GridSize(dimension->flex());
  5397. return {};
  5398. }
  5399. Optional<CSS::GridFitContent> Parser::parse_fit_content(Vector<ComponentValue> const& component_values)
  5400. {
  5401. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-fit-content
  5402. // 'fit-content( <length-percentage> )'
  5403. // Represents the formula max(minimum, min(limit, max-content)), where minimum represents an auto minimum (which is often, but not always,
  5404. // equal to a min-content minimum), and limit is the track sizing function passed as an argument to fit-content().
  5405. // This is essentially calculated as the smaller of minmax(auto, max-content) and minmax(auto, limit).
  5406. auto function_tokens = TokenStream(component_values);
  5407. function_tokens.skip_whitespace();
  5408. auto maybe_length_percentage = parse_length_percentage(function_tokens);
  5409. if (maybe_length_percentage.has_value())
  5410. return CSS::GridFitContent(CSS::GridSize(CSS::GridSize::Type::FitContent, maybe_length_percentage.value()));
  5411. return {};
  5412. }
  5413. Optional<CSS::GridMinMax> Parser::parse_min_max(Vector<ComponentValue> const& component_values)
  5414. {
  5415. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  5416. // 'minmax(min, max)'
  5417. // Defines a size range greater than or equal to min and less than or equal to max. If the max is
  5418. // less than the min, then the max will be floored by the min (essentially yielding minmax(min,
  5419. // min)). As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  5420. auto function_tokens = TokenStream(component_values);
  5421. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  5422. if (comma_separated_list.size() != 2)
  5423. return {};
  5424. TokenStream part_one_tokens { comma_separated_list[0] };
  5425. part_one_tokens.skip_whitespace();
  5426. if (!part_one_tokens.has_next_token())
  5427. return {};
  5428. auto current_token = part_one_tokens.next_token();
  5429. auto min_grid_size = parse_grid_size(current_token);
  5430. TokenStream part_two_tokens { comma_separated_list[1] };
  5431. part_two_tokens.skip_whitespace();
  5432. if (!part_two_tokens.has_next_token())
  5433. return {};
  5434. current_token = part_two_tokens.next_token();
  5435. auto max_grid_size = parse_grid_size(current_token);
  5436. if (min_grid_size.has_value() && max_grid_size.has_value()) {
  5437. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  5438. // As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  5439. if (min_grid_size.value().is_flexible_length())
  5440. return {};
  5441. return CSS::GridMinMax(min_grid_size.value(), max_grid_size.value());
  5442. }
  5443. return {};
  5444. }
  5445. Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& component_values)
  5446. {
  5447. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  5448. // 7.2.3.1. Syntax of repeat()
  5449. // The generic form of the repeat() syntax is, approximately,
  5450. // repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> )
  5451. auto is_auto_fill = false;
  5452. auto is_auto_fit = false;
  5453. auto function_tokens = TokenStream(component_values);
  5454. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  5455. if (comma_separated_list.size() != 2)
  5456. return {};
  5457. // The first argument specifies the number of repetitions.
  5458. TokenStream part_one_tokens { comma_separated_list[0] };
  5459. part_one_tokens.skip_whitespace();
  5460. if (!part_one_tokens.has_next_token())
  5461. return {};
  5462. auto& current_token = part_one_tokens.next_token();
  5463. auto repeat_count = 0;
  5464. if (current_token.is(Token::Type::Number) && current_token.token().number().is_integer() && current_token.token().number_value() > 0)
  5465. repeat_count = current_token.token().number_value();
  5466. else if (current_token.is_ident("auto-fill"sv))
  5467. is_auto_fill = true;
  5468. else if (current_token.is_ident("auto-fit"sv))
  5469. is_auto_fit = true;
  5470. // The second argument is a track list, which is repeated that number of times.
  5471. TokenStream part_two_tokens { comma_separated_list[1] };
  5472. part_two_tokens.skip_whitespace();
  5473. if (!part_two_tokens.has_next_token())
  5474. return {};
  5475. Vector<Variant<ExplicitGridTrack, GridLineNames>> repeat_params;
  5476. auto last_object_was_line_names = false;
  5477. while (part_two_tokens.has_next_token()) {
  5478. auto token = part_two_tokens.next_token();
  5479. Vector<String> line_names;
  5480. if (token.is_block()) {
  5481. if (last_object_was_line_names)
  5482. return {};
  5483. last_object_was_line_names = true;
  5484. if (!token.block().is_square())
  5485. return {};
  5486. TokenStream block_tokens { token.block().values() };
  5487. while (block_tokens.has_next_token()) {
  5488. auto current_block_token = block_tokens.next_token();
  5489. line_names.append(current_block_token.token().ident().to_string());
  5490. block_tokens.skip_whitespace();
  5491. }
  5492. repeat_params.append(GridLineNames { move(line_names) });
  5493. part_two_tokens.skip_whitespace();
  5494. } else {
  5495. last_object_was_line_names = false;
  5496. auto track_sizing_function = parse_track_sizing_function(token);
  5497. if (!track_sizing_function.has_value())
  5498. return {};
  5499. // However, there are some restrictions:
  5500. // The repeat() notation can’t be nested.
  5501. if (track_sizing_function.value().is_repeat())
  5502. return {};
  5503. // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.
  5504. // Note that 'auto' is also an intrinsic size (and thus not permitted) but we can't use
  5505. // track_sizing_function.is_auto(..) to check for it, as it requires AvailableSize, which is why there is
  5506. // a separate check for it below.
  5507. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  5508. // https://www.w3.org/TR/css-grid-2/#intrinsic-sizing-function
  5509. if (track_sizing_function.value().is_default()
  5510. && (track_sizing_function.value().grid_size().is_flexible_length() || token.is_ident("auto"sv))
  5511. && (is_auto_fill || is_auto_fit))
  5512. return {};
  5513. repeat_params.append(track_sizing_function.value());
  5514. part_two_tokens.skip_whitespace();
  5515. }
  5516. }
  5517. // Thus the precise syntax of the repeat() notation has several forms:
  5518. // <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? )
  5519. // <auto-repeat> = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  5520. // <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  5521. // <name-repeat> = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)
  5522. // The <track-repeat> variant can represent the repetition of any <track-size>, but is limited to a
  5523. // fixed number of repetitions.
  5524. // The <auto-repeat> variant can repeat automatically to fill a space, but requires definite track
  5525. // sizes so that the number of repetitions can be calculated. It can only appear once in the track
  5526. // list, but the same track list can also contain <fixed-repeat>s.
  5527. // The <name-repeat> variant is for adding line names to subgrids. It can only be used with the
  5528. // subgrid keyword and cannot specify track sizes, only line names.
  5529. // If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to
  5530. // each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a]
  5531. // 1fr [b a] 1fr [b].
  5532. if (is_auto_fill)
  5533. return GridRepeat(GridTrackSizeList(move(repeat_params)), GridRepeat::Type::AutoFill);
  5534. else if (is_auto_fit)
  5535. return GridRepeat(GridTrackSizeList(move(repeat_params)), GridRepeat::Type::AutoFit);
  5536. else
  5537. return GridRepeat(GridTrackSizeList(move(repeat_params)), repeat_count);
  5538. }
  5539. Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentValue const& token)
  5540. {
  5541. if (token.is_function()) {
  5542. auto const& function_token = token.function();
  5543. if (function_token.name().equals_ignoring_ascii_case("repeat"sv)) {
  5544. auto maybe_repeat = parse_repeat(function_token.values());
  5545. if (maybe_repeat.has_value())
  5546. return CSS::ExplicitGridTrack(maybe_repeat.value());
  5547. else
  5548. return {};
  5549. } else if (function_token.name().equals_ignoring_ascii_case("minmax"sv)) {
  5550. auto maybe_min_max_value = parse_min_max(function_token.values());
  5551. if (maybe_min_max_value.has_value())
  5552. return CSS::ExplicitGridTrack(maybe_min_max_value.value());
  5553. else
  5554. return {};
  5555. } else if (function_token.name().equals_ignoring_ascii_case("fit-content"sv)) {
  5556. auto maybe_fit_content_value = parse_fit_content(function_token.values());
  5557. if (maybe_fit_content_value.has_value())
  5558. return CSS::ExplicitGridTrack(maybe_fit_content_value.value());
  5559. return {};
  5560. } else if (auto maybe_calculated = parse_calculated_value(token)) {
  5561. return CSS::ExplicitGridTrack(GridSize(LengthPercentage(maybe_calculated.release_nonnull())));
  5562. }
  5563. return {};
  5564. } else if (token.is_ident("auto"sv)) {
  5565. return CSS::ExplicitGridTrack(GridSize(Length::make_auto()));
  5566. } else if (token.is_block()) {
  5567. return {};
  5568. } else {
  5569. auto grid_size = parse_grid_size(token);
  5570. if (!grid_size.has_value())
  5571. return {};
  5572. return CSS::ExplicitGridTrack(grid_size.value());
  5573. }
  5574. }
  5575. RefPtr<CSSStyleValue> Parser::parse_grid_track_size_list(TokenStream<ComponentValue>& tokens, bool allow_separate_line_name_blocks)
  5576. {
  5577. if (auto none = parse_all_as_single_none_value(tokens))
  5578. return GridTrackSizeListStyleValue::make_none();
  5579. auto transaction = tokens.begin_transaction();
  5580. Vector<Variant<ExplicitGridTrack, GridLineNames>> track_list;
  5581. auto last_object_was_line_names = false;
  5582. while (tokens.has_next_token()) {
  5583. auto token = tokens.next_token();
  5584. if (token.is_block()) {
  5585. if (last_object_was_line_names && !allow_separate_line_name_blocks) {
  5586. transaction.commit();
  5587. return GridTrackSizeListStyleValue::make_auto();
  5588. }
  5589. last_object_was_line_names = true;
  5590. Vector<String> line_names;
  5591. if (!token.block().is_square()) {
  5592. transaction.commit();
  5593. return GridTrackSizeListStyleValue::make_auto();
  5594. }
  5595. TokenStream block_tokens { token.block().values() };
  5596. block_tokens.skip_whitespace();
  5597. while (block_tokens.has_next_token()) {
  5598. auto current_block_token = block_tokens.next_token();
  5599. line_names.append(current_block_token.token().ident().to_string());
  5600. block_tokens.skip_whitespace();
  5601. }
  5602. track_list.append(GridLineNames { move(line_names) });
  5603. } else {
  5604. last_object_was_line_names = false;
  5605. auto track_sizing_function = parse_track_sizing_function(token);
  5606. if (!track_sizing_function.has_value()) {
  5607. transaction.commit();
  5608. return GridTrackSizeListStyleValue::make_auto();
  5609. }
  5610. // FIXME: Handle multiple repeat values (should combine them here, or remove
  5611. // any other ones if the first one is auto-fill, etc.)
  5612. track_list.append(track_sizing_function.value());
  5613. }
  5614. }
  5615. transaction.commit();
  5616. return GridTrackSizeListStyleValue::create(GridTrackSizeList(move(track_list)));
  5617. }
  5618. // https://www.w3.org/TR/css-grid-1/#grid-auto-flow-property
  5619. RefPtr<GridAutoFlowStyleValue> Parser::parse_grid_auto_flow_value(TokenStream<ComponentValue>& tokens)
  5620. {
  5621. // [ row | column ] || dense
  5622. if (!tokens.has_next_token())
  5623. return nullptr;
  5624. auto transaction = tokens.begin_transaction();
  5625. auto parse_axis = [&]() -> Optional<GridAutoFlowStyleValue::Axis> {
  5626. auto transaction = tokens.begin_transaction();
  5627. auto token = tokens.next_token();
  5628. if (!token.is(Token::Type::Ident))
  5629. return {};
  5630. auto const& ident = token.token().ident();
  5631. if (ident.equals_ignoring_ascii_case("row"sv)) {
  5632. transaction.commit();
  5633. return GridAutoFlowStyleValue::Axis::Row;
  5634. } else if (ident.equals_ignoring_ascii_case("column"sv)) {
  5635. transaction.commit();
  5636. return GridAutoFlowStyleValue::Axis::Column;
  5637. }
  5638. return {};
  5639. };
  5640. auto parse_dense = [&]() -> Optional<GridAutoFlowStyleValue::Dense> {
  5641. auto transaction = tokens.begin_transaction();
  5642. auto token = tokens.next_token();
  5643. if (!token.is(Token::Type::Ident))
  5644. return {};
  5645. auto const& ident = token.token().ident();
  5646. if (ident.equals_ignoring_ascii_case("dense"sv)) {
  5647. transaction.commit();
  5648. return GridAutoFlowStyleValue::Dense::Yes;
  5649. }
  5650. return {};
  5651. };
  5652. Optional<GridAutoFlowStyleValue::Axis> axis;
  5653. Optional<GridAutoFlowStyleValue::Dense> dense;
  5654. if (axis = parse_axis(); axis.has_value()) {
  5655. dense = parse_dense();
  5656. } else if (dense = parse_dense(); dense.has_value()) {
  5657. axis = parse_axis();
  5658. }
  5659. if (tokens.has_next_token())
  5660. return nullptr;
  5661. transaction.commit();
  5662. return GridAutoFlowStyleValue::create(axis.value_or(GridAutoFlowStyleValue::Axis::Row), dense.value_or(GridAutoFlowStyleValue::Dense::No));
  5663. }
  5664. // https://drafts.csswg.org/css-overflow/#propdef-scrollbar-gutter
  5665. RefPtr<CSSStyleValue> Parser::parse_scrollbar_gutter_value(TokenStream<ComponentValue>& tokens)
  5666. {
  5667. // auto | stable && both-edges?
  5668. if (!tokens.has_next_token())
  5669. return nullptr;
  5670. auto transaction = tokens.begin_transaction();
  5671. auto parse_stable = [&]() -> Optional<bool> {
  5672. auto transaction = tokens.begin_transaction();
  5673. auto token = tokens.next_token();
  5674. if (!token.is(Token::Type::Ident))
  5675. return {};
  5676. auto const& ident = token.token().ident();
  5677. if (ident.equals_ignoring_ascii_case("auto"sv)) {
  5678. transaction.commit();
  5679. return false;
  5680. } else if (ident.equals_ignoring_ascii_case("stable"sv)) {
  5681. transaction.commit();
  5682. return true;
  5683. }
  5684. return {};
  5685. };
  5686. auto parse_both_edges = [&]() -> Optional<bool> {
  5687. auto transaction = tokens.begin_transaction();
  5688. auto token = tokens.next_token();
  5689. if (!token.is(Token::Type::Ident))
  5690. return {};
  5691. auto const& ident = token.token().ident();
  5692. if (ident.equals_ignoring_ascii_case("both-edges"sv)) {
  5693. transaction.commit();
  5694. return true;
  5695. }
  5696. return {};
  5697. };
  5698. Optional<bool> stable;
  5699. Optional<bool> both_edges;
  5700. if (stable = parse_stable(); stable.has_value()) {
  5701. if (stable.value())
  5702. both_edges = parse_both_edges();
  5703. } else if (both_edges = parse_both_edges(); both_edges.has_value()) {
  5704. stable = parse_stable();
  5705. if (!stable.has_value() || !stable.value())
  5706. return nullptr;
  5707. }
  5708. if (tokens.has_next_token())
  5709. return nullptr;
  5710. transaction.commit();
  5711. ScrollbarGutter gutter_value;
  5712. if (both_edges.has_value())
  5713. gutter_value = ScrollbarGutter::BothEdges;
  5714. else if (stable.has_value() && stable.value())
  5715. gutter_value = ScrollbarGutter::Stable;
  5716. else
  5717. gutter_value = ScrollbarGutter::Auto;
  5718. return ScrollbarGutterStyleValue::create(gutter_value);
  5719. }
  5720. RefPtr<CSSStyleValue> Parser::parse_grid_auto_track_sizes(TokenStream<ComponentValue>& tokens)
  5721. {
  5722. // https://www.w3.org/TR/css-grid-2/#auto-tracks
  5723. // <track-size>+
  5724. Vector<Variant<ExplicitGridTrack, GridLineNames>> track_list;
  5725. auto transaction = tokens.begin_transaction();
  5726. while (tokens.has_next_token()) {
  5727. auto token = tokens.next_token();
  5728. auto track_sizing_function = parse_track_sizing_function(token);
  5729. if (!track_sizing_function.has_value()) {
  5730. transaction.commit();
  5731. return GridTrackSizeListStyleValue::make_auto();
  5732. }
  5733. // FIXME: Handle multiple repeat values (should combine them here, or remove
  5734. // any other ones if the first one is auto-fill, etc.)
  5735. track_list.append(track_sizing_function.value());
  5736. }
  5737. transaction.commit();
  5738. return GridTrackSizeListStyleValue::create(GridTrackSizeList(move(track_list)));
  5739. }
  5740. RefPtr<CSSStyleValue> Parser::parse_grid_track_placement(TokenStream<ComponentValue>& tokens)
  5741. {
  5742. // FIXME: This shouldn't be needed. Right now, the below code returns a CSSStyleValue even if no tokens are consumed!
  5743. if (!tokens.has_next_token())
  5744. return nullptr;
  5745. // https://www.w3.org/TR/css-grid-2/#line-placement
  5746. // Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
  5747. // <grid-line> =
  5748. // auto |
  5749. // <custom-ident> |
  5750. // [ <integer> && <custom-ident>? ] |
  5751. // [ span && [ <integer> || <custom-ident> ] ]
  5752. auto is_valid_integer = [](auto& token) -> bool {
  5753. // An <integer> value of zero makes the declaration invalid.
  5754. if (token.is(Token::Type::Number) && token.token().number().is_integer() && token.token().number_value() != 0)
  5755. return true;
  5756. return false;
  5757. };
  5758. auto parse_custom_ident = [this](auto& tokens) {
  5759. // The <custom-ident> additionally excludes the keywords span and auto.
  5760. return parse_custom_ident_value(tokens, { "span"sv, "auto"sv });
  5761. };
  5762. auto transaction = tokens.begin_transaction();
  5763. // FIXME: Handle the single-token case inside the loop instead, so that we can more easily call this from
  5764. // `parse_grid_area_shorthand_value()` using a single TokenStream.
  5765. if (tokens.remaining_token_count() == 1) {
  5766. if (auto custom_ident = parse_custom_ident(tokens)) {
  5767. transaction.commit();
  5768. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line({}, custom_ident->custom_ident().to_string()));
  5769. }
  5770. auto& token = tokens.next_token();
  5771. if (auto maybe_calculated = parse_calculated_value(token); maybe_calculated && maybe_calculated->resolves_to_number()) {
  5772. transaction.commit();
  5773. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(static_cast<int>(maybe_calculated->resolve_integer().value()), {}));
  5774. }
  5775. if (token.is_ident("auto"sv)) {
  5776. transaction.commit();
  5777. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto());
  5778. }
  5779. if (token.is_ident("span"sv)) {
  5780. transaction.commit();
  5781. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(1));
  5782. }
  5783. if (is_valid_integer(token)) {
  5784. transaction.commit();
  5785. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(static_cast<int>(token.token().number_value()), {}));
  5786. }
  5787. return nullptr;
  5788. }
  5789. auto span_value = false;
  5790. auto span_or_position_value = 0;
  5791. String identifier_value;
  5792. while (tokens.has_next_token()) {
  5793. auto& token = tokens.peek_token();
  5794. if (token.is_ident("auto"sv))
  5795. return nullptr;
  5796. if (token.is_ident("span"sv)) {
  5797. if (span_value)
  5798. return nullptr;
  5799. (void)tokens.next_token(); // span
  5800. span_value = true;
  5801. continue;
  5802. }
  5803. if (is_valid_integer(token)) {
  5804. if (span_or_position_value != 0)
  5805. return nullptr;
  5806. span_or_position_value = static_cast<int>(tokens.next_token().token().to_integer());
  5807. continue;
  5808. }
  5809. if (auto custom_ident = parse_custom_ident(tokens)) {
  5810. if (!identifier_value.is_empty())
  5811. return nullptr;
  5812. identifier_value = custom_ident->custom_ident().to_string();
  5813. continue;
  5814. }
  5815. break;
  5816. }
  5817. // Negative integers or zero are invalid.
  5818. if (span_value && span_or_position_value < 1)
  5819. return nullptr;
  5820. // If the <integer> is omitted, it defaults to 1.
  5821. if (span_or_position_value == 0)
  5822. span_or_position_value = 1;
  5823. transaction.commit();
  5824. if (!identifier_value.is_empty())
  5825. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(span_or_position_value, identifier_value));
  5826. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(span_or_position_value));
  5827. }
  5828. RefPtr<CSSStyleValue> Parser::parse_grid_track_placement_shorthand_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  5829. {
  5830. auto start_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnStart : PropertyID::GridRowStart;
  5831. auto end_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnEnd : PropertyID::GridRowEnd;
  5832. auto transaction = tokens.begin_transaction();
  5833. auto current_token = tokens.next_token();
  5834. Vector<ComponentValue> track_start_placement_tokens;
  5835. while (true) {
  5836. if (current_token.is_delim('/'))
  5837. break;
  5838. track_start_placement_tokens.append(current_token);
  5839. if (!tokens.has_next_token())
  5840. break;
  5841. current_token = tokens.next_token();
  5842. }
  5843. Vector<ComponentValue> track_end_placement_tokens;
  5844. if (tokens.has_next_token()) {
  5845. current_token = tokens.next_token();
  5846. while (true) {
  5847. track_end_placement_tokens.append(current_token);
  5848. if (!tokens.has_next_token())
  5849. break;
  5850. current_token = tokens.next_token();
  5851. }
  5852. }
  5853. TokenStream track_start_placement_token_stream { track_start_placement_tokens };
  5854. auto parsed_start_value = parse_grid_track_placement(track_start_placement_token_stream);
  5855. if (parsed_start_value && track_end_placement_tokens.is_empty()) {
  5856. transaction.commit();
  5857. return ShorthandStyleValue::create(property_id,
  5858. { start_property, end_property },
  5859. { parsed_start_value.release_nonnull(), GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto()) });
  5860. }
  5861. TokenStream track_end_placement_token_stream { track_end_placement_tokens };
  5862. auto parsed_end_value = parse_grid_track_placement(track_end_placement_token_stream);
  5863. if (parsed_start_value && parsed_end_value) {
  5864. transaction.commit();
  5865. return ShorthandStyleValue::create(property_id,
  5866. { start_property, end_property },
  5867. { parsed_start_value.release_nonnull(), parsed_end_value.release_nonnull() });
  5868. }
  5869. return nullptr;
  5870. }
  5871. // https://www.w3.org/TR/css-grid-2/#explicit-grid-shorthand
  5872. // 7.4. Explicit Grid Shorthand: the grid-template property
  5873. RefPtr<CSSStyleValue> Parser::parse_grid_track_size_list_shorthand_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  5874. {
  5875. // The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows,
  5876. // and grid-template-areas in a single declaration. It has several distinct syntax forms:
  5877. // none
  5878. // - Sets all three properties to their initial values (none).
  5879. // <'grid-template-rows'> / <'grid-template-columns'>
  5880. // - Sets grid-template-rows and grid-template-columns to the specified values, respectively, and sets grid-template-areas to none.
  5881. // [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
  5882. // - Sets grid-template-areas to the strings listed.
  5883. // - Sets grid-template-rows to the <track-size>s following each string (filling in auto for any missing sizes),
  5884. // and splicing in the named lines defined before/after each size.
  5885. // - Sets grid-template-columns to the track listing specified after the slash (or none, if not specified).
  5886. auto transaction = tokens.begin_transaction();
  5887. // FIXME: Read the parts in place if possible, instead of constructing separate vectors and streams.
  5888. Vector<ComponentValue> template_rows_tokens;
  5889. Vector<ComponentValue> template_columns_tokens;
  5890. Vector<ComponentValue> template_area_tokens;
  5891. bool found_forward_slash = false;
  5892. while (tokens.has_next_token()) {
  5893. auto& token = tokens.next_token();
  5894. if (token.is_delim('/')) {
  5895. if (found_forward_slash)
  5896. return nullptr;
  5897. found_forward_slash = true;
  5898. continue;
  5899. }
  5900. if (found_forward_slash) {
  5901. template_columns_tokens.append(token);
  5902. continue;
  5903. }
  5904. if (token.is(Token::Type::String))
  5905. template_area_tokens.append(token);
  5906. else
  5907. template_rows_tokens.append(token);
  5908. }
  5909. TokenStream template_area_token_stream { template_area_tokens };
  5910. TokenStream template_rows_token_stream { template_rows_tokens };
  5911. TokenStream template_columns_token_stream { template_columns_tokens };
  5912. auto parsed_template_areas_values = parse_grid_template_areas_value(template_area_token_stream);
  5913. auto parsed_template_rows_values = parse_grid_track_size_list(template_rows_token_stream, true);
  5914. auto parsed_template_columns_values = parse_grid_track_size_list(template_columns_token_stream);
  5915. if (template_area_token_stream.has_next_token()
  5916. || template_rows_token_stream.has_next_token()
  5917. || template_columns_token_stream.has_next_token())
  5918. return nullptr;
  5919. transaction.commit();
  5920. return ShorthandStyleValue::create(property_id,
  5921. { PropertyID::GridTemplateAreas, PropertyID::GridTemplateRows, PropertyID::GridTemplateColumns },
  5922. { parsed_template_areas_values.release_nonnull(), parsed_template_rows_values.release_nonnull(), parsed_template_columns_values.release_nonnull() });
  5923. }
  5924. RefPtr<CSSStyleValue> Parser::parse_grid_area_shorthand_value(TokenStream<ComponentValue>& tokens)
  5925. {
  5926. auto transaction = tokens.begin_transaction();
  5927. auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void {
  5928. while (tokens.has_next_token()) {
  5929. auto& current_token = tokens.next_token();
  5930. if (check_for_delimiter && current_token.is_delim('/'))
  5931. break;
  5932. placement_tokens.append(current_token);
  5933. }
  5934. };
  5935. Vector<ComponentValue> row_start_placement_tokens;
  5936. parse_placement_tokens(row_start_placement_tokens);
  5937. Vector<ComponentValue> column_start_placement_tokens;
  5938. if (tokens.has_next_token())
  5939. parse_placement_tokens(column_start_placement_tokens);
  5940. Vector<ComponentValue> row_end_placement_tokens;
  5941. if (tokens.has_next_token())
  5942. parse_placement_tokens(row_end_placement_tokens);
  5943. Vector<ComponentValue> column_end_placement_tokens;
  5944. if (tokens.has_next_token())
  5945. parse_placement_tokens(column_end_placement_tokens, false);
  5946. // https://www.w3.org/TR/css-grid-2/#placement-shorthands
  5947. // The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and
  5948. // grid-column-end.
  5949. TokenStream row_start_placement_token_stream { row_start_placement_tokens };
  5950. auto row_start_style_value = parse_grid_track_placement(row_start_placement_token_stream);
  5951. if (row_start_placement_token_stream.has_next_token())
  5952. return nullptr;
  5953. TokenStream column_start_placement_token_stream { column_start_placement_tokens };
  5954. auto column_start_style_value = parse_grid_track_placement(column_start_placement_token_stream);
  5955. if (column_start_placement_token_stream.has_next_token())
  5956. return nullptr;
  5957. TokenStream row_end_placement_token_stream { row_end_placement_tokens };
  5958. auto row_end_style_value = parse_grid_track_placement(row_end_placement_token_stream);
  5959. if (row_end_placement_token_stream.has_next_token())
  5960. return nullptr;
  5961. TokenStream column_end_placement_token_stream { column_end_placement_tokens };
  5962. auto column_end_style_value = parse_grid_track_placement(column_end_placement_token_stream);
  5963. if (column_end_placement_token_stream.has_next_token())
  5964. return nullptr;
  5965. // If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start
  5966. // is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the
  5967. // fourth value.
  5968. auto row_start = GridTrackPlacement::make_auto();
  5969. auto column_start = GridTrackPlacement::make_auto();
  5970. auto row_end = GridTrackPlacement::make_auto();
  5971. auto column_end = GridTrackPlacement::make_auto();
  5972. if (row_start_style_value)
  5973. row_start = row_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  5974. // When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to
  5975. // that value. Otherwise, it is set to auto.
  5976. if (column_start_style_value)
  5977. column_start = column_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  5978. else
  5979. column_start = row_start;
  5980. // When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that
  5981. // <custom-ident>; otherwise, it is set to auto.
  5982. if (row_end_style_value)
  5983. row_end = row_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  5984. else
  5985. row_end = column_start;
  5986. // When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to
  5987. // that <custom-ident>; otherwise, it is set to auto.
  5988. if (column_end_style_value)
  5989. column_end = column_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  5990. else
  5991. column_end = row_end;
  5992. transaction.commit();
  5993. return ShorthandStyleValue::create(PropertyID::GridArea,
  5994. { PropertyID::GridRowStart, PropertyID::GridColumnStart, PropertyID::GridRowEnd, PropertyID::GridColumnEnd },
  5995. { GridTrackPlacementStyleValue::create(row_start), GridTrackPlacementStyleValue::create(column_start), GridTrackPlacementStyleValue::create(row_end), GridTrackPlacementStyleValue::create(column_end) });
  5996. }
  5997. RefPtr<CSSStyleValue> Parser::parse_grid_shorthand_value(TokenStream<ComponentValue>& tokens)
  5998. {
  5999. // <'grid-template'> |
  6000. // FIXME: <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? |
  6001. // FIXME: [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
  6002. return parse_grid_track_size_list_shorthand_value(PropertyID::Grid, tokens);
  6003. }
  6004. // https://www.w3.org/TR/css-grid-1/#grid-template-areas-property
  6005. RefPtr<CSSStyleValue> Parser::parse_grid_template_areas_value(TokenStream<ComponentValue>& tokens)
  6006. {
  6007. // none | <string>+
  6008. Vector<Vector<String>> grid_area_rows;
  6009. if (auto none = parse_all_as_single_none_value(tokens))
  6010. return GridTemplateAreaStyleValue::create(move(grid_area_rows));
  6011. auto transaction = tokens.begin_transaction();
  6012. while (tokens.has_next_token() && tokens.peek_token().is(Token::Type::String)) {
  6013. Vector<String> grid_area_columns;
  6014. auto const parts = MUST(tokens.next_token().token().string().to_string().split(' '));
  6015. for (auto& part : parts) {
  6016. grid_area_columns.append(part);
  6017. }
  6018. grid_area_rows.append(move(grid_area_columns));
  6019. }
  6020. transaction.commit();
  6021. return GridTemplateAreaStyleValue::create(grid_area_rows);
  6022. }
  6023. static bool block_contains_var_or_attr(Block const& block);
  6024. static bool function_contains_var_or_attr(Function const& function)
  6025. {
  6026. if (function.name().equals_ignoring_ascii_case("var"sv) || function.name().equals_ignoring_ascii_case("attr"sv))
  6027. return true;
  6028. for (auto const& token : function.values()) {
  6029. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6030. return true;
  6031. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6032. return true;
  6033. }
  6034. return false;
  6035. }
  6036. bool block_contains_var_or_attr(Block const& block)
  6037. {
  6038. for (auto const& token : block.values()) {
  6039. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6040. return true;
  6041. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6042. return true;
  6043. }
  6044. return false;
  6045. }
  6046. Parser::ParseErrorOr<NonnullRefPtr<CSSStyleValue>> Parser::parse_css_value(PropertyID property_id, TokenStream<ComponentValue>& unprocessed_tokens)
  6047. {
  6048. m_context.set_current_property_id(property_id);
  6049. Vector<ComponentValue> component_values;
  6050. bool contains_var_or_attr = false;
  6051. bool const property_accepts_custom_ident = property_accepts_type(property_id, ValueType::CustomIdent);
  6052. while (unprocessed_tokens.has_next_token()) {
  6053. auto const& token = unprocessed_tokens.next_token();
  6054. if (token.is(Token::Type::Semicolon)) {
  6055. unprocessed_tokens.reconsume_current_input_token();
  6056. break;
  6057. }
  6058. if (property_id != PropertyID::Custom) {
  6059. if (token.is(Token::Type::Whitespace))
  6060. continue;
  6061. if (!property_accepts_custom_ident && token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  6062. return ParseError::IncludesIgnoredVendorPrefix;
  6063. }
  6064. if (!contains_var_or_attr) {
  6065. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6066. contains_var_or_attr = true;
  6067. else if (token.is_block() && block_contains_var_or_attr(token.block()))
  6068. contains_var_or_attr = true;
  6069. }
  6070. component_values.append(token);
  6071. }
  6072. if (property_id == PropertyID::Custom || contains_var_or_attr)
  6073. return UnresolvedStyleValue::create(move(component_values), contains_var_or_attr);
  6074. if (component_values.is_empty())
  6075. return ParseError::SyntaxError;
  6076. auto tokens = TokenStream { component_values };
  6077. if (component_values.size() == 1) {
  6078. if (auto parsed_value = parse_builtin_value(tokens))
  6079. return parsed_value.release_nonnull();
  6080. }
  6081. // Special-case property handling
  6082. switch (property_id) {
  6083. case PropertyID::AspectRatio:
  6084. if (auto parsed_value = parse_aspect_ratio_value(tokens); parsed_value && !tokens.has_next_token())
  6085. return parsed_value.release_nonnull();
  6086. return ParseError::SyntaxError;
  6087. case PropertyID::BackdropFilter:
  6088. if (auto parsed_value = parse_filter_value_list_value(tokens); parsed_value && !tokens.has_next_token())
  6089. return parsed_value.release_nonnull();
  6090. return ParseError::SyntaxError;
  6091. case PropertyID::Background:
  6092. if (auto parsed_value = parse_background_value(tokens); parsed_value && !tokens.has_next_token())
  6093. return parsed_value.release_nonnull();
  6094. return ParseError::SyntaxError;
  6095. case PropertyID::BackgroundAttachment:
  6096. case PropertyID::BackgroundClip:
  6097. case PropertyID::BackgroundImage:
  6098. case PropertyID::BackgroundOrigin:
  6099. case PropertyID::WebkitBackgroundClip:
  6100. case PropertyID::WebkitBackgroundOrigin:
  6101. if (auto parsed_value = parse_simple_comma_separated_value_list(property_id, tokens))
  6102. return parsed_value.release_nonnull();
  6103. return ParseError::SyntaxError;
  6104. case PropertyID::BackgroundPosition:
  6105. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_position_value(tokens, PositionParsingMode::BackgroundPosition); }))
  6106. return parsed_value.release_nonnull();
  6107. return ParseError::SyntaxError;
  6108. case PropertyID::BackgroundPositionX:
  6109. case PropertyID::BackgroundPositionY:
  6110. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this, property_id](auto& tokens) { return parse_single_background_position_x_or_y_value(tokens, property_id); }))
  6111. return parsed_value.release_nonnull();
  6112. return ParseError::SyntaxError;
  6113. case PropertyID::BackgroundRepeat:
  6114. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
  6115. return parsed_value.release_nonnull();
  6116. return ParseError::SyntaxError;
  6117. case PropertyID::BackgroundSize:
  6118. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
  6119. return parsed_value.release_nonnull();
  6120. return ParseError::SyntaxError;
  6121. case PropertyID::Border:
  6122. case PropertyID::BorderBottom:
  6123. case PropertyID::BorderLeft:
  6124. case PropertyID::BorderRight:
  6125. case PropertyID::BorderTop:
  6126. if (auto parsed_value = parse_border_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6127. return parsed_value.release_nonnull();
  6128. return ParseError::SyntaxError;
  6129. case PropertyID::BorderTopLeftRadius:
  6130. case PropertyID::BorderTopRightRadius:
  6131. case PropertyID::BorderBottomRightRadius:
  6132. case PropertyID::BorderBottomLeftRadius:
  6133. case PropertyID::WebkitBorderTopLeftRadius:
  6134. case PropertyID::WebkitBorderTopRightRadius:
  6135. case PropertyID::WebkitBorderBottomRightRadius:
  6136. case PropertyID::WebkitBorderBottomLeftRadius:
  6137. if (auto parsed_value = parse_border_radius_value(tokens); parsed_value && !tokens.has_next_token())
  6138. return parsed_value.release_nonnull();
  6139. return ParseError::SyntaxError;
  6140. case PropertyID::BorderRadius:
  6141. case PropertyID::WebkitBorderRadius:
  6142. if (auto parsed_value = parse_border_radius_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6143. return parsed_value.release_nonnull();
  6144. return ParseError::SyntaxError;
  6145. case PropertyID::BoxShadow:
  6146. case PropertyID::WebkitBoxShadow:
  6147. if (auto parsed_value = parse_shadow_value(tokens, AllowInsetKeyword::Yes); parsed_value && !tokens.has_next_token())
  6148. return parsed_value.release_nonnull();
  6149. return ParseError::SyntaxError;
  6150. case PropertyID::Content:
  6151. if (auto parsed_value = parse_content_value(tokens); parsed_value && !tokens.has_next_token())
  6152. return parsed_value.release_nonnull();
  6153. return ParseError::SyntaxError;
  6154. case PropertyID::CounterIncrement:
  6155. if (auto parsed_value = parse_counter_increment_value(tokens); parsed_value && !tokens.has_next_token())
  6156. return parsed_value.release_nonnull();
  6157. return ParseError::SyntaxError;
  6158. case PropertyID::CounterReset:
  6159. if (auto parsed_value = parse_counter_reset_value(tokens); parsed_value && !tokens.has_next_token())
  6160. return parsed_value.release_nonnull();
  6161. return ParseError::SyntaxError;
  6162. case PropertyID::CounterSet:
  6163. if (auto parsed_value = parse_counter_set_value(tokens); parsed_value && !tokens.has_next_token())
  6164. return parsed_value.release_nonnull();
  6165. return ParseError::SyntaxError;
  6166. case PropertyID::Display:
  6167. if (auto parsed_value = parse_display_value(tokens); parsed_value && !tokens.has_next_token())
  6168. return parsed_value.release_nonnull();
  6169. return ParseError::SyntaxError;
  6170. case PropertyID::Flex:
  6171. case PropertyID::WebkitFlex:
  6172. if (auto parsed_value = parse_flex_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6173. return parsed_value.release_nonnull();
  6174. return ParseError::SyntaxError;
  6175. case PropertyID::FlexFlow:
  6176. case PropertyID::WebkitFlexFlow:
  6177. if (auto parsed_value = parse_flex_flow_value(tokens); parsed_value && !tokens.has_next_token())
  6178. return parsed_value.release_nonnull();
  6179. return ParseError::SyntaxError;
  6180. case PropertyID::Font:
  6181. if (auto parsed_value = parse_font_value(tokens); parsed_value && !tokens.has_next_token())
  6182. return parsed_value.release_nonnull();
  6183. return ParseError::SyntaxError;
  6184. case PropertyID::FontFamily:
  6185. if (auto parsed_value = parse_font_family_value(tokens); parsed_value && !tokens.has_next_token())
  6186. return parsed_value.release_nonnull();
  6187. return ParseError::SyntaxError;
  6188. case PropertyID::GridArea:
  6189. if (auto parsed_value = parse_grid_area_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6190. return parsed_value.release_nonnull();
  6191. return ParseError::SyntaxError;
  6192. case PropertyID::GridAutoFlow:
  6193. if (auto parsed_value = parse_grid_auto_flow_value(tokens); parsed_value && !tokens.has_next_token())
  6194. return parsed_value.release_nonnull();
  6195. return ParseError::SyntaxError;
  6196. case PropertyID::GridColumn:
  6197. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6198. return parsed_value.release_nonnull();
  6199. return ParseError::SyntaxError;
  6200. case PropertyID::GridColumnEnd:
  6201. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6202. return parsed_value.release_nonnull();
  6203. return ParseError::SyntaxError;
  6204. case PropertyID::GridColumnStart:
  6205. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6206. return parsed_value.release_nonnull();
  6207. return ParseError::SyntaxError;
  6208. case PropertyID::GridRow:
  6209. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6210. return parsed_value.release_nonnull();
  6211. return ParseError::SyntaxError;
  6212. case PropertyID::GridRowEnd:
  6213. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6214. return parsed_value.release_nonnull();
  6215. return ParseError::SyntaxError;
  6216. case PropertyID::GridRowStart:
  6217. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6218. return parsed_value.release_nonnull();
  6219. return ParseError::SyntaxError;
  6220. case PropertyID::Grid:
  6221. if (auto parsed_value = parse_grid_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6222. return parsed_value.release_nonnull();
  6223. return ParseError::SyntaxError;
  6224. case PropertyID::GridTemplate:
  6225. if (auto parsed_value = parse_grid_track_size_list_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6226. return parsed_value.release_nonnull();
  6227. return ParseError::SyntaxError;
  6228. case PropertyID::GridTemplateAreas:
  6229. if (auto parsed_value = parse_grid_template_areas_value(tokens); parsed_value && !tokens.has_next_token())
  6230. return parsed_value.release_nonnull();
  6231. return ParseError::SyntaxError;
  6232. case PropertyID::GridTemplateColumns:
  6233. if (auto parsed_value = parse_grid_track_size_list(tokens); parsed_value && !tokens.has_next_token())
  6234. return parsed_value.release_nonnull();
  6235. return ParseError::SyntaxError;
  6236. case PropertyID::GridTemplateRows:
  6237. if (auto parsed_value = parse_grid_track_size_list(tokens); parsed_value && !tokens.has_next_token())
  6238. return parsed_value.release_nonnull();
  6239. return ParseError::SyntaxError;
  6240. case PropertyID::GridAutoColumns:
  6241. if (auto parsed_value = parse_grid_auto_track_sizes(tokens); parsed_value && !tokens.has_next_token())
  6242. return parsed_value.release_nonnull();
  6243. return ParseError::SyntaxError;
  6244. case PropertyID::GridAutoRows:
  6245. if (auto parsed_value = parse_grid_auto_track_sizes(tokens); parsed_value && !tokens.has_next_token())
  6246. return parsed_value.release_nonnull();
  6247. return ParseError::SyntaxError;
  6248. case PropertyID::ListStyle:
  6249. if (auto parsed_value = parse_list_style_value(tokens); parsed_value && !tokens.has_next_token())
  6250. return parsed_value.release_nonnull();
  6251. return ParseError::SyntaxError;
  6252. case PropertyID::MathDepth:
  6253. if (auto parsed_value = parse_math_depth_value(tokens); parsed_value && !tokens.has_next_token())
  6254. return parsed_value.release_nonnull();
  6255. return ParseError::SyntaxError;
  6256. case PropertyID::Overflow:
  6257. if (auto parsed_value = parse_overflow_value(tokens); parsed_value && !tokens.has_next_token())
  6258. return parsed_value.release_nonnull();
  6259. return ParseError::SyntaxError;
  6260. case PropertyID::PlaceContent:
  6261. if (auto parsed_value = parse_place_content_value(tokens); parsed_value && !tokens.has_next_token())
  6262. return parsed_value.release_nonnull();
  6263. return ParseError::SyntaxError;
  6264. case PropertyID::PlaceItems:
  6265. if (auto parsed_value = parse_place_items_value(tokens); parsed_value && !tokens.has_next_token())
  6266. return parsed_value.release_nonnull();
  6267. return ParseError::SyntaxError;
  6268. case PropertyID::PlaceSelf:
  6269. if (auto parsed_value = parse_place_self_value(tokens); parsed_value && !tokens.has_next_token())
  6270. return parsed_value.release_nonnull();
  6271. return ParseError::SyntaxError;
  6272. case PropertyID::Quotes:
  6273. if (auto parsed_value = parse_quotes_value(tokens); parsed_value && !tokens.has_next_token())
  6274. return parsed_value.release_nonnull();
  6275. return ParseError::SyntaxError;
  6276. case PropertyID::ScrollbarGutter:
  6277. if (auto parsed_value = parse_scrollbar_gutter_value(tokens); parsed_value && !tokens.has_next_token())
  6278. return parsed_value.release_nonnull();
  6279. return ParseError::SyntaxError;
  6280. case PropertyID::TextDecoration:
  6281. if (auto parsed_value = parse_text_decoration_value(tokens); parsed_value && !tokens.has_next_token())
  6282. return parsed_value.release_nonnull();
  6283. return ParseError::SyntaxError;
  6284. case PropertyID::TextDecorationLine:
  6285. if (auto parsed_value = parse_text_decoration_line_value(tokens); parsed_value && !tokens.has_next_token())
  6286. return parsed_value.release_nonnull();
  6287. return ParseError::SyntaxError;
  6288. case PropertyID::TextShadow:
  6289. if (auto parsed_value = parse_shadow_value(tokens, AllowInsetKeyword::No); parsed_value && !tokens.has_next_token())
  6290. return parsed_value.release_nonnull();
  6291. return ParseError::SyntaxError;
  6292. case PropertyID::Transform:
  6293. case PropertyID::WebkitTransform:
  6294. if (auto parsed_value = parse_transform_value(tokens); parsed_value && !tokens.has_next_token())
  6295. return parsed_value.release_nonnull();
  6296. return ParseError::SyntaxError;
  6297. case PropertyID::TransformOrigin:
  6298. case PropertyID::WebkitTransformOrigin:
  6299. if (auto parsed_value = parse_transform_origin_value(tokens); parsed_value && !tokens.has_next_token())
  6300. return parsed_value.release_nonnull();
  6301. return ParseError::SyntaxError;
  6302. case PropertyID::Transition:
  6303. case PropertyID::WebkitTransition:
  6304. if (auto parsed_value = parse_transition_value(tokens); parsed_value && !tokens.has_next_token())
  6305. return parsed_value.release_nonnull();
  6306. return ParseError::SyntaxError;
  6307. default:
  6308. break;
  6309. }
  6310. // If there's only 1 ComponentValue, we can only produce a single CSSStyleValue.
  6311. if (component_values.size() == 1) {
  6312. auto stream = TokenStream { component_values };
  6313. if (auto parsed_value = parse_css_value_for_property(property_id, stream))
  6314. return parsed_value.release_nonnull();
  6315. } else {
  6316. StyleValueVector parsed_values;
  6317. auto stream = TokenStream { component_values };
  6318. while (auto parsed_value = parse_css_value_for_property(property_id, stream)) {
  6319. parsed_values.append(parsed_value.release_nonnull());
  6320. if (!stream.has_next_token())
  6321. break;
  6322. }
  6323. // Some types (such as <ratio>) can be made from multiple ComponentValues, so if we only made 1 CSSStyleValue, return it directly.
  6324. if (parsed_values.size() == 1)
  6325. return *parsed_values.take_first();
  6326. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  6327. return StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space);
  6328. }
  6329. // We have multiple values, but the property claims to accept only a single one, check if it's a shorthand property.
  6330. auto unassigned_properties = longhands_for_shorthand(property_id);
  6331. if (unassigned_properties.is_empty())
  6332. return ParseError::SyntaxError;
  6333. auto stream = TokenStream { component_values };
  6334. HashMap<UnderlyingType<PropertyID>, Vector<ValueComparingNonnullRefPtr<CSSStyleValue const>>> assigned_values;
  6335. while (stream.has_next_token() && !unassigned_properties.is_empty()) {
  6336. auto property_and_value = parse_css_value_for_properties(unassigned_properties, stream);
  6337. if (property_and_value.has_value()) {
  6338. auto property = property_and_value->property;
  6339. auto value = property_and_value->style_value;
  6340. auto& values = assigned_values.ensure(to_underlying(property));
  6341. if (values.size() + 1 == property_maximum_value_count(property)) {
  6342. // We're done with this property, move on to the next one.
  6343. unassigned_properties.remove_first_matching([&](auto& unassigned_property) { return unassigned_property == property; });
  6344. }
  6345. values.append(value.release_nonnull());
  6346. continue;
  6347. }
  6348. // No property matched, so we're done.
  6349. dbgln("No property (from {} properties) matched {}", unassigned_properties.size(), stream.peek_token().to_debug_string());
  6350. for (auto id : unassigned_properties)
  6351. dbgln(" {}", string_from_property_id(id));
  6352. break;
  6353. }
  6354. for (auto& property : unassigned_properties)
  6355. assigned_values.ensure(to_underlying(property)).append(property_initial_value(m_context.realm(), property));
  6356. stream.skip_whitespace();
  6357. if (stream.has_next_token())
  6358. return ParseError::SyntaxError;
  6359. Vector<PropertyID> longhand_properties;
  6360. longhand_properties.ensure_capacity(assigned_values.size());
  6361. for (auto& it : assigned_values)
  6362. longhand_properties.unchecked_append(static_cast<PropertyID>(it.key));
  6363. StyleValueVector longhand_values;
  6364. longhand_values.ensure_capacity(assigned_values.size());
  6365. for (auto& it : assigned_values) {
  6366. if (it.value.size() == 1)
  6367. longhand_values.unchecked_append(it.value.take_first());
  6368. else
  6369. longhand_values.unchecked_append(StyleValueList::create(move(it.value), StyleValueList::Separator::Space));
  6370. }
  6371. return { ShorthandStyleValue::create(property_id, move(longhand_properties), move(longhand_values)) };
  6372. }
  6373. RefPtr<CSSStyleValue> Parser::parse_css_value_for_property(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6374. {
  6375. return parse_css_value_for_properties({ &property_id, 1 }, tokens)
  6376. .map([](auto& it) { return it.style_value; })
  6377. .value_or(nullptr);
  6378. }
  6379. Optional<Parser::PropertyAndValue> Parser::parse_css_value_for_properties(ReadonlySpan<PropertyID> property_ids, TokenStream<ComponentValue>& tokens)
  6380. {
  6381. auto any_property_accepts_type = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  6382. for (auto const& property : property_ids) {
  6383. if (property_accepts_type(property, value_type))
  6384. return property;
  6385. }
  6386. return {};
  6387. };
  6388. auto any_property_accepts_type_percentage = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  6389. for (auto const& property : property_ids) {
  6390. if (property_accepts_type(property, value_type) && property_accepts_type(property, ValueType::Percentage))
  6391. return property;
  6392. }
  6393. return {};
  6394. };
  6395. auto any_property_accepts_keyword = [](ReadonlySpan<PropertyID> property_ids, Keyword keyword) -> Optional<PropertyID> {
  6396. for (auto const& property : property_ids) {
  6397. if (property_accepts_keyword(property, keyword))
  6398. return property;
  6399. }
  6400. return {};
  6401. };
  6402. auto& peek_token = tokens.peek_token();
  6403. if (auto property = any_property_accepts_type(property_ids, ValueType::EasingFunction); property.has_value()) {
  6404. if (auto maybe_easing_function = parse_easing_value(tokens))
  6405. return PropertyAndValue { *property, maybe_easing_function };
  6406. }
  6407. if (peek_token.is(Token::Type::Ident)) {
  6408. // NOTE: We do not try to parse "CSS-wide keywords" here. https://www.w3.org/TR/css-values-4/#common-keywords
  6409. // These are only valid on their own, and so should be parsed directly in `parse_css_value()`.
  6410. auto keyword = keyword_from_string(peek_token.token().ident());
  6411. if (keyword.has_value()) {
  6412. if (auto property = any_property_accepts_keyword(property_ids, keyword.value()); property.has_value()) {
  6413. (void)tokens.next_token();
  6414. return PropertyAndValue { *property, CSSKeywordValue::create(keyword.value()) };
  6415. }
  6416. }
  6417. // Custom idents
  6418. if (auto property = any_property_accepts_type(property_ids, ValueType::CustomIdent); property.has_value()) {
  6419. if (auto custom_ident = parse_custom_ident_value(tokens, {}))
  6420. return PropertyAndValue { *property, custom_ident };
  6421. }
  6422. }
  6423. if (auto property = any_property_accepts_type(property_ids, ValueType::Color); property.has_value()) {
  6424. if (auto maybe_color = parse_color_value(tokens))
  6425. return PropertyAndValue { *property, maybe_color };
  6426. }
  6427. if (auto property = any_property_accepts_type(property_ids, ValueType::Counter); property.has_value()) {
  6428. if (auto maybe_counter = parse_counter_value(tokens))
  6429. return PropertyAndValue { *property, maybe_counter };
  6430. }
  6431. if (auto property = any_property_accepts_type(property_ids, ValueType::Image); property.has_value()) {
  6432. if (auto maybe_image = parse_image_value(tokens))
  6433. return PropertyAndValue { *property, maybe_image };
  6434. }
  6435. if (auto property = any_property_accepts_type(property_ids, ValueType::Position); property.has_value()) {
  6436. if (auto maybe_position = parse_position_value(tokens))
  6437. return PropertyAndValue { *property, maybe_position };
  6438. }
  6439. if (auto property = any_property_accepts_type(property_ids, ValueType::BackgroundPosition); property.has_value()) {
  6440. if (auto maybe_position = parse_position_value(tokens, PositionParsingMode::BackgroundPosition))
  6441. return PropertyAndValue { *property, maybe_position };
  6442. }
  6443. if (auto property = any_property_accepts_type(property_ids, ValueType::BasicShape); property.has_value()) {
  6444. if (auto maybe_basic_shape = parse_basic_shape_value(tokens))
  6445. return PropertyAndValue { *property, maybe_basic_shape };
  6446. }
  6447. if (auto property = any_property_accepts_type(property_ids, ValueType::Ratio); property.has_value()) {
  6448. if (auto maybe_ratio = parse_ratio_value(tokens))
  6449. return PropertyAndValue { *property, maybe_ratio };
  6450. }
  6451. auto property_accepting_integer = any_property_accepts_type(property_ids, ValueType::Integer);
  6452. auto property_accepting_number = any_property_accepts_type(property_ids, ValueType::Number);
  6453. bool property_accepts_numeric = property_accepting_integer.has_value() || property_accepting_number.has_value();
  6454. if (peek_token.is(Token::Type::Number) && property_accepts_numeric) {
  6455. if (peek_token.token().number().is_integer() && property_accepting_integer.has_value()) {
  6456. auto integer = IntegerStyleValue::create(peek_token.token().number().integer_value());
  6457. if (property_accepts_integer(*property_accepting_integer, integer->as_integer().integer())) {
  6458. (void)tokens.next_token(); // integer
  6459. return PropertyAndValue { *property_accepting_integer, integer };
  6460. }
  6461. }
  6462. if (property_accepting_number.has_value()) {
  6463. auto number = NumberStyleValue::create(peek_token.token().number().value());
  6464. if (property_accepts_number(*property_accepting_number, number->as_number().number())) {
  6465. (void)tokens.next_token(); // number
  6466. return PropertyAndValue { *property_accepting_number, number };
  6467. }
  6468. }
  6469. }
  6470. if (peek_token.is(Token::Type::Percentage)) {
  6471. auto percentage = Percentage(peek_token.token().percentage());
  6472. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value() && property_accepts_percentage(*property, percentage)) {
  6473. (void)tokens.next_token();
  6474. return PropertyAndValue { *property, PercentageStyleValue::create(percentage) };
  6475. }
  6476. }
  6477. if (auto property = any_property_accepts_type(property_ids, ValueType::Rect); property.has_value()) {
  6478. if (auto maybe_rect = parse_rect_value(tokens))
  6479. return PropertyAndValue { *property, maybe_rect };
  6480. }
  6481. if (peek_token.is(Token::Type::String)) {
  6482. if (auto property = any_property_accepts_type(property_ids, ValueType::String); property.has_value())
  6483. return PropertyAndValue { *property, StringStyleValue::create(tokens.next_token().token().string()) };
  6484. }
  6485. if (auto property = any_property_accepts_type(property_ids, ValueType::Url); property.has_value()) {
  6486. if (auto url = parse_url_value(tokens))
  6487. return PropertyAndValue { *property, url };
  6488. }
  6489. bool property_accepts_dimension = any_property_accepts_type(property_ids, ValueType::Angle).has_value()
  6490. || any_property_accepts_type(property_ids, ValueType::Flex).has_value()
  6491. || any_property_accepts_type(property_ids, ValueType::Frequency).has_value()
  6492. || any_property_accepts_type(property_ids, ValueType::Length).has_value()
  6493. || any_property_accepts_type(property_ids, ValueType::Percentage).has_value()
  6494. || any_property_accepts_type(property_ids, ValueType::Resolution).has_value()
  6495. || any_property_accepts_type(property_ids, ValueType::Time).has_value();
  6496. if (property_accepts_dimension) {
  6497. if (peek_token.is(Token::Type::Number) && m_context.is_parsing_svg_presentation_attribute()) {
  6498. auto transaction = tokens.begin_transaction();
  6499. auto token = tokens.next_token();
  6500. // https://svgwg.org/svg2-draft/types.html#presentation-attribute-css-value
  6501. // We need to allow <number> in any place that expects a <length> or <angle>.
  6502. // FIXME: How should these numbers be interpreted? https://github.com/w3c/svgwg/issues/792
  6503. // For now: Convert them to px lengths, or deg angles.
  6504. auto angle = Angle::make_degrees(token.token().number_value());
  6505. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  6506. transaction.commit();
  6507. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  6508. }
  6509. auto length = Length::make_px(CSSPixels::nearest_value_for(token.token().number_value()));
  6510. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  6511. transaction.commit();
  6512. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  6513. }
  6514. }
  6515. auto transaction = tokens.begin_transaction();
  6516. if (auto maybe_dimension = parse_dimension(peek_token); maybe_dimension.has_value()) {
  6517. (void)tokens.next_token();
  6518. auto dimension = maybe_dimension.release_value();
  6519. if (dimension.is_angle()) {
  6520. auto angle = dimension.angle();
  6521. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  6522. transaction.commit();
  6523. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  6524. }
  6525. }
  6526. if (dimension.is_flex()) {
  6527. auto flex = dimension.flex();
  6528. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value() && property_accepts_flex(*property, flex)) {
  6529. transaction.commit();
  6530. return PropertyAndValue { *property, FlexStyleValue::create(flex) };
  6531. }
  6532. }
  6533. if (dimension.is_frequency()) {
  6534. auto frequency = dimension.frequency();
  6535. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value() && property_accepts_frequency(*property, frequency)) {
  6536. transaction.commit();
  6537. return PropertyAndValue { *property, FrequencyStyleValue::create(frequency) };
  6538. }
  6539. }
  6540. if (dimension.is_length()) {
  6541. auto length = dimension.length();
  6542. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  6543. transaction.commit();
  6544. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  6545. }
  6546. }
  6547. if (dimension.is_resolution()) {
  6548. auto resolution = dimension.resolution();
  6549. if (auto property = any_property_accepts_type(property_ids, ValueType::Resolution); property.has_value() && property_accepts_resolution(*property, resolution)) {
  6550. transaction.commit();
  6551. return PropertyAndValue { *property, ResolutionStyleValue::create(resolution) };
  6552. }
  6553. }
  6554. if (dimension.is_time()) {
  6555. auto time = dimension.time();
  6556. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value() && property_accepts_time(*property, time)) {
  6557. transaction.commit();
  6558. return PropertyAndValue { *property, TimeStyleValue::create(time) };
  6559. }
  6560. }
  6561. }
  6562. }
  6563. // In order to not end up parsing `calc()` and other math expressions multiple times,
  6564. // we parse it once, and then see if its resolved type matches what the property accepts.
  6565. if (peek_token.is_function() && (property_accepts_dimension || property_accepts_numeric)) {
  6566. if (auto maybe_calculated = parse_calculated_value(peek_token); maybe_calculated) {
  6567. (void)tokens.next_token();
  6568. auto& calculated = *maybe_calculated;
  6569. // This is a bit sensitive to ordering: `<foo>` and `<percentage>` have to be checked before `<foo-percentage>`.
  6570. // FIXME: When parsing SVG presentation attributes, <number> is permitted wherever <length>, <length-percentage>, or <angle> are.
  6571. // The specifics are unclear, so I'm ignoring this for calculated values for now.
  6572. // See https://github.com/w3c/svgwg/issues/792
  6573. if (calculated.resolves_to_percentage()) {
  6574. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value())
  6575. return PropertyAndValue { *property, calculated };
  6576. } else if (calculated.resolves_to_angle()) {
  6577. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value())
  6578. return PropertyAndValue { *property, calculated };
  6579. } else if (calculated.resolves_to_angle_percentage()) {
  6580. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Angle); property.has_value())
  6581. return PropertyAndValue { *property, calculated };
  6582. } else if (calculated.resolves_to_flex()) {
  6583. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value())
  6584. return PropertyAndValue { *property, calculated };
  6585. } else if (calculated.resolves_to_frequency()) {
  6586. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value())
  6587. return PropertyAndValue { *property, calculated };
  6588. } else if (calculated.resolves_to_frequency_percentage()) {
  6589. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Frequency); property.has_value())
  6590. return PropertyAndValue { *property, calculated };
  6591. } else if (calculated.resolves_to_number()) {
  6592. if (property_accepts_numeric) {
  6593. auto property_or_resolved = property_accepting_integer.value_or_lazy_evaluated([property_accepting_number]() { return property_accepting_number.value(); });
  6594. return PropertyAndValue { property_or_resolved, calculated };
  6595. }
  6596. } else if (calculated.resolves_to_number_percentage()) {
  6597. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Number); property.has_value())
  6598. return PropertyAndValue { *property, calculated };
  6599. } else if (calculated.resolves_to_length()) {
  6600. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value())
  6601. return PropertyAndValue { *property, calculated };
  6602. } else if (calculated.resolves_to_length_percentage()) {
  6603. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Length); property.has_value())
  6604. return PropertyAndValue { *property, calculated };
  6605. } else if (calculated.resolves_to_time()) {
  6606. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value())
  6607. return PropertyAndValue { *property, calculated };
  6608. } else if (calculated.resolves_to_time_percentage()) {
  6609. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Time); property.has_value())
  6610. return PropertyAndValue { *property, calculated };
  6611. }
  6612. }
  6613. }
  6614. if (auto property = any_property_accepts_type(property_ids, ValueType::Paint); property.has_value()) {
  6615. if (auto value = parse_paint_value(tokens))
  6616. return PropertyAndValue { *property, value.release_nonnull() };
  6617. }
  6618. return OptionalNone {};
  6619. }
  6620. class UnparsedCalculationNode final : public CalculationNode {
  6621. public:
  6622. static NonnullOwnPtr<UnparsedCalculationNode> create(ComponentValue component_value)
  6623. {
  6624. return adopt_own(*new (nothrow) UnparsedCalculationNode(move(component_value)));
  6625. }
  6626. virtual ~UnparsedCalculationNode() = default;
  6627. ComponentValue& component_value() { return m_component_value; }
  6628. virtual String to_string() const override { VERIFY_NOT_REACHED(); }
  6629. virtual Optional<CalculatedStyleValue::ResolvedType> resolved_type() const override { VERIFY_NOT_REACHED(); }
  6630. virtual Optional<CSSNumericType> determine_type(Web::CSS::PropertyID) const override { VERIFY_NOT_REACHED(); }
  6631. virtual bool contains_percentage() const override { VERIFY_NOT_REACHED(); }
  6632. virtual CalculatedStyleValue::CalculationResult resolve(Optional<Length::ResolutionContext const&>, CalculatedStyleValue::PercentageBasis const&) const override { VERIFY_NOT_REACHED(); }
  6633. virtual void for_each_child_node(AK::Function<void(NonnullOwnPtr<CalculationNode>&)> const&) override { }
  6634. virtual void dump(StringBuilder& builder, int indent) const override
  6635. {
  6636. builder.appendff("{: >{}}UNPARSED({})\n", "", indent, m_component_value.to_debug_string());
  6637. }
  6638. virtual bool equals(CalculationNode const&) const override { return false; }
  6639. private:
  6640. UnparsedCalculationNode(ComponentValue component_value)
  6641. : CalculationNode(Type::Unparsed)
  6642. , m_component_value(move(component_value))
  6643. {
  6644. }
  6645. ComponentValue m_component_value;
  6646. };
  6647. // https://html.spec.whatwg.org/multipage/images.html#parsing-a-sizes-attribute
  6648. LengthOrCalculated Parser::Parser::parse_as_sizes_attribute()
  6649. {
  6650. // 1. Let unparsed sizes list be the result of parsing a comma-separated list of component values
  6651. // from the value of element's sizes attribute (or the empty string, if the attribute is absent).
  6652. auto unparsed_sizes_list = parse_a_comma_separated_list_of_component_values(m_token_stream);
  6653. // 2. Let size be null.
  6654. Optional<LengthOrCalculated> size;
  6655. // 3. For each unparsed size in unparsed sizes list:
  6656. for (auto& unparsed_size : unparsed_sizes_list) {
  6657. // 1. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  6658. // If unparsed size is now empty, that is a parse error; continue.
  6659. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  6660. unparsed_size.take_last();
  6661. if (unparsed_size.is_empty()) {
  6662. log_parse_error();
  6663. continue;
  6664. }
  6665. // 2. If the last component value in unparsed size is a valid non-negative <source-size-value>,
  6666. // let size be its value and remove the component value from unparsed size.
  6667. // FIXME: Any CSS function other than the math functions is invalid.
  6668. // Otherwise, there is a parse error; continue.
  6669. auto last_value_stream = TokenStream<ComponentValue>::of_single_token(unparsed_size.last());
  6670. if (auto source_size_value = parse_source_size_value(last_value_stream); source_size_value.has_value()) {
  6671. size = source_size_value.value();
  6672. unparsed_size.take_last();
  6673. } else {
  6674. log_parse_error();
  6675. continue;
  6676. }
  6677. // 3. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  6678. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  6679. unparsed_size.take_last();
  6680. // If unparsed size is now empty, then return size.
  6681. if (unparsed_size.is_empty())
  6682. return size.value();
  6683. // FIXME: If this was not the keyword auto and it was not the last item in unparsed sizes list, that is a parse error.
  6684. // 4. Parse the remaining component values in unparsed size as a <media-condition>.
  6685. // If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue.
  6686. TokenStream<ComponentValue> token_stream { unparsed_size };
  6687. auto media_condition = parse_media_condition(token_stream, MediaCondition::AllowOr::Yes);
  6688. auto context_window = m_context.window();
  6689. if (context_window && media_condition && media_condition->evaluate(*context_window) == MatchResult::True) {
  6690. return size.value();
  6691. }
  6692. // 5. If size is not auto, then return size.
  6693. if (size.value().is_calculated() || !size.value().value().is_auto())
  6694. return size.value();
  6695. }
  6696. return Length(100, Length::Type::Vw);
  6697. }
  6698. // https://www.w3.org/TR/css-values-4/#parse-a-calculation
  6699. OwnPtr<CalculationNode> Parser::parse_a_calculation(Vector<ComponentValue> const& original_values)
  6700. {
  6701. // 1. Discard any <whitespace-token>s from values.
  6702. // 2. An item in values is an “operator” if it’s a <delim-token> with the value "+", "-", "*", or "/". Otherwise, it’s a “value”.
  6703. struct Operator {
  6704. char delim;
  6705. };
  6706. using Value = Variant<NonnullOwnPtr<CalculationNode>, Operator>;
  6707. Vector<Value> values;
  6708. for (auto& value : original_values) {
  6709. if (value.is(Token::Type::Whitespace))
  6710. continue;
  6711. if (value.is(Token::Type::Delim)) {
  6712. if (first_is_one_of(value.token().delim(), static_cast<u32>('+'), static_cast<u32>('-'), static_cast<u32>('*'), static_cast<u32>('/'))) {
  6713. // NOTE: Sequential operators are invalid syntax.
  6714. if (!values.is_empty() && values.last().has<Operator>())
  6715. return nullptr;
  6716. values.append(Operator { static_cast<char>(value.token().delim()) });
  6717. continue;
  6718. }
  6719. }
  6720. if (value.is(Token::Type::Ident)) {
  6721. auto maybe_constant = CalculationNode::constant_type_from_string(value.token().ident());
  6722. if (maybe_constant.has_value()) {
  6723. values.append({ ConstantCalculationNode::create(maybe_constant.value()) });
  6724. continue;
  6725. }
  6726. }
  6727. if (value.is(Token::Type::Number)) {
  6728. values.append({ NumericCalculationNode::create(value.token().number()) });
  6729. continue;
  6730. }
  6731. if (auto dimension = parse_dimension(value); dimension.has_value()) {
  6732. if (dimension->is_angle())
  6733. values.append({ NumericCalculationNode::create(dimension->angle()) });
  6734. else if (dimension->is_frequency())
  6735. values.append({ NumericCalculationNode::create(dimension->frequency()) });
  6736. else if (dimension->is_length())
  6737. values.append({ NumericCalculationNode::create(dimension->length()) });
  6738. else if (dimension->is_percentage())
  6739. values.append({ NumericCalculationNode::create(dimension->percentage()) });
  6740. // FIXME: Resolutions, once calc() supports them.
  6741. else if (dimension->is_time())
  6742. values.append({ NumericCalculationNode::create(dimension->time()) });
  6743. else if (dimension->is_flex()) {
  6744. // https://www.w3.org/TR/css3-grid-layout/#fr-unit
  6745. // NOTE: <flex> values are not <length>s (nor are they compatible with <length>s, like some <percentage> values),
  6746. // so they cannot be represented in or combined with other unit types in calc() expressions.
  6747. return nullptr;
  6748. } else {
  6749. VERIFY_NOT_REACHED();
  6750. }
  6751. continue;
  6752. }
  6753. values.append({ UnparsedCalculationNode::create(value) });
  6754. }
  6755. // If we have no values, the syntax is invalid.
  6756. if (values.is_empty())
  6757. return nullptr;
  6758. // NOTE: If the first or last value is an operator, the syntax is invalid.
  6759. if (values.first().has<Operator>() || values.last().has<Operator>())
  6760. return nullptr;
  6761. // 3. Collect children into Product and Invert nodes.
  6762. // For every consecutive run of value items in values separated by "*" or "/" operators:
  6763. while (true) {
  6764. Optional<size_t> first_product_operator = values.find_first_index_if([](auto const& item) {
  6765. return item.template has<Operator>()
  6766. && first_is_one_of(item.template get<Operator>().delim, '*', '/');
  6767. });
  6768. if (!first_product_operator.has_value())
  6769. break;
  6770. auto start_of_run = first_product_operator.value() - 1;
  6771. auto end_of_run = first_product_operator.value() + 1;
  6772. for (auto i = start_of_run + 1; i < values.size(); i += 2) {
  6773. auto& item = values[i];
  6774. if (!item.has<Operator>()) {
  6775. end_of_run = i - 1;
  6776. break;
  6777. }
  6778. auto delim = item.get<Operator>().delim;
  6779. if (!first_is_one_of(delim, '*', '/')) {
  6780. end_of_run = i - 1;
  6781. break;
  6782. }
  6783. }
  6784. // 1. For each "/" operator in the run, replace its right-hand value item rhs with an Invert node containing rhs as its child.
  6785. Vector<NonnullOwnPtr<CalculationNode>> run_values;
  6786. run_values.append(move(values[start_of_run].get<NonnullOwnPtr<CalculationNode>>()));
  6787. for (auto i = start_of_run + 1; i <= end_of_run; i += 2) {
  6788. auto& operator_ = values[i].get<Operator>().delim;
  6789. auto& rhs = values[i + 1];
  6790. if (operator_ == '/') {
  6791. run_values.append(InvertCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  6792. continue;
  6793. }
  6794. VERIFY(operator_ == '*');
  6795. run_values.append(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  6796. }
  6797. // 2. Replace the entire run with a Product node containing the value items of the run as its children.
  6798. auto product_node = ProductCalculationNode::create(move(run_values));
  6799. values.remove(start_of_run, end_of_run - start_of_run + 1);
  6800. values.insert(start_of_run, { move(product_node) });
  6801. }
  6802. // 4. Collect children into Sum and Negate nodes.
  6803. Optional<NonnullOwnPtr<CalculationNode>> single_value;
  6804. {
  6805. // 1. For each "-" operator item in values, replace its right-hand value item rhs with a Negate node containing rhs as its child.
  6806. for (auto i = 0u; i < values.size(); ++i) {
  6807. auto& maybe_minus_operator = values[i];
  6808. if (!maybe_minus_operator.has<Operator>() || maybe_minus_operator.get<Operator>().delim != '-')
  6809. continue;
  6810. auto rhs_index = ++i;
  6811. auto& rhs = values[rhs_index];
  6812. NonnullOwnPtr<CalculationNode> negate_node = NegateCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  6813. values.remove(rhs_index);
  6814. values.insert(rhs_index, move(negate_node));
  6815. }
  6816. // 2. If values has only one item, and it is a Product node or a parenthesized simple block, replace values with that item.
  6817. if (values.size() == 1) {
  6818. values.first().visit(
  6819. [&](ComponentValue& component_value) {
  6820. if (component_value.is_block() && component_value.block().is_paren())
  6821. single_value = UnparsedCalculationNode::create(component_value);
  6822. },
  6823. [&](NonnullOwnPtr<CalculationNode>& node) {
  6824. if (node->type() == CalculationNode::Type::Product)
  6825. single_value = move(node);
  6826. },
  6827. [](auto&) {});
  6828. }
  6829. // Otherwise, replace values with a Sum node containing the value items of values as its children.
  6830. if (!single_value.has_value()) {
  6831. values.remove_all_matching([](Value& value) { return value.has<Operator>(); });
  6832. Vector<NonnullOwnPtr<CalculationNode>> value_items;
  6833. value_items.ensure_capacity(values.size());
  6834. for (auto& value : values) {
  6835. if (value.has<Operator>())
  6836. continue;
  6837. value_items.unchecked_append(move(value.get<NonnullOwnPtr<CalculationNode>>()));
  6838. }
  6839. single_value = SumCalculationNode::create(move(value_items));
  6840. }
  6841. }
  6842. // 5. At this point values is a tree of Sum, Product, Negate, and Invert nodes, with other types of values at the leaf nodes. Process the leaf nodes.
  6843. // For every leaf node leaf in values:
  6844. bool parsing_failed_for_child_node = false;
  6845. single_value.value()->for_each_child_node([&](NonnullOwnPtr<CalculationNode>& node) {
  6846. if (node->type() != CalculationNode::Type::Unparsed)
  6847. return;
  6848. auto& unparsed_node = static_cast<UnparsedCalculationNode&>(*node);
  6849. auto& component_value = unparsed_node.component_value();
  6850. // 1. If leaf is a parenthesized simple block, replace leaf with the result of parsing a calculation from leaf’s contents.
  6851. if (component_value.is_block() && component_value.block().is_paren()) {
  6852. auto leaf_calculation = parse_a_calculation(component_value.block().values());
  6853. if (!leaf_calculation) {
  6854. parsing_failed_for_child_node = true;
  6855. return;
  6856. }
  6857. node = leaf_calculation.release_nonnull();
  6858. return;
  6859. }
  6860. // 2. If leaf is a math function, replace leaf with the internal representation of that math function.
  6861. // NOTE: All function tokens at this point should be math functions.
  6862. else if (component_value.is_function()) {
  6863. auto& function = component_value.function();
  6864. auto leaf_calculation = parse_a_calc_function_node(function);
  6865. if (!leaf_calculation) {
  6866. parsing_failed_for_child_node = true;
  6867. return;
  6868. }
  6869. node = leaf_calculation.release_nonnull();
  6870. return;
  6871. }
  6872. // NOTE: If we get here, then we have an UnparsedCalculationNode that didn't get replaced with something else.
  6873. // So, the calc() is invalid.
  6874. dbgln_if(CSS_PARSER_DEBUG, "Leftover UnparsedCalculationNode in calc tree! That probably means the syntax is invalid, but maybe we just didn't implement `{}` yet.", component_value.to_debug_string());
  6875. parsing_failed_for_child_node = true;
  6876. return;
  6877. });
  6878. if (parsing_failed_for_child_node)
  6879. return nullptr;
  6880. // FIXME: 6. Return the result of simplifying a calculation tree from values.
  6881. return single_value.release_value();
  6882. }
  6883. bool Parser::has_ignored_vendor_prefix(StringView string)
  6884. {
  6885. if (!string.starts_with('-'))
  6886. return false;
  6887. if (string.starts_with("--"sv))
  6888. return false;
  6889. if (string.starts_with("-libweb-"sv))
  6890. return false;
  6891. return true;
  6892. }
  6893. NonnullRefPtr<CSSStyleValue> Parser::resolve_unresolved_style_value(ParsingContext const& context, DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, PropertyID property_id, UnresolvedStyleValue const& unresolved)
  6894. {
  6895. // Unresolved always contains a var() or attr(), unless it is a custom property's value, in which case we shouldn't be trying
  6896. // to produce a different CSSStyleValue from it.
  6897. VERIFY(unresolved.contains_var_or_attr());
  6898. // If the value is invalid, we fall back to `unset`: https://www.w3.org/TR/css-variables-1/#invalid-at-computed-value-time
  6899. auto parser = Parser::create(context, ""sv);
  6900. return parser.resolve_unresolved_style_value(element, pseudo_element, property_id, unresolved);
  6901. }
  6902. class PropertyDependencyNode : public RefCounted<PropertyDependencyNode> {
  6903. public:
  6904. static NonnullRefPtr<PropertyDependencyNode> create(FlyString name)
  6905. {
  6906. return adopt_ref(*new PropertyDependencyNode(move(name)));
  6907. }
  6908. void add_child(NonnullRefPtr<PropertyDependencyNode> new_child)
  6909. {
  6910. for (auto const& child : m_children) {
  6911. if (child->m_name == new_child->m_name)
  6912. return;
  6913. }
  6914. // We detect self-reference already.
  6915. VERIFY(new_child->m_name != m_name);
  6916. m_children.append(move(new_child));
  6917. }
  6918. bool has_cycles()
  6919. {
  6920. if (m_marked)
  6921. return true;
  6922. TemporaryChange change { m_marked, true };
  6923. for (auto& child : m_children) {
  6924. if (child->has_cycles())
  6925. return true;
  6926. }
  6927. return false;
  6928. }
  6929. private:
  6930. explicit PropertyDependencyNode(FlyString name)
  6931. : m_name(move(name))
  6932. {
  6933. }
  6934. FlyString m_name;
  6935. Vector<NonnullRefPtr<PropertyDependencyNode>> m_children;
  6936. bool m_marked { false };
  6937. };
  6938. NonnullRefPtr<CSSStyleValue> Parser::resolve_unresolved_style_value(DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, PropertyID property_id, UnresolvedStyleValue const& unresolved)
  6939. {
  6940. TokenStream unresolved_values_without_variables_expanded { unresolved.values() };
  6941. Vector<ComponentValue> values_with_variables_expanded;
  6942. HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>> dependencies;
  6943. if (!expand_variables(element, pseudo_element, string_from_property_id(property_id), dependencies, unresolved_values_without_variables_expanded, values_with_variables_expanded))
  6944. return CSSKeywordValue::create(Keyword::Unset);
  6945. TokenStream unresolved_values_with_variables_expanded { values_with_variables_expanded };
  6946. Vector<ComponentValue> expanded_values;
  6947. if (!expand_unresolved_values(element, string_from_property_id(property_id), unresolved_values_with_variables_expanded, expanded_values))
  6948. return CSSKeywordValue::create(Keyword::Unset);
  6949. auto expanded_value_tokens = TokenStream { expanded_values };
  6950. if (auto parsed_value = parse_css_value(property_id, expanded_value_tokens); !parsed_value.is_error())
  6951. return parsed_value.release_value();
  6952. return CSSKeywordValue::create(Keyword::Unset);
  6953. }
  6954. static RefPtr<CSSStyleValue const> get_custom_property(DOM::Element const& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, FlyString const& custom_property_name)
  6955. {
  6956. if (pseudo_element.has_value()) {
  6957. if (auto it = element.custom_properties(pseudo_element).find(custom_property_name); it != element.custom_properties(pseudo_element).end())
  6958. return it->value.value;
  6959. }
  6960. for (auto const* current_element = &element; current_element; current_element = current_element->parent_or_shadow_host_element()) {
  6961. if (auto it = current_element->custom_properties({}).find(custom_property_name); it != current_element->custom_properties({}).end())
  6962. return it->value.value;
  6963. }
  6964. return nullptr;
  6965. }
  6966. bool Parser::expand_variables(DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, FlyString const& property_name, HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>>& dependencies, TokenStream<ComponentValue>& source, Vector<ComponentValue>& dest)
  6967. {
  6968. // Arbitrary large value chosen to avoid the billion-laughs attack.
  6969. // https://www.w3.org/TR/css-variables-1/#long-variables
  6970. size_t const MAX_VALUE_COUNT = 16384;
  6971. if (source.remaining_token_count() + dest.size() > MAX_VALUE_COUNT) {
  6972. dbgln("Stopped expanding CSS variables: maximum length reached.");
  6973. return false;
  6974. }
  6975. auto get_dependency_node = [&](FlyString const& name) -> NonnullRefPtr<PropertyDependencyNode> {
  6976. if (auto existing = dependencies.get(name); existing.has_value())
  6977. return *existing.value();
  6978. auto new_node = PropertyDependencyNode::create(name);
  6979. dependencies.set(name, new_node);
  6980. return new_node;
  6981. };
  6982. while (source.has_next_token()) {
  6983. auto const& value = source.next_token();
  6984. if (value.is_block()) {
  6985. auto const& source_block = value.block();
  6986. Vector<ComponentValue> block_values;
  6987. TokenStream source_block_contents { source_block.values() };
  6988. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_block_contents, block_values))
  6989. return false;
  6990. NonnullRefPtr<Block> block = Block::create(source_block.token(), move(block_values));
  6991. dest.empend(block);
  6992. continue;
  6993. }
  6994. if (!value.is_function()) {
  6995. dest.empend(value);
  6996. continue;
  6997. }
  6998. if (!value.function().name().equals_ignoring_ascii_case("var"sv)) {
  6999. auto const& source_function = value.function();
  7000. Vector<ComponentValue> function_values;
  7001. TokenStream source_function_contents { source_function.values() };
  7002. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_function_contents, function_values))
  7003. return false;
  7004. NonnullRefPtr<Function> function = Function::create(source_function.name(), move(function_values));
  7005. dest.empend(function);
  7006. continue;
  7007. }
  7008. TokenStream var_contents { value.function().values() };
  7009. var_contents.skip_whitespace();
  7010. if (!var_contents.has_next_token())
  7011. return false;
  7012. auto const& custom_property_name_token = var_contents.next_token();
  7013. if (!custom_property_name_token.is(Token::Type::Ident))
  7014. return false;
  7015. auto custom_property_name = custom_property_name_token.token().ident();
  7016. if (!custom_property_name.bytes_as_string_view().starts_with("--"sv))
  7017. return false;
  7018. // Detect dependency cycles. https://www.w3.org/TR/css-variables-1/#cycles
  7019. // We do not do this by the spec, since we are not keeping a graph of var dependencies around,
  7020. // but rebuilding it every time.
  7021. if (custom_property_name == property_name)
  7022. return false;
  7023. auto parent = get_dependency_node(property_name);
  7024. auto child = get_dependency_node(custom_property_name);
  7025. parent->add_child(child);
  7026. if (parent->has_cycles())
  7027. return false;
  7028. if (auto custom_property_value = get_custom_property(element, pseudo_element, custom_property_name)) {
  7029. VERIFY(custom_property_value->is_unresolved());
  7030. TokenStream custom_property_tokens { custom_property_value->as_unresolved().values() };
  7031. if (!expand_variables(element, pseudo_element, custom_property_name, dependencies, custom_property_tokens, dest))
  7032. return false;
  7033. continue;
  7034. }
  7035. // Use the provided fallback value, if any.
  7036. var_contents.skip_whitespace();
  7037. if (var_contents.has_next_token()) {
  7038. auto const& comma_token = var_contents.next_token();
  7039. if (!comma_token.is(Token::Type::Comma))
  7040. return false;
  7041. var_contents.skip_whitespace();
  7042. if (!expand_variables(element, pseudo_element, property_name, dependencies, var_contents, dest))
  7043. return false;
  7044. }
  7045. }
  7046. return true;
  7047. }
  7048. bool Parser::expand_unresolved_values(DOM::Element& element, FlyString const& property_name, TokenStream<ComponentValue>& source, Vector<ComponentValue>& dest)
  7049. {
  7050. while (source.has_next_token()) {
  7051. auto const& value = source.next_token();
  7052. if (value.is_function()) {
  7053. if (value.function().name().equals_ignoring_ascii_case("attr"sv)) {
  7054. if (!substitute_attr_function(element, property_name, value.function(), dest))
  7055. return false;
  7056. continue;
  7057. }
  7058. if (auto maybe_calc_value = parse_calculated_value(value); maybe_calc_value && maybe_calc_value->is_calculated()) {
  7059. auto& calc_value = maybe_calc_value->as_calculated();
  7060. if (calc_value.resolves_to_angle()) {
  7061. auto resolved_value = calc_value.resolve_angle();
  7062. dest.empend(Token::create_dimension(resolved_value->to_degrees(), "deg"_fly_string));
  7063. continue;
  7064. }
  7065. if (calc_value.resolves_to_frequency()) {
  7066. auto resolved_value = calc_value.resolve_frequency();
  7067. dest.empend(Token::create_dimension(resolved_value->to_hertz(), "hz"_fly_string));
  7068. continue;
  7069. }
  7070. if (calc_value.resolves_to_length()) {
  7071. // FIXME: In order to resolve lengths, we need to know the font metrics in case a font-relative unit
  7072. // is used. So... we can't do that until style is computed?
  7073. // This might be easier once we have calc-simplification implemented.
  7074. }
  7075. if (calc_value.resolves_to_percentage()) {
  7076. auto resolved_value = calc_value.resolve_percentage();
  7077. dest.empend(Token::create_percentage(resolved_value.value().value()));
  7078. continue;
  7079. }
  7080. if (calc_value.resolves_to_time()) {
  7081. auto resolved_value = calc_value.resolve_time();
  7082. dest.empend(Token::create_dimension(resolved_value->to_seconds(), "s"_fly_string));
  7083. continue;
  7084. }
  7085. if (calc_value.resolves_to_number()) {
  7086. auto resolved_value = calc_value.resolve_number();
  7087. dest.empend(Token::create_number(resolved_value.value()));
  7088. continue;
  7089. }
  7090. }
  7091. auto const& source_function = value.function();
  7092. Vector<ComponentValue> function_values;
  7093. TokenStream source_function_contents { source_function.values() };
  7094. if (!expand_unresolved_values(element, property_name, source_function_contents, function_values))
  7095. return false;
  7096. NonnullRefPtr<Function> function = Function::create(source_function.name(), move(function_values));
  7097. dest.empend(function);
  7098. continue;
  7099. }
  7100. if (value.is_block()) {
  7101. auto const& source_block = value.block();
  7102. TokenStream source_block_values { source_block.values() };
  7103. Vector<ComponentValue> block_values;
  7104. if (!expand_unresolved_values(element, property_name, source_block_values, block_values))
  7105. return false;
  7106. NonnullRefPtr<Block> block = Block::create(source_block.token(), move(block_values));
  7107. dest.empend(move(block));
  7108. continue;
  7109. }
  7110. dest.empend(value.token());
  7111. }
  7112. return true;
  7113. }
  7114. // https://drafts.csswg.org/css-values-5/#attr-substitution
  7115. bool Parser::substitute_attr_function(DOM::Element& element, FlyString const& property_name, Function const& attr_function, Vector<ComponentValue>& dest)
  7116. {
  7117. // First, parse the arguments to attr():
  7118. // attr() = attr( <q-name> <attr-type>? , <declaration-value>?)
  7119. // <attr-type> = string | url | ident | color | number | percentage | length | angle | time | frequency | flex | <dimension-unit>
  7120. TokenStream attr_contents { attr_function.values() };
  7121. attr_contents.skip_whitespace();
  7122. if (!attr_contents.has_next_token())
  7123. return false;
  7124. // - Attribute name
  7125. // FIXME: Support optional attribute namespace
  7126. if (!attr_contents.peek_token().is(Token::Type::Ident))
  7127. return false;
  7128. auto attribute_name = attr_contents.next_token().token().ident();
  7129. attr_contents.skip_whitespace();
  7130. // - Attribute type (optional)
  7131. auto attribute_type = "string"_fly_string;
  7132. if (attr_contents.peek_token().is(Token::Type::Ident)) {
  7133. attribute_type = attr_contents.next_token().token().ident();
  7134. attr_contents.skip_whitespace();
  7135. }
  7136. // - Comma, then fallback values (optional)
  7137. bool has_fallback_values = false;
  7138. if (attr_contents.has_next_token()) {
  7139. if (!attr_contents.peek_token().is(Token::Type::Comma))
  7140. return false;
  7141. (void)attr_contents.next_token(); // Comma
  7142. has_fallback_values = true;
  7143. }
  7144. // Then, run the substitution algorithm:
  7145. // 1. If the attr() function has a substitution value, replace the attr() function by the substitution value.
  7146. // https://drafts.csswg.org/css-values-5/#attr-types
  7147. if (element.has_attribute(attribute_name)) {
  7148. auto attribute_value = element.get_attribute_value(attribute_name);
  7149. if (attribute_type.equals_ignoring_ascii_case("angle"_fly_string)) {
  7150. // Parse a component value from the attribute’s value.
  7151. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7152. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7153. // Otherwise, there is no substitution value.
  7154. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7155. if (Angle::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7156. dest.append(component_value.release_value());
  7157. return true;
  7158. }
  7159. }
  7160. } else if (attribute_type.equals_ignoring_ascii_case("color"_fly_string)) {
  7161. // Parse a component value from the attribute’s value.
  7162. // If the result is a <hex-color> or a named color ident, the substitution value is that result as a <color>.
  7163. // Otherwise there is no substitution value.
  7164. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7165. if (component_value.has_value()) {
  7166. if ((component_value->is(Token::Type::Hash)
  7167. && Color::from_string(MUST(String::formatted("#{}", component_value->token().hash_value()))).has_value())
  7168. || (component_value->is(Token::Type::Ident)
  7169. && Color::from_string(component_value->token().ident()).has_value())) {
  7170. dest.append(component_value.release_value());
  7171. return true;
  7172. }
  7173. }
  7174. } else if (attribute_type.equals_ignoring_ascii_case("flex"_fly_string)) {
  7175. // Parse a component value from the attribute’s value.
  7176. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7177. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7178. // Otherwise, there is no substitution value.
  7179. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7180. if (Flex::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7181. dest.append(component_value.release_value());
  7182. return true;
  7183. }
  7184. }
  7185. } else if (attribute_type.equals_ignoring_ascii_case("frequency"_fly_string)) {
  7186. // Parse a component value from the attribute’s value.
  7187. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7188. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7189. // Otherwise, there is no substitution value.
  7190. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7191. if (Frequency::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7192. dest.append(component_value.release_value());
  7193. return true;
  7194. }
  7195. }
  7196. } else if (attribute_type.equals_ignoring_ascii_case("ident"_fly_string)) {
  7197. // The substitution value is a CSS <custom-ident>, whose value is the literal value of the attribute,
  7198. // with leading and trailing ASCII whitespace stripped. (No CSS parsing of the value is performed.)
  7199. // If the attribute value, after trimming, is the empty string, there is instead no substitution value.
  7200. // If the <custom-ident>’s value is a CSS-wide keyword or `default`, there is instead no substitution value.
  7201. auto substitution_value = MUST(attribute_value.trim(Infra::ASCII_WHITESPACE));
  7202. if (!substitution_value.is_empty()
  7203. && !substitution_value.equals_ignoring_ascii_case("default"sv)
  7204. && !is_css_wide_keyword(substitution_value)) {
  7205. dest.empend(Token::create_ident(substitution_value));
  7206. return true;
  7207. }
  7208. } else if (attribute_type.equals_ignoring_ascii_case("length"_fly_string)) {
  7209. // Parse a component value from the attribute’s value.
  7210. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7211. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7212. // Otherwise, there is no substitution value.
  7213. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7214. if (Length::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7215. dest.append(component_value.release_value());
  7216. return true;
  7217. }
  7218. }
  7219. } else if (attribute_type.equals_ignoring_ascii_case("number"_fly_string)) {
  7220. // Parse a component value from the attribute’s value.
  7221. // If the result is a <number-token>, the result is the substitution value.
  7222. // Otherwise, there is no substitution value.
  7223. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7224. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  7225. dest.append(component_value.release_value());
  7226. return true;
  7227. }
  7228. } else if (attribute_type.equals_ignoring_ascii_case("percentage"_fly_string)) {
  7229. // Parse a component value from the attribute’s value.
  7230. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7231. // If the result is a <percentage-token>, the result is the substitution value.
  7232. // Otherwise, there is no substitution value.
  7233. if (component_value.has_value() && component_value->is(Token::Type::Percentage)) {
  7234. dest.append(component_value.release_value());
  7235. return true;
  7236. }
  7237. } else if (attribute_type.equals_ignoring_ascii_case("string"_fly_string)) {
  7238. // The substitution value is a CSS string, whose value is the literal value of the attribute.
  7239. // (No CSS parsing or "cleanup" of the value is performed.)
  7240. // No value triggers fallback.
  7241. dest.empend(Token::create_string(attribute_value));
  7242. return true;
  7243. } else if (attribute_type.equals_ignoring_ascii_case("time"_fly_string)) {
  7244. // Parse a component value from the attribute’s value.
  7245. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7246. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7247. // Otherwise, there is no substitution value.
  7248. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7249. if (Time::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7250. dest.append(component_value.release_value());
  7251. return true;
  7252. }
  7253. }
  7254. } else if (attribute_type.equals_ignoring_ascii_case("url"_fly_string)) {
  7255. // The substitution value is a CSS <url> value, whose url is the literal value of the attribute.
  7256. // (No CSS parsing or "cleanup" of the value is performed.)
  7257. // No value triggers fallback.
  7258. dest.empend(Token::create_url(attribute_value));
  7259. return true;
  7260. } else {
  7261. // Dimension units
  7262. // Parse a component value from the attribute’s value.
  7263. // If the result is a <number-token>, the substitution value is a dimension with the result’s value, and the given unit.
  7264. // Otherwise, there is no substitution value.
  7265. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7266. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  7267. if (attribute_value == "%"sv) {
  7268. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7269. return true;
  7270. } else if (auto angle_unit = Angle::unit_from_name(attribute_type); angle_unit.has_value()) {
  7271. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7272. return true;
  7273. } else if (auto flex_unit = Flex::unit_from_name(attribute_type); flex_unit.has_value()) {
  7274. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7275. return true;
  7276. } else if (auto frequency_unit = Frequency::unit_from_name(attribute_type); frequency_unit.has_value()) {
  7277. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7278. return true;
  7279. } else if (auto length_unit = Length::unit_from_name(attribute_type); length_unit.has_value()) {
  7280. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7281. return true;
  7282. } else if (auto time_unit = Time::unit_from_name(attribute_type); time_unit.has_value()) {
  7283. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7284. return true;
  7285. } else {
  7286. // Not a dimension unit.
  7287. return false;
  7288. }
  7289. }
  7290. }
  7291. }
  7292. // 2. Otherwise, if the attr() function has a fallback value as its last argument, replace the attr() function by the fallback value.
  7293. // If there are any var() or attr() references in the fallback, substitute them as well.
  7294. if (has_fallback_values)
  7295. return expand_unresolved_values(element, property_name, attr_contents, dest);
  7296. if (attribute_type.equals_ignoring_ascii_case("string"_fly_string)) {
  7297. // If the <attr-type> argument is string, defaults to the empty string if omitted
  7298. dest.empend(Token::create_string({}));
  7299. return true;
  7300. }
  7301. // 3. Otherwise, the property containing the attr() function is invalid at computed-value time.
  7302. return false;
  7303. }
  7304. }