Parser.cpp 296 KB

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