Parser.cpp 308 KB

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