Parser.cpp 307 KB

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