Parser.cpp 297 KB

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