Parser.cpp 290 KB

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