Parser.cpp 310 KB

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