Parser.cpp 297 KB

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