Parser.cpp 302 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, the SerenityOS developers.
  4. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
  6. * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include <AK/CharacterTypes.h>
  11. #include <AK/Debug.h>
  12. #include <AK/GenericLexer.h>
  13. #include <AK/SourceLocation.h>
  14. #include <AK/TemporaryChange.h>
  15. #include <LibWeb/CSS/CSSFontFaceRule.h>
  16. #include <LibWeb/CSS/CSSImportRule.h>
  17. #include <LibWeb/CSS/CSSKeyframeRule.h>
  18. #include <LibWeb/CSS/CSSKeyframesRule.h>
  19. #include <LibWeb/CSS/CSSMediaRule.h>
  20. #include <LibWeb/CSS/CSSNamespaceRule.h>
  21. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  22. #include <LibWeb/CSS/CSSStyleRule.h>
  23. #include <LibWeb/CSS/CSSStyleSheet.h>
  24. #include <LibWeb/CSS/CSSSupportsRule.h>
  25. #include <LibWeb/CSS/CalculatedOr.h>
  26. #include <LibWeb/CSS/EdgeRect.h>
  27. #include <LibWeb/CSS/MediaList.h>
  28. #include <LibWeb/CSS/Parser/Block.h>
  29. #include <LibWeb/CSS/Parser/ComponentValue.h>
  30. #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
  31. #include <LibWeb/CSS/Parser/Function.h>
  32. #include <LibWeb/CSS/Parser/Parser.h>
  33. #include <LibWeb/CSS/Parser/Rule.h>
  34. #include <LibWeb/CSS/Selector.h>
  35. #include <LibWeb/CSS/StyleValue.h>
  36. #include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
  37. #include <LibWeb/CSS/StyleValues/BackgroundRepeatStyleValue.h>
  38. #include <LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h>
  39. #include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h>
  40. #include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
  41. #include <LibWeb/CSS/StyleValues/ContentStyleValue.h>
  42. #include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
  43. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  44. #include <LibWeb/CSS/StyleValues/EasingStyleValue.h>
  45. #include <LibWeb/CSS/StyleValues/EdgeStyleValue.h>
  46. #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h>
  47. #include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
  48. #include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
  49. #include <LibWeb/CSS/StyleValues/GridAutoFlowStyleValue.h>
  50. #include <LibWeb/CSS/StyleValues/GridTemplateAreaStyleValue.h>
  51. #include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
  52. #include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
  53. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  54. #include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
  55. #include <LibWeb/CSS/StyleValues/InheritStyleValue.h>
  56. #include <LibWeb/CSS/StyleValues/InitialStyleValue.h>
  57. #include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
  58. #include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
  59. #include <LibWeb/CSS/StyleValues/MathDepthStyleValue.h>
  60. #include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
  61. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  62. #include <LibWeb/CSS/StyleValues/PositionStyleValue.h>
  63. #include <LibWeb/CSS/StyleValues/RatioStyleValue.h>
  64. #include <LibWeb/CSS/StyleValues/RectStyleValue.h>
  65. #include <LibWeb/CSS/StyleValues/ResolutionStyleValue.h>
  66. #include <LibWeb/CSS/StyleValues/RevertStyleValue.h>
  67. #include <LibWeb/CSS/StyleValues/ShadowStyleValue.h>
  68. #include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>
  69. #include <LibWeb/CSS/StyleValues/StringStyleValue.h>
  70. #include <LibWeb/CSS/StyleValues/StyleValueList.h>
  71. #include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
  72. #include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
  73. #include <LibWeb/CSS/StyleValues/URLStyleValue.h>
  74. #include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
  75. #include <LibWeb/CSS/StyleValues/UnsetStyleValue.h>
  76. #include <LibWeb/Dump.h>
  77. #include <LibWeb/Infra/Strings.h>
  78. static void log_parse_error(SourceLocation const& location = SourceLocation::current())
  79. {
  80. dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
  81. }
  82. namespace Web::CSS::Parser {
  83. ErrorOr<Parser> Parser::create(ParsingContext const& context, StringView input, StringView encoding)
  84. {
  85. auto tokens = TRY(Tokenizer::tokenize(input, encoding));
  86. return Parser { context, move(tokens) };
  87. }
  88. Parser::Parser(ParsingContext const& context, Vector<Token> tokens)
  89. : m_context(context)
  90. , m_tokens(move(tokens))
  91. , m_token_stream(m_tokens)
  92. {
  93. }
  94. Parser::Parser(Parser&& other)
  95. : m_context(other.m_context)
  96. , m_tokens(move(other.m_tokens))
  97. , m_token_stream(m_tokens)
  98. {
  99. // Moving the TokenStream directly from `other` would break it, because TokenStream holds
  100. // a reference to the Vector<Token>, so it would be pointing at the old Parser's tokens.
  101. // So instead, we create a new TokenStream from this Parser's tokens, and then tell it to
  102. // copy the other TokenStream's state. This is quite hacky.
  103. m_token_stream.copy_state({}, other.m_token_stream);
  104. }
  105. // 5.3.3. Parse a stylesheet
  106. // https://www.w3.org/TR/css-syntax-3/#parse-stylesheet
  107. template<typename T>
  108. Parser::ParsedStyleSheet Parser::parse_a_stylesheet(TokenStream<T>& tokens, Optional<AK::URL> location)
  109. {
  110. // To parse a stylesheet from an input given an optional url location:
  111. // 1. If input is a byte stream for stylesheet, decode bytes from input, and set input to the result.
  112. // 2. Normalize input, and set input to the result.
  113. // NOTE: These are done automatically when creating the Parser.
  114. // 3. Create a new stylesheet, with its location set to location (or null, if location was not passed).
  115. ParsedStyleSheet style_sheet;
  116. style_sheet.location = move(location);
  117. // 4. Consume a list of rules from input, with the top-level flag set, and set the stylesheet’s value to the result.
  118. style_sheet.rules = consume_a_list_of_rules(tokens, TopLevel::Yes);
  119. // 5. Return the stylesheet.
  120. return style_sheet;
  121. }
  122. // https://www.w3.org/TR/css-syntax-3/#parse-a-css-stylesheet
  123. CSSStyleSheet* Parser::parse_as_css_stylesheet(Optional<AK::URL> location)
  124. {
  125. // To parse a CSS stylesheet, first parse a stylesheet.
  126. auto style_sheet = parse_a_stylesheet(m_token_stream, {});
  127. // Interpret all of the resulting top-level qualified rules as style rules, defined below.
  128. JS::MarkedVector<CSSRule*> rules(m_context.realm().heap());
  129. for (auto& raw_rule : style_sheet.rules) {
  130. auto* rule = convert_to_rule(raw_rule);
  131. // If any style rule is invalid, or any at-rule is not recognized or is invalid according to its grammar or context, it’s a parse error. Discard that rule.
  132. if (rule)
  133. rules.append(rule);
  134. }
  135. auto rule_list = CSSRuleList::create(m_context.realm(), rules);
  136. auto media_list = MediaList::create(m_context.realm(), {});
  137. return CSSStyleSheet::create(m_context.realm(), rule_list, media_list, move(location));
  138. }
  139. RefPtr<Supports> Parser::parse_as_supports()
  140. {
  141. return parse_a_supports(m_token_stream);
  142. }
  143. template<typename T>
  144. RefPtr<Supports> Parser::parse_a_supports(TokenStream<T>& tokens)
  145. {
  146. auto component_values = parse_a_list_of_component_values(tokens);
  147. TokenStream<ComponentValue> token_stream { component_values };
  148. auto maybe_condition = parse_supports_condition(token_stream);
  149. token_stream.skip_whitespace();
  150. if (maybe_condition && !token_stream.has_next_token())
  151. return Supports::create(maybe_condition.release_nonnull());
  152. return {};
  153. }
  154. OwnPtr<Supports::Condition> Parser::parse_supports_condition(TokenStream<ComponentValue>& tokens)
  155. {
  156. auto transaction = tokens.begin_transaction();
  157. tokens.skip_whitespace();
  158. auto const& peeked_token = tokens.peek_token();
  159. // `not <supports-in-parens>`
  160. if (peeked_token.is(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().bytes_as_string_view();
  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 flex_type = Flex::unit_from_name(unit_string); flex_type.has_value())
  1503. return Flex { numeric_value, flex_type.release_value() };
  1504. if (auto frequency_type = Frequency::unit_from_name(unit_string); frequency_type.has_value())
  1505. return Frequency { numeric_value, frequency_type.release_value() };
  1506. if (auto resolution_type = Resolution::unit_from_name(unit_string); resolution_type.has_value())
  1507. return Resolution { numeric_value, resolution_type.release_value() };
  1508. if (auto time_type = Time::unit_from_name(unit_string); time_type.has_value())
  1509. return Time { numeric_value, time_type.release_value() };
  1510. }
  1511. if (component_value.is(Token::Type::Percentage))
  1512. return Percentage { component_value.token().percentage() };
  1513. if (component_value.is(Token::Type::Number)) {
  1514. auto numeric_value = component_value.token().number_value();
  1515. if (numeric_value == 0)
  1516. return Length::make_px(0);
  1517. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
  1518. // https://quirks.spec.whatwg.org/#quirky-length-value
  1519. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  1520. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  1521. // expression, and must not be supported in the supports() static method of the CSS interface."
  1522. return Length::make_px(CSSPixels::nearest_value_for(numeric_value));
  1523. }
  1524. }
  1525. return {};
  1526. }
  1527. Optional<LengthOrCalculated> Parser::parse_source_size_value(ComponentValue const& component_value)
  1528. {
  1529. if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_ascii_case("auto"sv)) {
  1530. return LengthOrCalculated { Length::make_auto() };
  1531. }
  1532. if (auto calculated_value = parse_calculated_value(component_value)) {
  1533. return LengthOrCalculated { calculated_value.release_nonnull() };
  1534. }
  1535. if (auto length = parse_length(component_value); length.has_value()) {
  1536. return LengthOrCalculated { length.release_value() };
  1537. }
  1538. return {};
  1539. }
  1540. Optional<Length> Parser::parse_length(ComponentValue const& component_value)
  1541. {
  1542. auto dimension = parse_dimension(component_value);
  1543. if (!dimension.has_value())
  1544. return {};
  1545. if (dimension->is_length())
  1546. return dimension->length();
  1547. return {};
  1548. }
  1549. Optional<Ratio> Parser::parse_ratio(TokenStream<ComponentValue>& tokens)
  1550. {
  1551. auto transaction = tokens.begin_transaction();
  1552. tokens.skip_whitespace();
  1553. auto read_number_value = [this](ComponentValue const& component_value) -> Optional<double> {
  1554. if (component_value.is(Token::Type::Number)) {
  1555. return component_value.token().number_value();
  1556. } else if (component_value.is_function()) {
  1557. auto maybe_calc = parse_calculated_value(component_value);
  1558. if (!maybe_calc || !maybe_calc->resolves_to_number())
  1559. return {};
  1560. if (auto resolved_number = maybe_calc->resolve_number(); resolved_number.has_value() && resolved_number.value() >= 0) {
  1561. return resolved_number.value();
  1562. }
  1563. }
  1564. return {};
  1565. };
  1566. // `<ratio> = <number [0,∞]> [ / <number [0,∞]> ]?`
  1567. auto maybe_numerator = read_number_value(tokens.next_token());
  1568. if (!maybe_numerator.has_value() || maybe_numerator.value() < 0)
  1569. return {};
  1570. auto numerator = maybe_numerator.value();
  1571. {
  1572. auto two_value_transaction = tokens.begin_transaction();
  1573. tokens.skip_whitespace();
  1574. auto solidus = tokens.next_token();
  1575. tokens.skip_whitespace();
  1576. auto maybe_denominator = read_number_value(tokens.next_token());
  1577. if (solidus.is_delim('/') && maybe_denominator.has_value() && maybe_denominator.value() >= 0) {
  1578. auto denominator = maybe_denominator.value();
  1579. // Two-value ratio
  1580. two_value_transaction.commit();
  1581. transaction.commit();
  1582. return Ratio { numerator, denominator };
  1583. }
  1584. }
  1585. // Single-value ratio
  1586. transaction.commit();
  1587. return Ratio { numerator };
  1588. }
  1589. // https://www.w3.org/TR/css-syntax-3/#urange-syntax
  1590. Optional<UnicodeRange> Parser::parse_unicode_range(TokenStream<ComponentValue>& tokens)
  1591. {
  1592. auto transaction = tokens.begin_transaction();
  1593. tokens.skip_whitespace();
  1594. // <urange> =
  1595. // u '+' <ident-token> '?'* |
  1596. // u <dimension-token> '?'* |
  1597. // u <number-token> '?'* |
  1598. // u <number-token> <dimension-token> |
  1599. // u <number-token> <number-token> |
  1600. // u '+' '?'+
  1601. // (All with no whitespace in between tokens.)
  1602. // NOTE: Parsing this is different from usual. We take these steps:
  1603. // 1. Match the grammar above against the tokens, concatenating them into a string using their original representation.
  1604. // 2. Then, parse that string according to the spec algorithm.
  1605. // Step 2 is performed by calling the other parse_unicode_range() overload.
  1606. auto is_ending_token = [](ComponentValue const& component_value) {
  1607. return component_value.is(Token::Type::EndOfFile)
  1608. || component_value.is(Token::Type::Comma)
  1609. || component_value.is(Token::Type::Semicolon)
  1610. || component_value.is(Token::Type::Whitespace);
  1611. };
  1612. auto create_unicode_range = [&](StringView text, auto& local_transaction) -> Optional<UnicodeRange> {
  1613. auto maybe_unicode_range = parse_unicode_range(text);
  1614. if (maybe_unicode_range.has_value()) {
  1615. local_transaction.commit();
  1616. transaction.commit();
  1617. }
  1618. return maybe_unicode_range;
  1619. };
  1620. // All options start with 'u'/'U'.
  1621. auto const& u = tokens.next_token();
  1622. if (!(u.is(Token::Type::Ident) && u.token().ident().equals_ignoring_ascii_case("u"sv))) {
  1623. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> does not start with 'u'");
  1624. return {};
  1625. }
  1626. auto const& second_token = tokens.next_token();
  1627. // u '+' <ident-token> '?'* |
  1628. // u '+' '?'+
  1629. if (second_token.is_delim('+')) {
  1630. auto local_transaction = tokens.begin_transaction();
  1631. StringBuilder string_builder;
  1632. string_builder.append(second_token.token().representation());
  1633. auto const& third_token = tokens.next_token();
  1634. if (third_token.is(Token::Type::Ident) || third_token.is_delim('?')) {
  1635. string_builder.append(third_token.token().representation());
  1636. while (tokens.peek_token().is_delim('?'))
  1637. string_builder.append(tokens.next_token().token().representation());
  1638. if (is_ending_token(tokens.peek_token()))
  1639. return create_unicode_range(string_builder.string_view(), local_transaction);
  1640. }
  1641. }
  1642. // u <dimension-token> '?'*
  1643. if (second_token.is(Token::Type::Dimension)) {
  1644. auto local_transaction = tokens.begin_transaction();
  1645. StringBuilder string_builder;
  1646. string_builder.append(second_token.token().representation());
  1647. while (tokens.peek_token().is_delim('?'))
  1648. string_builder.append(tokens.next_token().token().representation());
  1649. if (is_ending_token(tokens.peek_token()))
  1650. return create_unicode_range(string_builder.string_view(), local_transaction);
  1651. }
  1652. // u <number-token> '?'* |
  1653. // u <number-token> <dimension-token> |
  1654. // u <number-token> <number-token>
  1655. if (second_token.is(Token::Type::Number)) {
  1656. auto local_transaction = tokens.begin_transaction();
  1657. StringBuilder string_builder;
  1658. string_builder.append(second_token.token().representation());
  1659. if (is_ending_token(tokens.peek_token()))
  1660. return create_unicode_range(string_builder.string_view(), local_transaction);
  1661. auto const& third_token = tokens.next_token();
  1662. if (third_token.is_delim('?')) {
  1663. string_builder.append(third_token.token().representation());
  1664. while (tokens.peek_token().is_delim('?'))
  1665. string_builder.append(tokens.next_token().token().representation());
  1666. if (is_ending_token(tokens.peek_token()))
  1667. return create_unicode_range(string_builder.string_view(), local_transaction);
  1668. } else if (third_token.is(Token::Type::Dimension)) {
  1669. string_builder.append(third_token.token().representation());
  1670. if (is_ending_token(tokens.peek_token()))
  1671. return create_unicode_range(string_builder.string_view(), local_transaction);
  1672. } else if (third_token.is(Token::Type::Number)) {
  1673. string_builder.append(third_token.token().representation());
  1674. if (is_ending_token(tokens.peek_token()))
  1675. return create_unicode_range(string_builder.string_view(), local_transaction);
  1676. }
  1677. }
  1678. if constexpr (CSS_PARSER_DEBUG) {
  1679. dbgln("CSSParser: Tokens did not match <urange> grammar.");
  1680. tokens.dump_all_tokens();
  1681. }
  1682. return {};
  1683. }
  1684. Optional<UnicodeRange> Parser::parse_unicode_range(StringView text)
  1685. {
  1686. auto make_valid_unicode_range = [&](u32 start_value, u32 end_value) -> Optional<UnicodeRange> {
  1687. // https://www.w3.org/TR/css-syntax-3/#maximum-allowed-code-point
  1688. constexpr u32 maximum_allowed_code_point = 0x10FFFF;
  1689. // To determine what codepoints the <urange> represents:
  1690. // 1. If end value is greater than the maximum allowed code point,
  1691. // the <urange> is invalid and a syntax error.
  1692. if (end_value > maximum_allowed_code_point) {
  1693. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: end_value ({}) > maximum ({})", end_value, maximum_allowed_code_point);
  1694. return {};
  1695. }
  1696. // 2. If start value is greater than end value, the <urange> is invalid and a syntax error.
  1697. if (start_value > end_value) {
  1698. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: start_value ({}) > end_value ({})", start_value, end_value);
  1699. return {};
  1700. }
  1701. // 3. Otherwise, the <urange> represents a contiguous range of codepoints from start value to end value, inclusive.
  1702. return UnicodeRange { start_value, end_value };
  1703. };
  1704. // 1. Skipping the first u token, concatenate the representations of all the tokens in the production together.
  1705. // Let this be text.
  1706. // NOTE: The concatenation is already done by the caller.
  1707. GenericLexer lexer { text };
  1708. // 2. If the first character of text is U+002B PLUS SIGN, consume it.
  1709. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  1710. if (lexer.next_is('+')) {
  1711. lexer.consume();
  1712. } else {
  1713. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Second character of <urange> was not '+'; got: '{}'", lexer.consume());
  1714. return {};
  1715. }
  1716. // 3. Consume as many hex digits from text as possible.
  1717. // then consume as many U+003F QUESTION MARK (?) code points as possible.
  1718. auto hex_digits = lexer.consume_while(is_ascii_hex_digit);
  1719. auto question_marks = lexer.consume_while([](auto it) { return it == '?'; });
  1720. // If zero code points were consumed, or more than six code points were consumed,
  1721. // this is an invalid <urange>, and this algorithm must exit.
  1722. size_t consumed_code_points = hex_digits.length() + question_marks.length();
  1723. if (consumed_code_points == 0 || consumed_code_points > 6) {
  1724. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value had {} digits/?s, expected between 1 and 6.", consumed_code_points);
  1725. return {};
  1726. }
  1727. StringView start_value_code_points { hex_digits.characters_without_null_termination(), consumed_code_points };
  1728. // If any U+003F QUESTION MARK (?) code points were consumed, then:
  1729. if (question_marks.length() > 0) {
  1730. // 1. If there are any code points left in text, this is an invalid <urange>,
  1731. // and this algorithm must exit.
  1732. if (lexer.tell_remaining() != 0) {
  1733. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  1734. return {};
  1735. }
  1736. // 2. Interpret the consumed code points as a hexadecimal number,
  1737. // with the U+003F QUESTION MARK (?) code points replaced by U+0030 DIGIT ZERO (0) code points.
  1738. // This is the start value.
  1739. auto start_value_string = start_value_code_points.replace("?"sv, "0"sv, ReplaceMode::All);
  1740. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_string);
  1741. if (!maybe_start_value.has_value()) {
  1742. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted start value did not parse as hex number.");
  1743. return {};
  1744. }
  1745. u32 start_value = maybe_start_value.release_value();
  1746. // 3. Interpret the consumed code points as a hexadecimal number again,
  1747. // with the U+003F QUESTION MARK (?) code points replaced by U+0046 LATIN CAPITAL LETTER F (F) code points.
  1748. // This is the end value.
  1749. auto end_value_string = start_value_code_points.replace("?"sv, "F"sv, ReplaceMode::All);
  1750. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_value_string);
  1751. if (!maybe_end_value.has_value()) {
  1752. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted end value did not parse as hex number.");
  1753. return {};
  1754. }
  1755. u32 end_value = maybe_end_value.release_value();
  1756. // 4. Exit this algorithm.
  1757. return make_valid_unicode_range(start_value, end_value);
  1758. }
  1759. // Otherwise, interpret the consumed code points as a hexadecimal number. This is the start value.
  1760. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_code_points);
  1761. if (!maybe_start_value.has_value()) {
  1762. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value did not parse as hex number.");
  1763. return {};
  1764. }
  1765. u32 start_value = maybe_start_value.release_value();
  1766. // 4. If there are no code points left in text, The end value is the same as the start value.
  1767. // Exit this algorithm.
  1768. if (lexer.tell_remaining() == 0)
  1769. return make_valid_unicode_range(start_value, start_value);
  1770. // 5. If the next code point in text is U+002D HYPHEN-MINUS (-), consume it.
  1771. if (lexer.next_is('-')) {
  1772. lexer.consume();
  1773. }
  1774. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  1775. else {
  1776. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start and end values not separated by '-'.");
  1777. return {};
  1778. }
  1779. // 6. Consume as many hex digits as possible from text.
  1780. auto end_hex_digits = lexer.consume_while(is_ascii_hex_digit);
  1781. // If zero hex digits were consumed, or more than 6 hex digits were consumed,
  1782. // this is an invalid <urange>, and this algorithm must exit.
  1783. if (end_hex_digits.length() == 0 || end_hex_digits.length() > 6) {
  1784. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value had {} digits, expected between 1 and 6.", end_hex_digits.length());
  1785. return {};
  1786. }
  1787. // If there are any code points left in text, this is an invalid <urange>, and this algorithm must exit.
  1788. if (lexer.tell_remaining() != 0) {
  1789. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  1790. return {};
  1791. }
  1792. // 7. Interpret the consumed code points as a hexadecimal number. This is the end value.
  1793. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_hex_digits);
  1794. if (!maybe_end_value.has_value()) {
  1795. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value did not parse as hex number.");
  1796. return {};
  1797. }
  1798. u32 end_value = maybe_end_value.release_value();
  1799. return make_valid_unicode_range(start_value, end_value);
  1800. }
  1801. RefPtr<StyleValue> Parser::parse_dimension_value(ComponentValue const& component_value)
  1802. {
  1803. // Numbers with no units can be lengths, in two situations:
  1804. // 1) We're in quirks mode, and it's an integer.
  1805. // 2) It's a 0.
  1806. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  1807. 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)))
  1808. return nullptr;
  1809. auto dimension = parse_dimension(component_value);
  1810. if (!dimension.has_value())
  1811. return nullptr;
  1812. if (dimension->is_angle())
  1813. return AngleStyleValue::create(dimension->angle());
  1814. if (dimension->is_frequency())
  1815. return FrequencyStyleValue::create(dimension->frequency());
  1816. if (dimension->is_length())
  1817. return LengthStyleValue::create(dimension->length());
  1818. if (dimension->is_percentage())
  1819. return PercentageStyleValue::create(dimension->percentage());
  1820. if (dimension->is_resolution())
  1821. return ResolutionStyleValue::create(dimension->resolution());
  1822. if (dimension->is_time())
  1823. return TimeStyleValue::create(dimension->time());
  1824. VERIFY_NOT_REACHED();
  1825. }
  1826. RefPtr<StyleValue> Parser::parse_integer_value(TokenStream<ComponentValue>& tokens)
  1827. {
  1828. auto peek_token = tokens.peek_token();
  1829. if (peek_token.is(Token::Type::Number) && peek_token.token().number().is_integer()) {
  1830. (void)tokens.next_token();
  1831. return IntegerStyleValue::create(peek_token.token().number().integer_value());
  1832. }
  1833. return nullptr;
  1834. }
  1835. RefPtr<StyleValue> Parser::parse_number_value(TokenStream<ComponentValue>& tokens)
  1836. {
  1837. auto peek_token = tokens.peek_token();
  1838. if (peek_token.is(Token::Type::Number)) {
  1839. (void)tokens.next_token();
  1840. return NumberStyleValue::create(peek_token.token().number().value());
  1841. }
  1842. return nullptr;
  1843. }
  1844. RefPtr<StyleValue> Parser::parse_identifier_value(ComponentValue const& component_value)
  1845. {
  1846. if (component_value.is(Token::Type::Ident)) {
  1847. auto value_id = value_id_from_string(component_value.token().ident());
  1848. if (value_id.has_value())
  1849. return IdentifierStyleValue::create(value_id.value());
  1850. }
  1851. return nullptr;
  1852. }
  1853. Optional<Color> Parser::parse_rgb_or_hsl_color(StringView function_name, Vector<ComponentValue> const& component_values)
  1854. {
  1855. Token params[4];
  1856. bool legacy_syntax = false;
  1857. auto tokens = TokenStream { component_values };
  1858. tokens.skip_whitespace();
  1859. auto const& component1 = tokens.next_token();
  1860. if (!component1.is(Token::Type::Number)
  1861. && !component1.is(Token::Type::Percentage)
  1862. && !component1.is(Token::Type::Dimension))
  1863. return {};
  1864. params[0] = component1.token();
  1865. tokens.skip_whitespace();
  1866. if (tokens.peek_token().is(Token::Type::Comma)) {
  1867. legacy_syntax = true;
  1868. tokens.next_token();
  1869. }
  1870. tokens.skip_whitespace();
  1871. auto const& component2 = tokens.next_token();
  1872. if (!component2.is(Token::Type::Number) && !component2.is(Token::Type::Percentage))
  1873. return {};
  1874. params[1] = component2.token();
  1875. tokens.skip_whitespace();
  1876. if (legacy_syntax && !tokens.next_token().is(Token::Type::Comma))
  1877. return {};
  1878. tokens.skip_whitespace();
  1879. auto const& component3 = tokens.next_token();
  1880. if (!component3.is(Token::Type::Number) && !component3.is(Token::Type::Percentage))
  1881. return {};
  1882. params[2] = component3.token();
  1883. tokens.skip_whitespace();
  1884. auto const& alpha_separator = tokens.peek_token();
  1885. bool has_comma = alpha_separator.is(Token::Type::Comma);
  1886. bool has_slash = alpha_separator.is_delim('/');
  1887. if (legacy_syntax ? has_comma : has_slash) {
  1888. tokens.next_token();
  1889. tokens.skip_whitespace();
  1890. auto const& component4 = tokens.next_token();
  1891. if (!component4.is(Token::Type::Number) && !component4.is(Token::Type::Percentage))
  1892. return {};
  1893. params[3] = component4.token();
  1894. }
  1895. tokens.skip_whitespace();
  1896. if (tokens.has_next_token())
  1897. return {};
  1898. if (function_name.equals_ignoring_ascii_case("rgb"sv)
  1899. || function_name.equals_ignoring_ascii_case("rgba"sv)) {
  1900. // https://www.w3.org/TR/css-color-4/#rgb-functions
  1901. u8 a_val = 255;
  1902. if (params[3].is(Token::Type::Number))
  1903. a_val = clamp(lround(params[3].number_value() * 255.0), 0, 255);
  1904. else if (params[3].is(Token::Type::Percentage))
  1905. a_val = clamp(lround(params[3].percentage() * 2.55), 0, 255);
  1906. if (params[0].is(Token::Type::Number)
  1907. && params[1].is(Token::Type::Number)
  1908. && params[2].is(Token::Type::Number)) {
  1909. u8 r_val = clamp(llroundf(params[0].number_value()), 0, 255);
  1910. u8 g_val = clamp(llroundf(params[1].number_value()), 0, 255);
  1911. u8 b_val = clamp(llroundf(params[2].number_value()), 0, 255);
  1912. return Color(r_val, g_val, b_val, a_val);
  1913. }
  1914. if (params[0].is(Token::Type::Percentage)
  1915. && params[1].is(Token::Type::Percentage)
  1916. && params[2].is(Token::Type::Percentage)) {
  1917. u8 r_val = lround(clamp(params[0].percentage() * 2.55, 0, 255));
  1918. u8 g_val = lround(clamp(params[1].percentage() * 2.55, 0, 255));
  1919. u8 b_val = lround(clamp(params[2].percentage() * 2.55, 0, 255));
  1920. return Color(r_val, g_val, b_val, a_val);
  1921. }
  1922. } else if (function_name.equals_ignoring_ascii_case("hsl"sv)
  1923. || function_name.equals_ignoring_ascii_case("hsla"sv)) {
  1924. // https://www.w3.org/TR/css-color-4/#the-hsl-notation
  1925. auto a_val = 1.0;
  1926. if (params[3].is(Token::Type::Number))
  1927. a_val = params[3].number_value();
  1928. else if (params[3].is(Token::Type::Percentage))
  1929. a_val = params[3].percentage() / 100.0;
  1930. if (params[0].is(Token::Type::Dimension)
  1931. && params[1].is(Token::Type::Percentage)
  1932. && params[2].is(Token::Type::Percentage)) {
  1933. auto numeric_value = params[0].dimension_value();
  1934. auto unit_string = params[0].dimension_unit();
  1935. auto angle_type = Angle::unit_from_name(unit_string);
  1936. if (!angle_type.has_value())
  1937. return {};
  1938. auto angle = Angle { numeric_value, angle_type.release_value() };
  1939. float h_val = fmod(angle.to_degrees(), 360.0);
  1940. float s_val = params[1].percentage() / 100.0;
  1941. float l_val = params[2].percentage() / 100.0;
  1942. return Color::from_hsla(h_val, s_val, l_val, a_val);
  1943. }
  1944. if (params[0].is(Token::Type::Number)
  1945. && params[1].is(Token::Type::Percentage)
  1946. && params[2].is(Token::Type::Percentage)) {
  1947. float h_val = fmod(params[0].number_value(), 360.0);
  1948. float s_val = params[1].percentage() / 100.0;
  1949. float l_val = params[2].percentage() / 100.0;
  1950. return Color::from_hsla(h_val, s_val, l_val, a_val);
  1951. }
  1952. }
  1953. return {};
  1954. }
  1955. // https://www.w3.org/TR/CSS2/visufx.html#value-def-shape
  1956. RefPtr<StyleValue> Parser::parse_rect_value(ComponentValue const& component_value)
  1957. {
  1958. if (!component_value.is_function())
  1959. return nullptr;
  1960. auto const& function = component_value.function();
  1961. if (!function.name().equals_ignoring_ascii_case("rect"sv))
  1962. return nullptr;
  1963. Vector<Length, 4> params;
  1964. auto tokens = TokenStream { function.values() };
  1965. enum class CommaRequirement {
  1966. Unknown,
  1967. RequiresCommas,
  1968. RequiresNoCommas
  1969. };
  1970. enum class Side {
  1971. Top = 0,
  1972. Right = 1,
  1973. Bottom = 2,
  1974. Left = 3
  1975. };
  1976. auto comma_requirement = CommaRequirement::Unknown;
  1977. // In CSS 2.1, the only valid <shape> value is: rect(<top>, <right>, <bottom>, <left>) where
  1978. // <top> and <bottom> specify offsets from the top border edge of the box, and <right>, and
  1979. // <left> specify offsets from the left border edge of the box.
  1980. for (size_t side = 0; side < 4; side++) {
  1981. tokens.skip_whitespace();
  1982. // <top>, <right>, <bottom>, and <left> may either have a <length> value or 'auto'.
  1983. // Negative lengths are permitted.
  1984. auto current_token = tokens.next_token().token();
  1985. if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto"sv)) {
  1986. params.append(Length::make_auto());
  1987. } else {
  1988. auto maybe_length = parse_length(current_token);
  1989. if (!maybe_length.has_value())
  1990. return nullptr;
  1991. params.append(maybe_length.value());
  1992. }
  1993. tokens.skip_whitespace();
  1994. // The last side, should be no more tokens following it.
  1995. if (static_cast<Side>(side) == Side::Left) {
  1996. if (tokens.has_next_token())
  1997. return nullptr;
  1998. break;
  1999. }
  2000. bool next_is_comma = tokens.peek_token().is(Token::Type::Comma);
  2001. // Authors should separate offset values with commas. User agents must support separation
  2002. // with commas, but may also support separation without commas (but not a combination),
  2003. // because a previous revision of this specification was ambiguous in this respect.
  2004. if (comma_requirement == CommaRequirement::Unknown)
  2005. comma_requirement = next_is_comma ? CommaRequirement::RequiresCommas : CommaRequirement::RequiresNoCommas;
  2006. if (comma_requirement == CommaRequirement::RequiresCommas) {
  2007. if (next_is_comma)
  2008. tokens.next_token();
  2009. else
  2010. return nullptr;
  2011. } else if (comma_requirement == CommaRequirement::RequiresNoCommas) {
  2012. if (next_is_comma)
  2013. return nullptr;
  2014. } else {
  2015. VERIFY_NOT_REACHED();
  2016. }
  2017. }
  2018. return RectStyleValue::create(EdgeRect { params[0], params[1], params[2], params[3] });
  2019. }
  2020. Optional<Color> Parser::parse_color(ComponentValue const& component_value)
  2021. {
  2022. // https://www.w3.org/TR/css-color-4/
  2023. if (component_value.is(Token::Type::Ident)) {
  2024. auto ident = component_value.token().ident();
  2025. auto color = Color::from_string(ident);
  2026. if (color.has_value())
  2027. return color;
  2028. } else if (component_value.is(Token::Type::Hash)) {
  2029. auto color = Color::from_string(DeprecatedString::formatted("#{}", component_value.token().hash_value()));
  2030. if (color.has_value())
  2031. return color;
  2032. return {};
  2033. } else if (component_value.is_function()) {
  2034. auto const& function = component_value.function();
  2035. auto const& values = function.values();
  2036. return parse_rgb_or_hsl_color(function.name(), values);
  2037. }
  2038. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  2039. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  2040. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  2041. // aborting on the first step that returns a value:
  2042. // 1. Let cv be the component value.
  2043. auto const& cv = component_value;
  2044. DeprecatedString serialization;
  2045. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  2046. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  2047. // 1. If cv’s type flag is not "integer", return an error.
  2048. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  2049. if (!cv.token().number().is_integer())
  2050. return {};
  2051. // 2. If cv’s value is less than zero, return an error.
  2052. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  2053. if (value < 0)
  2054. return {};
  2055. // 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.
  2056. StringBuilder serialization_builder;
  2057. serialization_builder.appendff("{}", value);
  2058. // 4. If cv is a <dimension-token>, append the unit to serialization.
  2059. if (cv.is(Token::Type::Dimension))
  2060. serialization_builder.append(cv.token().dimension_unit());
  2061. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  2062. serialization = serialization_builder.to_deprecated_string();
  2063. if (serialization_builder.length() < 6) {
  2064. StringBuilder builder;
  2065. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  2066. builder.append('0');
  2067. builder.append(serialization_builder.string_view());
  2068. serialization = builder.to_deprecated_string();
  2069. }
  2070. }
  2071. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  2072. else {
  2073. if (!cv.is(Token::Type::Ident))
  2074. return {};
  2075. serialization = cv.token().ident().bytes_as_string_view();
  2076. }
  2077. // 4. If serialization does not consist of three or six characters, return an error.
  2078. if (serialization.length() != 3 && serialization.length() != 6)
  2079. return {};
  2080. // 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.
  2081. for (auto c : serialization) {
  2082. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  2083. return {};
  2084. }
  2085. // 6. Return the concatenation of "#" (U+0023) and serialization.
  2086. DeprecatedString concatenation = DeprecatedString::formatted("#{}", serialization);
  2087. return Color::from_string(concatenation);
  2088. }
  2089. return {};
  2090. }
  2091. RefPtr<StyleValue> Parser::parse_color_value(ComponentValue const& component_value)
  2092. {
  2093. auto color = parse_color(component_value);
  2094. if (color.has_value())
  2095. return ColorStyleValue::create(color.value());
  2096. if (component_value.is(Token::Type::Ident)) {
  2097. auto ident = value_id_from_string(component_value.token().ident());
  2098. if (ident.has_value() && IdentifierStyleValue::is_color(ident.value()))
  2099. return IdentifierStyleValue::create(ident.value());
  2100. }
  2101. return nullptr;
  2102. }
  2103. RefPtr<StyleValue> Parser::parse_ratio_value(TokenStream<ComponentValue>& tokens)
  2104. {
  2105. if (auto ratio = parse_ratio(tokens); ratio.has_value())
  2106. return RatioStyleValue::create(ratio.release_value());
  2107. return nullptr;
  2108. }
  2109. RefPtr<StyleValue> Parser::parse_string_value(ComponentValue const& component_value)
  2110. {
  2111. if (component_value.is(Token::Type::String))
  2112. return StringStyleValue::create(MUST(String::from_utf8(component_value.token().string())));
  2113. return nullptr;
  2114. }
  2115. RefPtr<StyleValue> Parser::parse_image_value(ComponentValue const& component_value)
  2116. {
  2117. auto url = parse_url_function(component_value);
  2118. if (url.has_value())
  2119. return ImageStyleValue::create(url.value());
  2120. auto linear_gradient = parse_linear_gradient_function(component_value);
  2121. if (linear_gradient)
  2122. return linear_gradient;
  2123. auto conic_gradient = parse_conic_gradient_function(component_value);
  2124. if (conic_gradient)
  2125. return conic_gradient;
  2126. return parse_radial_gradient_function(component_value);
  2127. }
  2128. // https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint
  2129. RefPtr<StyleValue> Parser::parse_paint_value(TokenStream<ComponentValue>& tokens)
  2130. {
  2131. // `<paint> = none | <color> | <url> [none | <color>]? | context-fill | context-stroke`
  2132. auto parse_color_or_none = [&]() -> Optional<RefPtr<StyleValue>> {
  2133. if (auto color = parse_color_value(tokens.peek_token())) {
  2134. (void)tokens.next_token();
  2135. return color;
  2136. }
  2137. // NOTE: <color> also accepts identifiers, so we do this identifier check last.
  2138. if (tokens.peek_token().is(Token::Type::Ident)) {
  2139. auto maybe_ident = value_id_from_string(tokens.peek_token().token().ident());
  2140. if (maybe_ident.has_value()) {
  2141. // FIXME: Accept `context-fill` and `context-stroke`
  2142. switch (*maybe_ident) {
  2143. case ValueID::None:
  2144. (void)tokens.next_token();
  2145. return IdentifierStyleValue::create(*maybe_ident);
  2146. default:
  2147. return nullptr;
  2148. }
  2149. }
  2150. }
  2151. return OptionalNone {};
  2152. };
  2153. // FIMXE: Allow context-fill/context-stroke here
  2154. if (auto color_or_none = parse_color_or_none(); color_or_none.has_value())
  2155. return *color_or_none;
  2156. if (auto url = parse_url_value(tokens.peek_token())) {
  2157. (void)tokens.next_token();
  2158. tokens.skip_whitespace();
  2159. if (auto color_or_none = parse_color_or_none(); color_or_none == nullptr) {
  2160. // Fail to parse if the fallback is invalid, but otherwise ignore it.
  2161. // FIXME: Use fallback color
  2162. return nullptr;
  2163. }
  2164. return url;
  2165. }
  2166. return nullptr;
  2167. }
  2168. template<typename ParseFunction>
  2169. RefPtr<StyleValue> Parser::parse_comma_separated_value_list(Vector<ComponentValue> const& component_values, ParseFunction parse_one_value)
  2170. {
  2171. auto tokens = TokenStream { component_values };
  2172. auto first = parse_one_value(tokens);
  2173. if (!first || !tokens.has_next_token())
  2174. return first;
  2175. StyleValueVector values;
  2176. values.append(first.release_nonnull());
  2177. while (tokens.has_next_token()) {
  2178. if (!tokens.next_token().is(Token::Type::Comma))
  2179. return nullptr;
  2180. if (auto maybe_value = parse_one_value(tokens)) {
  2181. values.append(maybe_value.release_nonnull());
  2182. continue;
  2183. }
  2184. return nullptr;
  2185. }
  2186. return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
  2187. }
  2188. RefPtr<StyleValue> Parser::parse_simple_comma_separated_value_list(PropertyID property_id, Vector<ComponentValue> const& component_values)
  2189. {
  2190. return parse_comma_separated_value_list(component_values, [=, this](auto& tokens) -> RefPtr<StyleValue> {
  2191. if (auto value = parse_css_value_for_property(property_id, tokens))
  2192. return value;
  2193. tokens.reconsume_current_input_token();
  2194. return nullptr;
  2195. });
  2196. }
  2197. static void remove_property(Vector<PropertyID>& properties, PropertyID property_to_remove)
  2198. {
  2199. properties.remove_first_matching([&](auto it) { return it == property_to_remove; });
  2200. }
  2201. // https://www.w3.org/TR/css-sizing-4/#aspect-ratio
  2202. RefPtr<StyleValue> Parser::parse_aspect_ratio_value(Vector<ComponentValue> const& component_values)
  2203. {
  2204. // `auto || <ratio>`
  2205. RefPtr<StyleValue> auto_value;
  2206. RefPtr<StyleValue> ratio_value;
  2207. auto tokens = TokenStream { component_values };
  2208. while (tokens.has_next_token()) {
  2209. auto maybe_value = parse_css_value_for_property(PropertyID::AspectRatio, tokens);
  2210. if (!maybe_value)
  2211. return nullptr;
  2212. if (maybe_value->is_ratio()) {
  2213. if (ratio_value)
  2214. return nullptr;
  2215. ratio_value = maybe_value.release_nonnull();
  2216. continue;
  2217. }
  2218. if (maybe_value->is_identifier() && maybe_value->as_identifier().id() == ValueID::Auto) {
  2219. if (auto_value)
  2220. return nullptr;
  2221. auto_value = maybe_value.release_nonnull();
  2222. continue;
  2223. }
  2224. return nullptr;
  2225. }
  2226. if (auto_value && ratio_value) {
  2227. return StyleValueList::create(
  2228. StyleValueVector { auto_value.release_nonnull(), ratio_value.release_nonnull() },
  2229. StyleValueList::Separator::Space);
  2230. }
  2231. if (ratio_value)
  2232. return ratio_value.release_nonnull();
  2233. if (auto_value)
  2234. return auto_value.release_nonnull();
  2235. return nullptr;
  2236. }
  2237. RefPtr<StyleValue> Parser::parse_background_value(Vector<ComponentValue> const& component_values)
  2238. {
  2239. 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) {
  2240. return ShorthandStyleValue::create(PropertyID::Background,
  2241. { PropertyID::BackgroundColor, PropertyID::BackgroundImage, PropertyID::BackgroundPosition, PropertyID::BackgroundSize, PropertyID::BackgroundRepeat, PropertyID::BackgroundAttachment, PropertyID::BackgroundOrigin, PropertyID::BackgroundClip },
  2242. { move(background_color), move(background_image), move(background_position), move(background_size), move(background_repeat), move(background_attachment), move(background_origin), move(background_clip) });
  2243. };
  2244. StyleValueVector background_images;
  2245. StyleValueVector background_positions;
  2246. StyleValueVector background_sizes;
  2247. StyleValueVector background_repeats;
  2248. StyleValueVector background_attachments;
  2249. StyleValueVector background_clips;
  2250. StyleValueVector background_origins;
  2251. RefPtr<StyleValue> background_color;
  2252. auto initial_background_image = property_initial_value(m_context.realm(), PropertyID::BackgroundImage);
  2253. auto initial_background_position = property_initial_value(m_context.realm(), PropertyID::BackgroundPosition);
  2254. auto initial_background_size = property_initial_value(m_context.realm(), PropertyID::BackgroundSize);
  2255. auto initial_background_repeat = property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat);
  2256. auto initial_background_attachment = property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment);
  2257. auto initial_background_clip = property_initial_value(m_context.realm(), PropertyID::BackgroundClip);
  2258. auto initial_background_origin = property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin);
  2259. auto initial_background_color = property_initial_value(m_context.realm(), PropertyID::BackgroundColor);
  2260. // Per-layer values
  2261. RefPtr<StyleValue> background_image;
  2262. RefPtr<StyleValue> background_position;
  2263. RefPtr<StyleValue> background_size;
  2264. RefPtr<StyleValue> background_repeat;
  2265. RefPtr<StyleValue> background_attachment;
  2266. RefPtr<StyleValue> background_clip;
  2267. RefPtr<StyleValue> background_origin;
  2268. bool has_multiple_layers = false;
  2269. // BackgroundSize is always parsed as part of BackgroundPosition, so we don't include it here.
  2270. Vector<PropertyID> remaining_layer_properties {
  2271. PropertyID::BackgroundAttachment,
  2272. PropertyID::BackgroundClip,
  2273. PropertyID::BackgroundColor,
  2274. PropertyID::BackgroundImage,
  2275. PropertyID::BackgroundOrigin,
  2276. PropertyID::BackgroundPosition,
  2277. PropertyID::BackgroundRepeat,
  2278. };
  2279. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  2280. if (allow_background_color) {
  2281. if (background_color)
  2282. return true;
  2283. } else {
  2284. if (background_color)
  2285. return false;
  2286. }
  2287. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  2288. };
  2289. auto complete_background_layer = [&]() {
  2290. background_images.append(background_image ? background_image.release_nonnull() : initial_background_image);
  2291. background_positions.append(background_position ? background_position.release_nonnull() : initial_background_position);
  2292. background_sizes.append(background_size ? background_size.release_nonnull() : initial_background_size);
  2293. background_repeats.append(background_repeat ? background_repeat.release_nonnull() : initial_background_repeat);
  2294. background_attachments.append(background_attachment ? background_attachment.release_nonnull() : initial_background_attachment);
  2295. if (!background_origin && !background_clip) {
  2296. background_origin = initial_background_origin;
  2297. background_clip = initial_background_clip;
  2298. } else if (!background_clip) {
  2299. background_clip = background_origin;
  2300. }
  2301. background_origins.append(background_origin.release_nonnull());
  2302. background_clips.append(background_clip.release_nonnull());
  2303. background_image = nullptr;
  2304. background_position = nullptr;
  2305. background_size = nullptr;
  2306. background_repeat = nullptr;
  2307. background_attachment = nullptr;
  2308. background_clip = nullptr;
  2309. background_origin = nullptr;
  2310. remaining_layer_properties.clear_with_capacity();
  2311. remaining_layer_properties.unchecked_append(PropertyID::BackgroundAttachment);
  2312. remaining_layer_properties.unchecked_append(PropertyID::BackgroundClip);
  2313. remaining_layer_properties.unchecked_append(PropertyID::BackgroundColor);
  2314. remaining_layer_properties.unchecked_append(PropertyID::BackgroundImage);
  2315. remaining_layer_properties.unchecked_append(PropertyID::BackgroundOrigin);
  2316. remaining_layer_properties.unchecked_append(PropertyID::BackgroundPosition);
  2317. remaining_layer_properties.unchecked_append(PropertyID::BackgroundRepeat);
  2318. };
  2319. auto tokens = TokenStream { component_values };
  2320. while (tokens.has_next_token()) {
  2321. if (tokens.peek_token().is(Token::Type::Comma)) {
  2322. has_multiple_layers = true;
  2323. if (!background_layer_is_valid(false))
  2324. return nullptr;
  2325. complete_background_layer();
  2326. (void)tokens.next_token();
  2327. continue;
  2328. }
  2329. auto value_and_property = parse_css_value_for_properties(remaining_layer_properties, tokens);
  2330. if (!value_and_property.has_value())
  2331. return nullptr;
  2332. auto& value = value_and_property->style_value;
  2333. remove_property(remaining_layer_properties, value_and_property->property);
  2334. switch (value_and_property->property) {
  2335. case PropertyID::BackgroundAttachment:
  2336. VERIFY(!background_attachment);
  2337. background_attachment = value.release_nonnull();
  2338. continue;
  2339. case PropertyID::BackgroundColor:
  2340. VERIFY(!background_color);
  2341. background_color = value.release_nonnull();
  2342. continue;
  2343. case PropertyID::BackgroundImage:
  2344. VERIFY(!background_image);
  2345. background_image = value.release_nonnull();
  2346. continue;
  2347. case PropertyID::BackgroundClip:
  2348. case PropertyID::BackgroundOrigin: {
  2349. // background-origin and background-clip accept the same values. From the spec:
  2350. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  2351. // If two values are present, then the first sets background-origin and the second background-clip."
  2352. // - https://www.w3.org/TR/css-backgrounds-3/#background
  2353. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  2354. // If we only get one, we copy the value before creating the ShorthandStyleValue.
  2355. if (!background_origin) {
  2356. background_origin = value.release_nonnull();
  2357. } else if (!background_clip) {
  2358. background_clip = value.release_nonnull();
  2359. } else {
  2360. VERIFY_NOT_REACHED();
  2361. }
  2362. continue;
  2363. }
  2364. case PropertyID::BackgroundPosition: {
  2365. VERIFY(!background_position);
  2366. tokens.reconsume_current_input_token();
  2367. if (auto maybe_background_position = parse_single_background_position_value(tokens)) {
  2368. background_position = maybe_background_position.release_nonnull();
  2369. // Attempt to parse `/ <background-size>`
  2370. auto transaction = tokens.begin_transaction();
  2371. auto& maybe_slash = tokens.next_token();
  2372. if (maybe_slash.is_delim('/')) {
  2373. if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
  2374. transaction.commit();
  2375. background_size = maybe_background_size.release_nonnull();
  2376. continue;
  2377. }
  2378. return nullptr;
  2379. }
  2380. continue;
  2381. }
  2382. return nullptr;
  2383. }
  2384. case PropertyID::BackgroundRepeat: {
  2385. VERIFY(!background_repeat);
  2386. tokens.reconsume_current_input_token();
  2387. if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
  2388. background_repeat = maybe_repeat.release_nonnull();
  2389. continue;
  2390. }
  2391. return nullptr;
  2392. }
  2393. default:
  2394. VERIFY_NOT_REACHED();
  2395. }
  2396. return nullptr;
  2397. }
  2398. if (!background_layer_is_valid(true))
  2399. return nullptr;
  2400. // We only need to create StyleValueLists if there are multiple layers.
  2401. // Otherwise, we can pass the single StyleValues directly.
  2402. if (has_multiple_layers) {
  2403. complete_background_layer();
  2404. if (!background_color)
  2405. background_color = initial_background_color;
  2406. return make_background_shorthand(
  2407. background_color.release_nonnull(),
  2408. StyleValueList::create(move(background_images), StyleValueList::Separator::Comma),
  2409. StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma),
  2410. StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma),
  2411. StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma),
  2412. StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma),
  2413. StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma),
  2414. StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma));
  2415. }
  2416. if (!background_color)
  2417. background_color = initial_background_color;
  2418. if (!background_image)
  2419. background_image = initial_background_image;
  2420. if (!background_position)
  2421. background_position = initial_background_position;
  2422. if (!background_size)
  2423. background_size = initial_background_size;
  2424. if (!background_repeat)
  2425. background_repeat = initial_background_repeat;
  2426. if (!background_attachment)
  2427. background_attachment = initial_background_attachment;
  2428. if (!background_origin && !background_clip) {
  2429. background_origin = initial_background_origin;
  2430. background_clip = initial_background_clip;
  2431. } else if (!background_clip) {
  2432. background_clip = background_origin;
  2433. }
  2434. return make_background_shorthand(
  2435. background_color.release_nonnull(),
  2436. background_image.release_nonnull(),
  2437. background_position.release_nonnull(),
  2438. background_size.release_nonnull(),
  2439. background_repeat.release_nonnull(),
  2440. background_attachment.release_nonnull(),
  2441. background_origin.release_nonnull(),
  2442. background_clip.release_nonnull());
  2443. }
  2444. static Optional<PositionEdge> identifier_to_edge(ValueID identifier)
  2445. {
  2446. switch (identifier) {
  2447. case ValueID::Top:
  2448. return PositionEdge::Top;
  2449. case ValueID::Bottom:
  2450. return PositionEdge::Bottom;
  2451. case ValueID::Left:
  2452. return PositionEdge::Left;
  2453. case ValueID::Right:
  2454. return PositionEdge::Right;
  2455. default:
  2456. return {};
  2457. }
  2458. }
  2459. static Optional<LengthPercentage> style_value_to_length_percentage(auto value)
  2460. {
  2461. if (value->is_percentage())
  2462. return LengthPercentage { value->as_percentage().percentage() };
  2463. if (value->is_length())
  2464. return LengthPercentage { value->as_length().length() };
  2465. if (value->is_calculated())
  2466. return LengthPercentage { value->as_calculated() };
  2467. return {};
  2468. }
  2469. RefPtr<StyleValue> Parser::parse_single_background_position_value(TokenStream<ComponentValue>& tokens)
  2470. {
  2471. // NOTE: This *looks* like it parses a <position>, but it doesn't. From the spec:
  2472. // "Note: The background-position property also accepts a three-value syntax.
  2473. // This has been disallowed generically because it creates parsing ambiguities
  2474. // when combined with other length or percentage components in a property value."
  2475. // - https://www.w3.org/TR/css-values-4/#typedef-position
  2476. // So, we'll need a separate function to parse <position> later.
  2477. auto transaction = tokens.begin_transaction();
  2478. auto is_horizontal = [](ValueID identifier) -> bool {
  2479. switch (identifier) {
  2480. case ValueID::Left:
  2481. case ValueID::Right:
  2482. return true;
  2483. default:
  2484. return false;
  2485. }
  2486. };
  2487. auto is_vertical = [](ValueID identifier) -> bool {
  2488. switch (identifier) {
  2489. case ValueID::Top:
  2490. case ValueID::Bottom:
  2491. return true;
  2492. default:
  2493. return false;
  2494. }
  2495. };
  2496. struct EdgeOffset {
  2497. PositionEdge edge;
  2498. LengthPercentage offset;
  2499. bool edge_provided;
  2500. bool offset_provided;
  2501. };
  2502. Optional<EdgeOffset> horizontal;
  2503. Optional<EdgeOffset> vertical;
  2504. bool found_center = false;
  2505. auto const center_offset = Percentage { 50 };
  2506. auto const zero_offset = Length::make_px(0);
  2507. while (tokens.has_next_token()) {
  2508. // Check if we're done
  2509. auto seen_items = (horizontal.has_value() ? 1 : 0) + (vertical.has_value() ? 1 : 0) + (found_center ? 1 : 0);
  2510. if (seen_items == 2)
  2511. break;
  2512. auto maybe_value = parse_css_value_for_property(PropertyID::BackgroundPosition, tokens);
  2513. if (!maybe_value)
  2514. break;
  2515. auto value = maybe_value.release_nonnull();
  2516. if (auto offset = style_value_to_length_percentage(value); offset.has_value()) {
  2517. if (!horizontal.has_value()) {
  2518. horizontal = EdgeOffset { PositionEdge::Left, *offset, false, true };
  2519. } else if (!vertical.has_value()) {
  2520. vertical = EdgeOffset { PositionEdge::Top, *offset, false, true };
  2521. } else {
  2522. return nullptr;
  2523. }
  2524. continue;
  2525. }
  2526. auto try_parse_offset = [&](bool& offset_provided) -> LengthPercentage {
  2527. auto transaction = tokens.begin_transaction();
  2528. if (tokens.has_next_token()) {
  2529. auto maybe_value = parse_css_value_for_property(PropertyID::BackgroundPosition, tokens);
  2530. if (!maybe_value)
  2531. return zero_offset;
  2532. auto offset = style_value_to_length_percentage(maybe_value.release_nonnull());
  2533. if (offset.has_value()) {
  2534. offset_provided = true;
  2535. transaction.commit();
  2536. return *offset;
  2537. }
  2538. }
  2539. return zero_offset;
  2540. };
  2541. if (value->is_identifier()) {
  2542. auto identifier = value->to_identifier();
  2543. if (is_horizontal(identifier)) {
  2544. bool offset_provided = false;
  2545. auto offset = try_parse_offset(offset_provided);
  2546. horizontal = EdgeOffset { *identifier_to_edge(identifier), offset, true, offset_provided };
  2547. } else if (is_vertical(identifier)) {
  2548. bool offset_provided = false;
  2549. auto offset = try_parse_offset(offset_provided);
  2550. vertical = EdgeOffset { *identifier_to_edge(identifier), offset, true, offset_provided };
  2551. } else if (identifier == ValueID::Center) {
  2552. found_center = true;
  2553. } else {
  2554. return nullptr;
  2555. }
  2556. continue;
  2557. }
  2558. tokens.reconsume_current_input_token();
  2559. break;
  2560. }
  2561. if (found_center) {
  2562. if (horizontal.has_value() && vertical.has_value())
  2563. return nullptr;
  2564. if (!horizontal.has_value())
  2565. horizontal = EdgeOffset { PositionEdge::Left, center_offset, true, false };
  2566. if (!vertical.has_value())
  2567. vertical = EdgeOffset { PositionEdge::Top, center_offset, true, false };
  2568. }
  2569. if (!horizontal.has_value() && !vertical.has_value())
  2570. return nullptr;
  2571. // Unpack `<edge> <length>`:
  2572. // The loop above reads this pattern as a single EdgeOffset, when actually, it should be treated
  2573. // as `x y` if the edge is horizontal, and `y` (with the second token reconsumed) otherwise.
  2574. if (!vertical.has_value() && horizontal->edge_provided && horizontal->offset_provided) {
  2575. // Split into `x y`
  2576. vertical = EdgeOffset { PositionEdge::Top, horizontal->offset, false, true };
  2577. horizontal->offset = zero_offset;
  2578. horizontal->offset_provided = false;
  2579. } else if (!horizontal.has_value() && vertical->edge_provided && vertical->offset_provided) {
  2580. // `y`, reconsume
  2581. vertical->offset = zero_offset;
  2582. vertical->offset_provided = false;
  2583. tokens.reconsume_current_input_token();
  2584. }
  2585. // If only one value is specified, the second value is assumed to be center.
  2586. if (!horizontal.has_value())
  2587. horizontal = EdgeOffset { PositionEdge::Left, center_offset, false, false };
  2588. if (!vertical.has_value())
  2589. vertical = EdgeOffset { PositionEdge::Top, center_offset, false, false };
  2590. transaction.commit();
  2591. return PositionStyleValue::create(
  2592. EdgeStyleValue::create(horizontal->edge, horizontal->offset),
  2593. EdgeStyleValue::create(vertical->edge, vertical->offset));
  2594. }
  2595. RefPtr<StyleValue> Parser::parse_single_background_position_x_or_y_value(TokenStream<ComponentValue>& tokens, PropertyID property)
  2596. {
  2597. PositionEdge relative_edge {};
  2598. if (property == PropertyID::BackgroundPositionX) {
  2599. // [ center | [ [ left | right | x-start | x-end ]? <length-percentage>? ]! ]#
  2600. relative_edge = PositionEdge::Left;
  2601. } else if (property == PropertyID::BackgroundPositionY) {
  2602. // [ center | [ [ top | bottom | y-start | y-end ]? <length-percentage>? ]! ]#
  2603. relative_edge = PositionEdge::Top;
  2604. } else {
  2605. VERIFY_NOT_REACHED();
  2606. }
  2607. auto transaction = tokens.begin_transaction();
  2608. if (!tokens.has_next_token())
  2609. return nullptr;
  2610. auto value = parse_css_value_for_property(property, tokens);
  2611. if (!value)
  2612. return nullptr;
  2613. if (value->is_identifier()) {
  2614. auto identifier = value->to_identifier();
  2615. if (identifier == ValueID::Center) {
  2616. transaction.commit();
  2617. return EdgeStyleValue::create(relative_edge, Percentage { 50 });
  2618. }
  2619. if (auto edge = identifier_to_edge(identifier); edge.has_value()) {
  2620. relative_edge = *edge;
  2621. } else {
  2622. return nullptr;
  2623. }
  2624. if (tokens.has_next_token()) {
  2625. value = parse_css_value_for_property(property, tokens);
  2626. if (!value) {
  2627. transaction.commit();
  2628. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  2629. }
  2630. }
  2631. }
  2632. auto offset = style_value_to_length_percentage(value);
  2633. if (offset.has_value()) {
  2634. transaction.commit();
  2635. return EdgeStyleValue::create(relative_edge, *offset);
  2636. }
  2637. // If no offset is provided create this element but with an offset of default value of zero
  2638. transaction.commit();
  2639. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  2640. }
  2641. RefPtr<StyleValue> Parser::parse_single_background_repeat_value(TokenStream<ComponentValue>& tokens)
  2642. {
  2643. auto transaction = tokens.begin_transaction();
  2644. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  2645. auto value_id = value.to_identifier();
  2646. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  2647. };
  2648. auto as_repeat = [](ValueID identifier) -> Optional<Repeat> {
  2649. switch (identifier) {
  2650. case ValueID::NoRepeat:
  2651. return Repeat::NoRepeat;
  2652. case ValueID::Repeat:
  2653. return Repeat::Repeat;
  2654. case ValueID::Round:
  2655. return Repeat::Round;
  2656. case ValueID::Space:
  2657. return Repeat::Space;
  2658. default:
  2659. return {};
  2660. }
  2661. };
  2662. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  2663. if (!maybe_x_value)
  2664. return nullptr;
  2665. auto x_value = maybe_x_value.release_nonnull();
  2666. if (is_directional_repeat(*x_value)) {
  2667. auto value_id = x_value->to_identifier();
  2668. transaction.commit();
  2669. return BackgroundRepeatStyleValue::create(
  2670. value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  2671. value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  2672. }
  2673. auto x_repeat = as_repeat(x_value->to_identifier());
  2674. if (!x_repeat.has_value())
  2675. return nullptr;
  2676. // See if we have a second value for Y
  2677. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  2678. if (!maybe_y_value) {
  2679. // We don't have a second value, so use x for both
  2680. transaction.commit();
  2681. return BackgroundRepeatStyleValue::create(x_repeat.value(), x_repeat.value());
  2682. }
  2683. auto y_value = maybe_y_value.release_nonnull();
  2684. if (is_directional_repeat(*y_value))
  2685. return nullptr;
  2686. auto y_repeat = as_repeat(y_value->to_identifier());
  2687. if (!y_repeat.has_value())
  2688. return nullptr;
  2689. transaction.commit();
  2690. return BackgroundRepeatStyleValue::create(x_repeat.value(), y_repeat.value());
  2691. }
  2692. RefPtr<StyleValue> Parser::parse_single_background_size_value(TokenStream<ComponentValue>& tokens)
  2693. {
  2694. auto transaction = tokens.begin_transaction();
  2695. auto get_length_percentage = [](StyleValue& style_value) -> Optional<LengthPercentage> {
  2696. if (style_value.has_auto())
  2697. return LengthPercentage { Length::make_auto() };
  2698. if (style_value.is_percentage())
  2699. return LengthPercentage { style_value.as_percentage().percentage() };
  2700. if (style_value.is_length())
  2701. return LengthPercentage { style_value.as_length().length() };
  2702. if (style_value.is_calculated())
  2703. return LengthPercentage { style_value.as_calculated() };
  2704. return {};
  2705. };
  2706. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  2707. if (!maybe_x_value)
  2708. return nullptr;
  2709. auto x_value = maybe_x_value.release_nonnull();
  2710. if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain) {
  2711. transaction.commit();
  2712. return x_value;
  2713. }
  2714. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  2715. if (!maybe_y_value) {
  2716. auto y_value = LengthPercentage { Length::make_auto() };
  2717. auto x_size = get_length_percentage(*x_value);
  2718. if (!x_size.has_value())
  2719. return nullptr;
  2720. transaction.commit();
  2721. return BackgroundSizeStyleValue::create(x_size.value(), y_value);
  2722. }
  2723. auto y_value = maybe_y_value.release_nonnull();
  2724. auto x_size = get_length_percentage(*x_value);
  2725. auto y_size = get_length_percentage(*y_value);
  2726. if (!x_size.has_value() || !y_size.has_value())
  2727. return nullptr;
  2728. transaction.commit();
  2729. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  2730. }
  2731. RefPtr<StyleValue> Parser::parse_border_value(PropertyID property_id, Vector<ComponentValue> const& component_values)
  2732. {
  2733. if (component_values.size() > 3)
  2734. return nullptr;
  2735. RefPtr<StyleValue> border_width;
  2736. RefPtr<StyleValue> border_color;
  2737. RefPtr<StyleValue> border_style;
  2738. auto color_property = PropertyID::Invalid;
  2739. auto style_property = PropertyID::Invalid;
  2740. auto width_property = PropertyID::Invalid;
  2741. switch (property_id) {
  2742. case PropertyID::Border:
  2743. color_property = PropertyID::BorderColor;
  2744. style_property = PropertyID::BorderStyle;
  2745. width_property = PropertyID::BorderWidth;
  2746. break;
  2747. case PropertyID::BorderBottom:
  2748. color_property = PropertyID::BorderBottomColor;
  2749. style_property = PropertyID::BorderBottomStyle;
  2750. width_property = PropertyID::BorderBottomWidth;
  2751. break;
  2752. case PropertyID::BorderLeft:
  2753. color_property = PropertyID::BorderLeftColor;
  2754. style_property = PropertyID::BorderLeftStyle;
  2755. width_property = PropertyID::BorderLeftWidth;
  2756. break;
  2757. case PropertyID::BorderRight:
  2758. color_property = PropertyID::BorderRightColor;
  2759. style_property = PropertyID::BorderRightStyle;
  2760. width_property = PropertyID::BorderRightWidth;
  2761. break;
  2762. case PropertyID::BorderTop:
  2763. color_property = PropertyID::BorderTopColor;
  2764. style_property = PropertyID::BorderTopStyle;
  2765. width_property = PropertyID::BorderTopWidth;
  2766. break;
  2767. default:
  2768. VERIFY_NOT_REACHED();
  2769. }
  2770. auto remaining_longhands = Vector { width_property, color_property, style_property };
  2771. auto tokens = TokenStream { component_values };
  2772. while (tokens.has_next_token()) {
  2773. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  2774. if (!property_and_value.has_value())
  2775. return nullptr;
  2776. auto& value = property_and_value->style_value;
  2777. remove_property(remaining_longhands, property_and_value->property);
  2778. if (property_and_value->property == width_property) {
  2779. VERIFY(!border_width);
  2780. border_width = value.release_nonnull();
  2781. } else if (property_and_value->property == color_property) {
  2782. VERIFY(!border_color);
  2783. border_color = value.release_nonnull();
  2784. } else if (property_and_value->property == style_property) {
  2785. VERIFY(!border_style);
  2786. border_style = value.release_nonnull();
  2787. } else {
  2788. VERIFY_NOT_REACHED();
  2789. }
  2790. }
  2791. if (!border_width)
  2792. border_width = property_initial_value(m_context.realm(), width_property);
  2793. if (!border_style)
  2794. border_style = property_initial_value(m_context.realm(), style_property);
  2795. if (!border_color)
  2796. border_color = property_initial_value(m_context.realm(), color_property);
  2797. return ShorthandStyleValue::create(property_id,
  2798. { width_property, style_property, color_property },
  2799. { border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull() });
  2800. }
  2801. RefPtr<StyleValue> Parser::parse_border_radius_value(Vector<ComponentValue> const& component_values)
  2802. {
  2803. if (component_values.size() == 2) {
  2804. auto horizontal = parse_dimension(component_values[0]);
  2805. auto vertical = parse_dimension(component_values[1]);
  2806. if (horizontal.has_value() && horizontal->is_length_percentage() && vertical.has_value() && vertical->is_length_percentage())
  2807. return BorderRadiusStyleValue::create(horizontal->length_percentage(), vertical->length_percentage());
  2808. return nullptr;
  2809. }
  2810. if (component_values.size() == 1) {
  2811. auto radius = parse_dimension(component_values[0]);
  2812. if (radius.has_value() && radius->is_length_percentage())
  2813. return BorderRadiusStyleValue::create(radius->length_percentage(), radius->length_percentage());
  2814. return nullptr;
  2815. }
  2816. return nullptr;
  2817. }
  2818. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(Vector<ComponentValue> const& component_values)
  2819. {
  2820. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  2821. auto top_right = [&](Vector<LengthPercentage>& radii) {
  2822. switch (radii.size()) {
  2823. case 4:
  2824. case 3:
  2825. case 2:
  2826. return radii[1];
  2827. case 1:
  2828. return radii[0];
  2829. default:
  2830. VERIFY_NOT_REACHED();
  2831. }
  2832. };
  2833. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  2834. switch (radii.size()) {
  2835. case 4:
  2836. case 3:
  2837. return radii[2];
  2838. case 2:
  2839. case 1:
  2840. return radii[0];
  2841. default:
  2842. VERIFY_NOT_REACHED();
  2843. }
  2844. };
  2845. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  2846. switch (radii.size()) {
  2847. case 4:
  2848. return radii[3];
  2849. case 3:
  2850. case 2:
  2851. return radii[1];
  2852. case 1:
  2853. return radii[0];
  2854. default:
  2855. VERIFY_NOT_REACHED();
  2856. }
  2857. };
  2858. Vector<LengthPercentage> horizontal_radii;
  2859. Vector<LengthPercentage> vertical_radii;
  2860. bool reading_vertical = false;
  2861. for (auto const& value : component_values) {
  2862. if (value.is_delim('/')) {
  2863. if (reading_vertical || horizontal_radii.is_empty())
  2864. return nullptr;
  2865. reading_vertical = true;
  2866. continue;
  2867. }
  2868. auto maybe_dimension = parse_dimension(value);
  2869. if (!maybe_dimension.has_value() || !maybe_dimension->is_length_percentage())
  2870. return nullptr;
  2871. if (reading_vertical) {
  2872. vertical_radii.append(maybe_dimension->length_percentage());
  2873. } else {
  2874. horizontal_radii.append(maybe_dimension->length_percentage());
  2875. }
  2876. }
  2877. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  2878. || horizontal_radii.is_empty()
  2879. || (reading_vertical && vertical_radii.is_empty()))
  2880. return nullptr;
  2881. auto top_left_radius = BorderRadiusStyleValue::create(top_left(horizontal_radii),
  2882. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii));
  2883. auto top_right_radius = BorderRadiusStyleValue::create(top_right(horizontal_radii),
  2884. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii));
  2885. auto bottom_right_radius = BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  2886. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii));
  2887. auto bottom_left_radius = BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  2888. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii));
  2889. return ShorthandStyleValue::create(PropertyID::BorderRadius,
  2890. { PropertyID::BorderTopLeftRadius, PropertyID::BorderTopRightRadius, PropertyID::BorderBottomRightRadius, PropertyID::BorderBottomLeftRadius },
  2891. { move(top_left_radius), move(top_right_radius), move(bottom_right_radius), move(bottom_left_radius) });
  2892. }
  2893. RefPtr<StyleValue> Parser::parse_shadow_value(Vector<ComponentValue> const& component_values, AllowInsetKeyword allow_inset_keyword)
  2894. {
  2895. // "none"
  2896. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  2897. auto ident = parse_identifier_value(component_values.first());
  2898. if (ident && ident->to_identifier() == ValueID::None)
  2899. return ident;
  2900. }
  2901. return parse_comma_separated_value_list(component_values, [this, allow_inset_keyword](auto& tokens) {
  2902. return parse_single_shadow_value(tokens, allow_inset_keyword);
  2903. });
  2904. }
  2905. RefPtr<StyleValue> Parser::parse_single_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  2906. {
  2907. auto transaction = tokens.begin_transaction();
  2908. Optional<Color> color;
  2909. RefPtr<StyleValue> offset_x;
  2910. RefPtr<StyleValue> offset_y;
  2911. RefPtr<StyleValue> blur_radius;
  2912. RefPtr<StyleValue> spread_distance;
  2913. Optional<ShadowPlacement> placement;
  2914. auto possibly_dynamic_length = [&](ComponentValue const& token) -> RefPtr<StyleValue> {
  2915. if (auto calculated_value = parse_calculated_value(token)) {
  2916. if (!calculated_value->resolves_to_length())
  2917. return nullptr;
  2918. return calculated_value;
  2919. }
  2920. auto maybe_length = parse_length(token);
  2921. if (!maybe_length.has_value())
  2922. return nullptr;
  2923. return LengthStyleValue::create(maybe_length.release_value());
  2924. };
  2925. while (tokens.has_next_token()) {
  2926. auto const& token = tokens.peek_token();
  2927. if (auto maybe_color = parse_color(token); maybe_color.has_value()) {
  2928. if (color.has_value())
  2929. return nullptr;
  2930. color = maybe_color.release_value();
  2931. tokens.next_token();
  2932. continue;
  2933. }
  2934. if (auto maybe_offset_x = possibly_dynamic_length(token); maybe_offset_x) {
  2935. // horizontal offset
  2936. if (offset_x)
  2937. return nullptr;
  2938. offset_x = maybe_offset_x;
  2939. tokens.next_token();
  2940. // vertical offset
  2941. if (!tokens.has_next_token())
  2942. return nullptr;
  2943. auto maybe_offset_y = possibly_dynamic_length(tokens.peek_token());
  2944. if (!maybe_offset_y)
  2945. return nullptr;
  2946. offset_y = maybe_offset_y;
  2947. tokens.next_token();
  2948. // blur radius (optional)
  2949. if (!tokens.has_next_token())
  2950. break;
  2951. auto maybe_blur_radius = possibly_dynamic_length(tokens.peek_token());
  2952. if (!maybe_blur_radius)
  2953. continue;
  2954. blur_radius = maybe_blur_radius;
  2955. tokens.next_token();
  2956. // spread distance (optional)
  2957. if (!tokens.has_next_token())
  2958. break;
  2959. auto maybe_spread_distance = possibly_dynamic_length(tokens.peek_token());
  2960. if (!maybe_spread_distance)
  2961. continue;
  2962. spread_distance = maybe_spread_distance;
  2963. tokens.next_token();
  2964. continue;
  2965. }
  2966. if (allow_inset_keyword == AllowInsetKeyword::Yes
  2967. && token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("inset"sv)) {
  2968. if (placement.has_value())
  2969. return nullptr;
  2970. placement = ShadowPlacement::Inner;
  2971. tokens.next_token();
  2972. continue;
  2973. }
  2974. if (token.is(Token::Type::Comma))
  2975. break;
  2976. return nullptr;
  2977. }
  2978. // FIXME: If color is absent, default to `currentColor`
  2979. if (!color.has_value())
  2980. color = Color::NamedColor::Black;
  2981. // x/y offsets are required
  2982. if (!offset_x || !offset_y)
  2983. return nullptr;
  2984. // Other lengths default to 0
  2985. if (!blur_radius)
  2986. blur_radius = LengthStyleValue::create(Length::make_px(0));
  2987. if (!spread_distance)
  2988. spread_distance = LengthStyleValue::create(Length::make_px(0));
  2989. // Placement is outer by default
  2990. if (!placement.has_value())
  2991. placement = ShadowPlacement::Outer;
  2992. transaction.commit();
  2993. 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());
  2994. }
  2995. RefPtr<StyleValue> Parser::parse_content_value(Vector<ComponentValue> const& component_values)
  2996. {
  2997. // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.
  2998. auto is_single_value_identifier = [](ValueID identifier) -> bool {
  2999. switch (identifier) {
  3000. case ValueID::None:
  3001. case ValueID::Normal:
  3002. return true;
  3003. default:
  3004. return false;
  3005. }
  3006. };
  3007. if (component_values.size() == 1) {
  3008. if (auto identifier = parse_identifier_value(component_values.first())) {
  3009. if (is_single_value_identifier(identifier->to_identifier()))
  3010. return identifier;
  3011. }
  3012. }
  3013. StyleValueVector content_values;
  3014. StyleValueVector alt_text_values;
  3015. bool in_alt_text = false;
  3016. auto tokens = TokenStream { component_values };
  3017. while (tokens.has_next_token()) {
  3018. auto& next = tokens.peek_token();
  3019. if (next.is_delim('/')) {
  3020. if (in_alt_text || content_values.is_empty())
  3021. return nullptr;
  3022. in_alt_text = true;
  3023. (void)tokens.next_token();
  3024. continue;
  3025. }
  3026. if (auto style_value = parse_css_value_for_property(PropertyID::Content, tokens)) {
  3027. if (is_single_value_identifier(style_value->to_identifier()))
  3028. return nullptr;
  3029. if (in_alt_text) {
  3030. alt_text_values.append(style_value.release_nonnull());
  3031. } else {
  3032. content_values.append(style_value.release_nonnull());
  3033. }
  3034. continue;
  3035. }
  3036. return nullptr;
  3037. }
  3038. if (content_values.is_empty())
  3039. return nullptr;
  3040. if (in_alt_text && alt_text_values.is_empty())
  3041. return nullptr;
  3042. RefPtr<StyleValueList> alt_text;
  3043. if (!alt_text_values.is_empty())
  3044. alt_text = StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space);
  3045. return ContentStyleValue::create(StyleValueList::create(move(content_values), StyleValueList::Separator::Space), move(alt_text));
  3046. }
  3047. // https://www.w3.org/TR/css-display-3/#the-display-properties
  3048. RefPtr<StyleValue> Parser::parse_display_value(Vector<ComponentValue> const& component_values)
  3049. {
  3050. auto parse_single_component_display = [&](Vector<ComponentValue> const& component_values) -> Optional<Display> {
  3051. if (auto identifier_value = parse_identifier_value(component_values.first())) {
  3052. auto identifier = identifier_value->to_identifier();
  3053. if (identifier == ValueID::ListItem)
  3054. return Display::from_short(Display::Short::ListItem);
  3055. if (auto display_outside = value_id_to_display_outside(identifier); display_outside.has_value()) {
  3056. switch (display_outside.value()) {
  3057. case DisplayOutside::Block:
  3058. return Display::from_short(Display::Short::Block);
  3059. case DisplayOutside::Inline:
  3060. return Display::from_short(Display::Short::Inline);
  3061. case DisplayOutside::RunIn:
  3062. return Display::from_short(Display::Short::RunIn);
  3063. }
  3064. }
  3065. if (auto display_inside = value_id_to_display_inside(identifier); display_inside.has_value()) {
  3066. switch (display_inside.value()) {
  3067. case DisplayInside::Flow:
  3068. return Display::from_short(Display::Short::Flow);
  3069. case DisplayInside::FlowRoot:
  3070. return Display::from_short(Display::Short::FlowRoot);
  3071. case DisplayInside::Table:
  3072. return Display::from_short(Display::Short::Table);
  3073. case DisplayInside::Flex:
  3074. return Display::from_short(Display::Short::Flex);
  3075. case DisplayInside::Grid:
  3076. return Display::from_short(Display::Short::Grid);
  3077. case DisplayInside::Ruby:
  3078. return Display::from_short(Display::Short::Ruby);
  3079. case DisplayInside::Math:
  3080. return Display::from_short(Display::Short::Math);
  3081. }
  3082. }
  3083. if (auto display_internal = value_id_to_display_internal(identifier); display_internal.has_value()) {
  3084. return Display { display_internal.value() };
  3085. }
  3086. if (auto display_box = value_id_to_display_box(identifier); display_box.has_value()) {
  3087. switch (display_box.value()) {
  3088. case DisplayBox::Contents:
  3089. return Display::from_short(Display::Short::Contents);
  3090. case DisplayBox::None:
  3091. return Display::from_short(Display::Short::None);
  3092. }
  3093. }
  3094. if (auto display_legacy = value_id_to_display_legacy(identifier); display_legacy.has_value()) {
  3095. switch (display_legacy.value()) {
  3096. case DisplayLegacy::InlineBlock:
  3097. return Display::from_short(Display::Short::InlineBlock);
  3098. case DisplayLegacy::InlineTable:
  3099. return Display::from_short(Display::Short::InlineTable);
  3100. case DisplayLegacy::InlineFlex:
  3101. return Display::from_short(Display::Short::InlineFlex);
  3102. case DisplayLegacy::InlineGrid:
  3103. return Display::from_short(Display::Short::InlineGrid);
  3104. }
  3105. }
  3106. }
  3107. return OptionalNone {};
  3108. };
  3109. auto parse_multi_component_display = [&](Vector<ComponentValue> const& component_values) -> Optional<Display> {
  3110. auto list_item = Display::ListItem::No;
  3111. Optional<DisplayInside> inside;
  3112. Optional<DisplayOutside> outside;
  3113. for (size_t i = 0; i < component_values.size(); ++i) {
  3114. if (auto value = parse_identifier_value(component_values[i])) {
  3115. auto identifier = value->to_identifier();
  3116. if (identifier == ValueID::ListItem) {
  3117. if (list_item == Display::ListItem::Yes)
  3118. return {};
  3119. list_item = Display::ListItem::Yes;
  3120. continue;
  3121. }
  3122. if (auto inside_value = value_id_to_display_inside(identifier); inside_value.has_value()) {
  3123. if (inside.has_value())
  3124. return {};
  3125. inside = inside_value.value();
  3126. continue;
  3127. }
  3128. if (auto outside_value = value_id_to_display_outside(identifier); outside_value.has_value()) {
  3129. if (outside.has_value())
  3130. return {};
  3131. outside = outside_value.value();
  3132. continue;
  3133. }
  3134. }
  3135. // Not a display value, abort.
  3136. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized display value: `{}`", component_values[i].to_string());
  3137. return {};
  3138. }
  3139. // The spec does not allow any other inside values to be combined with list-item
  3140. // <display-outside>? && [ flow | flow-root ]? && list-item
  3141. if (list_item == Display::ListItem::Yes && inside.has_value() && inside != DisplayInside::Flow && inside != DisplayInside::FlowRoot)
  3142. return {};
  3143. return Display { outside.value_or(DisplayOutside::Block), inside.value_or(DisplayInside::Flow), list_item };
  3144. };
  3145. Optional<Display> display;
  3146. if (component_values.size() == 1)
  3147. display = parse_single_component_display(component_values);
  3148. else
  3149. display = parse_multi_component_display(component_values);
  3150. if (display.has_value())
  3151. return DisplayStyleValue::create(display.value());
  3152. return nullptr;
  3153. }
  3154. RefPtr<StyleValue> Parser::parse_filter_value_list_value(Vector<ComponentValue> const& component_values)
  3155. {
  3156. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  3157. auto ident = parse_identifier_value(component_values.first());
  3158. if (ident && ident->to_identifier() == ValueID::None)
  3159. return ident;
  3160. }
  3161. TokenStream tokens { component_values };
  3162. // FIXME: <url>s are ignored for now
  3163. // <filter-value-list> = [ <filter-function> | <url> ]+
  3164. enum class FilterToken {
  3165. // Color filters:
  3166. Brightness,
  3167. Contrast,
  3168. Grayscale,
  3169. Invert,
  3170. Opacity,
  3171. Saturate,
  3172. Sepia,
  3173. // Special filters:
  3174. Blur,
  3175. DropShadow,
  3176. HueRotate
  3177. };
  3178. auto filter_token_to_operation = [&](auto filter) {
  3179. VERIFY(to_underlying(filter) < to_underlying(FilterToken::Blur));
  3180. return static_cast<Filter::Color::Operation>(filter);
  3181. };
  3182. auto parse_number_percentage = [&](auto& token) -> Optional<NumberPercentage> {
  3183. if (token.is(Token::Type::Percentage))
  3184. return NumberPercentage(Percentage(token.token().percentage()));
  3185. if (token.is(Token::Type::Number))
  3186. return NumberPercentage(Number(Number::Type::Number, token.token().number_value()));
  3187. return {};
  3188. };
  3189. auto parse_filter_function_name = [&](auto name) -> Optional<FilterToken> {
  3190. if (name.equals_ignoring_ascii_case("blur"sv))
  3191. return FilterToken::Blur;
  3192. if (name.equals_ignoring_ascii_case("brightness"sv))
  3193. return FilterToken::Brightness;
  3194. if (name.equals_ignoring_ascii_case("contrast"sv))
  3195. return FilterToken::Contrast;
  3196. if (name.equals_ignoring_ascii_case("drop-shadow"sv))
  3197. return FilterToken::DropShadow;
  3198. if (name.equals_ignoring_ascii_case("grayscale"sv))
  3199. return FilterToken::Grayscale;
  3200. if (name.equals_ignoring_ascii_case("hue-rotate"sv))
  3201. return FilterToken::HueRotate;
  3202. if (name.equals_ignoring_ascii_case("invert"sv))
  3203. return FilterToken::Invert;
  3204. if (name.equals_ignoring_ascii_case("opacity"sv))
  3205. return FilterToken::Opacity;
  3206. if (name.equals_ignoring_ascii_case("saturate"sv))
  3207. return FilterToken::Saturate;
  3208. if (name.equals_ignoring_ascii_case("sepia"sv))
  3209. return FilterToken::Sepia;
  3210. return {};
  3211. };
  3212. auto parse_filter_function = [&](auto filter_token, auto function_values) -> Optional<FilterFunction> {
  3213. TokenStream tokens { function_values };
  3214. tokens.skip_whitespace();
  3215. auto if_no_more_tokens_return = [&](auto filter) -> Optional<FilterFunction> {
  3216. tokens.skip_whitespace();
  3217. if (tokens.has_next_token())
  3218. return {};
  3219. return filter;
  3220. };
  3221. if (filter_token == FilterToken::Blur) {
  3222. // blur( <length>? )
  3223. if (!tokens.has_next_token())
  3224. return Filter::Blur {};
  3225. auto blur_radius = parse_length(tokens.next_token());
  3226. if (!blur_radius.has_value())
  3227. return {};
  3228. return if_no_more_tokens_return(Filter::Blur { *blur_radius });
  3229. } else if (filter_token == FilterToken::DropShadow) {
  3230. if (!tokens.has_next_token())
  3231. return {};
  3232. auto next_token = [&]() -> auto& {
  3233. auto& token = tokens.next_token();
  3234. tokens.skip_whitespace();
  3235. return token;
  3236. };
  3237. // drop-shadow( [ <color>? && <length>{2,3} ] )
  3238. // Note: The following code is a little awkward to allow the color to be before or after the lengths.
  3239. auto& first_param = next_token();
  3240. Optional<Length> maybe_radius = {};
  3241. auto maybe_color = parse_color(first_param);
  3242. auto x_offset = parse_length(maybe_color.has_value() ? next_token() : first_param);
  3243. if (!x_offset.has_value() || !tokens.has_next_token()) {
  3244. return {};
  3245. }
  3246. auto y_offset = parse_length(next_token());
  3247. if (!y_offset.has_value()) {
  3248. return {};
  3249. }
  3250. if (tokens.has_next_token()) {
  3251. auto& token = next_token();
  3252. maybe_radius = parse_length(token);
  3253. if (!maybe_color.has_value() && (!maybe_radius.has_value() || tokens.has_next_token())) {
  3254. maybe_color = parse_color(!maybe_radius.has_value() ? token : next_token());
  3255. if (!maybe_color.has_value()) {
  3256. return {};
  3257. }
  3258. } else if (!maybe_radius.has_value()) {
  3259. return {};
  3260. }
  3261. }
  3262. return if_no_more_tokens_return(Filter::DropShadow { *x_offset, *y_offset, maybe_radius, maybe_color });
  3263. } else if (filter_token == FilterToken::HueRotate) {
  3264. // hue-rotate( [ <angle> | <zero> ]? )
  3265. if (!tokens.has_next_token())
  3266. return Filter::HueRotate {};
  3267. auto& token = tokens.next_token();
  3268. if (token.is(Token::Type::Number)) {
  3269. // hue-rotate(0)
  3270. auto number = token.token().number();
  3271. if (number.is_integer() && number.integer_value() == 0)
  3272. return if_no_more_tokens_return(Filter::HueRotate { Filter::HueRotate::Zero {} });
  3273. return {};
  3274. }
  3275. if (!token.is(Token::Type::Dimension))
  3276. return {};
  3277. auto angle_value = token.token().dimension_value();
  3278. auto angle_unit_name = token.token().dimension_unit();
  3279. auto angle_unit = Angle::unit_from_name(angle_unit_name);
  3280. if (!angle_unit.has_value())
  3281. return {};
  3282. Angle angle { angle_value, angle_unit.release_value() };
  3283. return if_no_more_tokens_return(Filter::HueRotate { angle });
  3284. } else {
  3285. // Simple filters:
  3286. // brightness( <number-percentage>? )
  3287. // contrast( <number-percentage>? )
  3288. // grayscale( <number-percentage>? )
  3289. // invert( <number-percentage>? )
  3290. // opacity( <number-percentage>? )
  3291. // sepia( <number-percentage>? )
  3292. // saturate( <number-percentage>? )
  3293. if (!tokens.has_next_token())
  3294. return Filter::Color { filter_token_to_operation(filter_token) };
  3295. auto amount = parse_number_percentage(tokens.next_token());
  3296. if (!amount.has_value())
  3297. return {};
  3298. return if_no_more_tokens_return(Filter::Color { filter_token_to_operation(filter_token), *amount });
  3299. }
  3300. };
  3301. Vector<FilterFunction> filter_value_list {};
  3302. while (tokens.has_next_token()) {
  3303. tokens.skip_whitespace();
  3304. if (!tokens.has_next_token())
  3305. break;
  3306. auto& token = tokens.next_token();
  3307. if (!token.is_function())
  3308. return nullptr;
  3309. auto filter_token = parse_filter_function_name(token.function().name());
  3310. if (!filter_token.has_value())
  3311. return nullptr;
  3312. auto filter_function = parse_filter_function(*filter_token, token.function().values());
  3313. if (!filter_function.has_value())
  3314. return nullptr;
  3315. filter_value_list.append(*filter_function);
  3316. }
  3317. if (filter_value_list.is_empty())
  3318. return nullptr;
  3319. return FilterValueListStyleValue::create(move(filter_value_list));
  3320. }
  3321. RefPtr<StyleValue> Parser::parse_flex_value(Vector<ComponentValue> const& component_values)
  3322. {
  3323. auto tokens = TokenStream { component_values };
  3324. auto make_flex_shorthand = [&](NonnullRefPtr<StyleValue> flex_grow, NonnullRefPtr<StyleValue> flex_shrink, NonnullRefPtr<StyleValue> flex_basis) {
  3325. return ShorthandStyleValue::create(PropertyID::Flex,
  3326. { PropertyID::FlexGrow, PropertyID::FlexShrink, PropertyID::FlexBasis },
  3327. { move(flex_grow), move(flex_shrink), move(flex_basis) });
  3328. };
  3329. if (component_values.size() == 1) {
  3330. // One-value syntax: <flex-grow> | <flex-basis> | none
  3331. auto properties = Array { PropertyID::FlexGrow, PropertyID::FlexBasis, PropertyID::Flex };
  3332. auto property_and_value = parse_css_value_for_properties(properties, tokens);
  3333. if (!property_and_value.has_value())
  3334. return nullptr;
  3335. auto& value = property_and_value->style_value;
  3336. switch (property_and_value->property) {
  3337. case PropertyID::FlexGrow: {
  3338. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  3339. // https://github.com/w3c/csswg-drafts/issues/5742
  3340. auto flex_basis = PercentageStyleValue::create(Percentage(0));
  3341. auto one = NumberStyleValue::create(1);
  3342. return make_flex_shorthand(*value, one, flex_basis);
  3343. }
  3344. case PropertyID::FlexBasis: {
  3345. auto one = NumberStyleValue::create(1);
  3346. return make_flex_shorthand(one, one, *value);
  3347. }
  3348. case PropertyID::Flex: {
  3349. if (value->is_identifier() && value->to_identifier() == ValueID::None) {
  3350. auto zero = NumberStyleValue::create(0);
  3351. return make_flex_shorthand(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  3352. }
  3353. break;
  3354. }
  3355. default:
  3356. VERIFY_NOT_REACHED();
  3357. }
  3358. return nullptr;
  3359. }
  3360. RefPtr<StyleValue> flex_grow;
  3361. RefPtr<StyleValue> flex_shrink;
  3362. RefPtr<StyleValue> flex_basis;
  3363. // NOTE: FlexGrow has to be before FlexBasis. `0` is a valid FlexBasis, but only
  3364. // if FlexGrow (along with optional FlexShrink) have already been specified.
  3365. auto remaining_longhands = Vector { PropertyID::FlexGrow, PropertyID::FlexBasis };
  3366. while (tokens.has_next_token()) {
  3367. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3368. if (!property_and_value.has_value())
  3369. return nullptr;
  3370. auto& value = property_and_value->style_value;
  3371. remove_property(remaining_longhands, property_and_value->property);
  3372. switch (property_and_value->property) {
  3373. case PropertyID::FlexGrow: {
  3374. VERIFY(!flex_grow);
  3375. flex_grow = value.release_nonnull();
  3376. // Flex-shrink may optionally follow directly after.
  3377. auto maybe_flex_shrink = parse_css_value_for_property(PropertyID::FlexShrink, tokens);
  3378. if (maybe_flex_shrink)
  3379. flex_shrink = maybe_flex_shrink.release_nonnull();
  3380. continue;
  3381. }
  3382. case PropertyID::FlexBasis: {
  3383. VERIFY(!flex_basis);
  3384. flex_basis = value.release_nonnull();
  3385. continue;
  3386. }
  3387. default:
  3388. VERIFY_NOT_REACHED();
  3389. }
  3390. }
  3391. if (!flex_grow)
  3392. flex_grow = property_initial_value(m_context.realm(), PropertyID::FlexGrow);
  3393. if (!flex_shrink)
  3394. flex_shrink = property_initial_value(m_context.realm(), PropertyID::FlexShrink);
  3395. if (!flex_basis) {
  3396. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  3397. // https://github.com/w3c/csswg-drafts/issues/5742
  3398. flex_basis = PercentageStyleValue::create(Percentage(0));
  3399. }
  3400. return make_flex_shorthand(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  3401. }
  3402. RefPtr<StyleValue> Parser::parse_flex_flow_value(Vector<ComponentValue> const& component_values)
  3403. {
  3404. if (component_values.size() > 2)
  3405. return nullptr;
  3406. RefPtr<StyleValue> flex_direction;
  3407. RefPtr<StyleValue> flex_wrap;
  3408. auto remaining_longhands = Vector { PropertyID::FlexDirection, PropertyID::FlexWrap };
  3409. auto tokens = TokenStream { component_values };
  3410. while (tokens.has_next_token()) {
  3411. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3412. if (!property_and_value.has_value())
  3413. return nullptr;
  3414. auto& value = property_and_value->style_value;
  3415. remove_property(remaining_longhands, property_and_value->property);
  3416. switch (property_and_value->property) {
  3417. case PropertyID::FlexDirection:
  3418. VERIFY(!flex_direction);
  3419. flex_direction = value.release_nonnull();
  3420. continue;
  3421. case PropertyID::FlexWrap:
  3422. VERIFY(!flex_wrap);
  3423. flex_wrap = value.release_nonnull();
  3424. continue;
  3425. default:
  3426. VERIFY_NOT_REACHED();
  3427. }
  3428. }
  3429. if (!flex_direction)
  3430. flex_direction = property_initial_value(m_context.realm(), PropertyID::FlexDirection);
  3431. if (!flex_wrap)
  3432. flex_wrap = property_initial_value(m_context.realm(), PropertyID::FlexWrap);
  3433. return ShorthandStyleValue::create(PropertyID::FlexFlow,
  3434. { PropertyID::FlexDirection, PropertyID::FlexWrap },
  3435. { flex_direction.release_nonnull(), flex_wrap.release_nonnull() });
  3436. }
  3437. static bool is_generic_font_family(ValueID identifier)
  3438. {
  3439. switch (identifier) {
  3440. case ValueID::Cursive:
  3441. case ValueID::Fantasy:
  3442. case ValueID::Monospace:
  3443. case ValueID::Serif:
  3444. case ValueID::SansSerif:
  3445. case ValueID::UiMonospace:
  3446. case ValueID::UiRounded:
  3447. case ValueID::UiSerif:
  3448. case ValueID::UiSansSerif:
  3449. return true;
  3450. default:
  3451. return false;
  3452. }
  3453. }
  3454. RefPtr<StyleValue> Parser::parse_font_value(Vector<ComponentValue> const& component_values)
  3455. {
  3456. RefPtr<StyleValue> font_stretch;
  3457. RefPtr<StyleValue> font_style;
  3458. RefPtr<StyleValue> font_weight;
  3459. RefPtr<StyleValue> font_size;
  3460. RefPtr<StyleValue> line_height;
  3461. RefPtr<StyleValue> font_families;
  3462. RefPtr<StyleValue> font_variant;
  3463. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  3464. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  3465. // So, we have to handle that separately.
  3466. int normal_count = 0;
  3467. auto tokens = TokenStream { component_values };
  3468. auto remaining_longhands = Vector { PropertyID::FontSize, PropertyID::FontStretch, PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight };
  3469. while (tokens.has_next_token()) {
  3470. auto& peek_token = tokens.peek_token();
  3471. if (peek_token.is(Token::Type::Ident) && value_id_from_string(peek_token.token().ident()) == ValueID::Normal) {
  3472. normal_count++;
  3473. (void)tokens.next_token();
  3474. continue;
  3475. }
  3476. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3477. if (!property_and_value.has_value())
  3478. return nullptr;
  3479. auto& value = property_and_value->style_value;
  3480. remove_property(remaining_longhands, property_and_value->property);
  3481. switch (property_and_value->property) {
  3482. case PropertyID::FontSize: {
  3483. VERIFY(!font_size);
  3484. font_size = value.release_nonnull();
  3485. // Consume `/ line-height` if present
  3486. if (tokens.peek_token().is_delim('/')) {
  3487. (void)tokens.next_token();
  3488. auto maybe_line_height = parse_css_value_for_property(PropertyID::LineHeight, tokens);
  3489. if (!maybe_line_height)
  3490. return nullptr;
  3491. line_height = maybe_line_height.release_nonnull();
  3492. }
  3493. // Consume font-families
  3494. auto maybe_font_families = parse_font_family_value(tokens);
  3495. // font-family comes last, so we must not have any tokens left over.
  3496. if (!maybe_font_families || tokens.has_next_token())
  3497. return nullptr;
  3498. font_families = maybe_font_families.release_nonnull();
  3499. continue;
  3500. }
  3501. case PropertyID::FontStretch: {
  3502. VERIFY(!font_stretch);
  3503. font_stretch = value.release_nonnull();
  3504. continue;
  3505. }
  3506. case PropertyID::FontStyle: {
  3507. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  3508. VERIFY(!font_style);
  3509. font_style = value.release_nonnull();
  3510. continue;
  3511. }
  3512. case PropertyID::FontVariant: {
  3513. VERIFY(!font_variant);
  3514. font_variant = value.release_nonnull();
  3515. continue;
  3516. }
  3517. case PropertyID::FontWeight: {
  3518. VERIFY(!font_weight);
  3519. font_weight = value.release_nonnull();
  3520. continue;
  3521. }
  3522. default:
  3523. VERIFY_NOT_REACHED();
  3524. }
  3525. return nullptr;
  3526. }
  3527. // Since normal is the default value for all the properties that can have it, we don't have to actually
  3528. // set anything to normal here. It'll be set when we create the ShorthandStyleValue below.
  3529. // We just need to make sure we were not given more normals than will fit.
  3530. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1) + (font_variant ? 0 : 1) + (font_stretch ? 0 : 1);
  3531. if (unset_value_count < normal_count)
  3532. return nullptr;
  3533. if (!font_size || !font_families)
  3534. return nullptr;
  3535. if (!font_style)
  3536. font_style = property_initial_value(m_context.realm(), PropertyID::FontStyle);
  3537. if (!font_variant)
  3538. font_variant = property_initial_value(m_context.realm(), PropertyID::FontVariant);
  3539. if (!font_weight)
  3540. font_weight = property_initial_value(m_context.realm(), PropertyID::FontWeight);
  3541. if (!font_stretch)
  3542. font_stretch = property_initial_value(m_context.realm(), PropertyID::FontStretch);
  3543. if (!line_height)
  3544. line_height = property_initial_value(m_context.realm(), PropertyID::LineHeight);
  3545. return ShorthandStyleValue::create(PropertyID::Font,
  3546. { PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight, PropertyID::FontStretch, PropertyID::FontSize, PropertyID::LineHeight, PropertyID::FontFamily },
  3547. { 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() });
  3548. }
  3549. RefPtr<StyleValue> Parser::parse_font_family_value(TokenStream<ComponentValue>& tokens)
  3550. {
  3551. auto next_is_comma_or_eof = [&]() -> bool {
  3552. return !tokens.has_next_token() || tokens.peek_token().is(Token::Type::Comma);
  3553. };
  3554. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  3555. // eg, these are equivalent:
  3556. // font-family: my cool font\!, serif;
  3557. // font-family: "my cool font!", serif;
  3558. StyleValueVector font_families;
  3559. Vector<DeprecatedString> current_name_parts;
  3560. while (tokens.has_next_token()) {
  3561. auto const& peek = tokens.peek_token();
  3562. if (peek.is(Token::Type::String)) {
  3563. // `font-family: my cool "font";` is invalid.
  3564. if (!current_name_parts.is_empty())
  3565. return nullptr;
  3566. (void)tokens.next_token(); // String
  3567. if (!next_is_comma_or_eof())
  3568. return nullptr;
  3569. font_families.append(StringStyleValue::create(MUST(String::from_utf8(peek.token().string()))));
  3570. (void)tokens.next_token(); // Comma
  3571. continue;
  3572. }
  3573. if (peek.is(Token::Type::Ident)) {
  3574. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  3575. // CSS-wide keywords are not allowed
  3576. if (auto builtin = parse_builtin_value(peek))
  3577. return nullptr;
  3578. auto maybe_ident = value_id_from_string(peek.token().ident());
  3579. // Can't have a generic-font-name as a token in an unquoted font name.
  3580. if (maybe_ident.has_value() && is_generic_font_family(maybe_ident.value())) {
  3581. if (!current_name_parts.is_empty())
  3582. return nullptr;
  3583. (void)tokens.next_token(); // Ident
  3584. if (!next_is_comma_or_eof())
  3585. return nullptr;
  3586. font_families.append(IdentifierStyleValue::create(maybe_ident.value()));
  3587. (void)tokens.next_token(); // Comma
  3588. continue;
  3589. }
  3590. current_name_parts.append(tokens.next_token().token().ident().bytes_as_string_view());
  3591. continue;
  3592. }
  3593. if (peek.is(Token::Type::Comma)) {
  3594. if (current_name_parts.is_empty())
  3595. return nullptr;
  3596. (void)tokens.next_token(); // Comma
  3597. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  3598. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  3599. current_name_parts.clear();
  3600. // Can't have a trailing comma
  3601. if (!tokens.has_next_token())
  3602. return nullptr;
  3603. continue;
  3604. }
  3605. return nullptr;
  3606. }
  3607. if (!current_name_parts.is_empty()) {
  3608. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  3609. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  3610. current_name_parts.clear();
  3611. }
  3612. if (font_families.is_empty())
  3613. return nullptr;
  3614. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  3615. }
  3616. CSSRule* Parser::parse_font_face_rule(TokenStream<ComponentValue>& tokens)
  3617. {
  3618. auto declarations_and_at_rules = parse_a_list_of_declarations(tokens);
  3619. Optional<FlyString> font_family;
  3620. Vector<FontFace::Source> src;
  3621. Vector<UnicodeRange> unicode_range;
  3622. Optional<int> weight;
  3623. Optional<int> slope;
  3624. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  3625. if (declaration_or_at_rule.is_at_rule()) {
  3626. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: CSS at-rules are not allowed in @font-face; discarding.");
  3627. continue;
  3628. }
  3629. auto const& declaration = declaration_or_at_rule.declaration();
  3630. if (declaration.name().equals_ignoring_ascii_case("font-weight"sv)) {
  3631. TokenStream token_stream { declaration.values() };
  3632. if (auto value = parse_css_value(CSS::PropertyID::FontWeight, token_stream); !value.is_error()) {
  3633. weight = value.value()->to_font_weight();
  3634. }
  3635. continue;
  3636. }
  3637. if (declaration.name().equals_ignoring_ascii_case("font-style"sv)) {
  3638. TokenStream token_stream { declaration.values() };
  3639. if (auto value = parse_css_value(CSS::PropertyID::FontStyle, token_stream); !value.is_error()) {
  3640. slope = value.value()->to_font_slope();
  3641. }
  3642. continue;
  3643. }
  3644. if (declaration.name().equals_ignoring_ascii_case("font-family"sv)) {
  3645. // FIXME: This is very similar to, but different from, the logic in parse_font_family_value().
  3646. // Ideally they could share code.
  3647. Vector<DeprecatedString> font_family_parts;
  3648. bool had_syntax_error = false;
  3649. for (size_t i = 0; i < declaration.values().size(); ++i) {
  3650. auto const& part = declaration.values()[i];
  3651. if (part.is(Token::Type::Whitespace))
  3652. continue;
  3653. if (part.is(Token::Type::String)) {
  3654. if (!font_family_parts.is_empty()) {
  3655. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3656. had_syntax_error = true;
  3657. break;
  3658. }
  3659. font_family_parts.append(part.token().string());
  3660. continue;
  3661. }
  3662. if (part.is(Token::Type::Ident)) {
  3663. if (is_css_wide_keyword(part.token().ident())) {
  3664. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3665. had_syntax_error = true;
  3666. break;
  3667. }
  3668. auto value_id = value_id_from_string(part.token().ident());
  3669. if (value_id.has_value() && is_generic_font_family(value_id.value())) {
  3670. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3671. had_syntax_error = true;
  3672. break;
  3673. }
  3674. font_family_parts.append(part.token().ident().bytes_as_string_view());
  3675. continue;
  3676. }
  3677. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3678. had_syntax_error = true;
  3679. break;
  3680. }
  3681. if (had_syntax_error || font_family_parts.is_empty())
  3682. continue;
  3683. font_family = String::join(' ', font_family_parts).release_value_but_fixme_should_propagate_errors();
  3684. continue;
  3685. }
  3686. if (declaration.name().equals_ignoring_ascii_case("src"sv)) {
  3687. TokenStream token_stream { declaration.values() };
  3688. Vector<FontFace::Source> supported_sources = parse_font_face_src(token_stream);
  3689. if (!supported_sources.is_empty())
  3690. src = move(supported_sources);
  3691. continue;
  3692. }
  3693. if (declaration.name().equals_ignoring_ascii_case("unicode-range"sv)) {
  3694. Vector<UnicodeRange> unicode_ranges;
  3695. bool unicode_range_invalid = false;
  3696. TokenStream all_tokens { declaration.values() };
  3697. auto range_token_lists = parse_a_comma_separated_list_of_component_values(all_tokens);
  3698. for (auto& range_tokens : range_token_lists) {
  3699. TokenStream range_token_stream { range_tokens };
  3700. auto maybe_unicode_range = parse_unicode_range(range_token_stream);
  3701. if (!maybe_unicode_range.has_value()) {
  3702. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face unicode-range format invalid; discarding.");
  3703. unicode_range_invalid = true;
  3704. break;
  3705. }
  3706. unicode_ranges.append(maybe_unicode_range.release_value());
  3707. }
  3708. if (unicode_range_invalid || unicode_ranges.is_empty())
  3709. continue;
  3710. unicode_range = move(unicode_ranges);
  3711. continue;
  3712. }
  3713. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unrecognized descriptor '{}' in @font-face; discarding.", declaration.name());
  3714. }
  3715. if (!font_family.has_value()) {
  3716. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face: no font-family!");
  3717. return {};
  3718. }
  3719. if (unicode_range.is_empty()) {
  3720. unicode_range.empend(0x0u, 0x10FFFFu);
  3721. }
  3722. return CSSFontFaceRule::create(m_context.realm(), FontFace { font_family.release_value(), weight, slope, move(src), move(unicode_range) });
  3723. }
  3724. Vector<FontFace::Source> Parser::parse_font_face_src(TokenStream<ComponentValue>& component_values)
  3725. {
  3726. // FIXME: Get this information from the system somehow?
  3727. // Format-name table: https://www.w3.org/TR/css-fonts-4/#font-format-definitions
  3728. auto font_format_is_supported = [](StringView name) {
  3729. // The spec requires us to treat opentype and truetype as synonymous.
  3730. if (name.is_one_of_ignoring_ascii_case("opentype"sv, "truetype"sv, "woff"sv, "woff2"sv))
  3731. return true;
  3732. return false;
  3733. };
  3734. Vector<FontFace::Source> supported_sources;
  3735. auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(component_values);
  3736. for (auto const& source_token_list : list_of_source_token_lists) {
  3737. TokenStream source_tokens { source_token_list };
  3738. source_tokens.skip_whitespace();
  3739. auto const& first = source_tokens.next_token();
  3740. // <url> [ format(<font-format>)]?
  3741. // FIXME: Implement optional tech() function from CSS-Fonts-4.
  3742. if (auto maybe_url = parse_url_function(first); maybe_url.has_value()) {
  3743. auto url = maybe_url.release_value();
  3744. if (!url.is_valid()) {
  3745. continue;
  3746. }
  3747. Optional<FlyString> format;
  3748. source_tokens.skip_whitespace();
  3749. if (!source_tokens.has_next_token()) {
  3750. supported_sources.empend(move(url), format);
  3751. continue;
  3752. }
  3753. auto maybe_function = source_tokens.next_token();
  3754. if (!maybe_function.is_function()) {
  3755. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (token after `url()` that isn't a function: {}); discarding.", maybe_function.to_debug_string());
  3756. return {};
  3757. }
  3758. auto const& function = maybe_function.function();
  3759. if (function.name().equals_ignoring_ascii_case("format"sv)) {
  3760. TokenStream format_tokens { function.values() };
  3761. format_tokens.skip_whitespace();
  3762. auto const& format_name_token = format_tokens.next_token();
  3763. StringView format_name;
  3764. if (format_name_token.is(Token::Type::Ident)) {
  3765. format_name = format_name_token.token().ident();
  3766. } else if (format_name_token.is(Token::Type::String)) {
  3767. format_name = format_name_token.token().string();
  3768. } else {
  3769. 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());
  3770. return {};
  3771. }
  3772. if (!font_format_is_supported(format_name)) {
  3773. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format({}) not supported; skipping.", format_name);
  3774. continue;
  3775. }
  3776. format = FlyString::from_utf8(format_name).release_value_but_fixme_should_propagate_errors();
  3777. } else {
  3778. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (unrecognized function token `{}`); discarding.", function.name());
  3779. return {};
  3780. }
  3781. source_tokens.skip_whitespace();
  3782. if (source_tokens.has_next_token()) {
  3783. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (extra token `{}`); discarding.", source_tokens.peek_token().to_debug_string());
  3784. return {};
  3785. }
  3786. supported_sources.empend(move(url), format);
  3787. continue;
  3788. }
  3789. if (first.is_function() && first.function().name().equals_ignoring_ascii_case("local"sv)) {
  3790. if (first.function().values().is_empty()) {
  3791. continue;
  3792. }
  3793. supported_sources.empend(first.function().values().first().to_string(), Optional<FlyString> {});
  3794. continue;
  3795. }
  3796. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (failed to parse url from: {}); discarding.", first.to_debug_string());
  3797. return {};
  3798. }
  3799. return supported_sources;
  3800. }
  3801. RefPtr<StyleValue> Parser::parse_list_style_value(Vector<ComponentValue> const& component_values)
  3802. {
  3803. if (component_values.size() > 3)
  3804. return nullptr;
  3805. RefPtr<StyleValue> list_position;
  3806. RefPtr<StyleValue> list_image;
  3807. RefPtr<StyleValue> list_type;
  3808. int found_nones = 0;
  3809. Vector<PropertyID> remaining_longhands { PropertyID::ListStyleImage, PropertyID::ListStylePosition, PropertyID::ListStyleType };
  3810. auto tokens = TokenStream { component_values };
  3811. while (tokens.has_next_token()) {
  3812. if (auto peek = tokens.peek_token(); peek.is(Token::Type::Ident) && peek.token().ident().equals_ignoring_ascii_case("none"sv)) {
  3813. (void)tokens.next_token();
  3814. found_nones++;
  3815. continue;
  3816. }
  3817. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3818. if (!property_and_value.has_value())
  3819. return nullptr;
  3820. auto& value = property_and_value->style_value;
  3821. remove_property(remaining_longhands, property_and_value->property);
  3822. switch (property_and_value->property) {
  3823. case PropertyID::ListStylePosition: {
  3824. VERIFY(!list_position);
  3825. list_position = value.release_nonnull();
  3826. continue;
  3827. }
  3828. case PropertyID::ListStyleImage: {
  3829. VERIFY(!list_image);
  3830. list_image = value.release_nonnull();
  3831. continue;
  3832. }
  3833. case PropertyID::ListStyleType: {
  3834. VERIFY(!list_type);
  3835. list_type = value.release_nonnull();
  3836. continue;
  3837. }
  3838. default:
  3839. VERIFY_NOT_REACHED();
  3840. }
  3841. }
  3842. if (found_nones > 2)
  3843. return nullptr;
  3844. if (found_nones == 2) {
  3845. if (list_image || list_type)
  3846. return nullptr;
  3847. auto none = IdentifierStyleValue::create(ValueID::None);
  3848. list_image = none;
  3849. list_type = none;
  3850. } else if (found_nones == 1) {
  3851. if (list_image && list_type)
  3852. return nullptr;
  3853. auto none = IdentifierStyleValue::create(ValueID::None);
  3854. if (!list_image)
  3855. list_image = none;
  3856. if (!list_type)
  3857. list_type = none;
  3858. }
  3859. if (!list_position)
  3860. list_position = property_initial_value(m_context.realm(), PropertyID::ListStylePosition);
  3861. if (!list_image)
  3862. list_image = property_initial_value(m_context.realm(), PropertyID::ListStyleImage);
  3863. if (!list_type)
  3864. list_type = property_initial_value(m_context.realm(), PropertyID::ListStyleType);
  3865. return ShorthandStyleValue::create(PropertyID::ListStyle,
  3866. { PropertyID::ListStylePosition, PropertyID::ListStyleImage, PropertyID::ListStyleType },
  3867. { list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull() });
  3868. }
  3869. RefPtr<StyleValue> Parser::parse_math_depth_value(Vector<ComponentValue> const& component_values)
  3870. {
  3871. // https://w3c.github.io/mathml-core/#propdef-math-depth
  3872. // auto-add | add(<integer>) | <integer>
  3873. auto tokens = TokenStream { component_values };
  3874. tokens.skip_whitespace();
  3875. auto token = tokens.next_token();
  3876. tokens.skip_whitespace();
  3877. if (tokens.has_next_token())
  3878. return nullptr;
  3879. // auto-add
  3880. if (token.is_ident("auto-add"sv))
  3881. return MathDepthStyleValue::create_auto_add();
  3882. // FIXME: Make it easier to parse "thing that might be <bar> or literally anything that resolves to it" and get rid of this
  3883. auto parse_something_that_resolves_to_integer = [this](ComponentValue& token) -> RefPtr<StyleValue> {
  3884. if (token.is(Token::Type::Number) && token.token().number().is_integer())
  3885. return IntegerStyleValue::create(token.token().to_integer());
  3886. if (auto value = parse_calculated_value(token); value && value->resolves_to_number())
  3887. return value;
  3888. return nullptr;
  3889. };
  3890. // add(<integer>)
  3891. if (token.is_function("add"sv)) {
  3892. auto add_tokens = TokenStream { token.function().values() };
  3893. add_tokens.skip_whitespace();
  3894. auto integer_token = add_tokens.next_token();
  3895. add_tokens.skip_whitespace();
  3896. if (add_tokens.has_next_token())
  3897. return nullptr;
  3898. if (auto integer_value = parse_something_that_resolves_to_integer(integer_token))
  3899. return MathDepthStyleValue::create_add(integer_value.release_nonnull());
  3900. return nullptr;
  3901. }
  3902. // <integer>
  3903. if (auto integer_value = parse_something_that_resolves_to_integer(token))
  3904. return MathDepthStyleValue::create_integer(integer_value.release_nonnull());
  3905. return nullptr;
  3906. }
  3907. RefPtr<StyleValue> Parser::parse_overflow_value(Vector<ComponentValue> const& component_values)
  3908. {
  3909. auto tokens = TokenStream { component_values };
  3910. if (component_values.size() == 1) {
  3911. auto maybe_value = parse_css_value_for_property(PropertyID::Overflow, tokens);
  3912. if (!maybe_value)
  3913. return nullptr;
  3914. return ShorthandStyleValue::create(PropertyID::Overflow,
  3915. { PropertyID::OverflowX, PropertyID::OverflowY },
  3916. { *maybe_value, *maybe_value });
  3917. }
  3918. if (component_values.size() == 2) {
  3919. auto maybe_x_value = parse_css_value_for_property(PropertyID::OverflowX, tokens);
  3920. auto maybe_y_value = parse_css_value_for_property(PropertyID::OverflowY, tokens);
  3921. if (!maybe_x_value || !maybe_y_value)
  3922. return nullptr;
  3923. return ShorthandStyleValue::create(PropertyID::Overflow,
  3924. { PropertyID::OverflowX, PropertyID::OverflowY },
  3925. { maybe_x_value.release_nonnull(), maybe_y_value.release_nonnull() });
  3926. }
  3927. return nullptr;
  3928. }
  3929. RefPtr<StyleValue> Parser::parse_place_content_value(Vector<ComponentValue> const& component_values)
  3930. {
  3931. if (component_values.size() > 2)
  3932. return nullptr;
  3933. auto tokens = TokenStream { component_values };
  3934. auto maybe_align_content_value = parse_css_value_for_property(PropertyID::AlignContent, tokens);
  3935. if (!maybe_align_content_value)
  3936. return nullptr;
  3937. if (component_values.size() == 1) {
  3938. if (!property_accepts_identifier(PropertyID::JustifyContent, maybe_align_content_value->to_identifier()))
  3939. return nullptr;
  3940. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  3941. { PropertyID::AlignContent, PropertyID::JustifyContent },
  3942. { *maybe_align_content_value, *maybe_align_content_value });
  3943. }
  3944. auto maybe_justify_content_value = parse_css_value_for_property(PropertyID::JustifyContent, tokens);
  3945. if (!maybe_justify_content_value)
  3946. return nullptr;
  3947. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  3948. { PropertyID::AlignContent, PropertyID::JustifyContent },
  3949. { maybe_align_content_value.release_nonnull(), maybe_justify_content_value.release_nonnull() });
  3950. }
  3951. RefPtr<StyleValue> Parser::parse_place_items_value(Vector<ComponentValue> const& component_values)
  3952. {
  3953. auto tokens = TokenStream { component_values };
  3954. auto maybe_align_items_value = parse_css_value_for_property(PropertyID::AlignItems, tokens);
  3955. if (!maybe_align_items_value)
  3956. return nullptr;
  3957. if (component_values.size() == 1) {
  3958. if (!property_accepts_identifier(PropertyID::JustifyItems, maybe_align_items_value->to_identifier()))
  3959. return nullptr;
  3960. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  3961. { PropertyID::AlignItems, PropertyID::JustifyItems },
  3962. { *maybe_align_items_value, *maybe_align_items_value });
  3963. }
  3964. auto maybe_justify_items_value = parse_css_value_for_property(PropertyID::JustifyItems, tokens);
  3965. if (!maybe_justify_items_value)
  3966. return nullptr;
  3967. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  3968. { PropertyID::AlignItems, PropertyID::JustifyItems },
  3969. { *maybe_align_items_value, *maybe_justify_items_value });
  3970. }
  3971. RefPtr<StyleValue> Parser::parse_place_self_value(Vector<ComponentValue> const& component_values)
  3972. {
  3973. auto tokens = TokenStream { component_values };
  3974. auto maybe_align_self_value = parse_css_value_for_property(PropertyID::AlignSelf, tokens);
  3975. if (!maybe_align_self_value)
  3976. return nullptr;
  3977. if (component_values.size() == 1) {
  3978. if (!property_accepts_identifier(PropertyID::JustifySelf, maybe_align_self_value->to_identifier()))
  3979. return nullptr;
  3980. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  3981. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  3982. { *maybe_align_self_value, *maybe_align_self_value });
  3983. }
  3984. auto maybe_justify_self_value = parse_css_value_for_property(PropertyID::JustifySelf, tokens);
  3985. if (!maybe_justify_self_value)
  3986. return nullptr;
  3987. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  3988. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  3989. { *maybe_align_self_value, *maybe_justify_self_value });
  3990. }
  3991. RefPtr<StyleValue> Parser::parse_quotes_value(Vector<ComponentValue> const& component_values)
  3992. {
  3993. // https://www.w3.org/TR/css-content-3/#quotes-property
  3994. // auto | none | [ <string> <string> ]+
  3995. if (component_values.size() == 1) {
  3996. auto identifier = parse_identifier_value(component_values.first());
  3997. if (identifier && property_accepts_identifier(PropertyID::Quotes, identifier->to_identifier()))
  3998. return identifier;
  3999. return nullptr;
  4000. }
  4001. // Parse an even number of <string> values.
  4002. if (component_values.size() % 2 != 0)
  4003. return nullptr;
  4004. auto tokens = TokenStream { component_values };
  4005. StyleValueVector string_values;
  4006. while (tokens.has_next_token()) {
  4007. auto maybe_string = parse_string_value(tokens.next_token());
  4008. if (!maybe_string)
  4009. return nullptr;
  4010. string_values.append(maybe_string.release_nonnull());
  4011. }
  4012. return StyleValueList::create(move(string_values), StyleValueList::Separator::Space);
  4013. }
  4014. RefPtr<StyleValue> Parser::parse_text_decoration_value(Vector<ComponentValue> const& component_values)
  4015. {
  4016. RefPtr<StyleValue> decoration_line;
  4017. RefPtr<StyleValue> decoration_thickness;
  4018. RefPtr<StyleValue> decoration_style;
  4019. RefPtr<StyleValue> decoration_color;
  4020. auto remaining_longhands = Vector { PropertyID::TextDecorationColor, PropertyID::TextDecorationLine, PropertyID::TextDecorationStyle, PropertyID::TextDecorationThickness };
  4021. auto tokens = TokenStream { component_values };
  4022. while (tokens.has_next_token()) {
  4023. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4024. if (!property_and_value.has_value())
  4025. return nullptr;
  4026. auto& value = property_and_value->style_value;
  4027. remove_property(remaining_longhands, property_and_value->property);
  4028. switch (property_and_value->property) {
  4029. case PropertyID::TextDecorationColor: {
  4030. VERIFY(!decoration_color);
  4031. decoration_color = value.release_nonnull();
  4032. continue;
  4033. }
  4034. case PropertyID::TextDecorationLine: {
  4035. VERIFY(!decoration_line);
  4036. tokens.reconsume_current_input_token();
  4037. auto parsed_decoration_line = parse_text_decoration_line_value(tokens);
  4038. if (!parsed_decoration_line)
  4039. return nullptr;
  4040. decoration_line = parsed_decoration_line.release_nonnull();
  4041. continue;
  4042. }
  4043. case PropertyID::TextDecorationThickness: {
  4044. VERIFY(!decoration_thickness);
  4045. decoration_thickness = value.release_nonnull();
  4046. continue;
  4047. }
  4048. case PropertyID::TextDecorationStyle: {
  4049. VERIFY(!decoration_style);
  4050. decoration_style = value.release_nonnull();
  4051. continue;
  4052. }
  4053. default:
  4054. VERIFY_NOT_REACHED();
  4055. }
  4056. }
  4057. if (!decoration_line)
  4058. decoration_line = property_initial_value(m_context.realm(), PropertyID::TextDecorationLine);
  4059. if (!decoration_thickness)
  4060. decoration_thickness = property_initial_value(m_context.realm(), PropertyID::TextDecorationThickness);
  4061. if (!decoration_style)
  4062. decoration_style = property_initial_value(m_context.realm(), PropertyID::TextDecorationStyle);
  4063. if (!decoration_color)
  4064. decoration_color = property_initial_value(m_context.realm(), PropertyID::TextDecorationColor);
  4065. return ShorthandStyleValue::create(PropertyID::TextDecoration,
  4066. { PropertyID::TextDecorationLine, PropertyID::TextDecorationThickness, PropertyID::TextDecorationStyle, PropertyID::TextDecorationColor },
  4067. { decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull() });
  4068. }
  4069. RefPtr<StyleValue> Parser::parse_text_decoration_line_value(TokenStream<ComponentValue>& tokens)
  4070. {
  4071. StyleValueVector style_values;
  4072. while (tokens.has_next_token()) {
  4073. auto maybe_value = parse_css_value_for_property(PropertyID::TextDecorationLine, tokens);
  4074. if (!maybe_value)
  4075. break;
  4076. auto value = maybe_value.release_nonnull();
  4077. if (auto maybe_line = value_id_to_text_decoration_line(value->to_identifier()); maybe_line.has_value()) {
  4078. if (maybe_line == TextDecorationLine::None) {
  4079. if (!style_values.is_empty())
  4080. break;
  4081. return value;
  4082. }
  4083. if (style_values.contains_slow(value))
  4084. break;
  4085. style_values.append(move(value));
  4086. continue;
  4087. }
  4088. break;
  4089. }
  4090. if (style_values.is_empty())
  4091. return nullptr;
  4092. return StyleValueList::create(move(style_values), StyleValueList::Separator::Space);
  4093. }
  4094. RefPtr<StyleValue> Parser::parse_easing_value(TokenStream<ComponentValue>& tokens)
  4095. {
  4096. auto transaction = tokens.begin_transaction();
  4097. tokens.skip_whitespace();
  4098. auto const& part = tokens.next_token();
  4099. StringView name;
  4100. Optional<Vector<ComponentValue> const&> arguments;
  4101. if (part.is(Token::Type::Ident)) {
  4102. name = part.token().ident();
  4103. } else if (part.is_function()) {
  4104. name = part.function().name();
  4105. arguments = part.function().values();
  4106. } else {
  4107. return nullptr;
  4108. }
  4109. auto maybe_function = easing_function_from_string(name);
  4110. if (!maybe_function.has_value())
  4111. return nullptr;
  4112. auto function = maybe_function.release_value();
  4113. auto function_metadata = easing_function_metadata(function);
  4114. if (function_metadata.parameters.is_empty() && arguments.has_value()) {
  4115. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: 0", name);
  4116. return nullptr;
  4117. }
  4118. StyleValueVector values;
  4119. size_t argument_index = 0;
  4120. if (arguments.has_value()) {
  4121. auto argument_tokens = TokenStream { *arguments };
  4122. auto arguments_values = parse_a_comma_separated_list_of_component_values(argument_tokens);
  4123. if (arguments_values.size() > function_metadata.parameters.size()) {
  4124. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", name, function_metadata.parameters.size());
  4125. return nullptr;
  4126. }
  4127. for (auto& argument_values : arguments_values) {
  4128. // Prune any whitespace before and after the actual argument values.
  4129. argument_values.remove_all_matching([](auto& value) { return value.is(Token::Type::Whitespace); });
  4130. if (argument_values.size() != 1) {
  4131. dbgln_if(CSS_PARSER_DEBUG, "Too many values in argument to {}. max: 1", name);
  4132. return nullptr;
  4133. }
  4134. auto& value = argument_values[0];
  4135. switch (function_metadata.parameters[argument_index].type) {
  4136. case EasingFunctionParameterType::Number: {
  4137. if (value.is(Token::Type::Number))
  4138. values.append(NumberStyleValue::create(value.token().number().value()));
  4139. else
  4140. return nullptr;
  4141. break;
  4142. }
  4143. case EasingFunctionParameterType::NumberZeroToOne: {
  4144. if (value.is(Token::Type::Number) && value.token().number_value() >= 0 && value.token().number_value() <= 1)
  4145. values.append(NumberStyleValue::create(value.token().number().value()));
  4146. else
  4147. return nullptr;
  4148. break;
  4149. }
  4150. case EasingFunctionParameterType::Integer: {
  4151. if (value.is(Token::Type::Number) && value.token().number().is_integer())
  4152. values.append(IntegerStyleValue::create(value.token().number().integer_value()));
  4153. else
  4154. return nullptr;
  4155. break;
  4156. }
  4157. case EasingFunctionParameterType::StepPosition: {
  4158. if (!value.is(Token::Type::Ident))
  4159. return nullptr;
  4160. auto ident = parse_identifier_value(value);
  4161. if (!ident)
  4162. return nullptr;
  4163. switch (ident->to_identifier()) {
  4164. case ValueID::JumpStart:
  4165. case ValueID::JumpEnd:
  4166. case ValueID::JumpNone:
  4167. case ValueID::Start:
  4168. case ValueID::End:
  4169. values.append(*ident);
  4170. break;
  4171. default:
  4172. return nullptr;
  4173. }
  4174. }
  4175. }
  4176. ++argument_index;
  4177. }
  4178. }
  4179. if (argument_index < function_metadata.parameters.size() && !function_metadata.parameters[argument_index].is_optional) {
  4180. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
  4181. return nullptr;
  4182. }
  4183. transaction.commit();
  4184. return EasingStyleValue::create(function, move(values));
  4185. }
  4186. RefPtr<StyleValue> Parser::parse_transform_value(Vector<ComponentValue> const& component_values)
  4187. {
  4188. StyleValueVector transformations;
  4189. auto tokens = TokenStream { component_values };
  4190. tokens.skip_whitespace();
  4191. while (tokens.has_next_token()) {
  4192. tokens.skip_whitespace();
  4193. auto const& part = tokens.next_token();
  4194. if (part.is(Token::Type::Ident) && part.token().ident().equals_ignoring_ascii_case("none"sv)) {
  4195. if (!transformations.is_empty())
  4196. return nullptr;
  4197. tokens.skip_whitespace();
  4198. if (tokens.has_next_token())
  4199. return nullptr;
  4200. return IdentifierStyleValue::create(ValueID::None);
  4201. }
  4202. if (!part.is_function())
  4203. return nullptr;
  4204. auto maybe_function = transform_function_from_string(part.function().name());
  4205. if (!maybe_function.has_value())
  4206. return nullptr;
  4207. auto function = maybe_function.release_value();
  4208. auto function_metadata = transform_function_metadata(function);
  4209. StyleValueVector values;
  4210. auto argument_tokens = TokenStream { part.function().values() };
  4211. argument_tokens.skip_whitespace();
  4212. size_t argument_index = 0;
  4213. while (argument_tokens.has_next_token()) {
  4214. if (argument_index == function_metadata.parameters.size()) {
  4215. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", part.function().name(), function_metadata.parameters.size());
  4216. return nullptr;
  4217. }
  4218. auto const& value = argument_tokens.next_token();
  4219. RefPtr<CalculatedStyleValue> maybe_calc_value = parse_calculated_value(value);
  4220. switch (function_metadata.parameters[argument_index].type) {
  4221. case TransformFunctionParameterType::Angle: {
  4222. // These are `<angle> | <zero>` in the spec, so we have to check for both kinds.
  4223. if (maybe_calc_value && maybe_calc_value->resolves_to_angle()) {
  4224. values.append(maybe_calc_value.release_nonnull());
  4225. } else if (value.is(Token::Type::Number) && value.token().number_value() == 0) {
  4226. values.append(AngleStyleValue::create(Angle::make_degrees(0)));
  4227. } else {
  4228. auto dimension_value = parse_dimension_value(value);
  4229. if (!dimension_value || !dimension_value->is_angle())
  4230. return nullptr;
  4231. values.append(dimension_value.release_nonnull());
  4232. }
  4233. break;
  4234. }
  4235. case TransformFunctionParameterType::Length: {
  4236. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  4237. values.append(maybe_calc_value.release_nonnull());
  4238. } else {
  4239. auto dimension_value = parse_dimension_value(value);
  4240. if (!dimension_value)
  4241. return nullptr;
  4242. if (dimension_value->is_length())
  4243. values.append(dimension_value.release_nonnull());
  4244. else
  4245. return nullptr;
  4246. }
  4247. break;
  4248. }
  4249. case TransformFunctionParameterType::LengthPercentage: {
  4250. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  4251. values.append(maybe_calc_value.release_nonnull());
  4252. } else {
  4253. auto dimension_value = parse_dimension_value(value);
  4254. if (!dimension_value)
  4255. return nullptr;
  4256. if (dimension_value->is_percentage() || dimension_value->is_length())
  4257. values.append(dimension_value.release_nonnull());
  4258. else
  4259. return nullptr;
  4260. }
  4261. break;
  4262. }
  4263. case TransformFunctionParameterType::Number: {
  4264. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  4265. values.append(maybe_calc_value.release_nonnull());
  4266. } else {
  4267. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  4268. argument_tokens.reconsume_current_input_token();
  4269. auto number = parse_number_value(argument_tokens);
  4270. if (!number)
  4271. return nullptr;
  4272. values.append(number.release_nonnull());
  4273. }
  4274. break;
  4275. }
  4276. }
  4277. argument_tokens.skip_whitespace();
  4278. if (argument_tokens.has_next_token()) {
  4279. // Arguments must be separated by commas.
  4280. if (!argument_tokens.next_token().is(Token::Type::Comma))
  4281. return nullptr;
  4282. argument_tokens.skip_whitespace();
  4283. // If there are no more parameters after the comma, this is invalid.
  4284. if (!argument_tokens.has_next_token())
  4285. return nullptr;
  4286. }
  4287. argument_index++;
  4288. }
  4289. if (argument_index < function_metadata.parameters.size() && function_metadata.parameters[argument_index].required) {
  4290. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
  4291. return nullptr;
  4292. }
  4293. transformations.append(TransformationStyleValue::create(function, move(values)));
  4294. }
  4295. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  4296. }
  4297. // https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
  4298. // FIXME: This only supports a 2D position
  4299. RefPtr<StyleValue> Parser::parse_transform_origin_value(Vector<ComponentValue> const& component_values)
  4300. {
  4301. enum class Axis {
  4302. None,
  4303. X,
  4304. Y,
  4305. };
  4306. struct AxisOffset {
  4307. Axis axis;
  4308. NonnullRefPtr<StyleValue> offset;
  4309. };
  4310. auto to_axis_offset = [](RefPtr<StyleValue> value) -> Optional<AxisOffset> {
  4311. if (!value)
  4312. return OptionalNone {};
  4313. if (value->is_percentage())
  4314. return AxisOffset { Axis::None, value->as_percentage() };
  4315. if (value->is_length())
  4316. return AxisOffset { Axis::None, value->as_length() };
  4317. if (value->is_identifier()) {
  4318. switch (value->to_identifier()) {
  4319. case ValueID::Top:
  4320. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(0)) };
  4321. case ValueID::Left:
  4322. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(0)) };
  4323. case ValueID::Center:
  4324. return AxisOffset { Axis::None, PercentageStyleValue::create(Percentage(50)) };
  4325. case ValueID::Bottom:
  4326. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(100)) };
  4327. case ValueID::Right:
  4328. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(100)) };
  4329. default:
  4330. return OptionalNone {};
  4331. }
  4332. }
  4333. return OptionalNone {};
  4334. };
  4335. auto make_list = [](NonnullRefPtr<StyleValue> const& x_value, NonnullRefPtr<StyleValue> const& y_value) -> NonnullRefPtr<StyleValueList> {
  4336. StyleValueVector values;
  4337. values.append(x_value);
  4338. values.append(y_value);
  4339. return StyleValueList::create(move(values), StyleValueList::Separator::Space);
  4340. };
  4341. auto tokens = TokenStream { component_values };
  4342. switch (component_values.size()) {
  4343. case 1: {
  4344. auto single_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  4345. if (!single_value.has_value())
  4346. return nullptr;
  4347. // If only one value is specified, the second value is assumed to be center.
  4348. // FIXME: If one or two values are specified, the third value is assumed to be 0px.
  4349. switch (single_value->axis) {
  4350. case Axis::None:
  4351. case Axis::X:
  4352. return make_list(single_value->offset, PercentageStyleValue::create(Percentage(50)));
  4353. case Axis::Y:
  4354. return make_list(PercentageStyleValue::create(Percentage(50)), single_value->offset);
  4355. }
  4356. VERIFY_NOT_REACHED();
  4357. }
  4358. case 2: {
  4359. auto first_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  4360. auto second_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  4361. if (!first_value.has_value() || !second_value.has_value())
  4362. return nullptr;
  4363. RefPtr<StyleValue> x_value;
  4364. RefPtr<StyleValue> y_value;
  4365. if (first_value->axis == Axis::X) {
  4366. x_value = first_value->offset;
  4367. } else if (first_value->axis == Axis::Y) {
  4368. y_value = first_value->offset;
  4369. }
  4370. if (second_value->axis == Axis::X) {
  4371. if (x_value)
  4372. return nullptr;
  4373. x_value = second_value->offset;
  4374. // Put the other in Y since its axis can't have been X
  4375. y_value = first_value->offset;
  4376. } else if (second_value->axis == Axis::Y) {
  4377. if (y_value)
  4378. return nullptr;
  4379. y_value = second_value->offset;
  4380. // Put the other in X since its axis can't have been Y
  4381. x_value = first_value->offset;
  4382. } else {
  4383. if (x_value) {
  4384. VERIFY(!y_value);
  4385. y_value = second_value->offset;
  4386. } else {
  4387. VERIFY(!x_value);
  4388. x_value = second_value->offset;
  4389. }
  4390. }
  4391. // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
  4392. // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
  4393. // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
  4394. if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
  4395. x_value = first_value->offset;
  4396. y_value = second_value->offset;
  4397. }
  4398. return make_list(x_value.release_nonnull(), y_value.release_nonnull());
  4399. }
  4400. }
  4401. return nullptr;
  4402. }
  4403. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  4404. {
  4405. auto component_values = parse_a_list_of_component_values(m_token_stream);
  4406. auto tokens = TokenStream(component_values);
  4407. auto parsed_value = parse_css_value(property_id, tokens);
  4408. if (parsed_value.is_error())
  4409. return nullptr;
  4410. return parsed_value.release_value();
  4411. }
  4412. Optional<CSS::GridSize> Parser::parse_grid_size(ComponentValue const& component_value)
  4413. {
  4414. if (component_value.is_function()) {
  4415. if (auto maybe_calculated = parse_calculated_value(component_value)) {
  4416. if (maybe_calculated->resolves_to_length_percentage())
  4417. return GridSize(LengthPercentage(maybe_calculated.release_nonnull()));
  4418. // FIXME: Support calculated <flex>
  4419. }
  4420. return {};
  4421. }
  4422. auto token = component_value.token();
  4423. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("auto"sv))
  4424. return GridSize::make_auto();
  4425. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("max-content"sv))
  4426. return GridSize(GridSize::Type::MaxContent);
  4427. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("min-content"sv))
  4428. return GridSize(GridSize::Type::MinContent);
  4429. auto dimension = parse_dimension(token);
  4430. if (!dimension.has_value())
  4431. return {};
  4432. if (dimension->is_length())
  4433. return GridSize(dimension->length());
  4434. else if (dimension->is_percentage())
  4435. return GridSize(dimension->percentage());
  4436. else if (dimension->is_flex())
  4437. return GridSize(dimension->flex());
  4438. return {};
  4439. }
  4440. Optional<CSS::GridMinMax> Parser::parse_min_max(Vector<ComponentValue> const& component_values)
  4441. {
  4442. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  4443. // 'minmax(min, max)'
  4444. // Defines a size range greater than or equal to min and less than or equal to max. If the max is
  4445. // less than the min, then the max will be floored by the min (essentially yielding minmax(min,
  4446. // min)). As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  4447. auto function_tokens = TokenStream(component_values);
  4448. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  4449. if (comma_separated_list.size() != 2)
  4450. return {};
  4451. TokenStream part_one_tokens { comma_separated_list[0] };
  4452. part_one_tokens.skip_whitespace();
  4453. if (!part_one_tokens.has_next_token())
  4454. return {};
  4455. auto current_token = part_one_tokens.next_token();
  4456. auto min_grid_size = parse_grid_size(current_token);
  4457. TokenStream part_two_tokens { comma_separated_list[1] };
  4458. part_two_tokens.skip_whitespace();
  4459. if (!part_two_tokens.has_next_token())
  4460. return {};
  4461. current_token = part_two_tokens.next_token();
  4462. auto max_grid_size = parse_grid_size(current_token);
  4463. if (min_grid_size.has_value() && max_grid_size.has_value()) {
  4464. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  4465. // As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  4466. if (min_grid_size.value().is_flexible_length())
  4467. return {};
  4468. return CSS::GridMinMax(min_grid_size.value(), max_grid_size.value());
  4469. }
  4470. return {};
  4471. }
  4472. Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& component_values)
  4473. {
  4474. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  4475. // 7.2.3.1. Syntax of repeat()
  4476. // The generic form of the repeat() syntax is, approximately,
  4477. // repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> )
  4478. auto is_auto_fill = false;
  4479. auto is_auto_fit = false;
  4480. auto function_tokens = TokenStream(component_values);
  4481. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  4482. if (comma_separated_list.size() != 2)
  4483. return {};
  4484. // The first argument specifies the number of repetitions.
  4485. TokenStream part_one_tokens { comma_separated_list[0] };
  4486. part_one_tokens.skip_whitespace();
  4487. if (!part_one_tokens.has_next_token())
  4488. return {};
  4489. auto current_token = part_one_tokens.next_token().token();
  4490. auto repeat_count = 0;
  4491. if (current_token.is(Token::Type::Number) && current_token.number().is_integer() && current_token.number_value() > 0)
  4492. repeat_count = current_token.number_value();
  4493. else if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto-fill"sv))
  4494. is_auto_fill = true;
  4495. else if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto-fit"sv))
  4496. is_auto_fit = true;
  4497. // The second argument is a track list, which is repeated that number of times.
  4498. TokenStream part_two_tokens { comma_separated_list[1] };
  4499. part_two_tokens.skip_whitespace();
  4500. if (!part_two_tokens.has_next_token())
  4501. return {};
  4502. Vector<CSS::ExplicitGridTrack> repeat_params;
  4503. Vector<Vector<String>> line_names_list;
  4504. auto last_object_was_line_names = false;
  4505. while (part_two_tokens.has_next_token()) {
  4506. auto token = part_two_tokens.next_token();
  4507. Vector<String> line_names;
  4508. if (token.is_block()) {
  4509. if (last_object_was_line_names)
  4510. return {};
  4511. last_object_was_line_names = true;
  4512. if (!token.block().is_square())
  4513. return {};
  4514. TokenStream block_tokens { token.block().values() };
  4515. while (block_tokens.has_next_token()) {
  4516. auto current_block_token = block_tokens.next_token();
  4517. auto maybe_string = String::from_utf8(current_block_token.token().ident());
  4518. if (maybe_string.is_error())
  4519. return {};
  4520. line_names.append(maybe_string.value());
  4521. block_tokens.skip_whitespace();
  4522. }
  4523. line_names_list.append(line_names);
  4524. part_two_tokens.skip_whitespace();
  4525. } else {
  4526. last_object_was_line_names = false;
  4527. auto track_sizing_function = parse_track_sizing_function(token);
  4528. if (!track_sizing_function.has_value())
  4529. return {};
  4530. // However, there are some restrictions:
  4531. // The repeat() notation can’t be nested.
  4532. if (track_sizing_function.value().is_repeat())
  4533. return {};
  4534. // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.
  4535. if (track_sizing_function.value().is_default() && track_sizing_function.value().grid_size().is_flexible_length() && (is_auto_fill || is_auto_fit))
  4536. return {};
  4537. repeat_params.append(track_sizing_function.value());
  4538. part_two_tokens.skip_whitespace();
  4539. }
  4540. }
  4541. while (line_names_list.size() <= repeat_params.size())
  4542. line_names_list.append({});
  4543. // Thus the precise syntax of the repeat() notation has several forms:
  4544. // <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? )
  4545. // <auto-repeat> = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  4546. // <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  4547. // <name-repeat> = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)
  4548. // The <track-repeat> variant can represent the repetition of any <track-size>, but is limited to a
  4549. // fixed number of repetitions.
  4550. // The <auto-repeat> variant can repeat automatically to fill a space, but requires definite track
  4551. // sizes so that the number of repetitions can be calculated. It can only appear once in the track
  4552. // list, but the same track list can also contain <fixed-repeat>s.
  4553. // The <name-repeat> variant is for adding line names to subgrids. It can only be used with the
  4554. // subgrid keyword and cannot specify track sizes, only line names.
  4555. // If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to
  4556. // each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a]
  4557. // 1fr [b a] 1fr [b].
  4558. if (is_auto_fill)
  4559. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFill);
  4560. else if (is_auto_fit)
  4561. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFit);
  4562. else
  4563. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), repeat_count);
  4564. }
  4565. Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentValue const& token)
  4566. {
  4567. if (token.is_function()) {
  4568. auto const& function_token = token.function();
  4569. if (function_token.name().equals_ignoring_ascii_case("repeat"sv)) {
  4570. auto maybe_repeat = parse_repeat(function_token.values());
  4571. if (maybe_repeat.has_value())
  4572. return CSS::ExplicitGridTrack(maybe_repeat.value());
  4573. else
  4574. return {};
  4575. } else if (function_token.name().equals_ignoring_ascii_case("minmax"sv)) {
  4576. auto maybe_min_max_value = parse_min_max(function_token.values());
  4577. if (maybe_min_max_value.has_value())
  4578. return CSS::ExplicitGridTrack(maybe_min_max_value.value());
  4579. else
  4580. return {};
  4581. } else if (auto maybe_calculated = parse_calculated_value(token)) {
  4582. return CSS::ExplicitGridTrack(GridSize(LengthPercentage(maybe_calculated.release_nonnull())));
  4583. }
  4584. return {};
  4585. } else if (token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("auto"sv)) {
  4586. return CSS::ExplicitGridTrack(GridSize(Length::make_auto()));
  4587. } else if (token.is_block()) {
  4588. return {};
  4589. } else {
  4590. auto grid_size = parse_grid_size(token);
  4591. if (!grid_size.has_value())
  4592. return {};
  4593. return CSS::ExplicitGridTrack(grid_size.value());
  4594. }
  4595. }
  4596. RefPtr<StyleValue> Parser::parse_grid_track_size_list(Vector<ComponentValue> const& component_values, bool allow_separate_line_name_blocks)
  4597. {
  4598. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  4599. auto ident = parse_identifier_value(component_values.first());
  4600. if (ident && ident->to_identifier() == ValueID::None) {
  4601. return GridTrackSizeListStyleValue::make_none();
  4602. }
  4603. }
  4604. Vector<CSS::ExplicitGridTrack> track_list;
  4605. Vector<Vector<String>> line_names_list;
  4606. auto last_object_was_line_names = false;
  4607. TokenStream tokens { component_values };
  4608. while (tokens.has_next_token()) {
  4609. auto token = tokens.next_token();
  4610. if (token.is_block()) {
  4611. if (last_object_was_line_names && !allow_separate_line_name_blocks)
  4612. return GridTrackSizeListStyleValue::make_auto();
  4613. last_object_was_line_names = true;
  4614. Vector<String> line_names;
  4615. if (!token.block().is_square())
  4616. return GridTrackSizeListStyleValue::make_auto();
  4617. TokenStream block_tokens { token.block().values() };
  4618. block_tokens.skip_whitespace();
  4619. while (block_tokens.has_next_token()) {
  4620. auto current_block_token = block_tokens.next_token();
  4621. auto maybe_string = String::from_utf8(current_block_token.token().ident());
  4622. if (maybe_string.is_error())
  4623. return nullptr;
  4624. line_names.append(maybe_string.value());
  4625. block_tokens.skip_whitespace();
  4626. }
  4627. line_names_list.append(line_names);
  4628. } else {
  4629. last_object_was_line_names = false;
  4630. auto track_sizing_function = parse_track_sizing_function(token);
  4631. if (!track_sizing_function.has_value())
  4632. return GridTrackSizeListStyleValue::make_auto();
  4633. // FIXME: Handle multiple repeat values (should combine them here, or remove
  4634. // any other ones if the first one is auto-fill, etc.)
  4635. track_list.append(track_sizing_function.value());
  4636. }
  4637. }
  4638. while (line_names_list.size() <= track_list.size())
  4639. line_names_list.append({});
  4640. return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, line_names_list));
  4641. }
  4642. // https://www.w3.org/TR/css-grid-1/#grid-auto-flow-property
  4643. RefPtr<GridAutoFlowStyleValue> Parser::parse_grid_auto_flow_value(Vector<ComponentValue> const& component_values)
  4644. {
  4645. // [ row | column ] || dense
  4646. TokenStream<ComponentValue> tokens { component_values };
  4647. if (!tokens.has_next_token())
  4648. return nullptr;
  4649. auto parse_axis = [&]() -> Optional<GridAutoFlowStyleValue::Axis> {
  4650. auto transaction = tokens.begin_transaction();
  4651. auto token = tokens.next_token();
  4652. if (!token.is(Token::Type::Ident))
  4653. return {};
  4654. auto const& ident = token.token().ident();
  4655. if (ident.equals_ignoring_ascii_case("row"sv)) {
  4656. transaction.commit();
  4657. return GridAutoFlowStyleValue::Axis::Row;
  4658. } else if (ident.equals_ignoring_ascii_case("column"sv)) {
  4659. transaction.commit();
  4660. return GridAutoFlowStyleValue::Axis::Column;
  4661. }
  4662. return {};
  4663. };
  4664. auto parse_dense = [&]() -> Optional<GridAutoFlowStyleValue::Dense> {
  4665. auto transaction = tokens.begin_transaction();
  4666. auto token = tokens.next_token();
  4667. if (!token.is(Token::Type::Ident))
  4668. return {};
  4669. auto const& ident = token.token().ident();
  4670. if (ident.equals_ignoring_ascii_case("dense"sv)) {
  4671. transaction.commit();
  4672. return GridAutoFlowStyleValue::Dense::Yes;
  4673. }
  4674. return {};
  4675. };
  4676. Optional<GridAutoFlowStyleValue::Axis> axis;
  4677. Optional<GridAutoFlowStyleValue::Dense> dense;
  4678. if (axis = parse_axis(); axis.has_value()) {
  4679. dense = parse_dense();
  4680. } else if (dense = parse_dense(); dense.has_value()) {
  4681. axis = parse_axis();
  4682. }
  4683. if (tokens.has_next_token())
  4684. return nullptr;
  4685. return GridAutoFlowStyleValue::create(axis.value_or(GridAutoFlowStyleValue::Axis::Row), dense.value_or(GridAutoFlowStyleValue::Dense::No));
  4686. }
  4687. RefPtr<StyleValue> Parser::parse_grid_auto_track_sizes(Vector<ComponentValue> const& component_values)
  4688. {
  4689. // https://www.w3.org/TR/css-grid-2/#auto-tracks
  4690. // <track-size>+
  4691. Vector<CSS::ExplicitGridTrack> track_list;
  4692. TokenStream tokens { component_values };
  4693. while (tokens.has_next_token()) {
  4694. auto token = tokens.next_token();
  4695. auto track_sizing_function = parse_track_sizing_function(token);
  4696. if (!track_sizing_function.has_value())
  4697. return GridTrackSizeListStyleValue::make_auto();
  4698. // FIXME: Handle multiple repeat values (should combine them here, or remove
  4699. // any other ones if the first one is auto-fill, etc.)
  4700. track_list.append(track_sizing_function.value());
  4701. }
  4702. return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, {}));
  4703. }
  4704. RefPtr<StyleValue> Parser::parse_grid_track_placement(Vector<ComponentValue> const& component_values)
  4705. {
  4706. // https://www.w3.org/TR/css-grid-2/#line-placement
  4707. // Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
  4708. // <grid-line> =
  4709. // auto |
  4710. // <custom-ident> |
  4711. // [ <integer> && <custom-ident>? ] |
  4712. // [ span && [ <integer> || <custom-ident> ] ]
  4713. auto is_auto = [](Token token) -> bool {
  4714. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("auto"sv))
  4715. return true;
  4716. return false;
  4717. };
  4718. auto is_span = [](Token token) -> bool {
  4719. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("span"sv))
  4720. return true;
  4721. return false;
  4722. };
  4723. auto is_valid_integer = [](Token token) -> bool {
  4724. // An <integer> value of zero makes the declaration invalid.
  4725. if (token.is(Token::Type::Number) && token.number().is_integer() && token.number_value() != 0)
  4726. return true;
  4727. return false;
  4728. };
  4729. auto is_identifier = [](Token token) -> bool {
  4730. // The <custom-ident> additionally excludes the keywords span and auto.
  4731. if (token.is(Token::Type::Ident) && !token.ident().equals_ignoring_ascii_case("span"sv) && !token.ident().equals_ignoring_ascii_case("auto"sv))
  4732. return true;
  4733. return false;
  4734. };
  4735. auto tokens = TokenStream { component_values };
  4736. tokens.skip_whitespace();
  4737. auto current_token = tokens.next_token().token();
  4738. if (!tokens.has_next_token()) {
  4739. if (is_auto(current_token))
  4740. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto());
  4741. if (is_span(current_token))
  4742. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(1));
  4743. if (is_valid_integer(current_token))
  4744. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(static_cast<int>(current_token.number_value()), {}));
  4745. if (is_identifier(current_token)) {
  4746. auto maybe_string = String::from_utf8(current_token.ident());
  4747. if (!maybe_string.is_error())
  4748. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line({}, maybe_string.value()));
  4749. }
  4750. return nullptr;
  4751. }
  4752. auto span_value = false;
  4753. auto span_or_position_value = 0;
  4754. String identifier_value;
  4755. while (true) {
  4756. if (is_auto(current_token))
  4757. return nullptr;
  4758. if (is_span(current_token)) {
  4759. if (span_value == false)
  4760. span_value = true;
  4761. else
  4762. return nullptr;
  4763. }
  4764. if (is_valid_integer(current_token)) {
  4765. if (span_or_position_value == 0)
  4766. span_or_position_value = static_cast<int>(current_token.number_value());
  4767. else
  4768. return nullptr;
  4769. }
  4770. if (is_identifier(current_token)) {
  4771. if (identifier_value.is_empty()) {
  4772. auto maybe_string = String::from_utf8(current_token.ident());
  4773. if (maybe_string.is_error())
  4774. return nullptr;
  4775. identifier_value = maybe_string.release_value();
  4776. } else {
  4777. return nullptr;
  4778. }
  4779. }
  4780. tokens.skip_whitespace();
  4781. if (tokens.has_next_token())
  4782. current_token = tokens.next_token().token();
  4783. else
  4784. break;
  4785. }
  4786. // Negative integers or zero are invalid.
  4787. if (span_value && span_or_position_value < 1)
  4788. return nullptr;
  4789. // If the <integer> is omitted, it defaults to 1.
  4790. if (span_or_position_value == 0)
  4791. span_or_position_value = 1;
  4792. if (!identifier_value.is_empty())
  4793. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(span_or_position_value, identifier_value));
  4794. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(span_or_position_value));
  4795. }
  4796. RefPtr<StyleValue> Parser::parse_grid_track_placement_shorthand_value(PropertyID property_id, Vector<ComponentValue> const& component_values)
  4797. {
  4798. auto start_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnStart : PropertyID::GridRowStart;
  4799. auto end_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnEnd : PropertyID::GridRowEnd;
  4800. auto tokens = TokenStream { component_values };
  4801. auto current_token = tokens.next_token().token();
  4802. Vector<ComponentValue> track_start_placement_tokens;
  4803. while (true) {
  4804. if (current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv)
  4805. break;
  4806. track_start_placement_tokens.append(current_token);
  4807. if (!tokens.has_next_token())
  4808. break;
  4809. current_token = tokens.next_token().token();
  4810. }
  4811. Vector<ComponentValue> track_end_placement_tokens;
  4812. if (tokens.has_next_token()) {
  4813. current_token = tokens.next_token().token();
  4814. while (true) {
  4815. track_end_placement_tokens.append(current_token);
  4816. if (!tokens.has_next_token())
  4817. break;
  4818. current_token = tokens.next_token().token();
  4819. }
  4820. }
  4821. auto parsed_start_value = parse_grid_track_placement(track_start_placement_tokens);
  4822. if (parsed_start_value && track_end_placement_tokens.is_empty()) {
  4823. return ShorthandStyleValue::create(property_id,
  4824. { start_property, end_property },
  4825. { parsed_start_value.release_nonnull(), GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto()) });
  4826. }
  4827. auto parsed_end_value = parse_grid_track_placement(track_end_placement_tokens);
  4828. if (parsed_start_value && parsed_end_value) {
  4829. return ShorthandStyleValue::create(property_id,
  4830. { start_property, end_property },
  4831. { parsed_start_value.release_nonnull(), parsed_end_value.release_nonnull() });
  4832. }
  4833. return nullptr;
  4834. }
  4835. // https://www.w3.org/TR/css-grid-2/#explicit-grid-shorthand
  4836. // 7.4. Explicit Grid Shorthand: the grid-template property
  4837. RefPtr<StyleValue> Parser::parse_grid_track_size_list_shorthand_value(PropertyID property_id, Vector<ComponentValue> const& component_values)
  4838. {
  4839. // The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows,
  4840. // and grid-template-areas in a single declaration. It has several distinct syntax forms:
  4841. // none
  4842. // - Sets all three properties to their initial values (none).
  4843. // <'grid-template-rows'> / <'grid-template-columns'>
  4844. // - Sets grid-template-rows and grid-template-columns to the specified values, respectively, and sets grid-template-areas to none.
  4845. // [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
  4846. // - Sets grid-template-areas to the strings listed.
  4847. // - Sets grid-template-rows to the <track-size>s following each string (filling in auto for any missing sizes),
  4848. // and splicing in the named lines defined before/after each size.
  4849. // - Sets grid-template-columns to the track listing specified after the slash (or none, if not specified).
  4850. Vector<ComponentValue> template_rows_tokens;
  4851. Vector<ComponentValue> template_columns_tokens;
  4852. Vector<ComponentValue> template_area_tokens;
  4853. int forward_slash_index = -1;
  4854. for (size_t x = 0; x < component_values.size(); x++) {
  4855. if (component_values[x].is_delim('/')) {
  4856. forward_slash_index = x;
  4857. break;
  4858. }
  4859. }
  4860. for (size_t x = 0; x < (forward_slash_index > -1 ? forward_slash_index : component_values.size()); x++) {
  4861. if (component_values[x].is_token() && component_values[x].token().is(Token::Type::String))
  4862. template_area_tokens.append(component_values[x]);
  4863. else
  4864. template_rows_tokens.append(component_values[x]);
  4865. }
  4866. if (forward_slash_index > -1) {
  4867. for (size_t x = forward_slash_index + 1; x < component_values.size(); x++)
  4868. template_columns_tokens.append(component_values[x]);
  4869. }
  4870. auto parsed_template_areas_values = parse_grid_template_areas_value(template_area_tokens);
  4871. auto parsed_template_rows_values = parse_grid_track_size_list(template_rows_tokens, true);
  4872. auto parsed_template_columns_values = parse_grid_track_size_list(template_columns_tokens);
  4873. return ShorthandStyleValue::create(property_id,
  4874. { PropertyID::GridTemplateAreas, PropertyID::GridTemplateRows, PropertyID::GridTemplateColumns },
  4875. { parsed_template_areas_values.release_nonnull(), parsed_template_rows_values.release_nonnull(), parsed_template_columns_values.release_nonnull() });
  4876. }
  4877. RefPtr<StyleValue> Parser::parse_grid_area_shorthand_value(Vector<ComponentValue> const& component_values)
  4878. {
  4879. auto tokens = TokenStream { component_values };
  4880. Token current_token;
  4881. auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void {
  4882. current_token = tokens.next_token().token();
  4883. while (true) {
  4884. if (check_for_delimiter && current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv)
  4885. break;
  4886. placement_tokens.append(current_token);
  4887. tokens.skip_whitespace();
  4888. if (!tokens.has_next_token())
  4889. break;
  4890. current_token = tokens.next_token().token();
  4891. }
  4892. };
  4893. Vector<ComponentValue> row_start_placement_tokens;
  4894. parse_placement_tokens(row_start_placement_tokens);
  4895. Vector<ComponentValue> column_start_placement_tokens;
  4896. if (tokens.has_next_token())
  4897. parse_placement_tokens(column_start_placement_tokens);
  4898. Vector<ComponentValue> row_end_placement_tokens;
  4899. if (tokens.has_next_token())
  4900. parse_placement_tokens(row_end_placement_tokens);
  4901. Vector<ComponentValue> column_end_placement_tokens;
  4902. if (tokens.has_next_token())
  4903. parse_placement_tokens(column_end_placement_tokens, false);
  4904. // https://www.w3.org/TR/css-grid-2/#placement-shorthands
  4905. // The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and
  4906. // grid-column-end.
  4907. auto row_start_style_value = parse_grid_track_placement(row_start_placement_tokens);
  4908. auto column_start_style_value = parse_grid_track_placement(column_start_placement_tokens);
  4909. auto row_end_style_value = parse_grid_track_placement(row_end_placement_tokens);
  4910. auto column_end_style_value = parse_grid_track_placement(column_end_placement_tokens);
  4911. // If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start
  4912. // is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the
  4913. // fourth value.
  4914. auto row_start = GridTrackPlacement::make_auto();
  4915. auto column_start = GridTrackPlacement::make_auto();
  4916. auto row_end = GridTrackPlacement::make_auto();
  4917. auto column_end = GridTrackPlacement::make_auto();
  4918. if (row_start_style_value)
  4919. row_start = row_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  4920. // When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to
  4921. // that value. Otherwise, it is set to auto.
  4922. if (column_start_style_value)
  4923. column_start = column_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  4924. else
  4925. column_start = row_start;
  4926. // When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that
  4927. // <custom-ident>; otherwise, it is set to auto.
  4928. if (row_end_style_value)
  4929. row_end = row_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  4930. else
  4931. row_end = column_start;
  4932. // When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to
  4933. // that <custom-ident>; otherwise, it is set to auto.
  4934. if (column_end_style_value)
  4935. column_end = column_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  4936. else
  4937. column_end = row_end;
  4938. return ShorthandStyleValue::create(PropertyID::GridArea,
  4939. { PropertyID::GridRowStart, PropertyID::GridColumnStart, PropertyID::GridRowEnd, PropertyID::GridColumnEnd },
  4940. { GridTrackPlacementStyleValue::create(row_start), GridTrackPlacementStyleValue::create(column_start), GridTrackPlacementStyleValue::create(row_end), GridTrackPlacementStyleValue::create(column_end) });
  4941. }
  4942. RefPtr<StyleValue> Parser::parse_grid_shorthand_value(Vector<ComponentValue> const& component_value)
  4943. {
  4944. // <'grid-template'> |
  4945. // FIXME: <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? |
  4946. // FIXME: [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
  4947. return parse_grid_track_size_list_shorthand_value(PropertyID::Grid, component_value);
  4948. }
  4949. RefPtr<StyleValue> Parser::parse_grid_template_areas_value(Vector<ComponentValue> const& component_values)
  4950. {
  4951. Vector<Vector<String>> grid_area_rows;
  4952. for (auto& component_value : component_values) {
  4953. Vector<String> grid_area_columns;
  4954. if (component_value.is(Token::Type::String)) {
  4955. auto const parts = MUST(MUST(String::from_utf8(component_value.token().string())).split(' '));
  4956. for (auto& part : parts) {
  4957. grid_area_columns.append(part);
  4958. }
  4959. }
  4960. grid_area_rows.append(move(grid_area_columns));
  4961. }
  4962. return GridTemplateAreaStyleValue::create(grid_area_rows);
  4963. }
  4964. static bool block_contains_var_or_attr(Block const& block);
  4965. static bool function_contains_var_or_attr(Function const& function)
  4966. {
  4967. if (function.name().equals_ignoring_ascii_case("var"sv) || function.name().equals_ignoring_ascii_case("attr"sv))
  4968. return true;
  4969. for (auto const& token : function.values()) {
  4970. if (token.is_function() && function_contains_var_or_attr(token.function()))
  4971. return true;
  4972. if (token.is_block() && block_contains_var_or_attr(token.block()))
  4973. return true;
  4974. }
  4975. return false;
  4976. }
  4977. bool block_contains_var_or_attr(Block const& block)
  4978. {
  4979. for (auto const& token : block.values()) {
  4980. if (token.is_function() && function_contains_var_or_attr(token.function()))
  4981. return true;
  4982. if (token.is_block() && block_contains_var_or_attr(token.block()))
  4983. return true;
  4984. }
  4985. return false;
  4986. }
  4987. Parser::ParseErrorOr<NonnullRefPtr<StyleValue>> Parser::parse_css_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  4988. {
  4989. m_context.set_current_property_id(property_id);
  4990. Vector<ComponentValue> component_values;
  4991. bool contains_var_or_attr = false;
  4992. bool const property_accepts_custom_ident = property_accepts_type(property_id, ValueType::CustomIdent);
  4993. while (tokens.has_next_token()) {
  4994. auto const& token = tokens.next_token();
  4995. if (token.is(Token::Type::Semicolon)) {
  4996. tokens.reconsume_current_input_token();
  4997. break;
  4998. }
  4999. if (property_id != PropertyID::Custom) {
  5000. if (token.is(Token::Type::Whitespace))
  5001. continue;
  5002. if (!property_accepts_custom_ident && token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  5003. return ParseError::IncludesIgnoredVendorPrefix;
  5004. }
  5005. if (!contains_var_or_attr) {
  5006. if (token.is_function() && function_contains_var_or_attr(token.function()))
  5007. contains_var_or_attr = true;
  5008. else if (token.is_block() && block_contains_var_or_attr(token.block()))
  5009. contains_var_or_attr = true;
  5010. }
  5011. component_values.append(token);
  5012. }
  5013. if (property_id == PropertyID::Custom || contains_var_or_attr)
  5014. return UnresolvedStyleValue::create(move(component_values), contains_var_or_attr);
  5015. if (component_values.is_empty())
  5016. return ParseError::SyntaxError;
  5017. if (component_values.size() == 1) {
  5018. if (auto parsed_value = parse_builtin_value(component_values.first()))
  5019. return parsed_value.release_nonnull();
  5020. }
  5021. // Special-case property handling
  5022. switch (property_id) {
  5023. case PropertyID::AspectRatio:
  5024. if (auto parsed_value = parse_aspect_ratio_value(component_values))
  5025. return parsed_value.release_nonnull();
  5026. return ParseError::SyntaxError;
  5027. case PropertyID::BackdropFilter:
  5028. if (auto parsed_value = parse_filter_value_list_value(component_values))
  5029. return parsed_value.release_nonnull();
  5030. return ParseError::SyntaxError;
  5031. case PropertyID::Background:
  5032. if (auto parsed_value = parse_background_value(component_values))
  5033. return parsed_value.release_nonnull();
  5034. return ParseError::SyntaxError;
  5035. case PropertyID::BackgroundAttachment:
  5036. case PropertyID::BackgroundClip:
  5037. case PropertyID::BackgroundImage:
  5038. case PropertyID::BackgroundOrigin:
  5039. if (auto parsed_value = parse_simple_comma_separated_value_list(property_id, component_values))
  5040. return parsed_value.release_nonnull();
  5041. return ParseError::SyntaxError;
  5042. case PropertyID::BackgroundPosition:
  5043. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_position_value(tokens); }))
  5044. return parsed_value.release_nonnull();
  5045. return ParseError::SyntaxError;
  5046. case PropertyID::BackgroundPositionX:
  5047. case PropertyID::BackgroundPositionY:
  5048. 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); }))
  5049. return parsed_value.release_nonnull();
  5050. return ParseError::SyntaxError;
  5051. case PropertyID::BackgroundRepeat:
  5052. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
  5053. return parsed_value.release_nonnull();
  5054. return ParseError::SyntaxError;
  5055. case PropertyID::BackgroundSize:
  5056. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
  5057. return parsed_value.release_nonnull();
  5058. return ParseError::SyntaxError;
  5059. case PropertyID::Border:
  5060. case PropertyID::BorderBottom:
  5061. case PropertyID::BorderLeft:
  5062. case PropertyID::BorderRight:
  5063. case PropertyID::BorderTop:
  5064. if (auto parsed_value = parse_border_value(property_id, component_values))
  5065. return parsed_value.release_nonnull();
  5066. return ParseError::SyntaxError;
  5067. case PropertyID::BorderTopLeftRadius:
  5068. case PropertyID::BorderTopRightRadius:
  5069. case PropertyID::BorderBottomRightRadius:
  5070. case PropertyID::BorderBottomLeftRadius:
  5071. if (auto parsed_value = parse_border_radius_value(component_values))
  5072. return parsed_value.release_nonnull();
  5073. return ParseError::SyntaxError;
  5074. case PropertyID::BorderRadius:
  5075. if (auto parsed_value = parse_border_radius_shorthand_value(component_values))
  5076. return parsed_value.release_nonnull();
  5077. return ParseError::SyntaxError;
  5078. case PropertyID::BoxShadow:
  5079. if (auto parsed_value = parse_shadow_value(component_values, AllowInsetKeyword::Yes))
  5080. return parsed_value.release_nonnull();
  5081. return ParseError::SyntaxError;
  5082. case PropertyID::Content:
  5083. if (auto parsed_value = parse_content_value(component_values))
  5084. return parsed_value.release_nonnull();
  5085. return ParseError::SyntaxError;
  5086. case PropertyID::Display:
  5087. if (auto parsed_value = parse_display_value(component_values))
  5088. return parsed_value.release_nonnull();
  5089. return ParseError::SyntaxError;
  5090. case PropertyID::Flex:
  5091. if (auto parsed_value = parse_flex_value(component_values))
  5092. return parsed_value.release_nonnull();
  5093. return ParseError::SyntaxError;
  5094. case PropertyID::FlexFlow:
  5095. if (auto parsed_value = parse_flex_flow_value(component_values))
  5096. return parsed_value.release_nonnull();
  5097. return ParseError::SyntaxError;
  5098. case PropertyID::Font:
  5099. if (auto parsed_value = parse_font_value(component_values))
  5100. return parsed_value.release_nonnull();
  5101. return ParseError::SyntaxError;
  5102. case PropertyID::FontFamily: {
  5103. auto tokens_without_whitespace = TokenStream { component_values };
  5104. if (auto parsed_value = parse_font_family_value(tokens_without_whitespace))
  5105. return parsed_value.release_nonnull();
  5106. return ParseError::SyntaxError;
  5107. }
  5108. case PropertyID::GridColumn:
  5109. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, component_values))
  5110. return parsed_value.release_nonnull();
  5111. return ParseError::SyntaxError;
  5112. case PropertyID::GridArea:
  5113. if (auto parsed_value = parse_grid_area_shorthand_value(component_values))
  5114. return parsed_value.release_nonnull();
  5115. return ParseError::SyntaxError;
  5116. case PropertyID::GridAutoFlow:
  5117. if (auto parsed_value = parse_grid_auto_flow_value(component_values))
  5118. return parsed_value.release_nonnull();
  5119. return ParseError::SyntaxError;
  5120. case PropertyID::GridTemplateAreas:
  5121. if (auto parsed_value = parse_grid_template_areas_value(component_values))
  5122. return parsed_value.release_nonnull();
  5123. return ParseError::SyntaxError;
  5124. case PropertyID::GridColumnEnd:
  5125. if (auto parsed_value = parse_grid_track_placement(component_values))
  5126. return parsed_value.release_nonnull();
  5127. return ParseError::SyntaxError;
  5128. case PropertyID::GridColumnStart:
  5129. if (auto parsed_value = parse_grid_track_placement(component_values))
  5130. return parsed_value.release_nonnull();
  5131. return ParseError::SyntaxError;
  5132. case PropertyID::GridRow:
  5133. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, component_values))
  5134. return parsed_value.release_nonnull();
  5135. return ParseError::SyntaxError;
  5136. case PropertyID::GridRowEnd:
  5137. if (auto parsed_value = parse_grid_track_placement(component_values))
  5138. return parsed_value.release_nonnull();
  5139. return ParseError::SyntaxError;
  5140. case PropertyID::GridRowStart:
  5141. if (auto parsed_value = parse_grid_track_placement(component_values))
  5142. return parsed_value.release_nonnull();
  5143. return ParseError::SyntaxError;
  5144. case PropertyID::Grid:
  5145. if (auto parsed_value = parse_grid_shorthand_value(component_values))
  5146. return parsed_value.release_nonnull();
  5147. return ParseError::SyntaxError;
  5148. case PropertyID::GridTemplate:
  5149. if (auto parsed_value = parse_grid_track_size_list_shorthand_value(property_id, component_values))
  5150. return parsed_value.release_nonnull();
  5151. return ParseError::SyntaxError;
  5152. case PropertyID::GridTemplateColumns:
  5153. if (auto parsed_value = parse_grid_track_size_list(component_values))
  5154. return parsed_value.release_nonnull();
  5155. return ParseError::SyntaxError;
  5156. case PropertyID::GridTemplateRows:
  5157. if (auto parsed_value = parse_grid_track_size_list(component_values))
  5158. return parsed_value.release_nonnull();
  5159. return ParseError::SyntaxError;
  5160. case PropertyID::GridAutoColumns:
  5161. if (auto parsed_value = parse_grid_auto_track_sizes(component_values))
  5162. return parsed_value.release_nonnull();
  5163. return ParseError::SyntaxError;
  5164. case PropertyID::GridAutoRows:
  5165. if (auto parsed_value = parse_grid_auto_track_sizes(component_values))
  5166. return parsed_value.release_nonnull();
  5167. return ParseError::SyntaxError;
  5168. case PropertyID::ListStyle:
  5169. if (auto parsed_value = parse_list_style_value(component_values))
  5170. return parsed_value.release_nonnull();
  5171. return ParseError::SyntaxError;
  5172. case PropertyID::MathDepth:
  5173. if (auto parsed_value = parse_math_depth_value(component_values))
  5174. return parsed_value.release_nonnull();
  5175. return ParseError::SyntaxError;
  5176. case PropertyID::ObjectPosition:
  5177. // FIXME: This should use a parse_position compatible to VALUES-4
  5178. // and not the background position, which is almost the same.
  5179. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_position_value(tokens); }))
  5180. return parsed_value.release_nonnull();
  5181. return ParseError::SyntaxError;
  5182. case PropertyID::Overflow:
  5183. if (auto parsed_value = parse_overflow_value(component_values))
  5184. return parsed_value.release_nonnull();
  5185. return ParseError::SyntaxError;
  5186. case PropertyID::PlaceContent:
  5187. if (auto parsed_value = parse_place_content_value(component_values))
  5188. return parsed_value.release_nonnull();
  5189. return ParseError::SyntaxError;
  5190. case PropertyID::PlaceItems:
  5191. if (auto parsed_value = parse_place_items_value(component_values))
  5192. return parsed_value.release_nonnull();
  5193. return ParseError::SyntaxError;
  5194. case PropertyID::PlaceSelf:
  5195. if (auto parsed_value = parse_place_self_value(component_values))
  5196. return parsed_value.release_nonnull();
  5197. return ParseError::SyntaxError;
  5198. case PropertyID::Quotes:
  5199. if (auto parsed_value = parse_quotes_value(component_values))
  5200. return parsed_value.release_nonnull();
  5201. return ParseError::SyntaxError;
  5202. case PropertyID::TextDecoration:
  5203. if (auto parsed_value = parse_text_decoration_value(component_values))
  5204. return parsed_value.release_nonnull();
  5205. return ParseError::SyntaxError;
  5206. case PropertyID::TextDecorationLine: {
  5207. TokenStream value_tokens { component_values };
  5208. auto parsed_value = parse_text_decoration_line_value(value_tokens);
  5209. if (parsed_value && !value_tokens.has_next_token())
  5210. return parsed_value.release_nonnull();
  5211. return ParseError::SyntaxError;
  5212. }
  5213. case PropertyID::TextShadow:
  5214. if (auto parsed_value = parse_shadow_value(component_values, AllowInsetKeyword::No))
  5215. return parsed_value.release_nonnull();
  5216. return ParseError::SyntaxError;
  5217. case PropertyID::Transform:
  5218. if (auto parsed_value = parse_transform_value(component_values))
  5219. return parsed_value.release_nonnull();
  5220. return ParseError::SyntaxError;
  5221. case PropertyID::TransformOrigin:
  5222. if (auto parsed_value = parse_transform_origin_value(component_values))
  5223. return parsed_value.release_nonnull();
  5224. return ParseError ::SyntaxError;
  5225. default:
  5226. break;
  5227. }
  5228. // If there's only 1 ComponentValue, we can only produce a single StyleValue.
  5229. if (component_values.size() == 1) {
  5230. auto stream = TokenStream { component_values };
  5231. if (auto parsed_value = parse_css_value_for_property(property_id, stream))
  5232. return parsed_value.release_nonnull();
  5233. } else {
  5234. StyleValueVector parsed_values;
  5235. auto stream = TokenStream { component_values };
  5236. while (auto parsed_value = parse_css_value_for_property(property_id, stream)) {
  5237. parsed_values.append(parsed_value.release_nonnull());
  5238. if (!stream.has_next_token())
  5239. break;
  5240. }
  5241. // Some types (such as <ratio>) can be made from multiple ComponentValues, so if we only made 1 StyleValue, return it directly.
  5242. if (parsed_values.size() == 1)
  5243. return *parsed_values.take_first();
  5244. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  5245. return StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space);
  5246. }
  5247. // We have multiple values, but the property claims to accept only a single one, check if it's a shorthand property.
  5248. auto unassigned_properties = longhands_for_shorthand(property_id);
  5249. if (unassigned_properties.is_empty())
  5250. return ParseError::SyntaxError;
  5251. auto stream = TokenStream { component_values };
  5252. HashMap<UnderlyingType<PropertyID>, Vector<ValueComparingNonnullRefPtr<StyleValue const>>> assigned_values;
  5253. while (stream.has_next_token() && !unassigned_properties.is_empty()) {
  5254. auto property_and_value = parse_css_value_for_properties(unassigned_properties, stream);
  5255. if (property_and_value.has_value()) {
  5256. auto property = property_and_value->property;
  5257. auto value = property_and_value->style_value;
  5258. auto& values = assigned_values.ensure(to_underlying(property));
  5259. if (values.size() + 1 == property_maximum_value_count(property)) {
  5260. // We're done with this property, move on to the next one.
  5261. unassigned_properties.remove_first_matching([&](auto& unassigned_property) { return unassigned_property == property; });
  5262. }
  5263. values.append(value.release_nonnull());
  5264. continue;
  5265. }
  5266. // No property matched, so we're done.
  5267. dbgln("No property (from {} properties) matched {}", unassigned_properties.size(), stream.peek_token().to_debug_string());
  5268. for (auto id : unassigned_properties)
  5269. dbgln(" {}", string_from_property_id(id));
  5270. break;
  5271. }
  5272. for (auto& property : unassigned_properties)
  5273. assigned_values.ensure(to_underlying(property)).append(property_initial_value(m_context.realm(), property));
  5274. stream.skip_whitespace();
  5275. if (stream.has_next_token())
  5276. return ParseError::SyntaxError;
  5277. Vector<PropertyID> longhand_properties;
  5278. longhand_properties.ensure_capacity(assigned_values.size());
  5279. for (auto& it : assigned_values)
  5280. longhand_properties.unchecked_append(static_cast<PropertyID>(it.key));
  5281. StyleValueVector longhand_values;
  5282. longhand_values.ensure_capacity(assigned_values.size());
  5283. for (auto& it : assigned_values) {
  5284. if (it.value.size() == 1)
  5285. longhand_values.unchecked_append(it.value.take_first());
  5286. else
  5287. longhand_values.unchecked_append(StyleValueList::create(move(it.value), StyleValueList::Separator::Space));
  5288. }
  5289. return { ShorthandStyleValue::create(property_id, move(longhand_properties), move(longhand_values)) };
  5290. }
  5291. RefPtr<StyleValue> Parser::parse_css_value_for_property(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  5292. {
  5293. return parse_css_value_for_properties({ &property_id, 1 }, tokens)
  5294. .map([](auto& it) { return it.style_value; })
  5295. .value_or(nullptr);
  5296. }
  5297. Optional<Parser::PropertyAndValue> Parser::parse_css_value_for_properties(ReadonlySpan<PropertyID> property_ids, TokenStream<ComponentValue>& tokens)
  5298. {
  5299. auto any_property_accepts_type = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  5300. for (auto const& property : property_ids) {
  5301. if (property_accepts_type(property, value_type))
  5302. return property;
  5303. }
  5304. return {};
  5305. };
  5306. auto any_property_accepts_type_percentage = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  5307. for (auto const& property : property_ids) {
  5308. if (property_accepts_type(property, value_type) && property_accepts_type(property, ValueType::Percentage))
  5309. return property;
  5310. }
  5311. return {};
  5312. };
  5313. auto any_property_accepts_identifier = [](ReadonlySpan<PropertyID> property_ids, ValueID identifier) -> Optional<PropertyID> {
  5314. for (auto const& property : property_ids) {
  5315. if (property_accepts_identifier(property, identifier))
  5316. return property;
  5317. }
  5318. return {};
  5319. };
  5320. auto& peek_token = tokens.peek_token();
  5321. if (auto property = any_property_accepts_type(property_ids, ValueType::EasingFunction); property.has_value()) {
  5322. if (auto maybe_easing_function = parse_easing_value(tokens))
  5323. return PropertyAndValue { *property, maybe_easing_function };
  5324. }
  5325. if (peek_token.is(Token::Type::Ident)) {
  5326. // NOTE: We do not try to parse "CSS-wide keywords" here. https://www.w3.org/TR/css-values-4/#common-keywords
  5327. // These are only valid on their own, and so should be parsed directly in `parse_css_value()`.
  5328. auto ident = value_id_from_string(peek_token.token().ident());
  5329. if (ident.has_value()) {
  5330. if (auto property = any_property_accepts_identifier(property_ids, ident.value()); property.has_value()) {
  5331. (void)tokens.next_token();
  5332. return PropertyAndValue { *property, IdentifierStyleValue::create(ident.value()) };
  5333. }
  5334. }
  5335. // Custom idents
  5336. if (auto property = any_property_accepts_type(property_ids, ValueType::CustomIdent); property.has_value()) {
  5337. (void)tokens.next_token();
  5338. return PropertyAndValue { *property, CustomIdentStyleValue::create(MUST(FlyString::from_utf8(peek_token.token().ident()))) };
  5339. }
  5340. }
  5341. if (auto property = any_property_accepts_type(property_ids, ValueType::Color); property.has_value()) {
  5342. if (auto maybe_color = parse_color_value(peek_token)) {
  5343. (void)tokens.next_token();
  5344. return PropertyAndValue { *property, maybe_color };
  5345. }
  5346. }
  5347. if (auto property = any_property_accepts_type(property_ids, ValueType::Image); property.has_value()) {
  5348. if (auto maybe_image = parse_image_value(peek_token)) {
  5349. (void)tokens.next_token();
  5350. return PropertyAndValue { *property, maybe_image };
  5351. }
  5352. }
  5353. if (auto property = any_property_accepts_type(property_ids, ValueType::Ratio); property.has_value()) {
  5354. if (auto maybe_ratio = parse_ratio_value(tokens))
  5355. return PropertyAndValue { *property, maybe_ratio };
  5356. }
  5357. auto property_accepting_integer = any_property_accepts_type(property_ids, ValueType::Integer);
  5358. auto property_accepting_number = any_property_accepts_type(property_ids, ValueType::Number);
  5359. bool property_accepts_numeric = property_accepting_integer.has_value() || property_accepting_number.has_value();
  5360. if (peek_token.is(Token::Type::Number) && property_accepts_numeric) {
  5361. if (property_accepting_integer.has_value()) {
  5362. auto transaction = tokens.begin_transaction();
  5363. if (auto integer = parse_integer_value(tokens); integer && property_accepts_integer(*property_accepting_integer, integer->as_integer().integer())) {
  5364. transaction.commit();
  5365. return PropertyAndValue { *property_accepting_integer, integer };
  5366. }
  5367. }
  5368. if (property_accepting_number.has_value()) {
  5369. auto transaction = tokens.begin_transaction();
  5370. if (auto number = parse_number_value(tokens); number && property_accepts_number(*property_accepting_number, number->as_number().number())) {
  5371. transaction.commit();
  5372. return PropertyAndValue { *property_accepting_number, number };
  5373. }
  5374. }
  5375. }
  5376. if (peek_token.is(Token::Type::Percentage)) {
  5377. auto percentage = Percentage(peek_token.token().percentage());
  5378. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value() && property_accepts_percentage(*property, percentage)) {
  5379. (void)tokens.next_token();
  5380. return PropertyAndValue { *property, PercentageStyleValue::create(percentage) };
  5381. }
  5382. }
  5383. if (auto property = any_property_accepts_type(property_ids, ValueType::Rect); property.has_value()) {
  5384. if (auto maybe_rect = parse_rect_value(peek_token)) {
  5385. (void)tokens.next_token();
  5386. return PropertyAndValue { *property, maybe_rect };
  5387. }
  5388. }
  5389. if (peek_token.is(Token::Type::String)) {
  5390. if (auto property = any_property_accepts_type(property_ids, ValueType::String); property.has_value())
  5391. return PropertyAndValue { *property, StringStyleValue::create(MUST(String::from_utf8(tokens.next_token().token().string()))) };
  5392. }
  5393. if (auto property = any_property_accepts_type(property_ids, ValueType::Url); property.has_value()) {
  5394. if (auto url = parse_url_value(peek_token)) {
  5395. (void)tokens.next_token();
  5396. return PropertyAndValue { *property, url };
  5397. }
  5398. }
  5399. bool property_accepts_dimension = any_property_accepts_type(property_ids, ValueType::Angle).has_value()
  5400. || any_property_accepts_type(property_ids, ValueType::Flex).has_value()
  5401. || any_property_accepts_type(property_ids, ValueType::Frequency).has_value()
  5402. || any_property_accepts_type(property_ids, ValueType::Length).has_value()
  5403. || any_property_accepts_type(property_ids, ValueType::Percentage).has_value()
  5404. || any_property_accepts_type(property_ids, ValueType::Resolution).has_value()
  5405. || any_property_accepts_type(property_ids, ValueType::Time).has_value();
  5406. if (property_accepts_dimension) {
  5407. if (peek_token.is(Token::Type::Number) && m_context.is_parsing_svg_presentation_attribute()) {
  5408. auto transaction = tokens.begin_transaction();
  5409. auto token = tokens.next_token();
  5410. // https://svgwg.org/svg2-draft/types.html#presentation-attribute-css-value
  5411. // We need to allow <number> in any place that expects a <length> or <angle>.
  5412. // FIXME: How should these numbers be interpreted? https://github.com/w3c/svgwg/issues/792
  5413. // For now: Convert them to px lengths, or deg angles.
  5414. auto angle = Angle::make_degrees(token.token().number_value());
  5415. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  5416. transaction.commit();
  5417. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  5418. }
  5419. auto length = Length::make_px(CSSPixels::nearest_value_for(token.token().number_value()));
  5420. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  5421. transaction.commit();
  5422. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  5423. }
  5424. }
  5425. auto transaction = tokens.begin_transaction();
  5426. if (auto maybe_dimension = parse_dimension(peek_token); maybe_dimension.has_value()) {
  5427. (void)tokens.next_token();
  5428. auto dimension = maybe_dimension.release_value();
  5429. if (dimension.is_angle()) {
  5430. auto angle = dimension.angle();
  5431. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  5432. transaction.commit();
  5433. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  5434. }
  5435. }
  5436. if (dimension.is_flex()) {
  5437. auto flex = dimension.flex();
  5438. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value() && property_accepts_flex(*property, flex)) {
  5439. transaction.commit();
  5440. return PropertyAndValue { *property, FlexStyleValue::create(flex) };
  5441. }
  5442. }
  5443. if (dimension.is_frequency()) {
  5444. auto frequency = dimension.frequency();
  5445. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value() && property_accepts_frequency(*property, frequency)) {
  5446. transaction.commit();
  5447. return PropertyAndValue { *property, FrequencyStyleValue::create(frequency) };
  5448. }
  5449. }
  5450. if (dimension.is_length()) {
  5451. auto length = dimension.length();
  5452. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  5453. transaction.commit();
  5454. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  5455. }
  5456. }
  5457. if (dimension.is_resolution()) {
  5458. auto resolution = dimension.resolution();
  5459. if (auto property = any_property_accepts_type(property_ids, ValueType::Resolution); property.has_value() && property_accepts_resolution(*property, resolution)) {
  5460. transaction.commit();
  5461. return PropertyAndValue { *property, ResolutionStyleValue::create(resolution) };
  5462. }
  5463. }
  5464. if (dimension.is_time()) {
  5465. auto time = dimension.time();
  5466. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value() && property_accepts_time(*property, time)) {
  5467. transaction.commit();
  5468. return PropertyAndValue { *property, TimeStyleValue::create(time) };
  5469. }
  5470. }
  5471. }
  5472. }
  5473. // In order to not end up parsing `calc()` and other math expressions multiple times,
  5474. // we parse it once, and then see if its resolved type matches what the property accepts.
  5475. if (peek_token.is_function() && (property_accepts_dimension || property_accepts_numeric)) {
  5476. if (auto maybe_calculated = parse_calculated_value(peek_token); maybe_calculated) {
  5477. (void)tokens.next_token();
  5478. auto& calculated = *maybe_calculated;
  5479. // This is a bit sensitive to ordering: `<foo>` and `<percentage>` have to be checked before `<foo-percentage>`.
  5480. // FIXME: When parsing SVG presentation attributes, <number> is permitted wherever <length>, <length-percentage>, or <angle> are.
  5481. // The specifics are unclear, so I'm ignoring this for calculated values for now.
  5482. // See https://github.com/w3c/svgwg/issues/792
  5483. if (calculated.resolves_to_percentage()) {
  5484. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value())
  5485. return PropertyAndValue { *property, calculated };
  5486. } else if (calculated.resolves_to_angle()) {
  5487. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value())
  5488. return PropertyAndValue { *property, calculated };
  5489. } else if (calculated.resolves_to_angle_percentage()) {
  5490. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Angle); property.has_value())
  5491. return PropertyAndValue { *property, calculated };
  5492. } else if (calculated.resolves_to_flex()) {
  5493. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value())
  5494. return PropertyAndValue { *property, calculated };
  5495. } else if (calculated.resolves_to_frequency()) {
  5496. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value())
  5497. return PropertyAndValue { *property, calculated };
  5498. } else if (calculated.resolves_to_frequency_percentage()) {
  5499. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Frequency); property.has_value())
  5500. return PropertyAndValue { *property, calculated };
  5501. } else if (calculated.resolves_to_number()) {
  5502. if (property_accepts_numeric) {
  5503. auto property_or_resolved = property_accepting_integer.value_or_lazy_evaluated([property_accepting_number]() { return property_accepting_number.value(); });
  5504. return PropertyAndValue { property_or_resolved, calculated };
  5505. }
  5506. } else if (calculated.resolves_to_number_percentage()) {
  5507. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Number); property.has_value())
  5508. return PropertyAndValue { *property, calculated };
  5509. } else if (calculated.resolves_to_length()) {
  5510. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value())
  5511. return PropertyAndValue { *property, calculated };
  5512. } else if (calculated.resolves_to_length_percentage()) {
  5513. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Length); property.has_value())
  5514. return PropertyAndValue { *property, calculated };
  5515. } else if (calculated.resolves_to_time()) {
  5516. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value())
  5517. return PropertyAndValue { *property, calculated };
  5518. } else if (calculated.resolves_to_time_percentage()) {
  5519. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Time); property.has_value())
  5520. return PropertyAndValue { *property, calculated };
  5521. }
  5522. }
  5523. }
  5524. if (auto property = any_property_accepts_type(property_ids, ValueType::Paint); property.has_value()) {
  5525. if (auto value = parse_paint_value(tokens))
  5526. return PropertyAndValue { *property, value.release_nonnull() };
  5527. }
  5528. return OptionalNone {};
  5529. }
  5530. class UnparsedCalculationNode final : public CalculationNode {
  5531. public:
  5532. static NonnullOwnPtr<UnparsedCalculationNode> create(ComponentValue component_value)
  5533. {
  5534. return adopt_own(*new (nothrow) UnparsedCalculationNode(move(component_value)));
  5535. }
  5536. virtual ~UnparsedCalculationNode() = default;
  5537. ComponentValue& component_value() { return m_component_value; }
  5538. virtual String to_string() const override { VERIFY_NOT_REACHED(); }
  5539. virtual Optional<CalculatedStyleValue::ResolvedType> resolved_type() const override { VERIFY_NOT_REACHED(); }
  5540. virtual Optional<CSSNumericType> determine_type(Web::CSS::PropertyID) const override { VERIFY_NOT_REACHED(); }
  5541. virtual bool contains_percentage() const override { VERIFY_NOT_REACHED(); }
  5542. virtual CalculatedStyleValue::CalculationResult resolve(Optional<Length::ResolutionContext const&>, CalculatedStyleValue::PercentageBasis const&) const override { VERIFY_NOT_REACHED(); }
  5543. virtual void for_each_child_node(AK::Function<void(NonnullOwnPtr<CalculationNode>&)> const&) override { }
  5544. virtual void dump(StringBuilder& builder, int indent) const override
  5545. {
  5546. builder.appendff("{: >{}}UNPARSED({})\n", "", indent, m_component_value.to_debug_string());
  5547. }
  5548. private:
  5549. UnparsedCalculationNode(ComponentValue component_value)
  5550. : CalculationNode(Type::Unparsed)
  5551. , m_component_value(move(component_value))
  5552. {
  5553. }
  5554. ComponentValue m_component_value;
  5555. };
  5556. // https://html.spec.whatwg.org/multipage/images.html#parsing-a-sizes-attribute
  5557. LengthOrCalculated Parser::Parser::parse_as_sizes_attribute()
  5558. {
  5559. // 1. Let unparsed sizes list be the result of parsing a comma-separated list of component values
  5560. // from the value of element's sizes attribute (or the empty string, if the attribute is absent).
  5561. auto unparsed_sizes_list = parse_a_comma_separated_list_of_component_values(m_token_stream);
  5562. // 2. Let size be null.
  5563. Optional<LengthOrCalculated> size;
  5564. // 3. For each unparsed size in unparsed sizes list:
  5565. for (auto& unparsed_size : unparsed_sizes_list) {
  5566. // 1. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  5567. // If unparsed size is now empty, that is a parse error; continue.
  5568. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  5569. unparsed_size.take_last();
  5570. if (unparsed_size.is_empty()) {
  5571. log_parse_error();
  5572. continue;
  5573. }
  5574. // 2. If the last component value in unparsed size is a valid non-negative <source-size-value>,
  5575. // let size be its value and remove the component value from unparsed size.
  5576. // FIXME: Any CSS function other than the math functions is invalid.
  5577. // Otherwise, there is a parse error; continue.
  5578. if (auto source_size_value = parse_source_size_value(unparsed_size.last()); source_size_value.has_value()) {
  5579. size = source_size_value.value();
  5580. unparsed_size.take_last();
  5581. } else {
  5582. log_parse_error();
  5583. continue;
  5584. }
  5585. // 3. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  5586. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  5587. unparsed_size.take_last();
  5588. // If unparsed size is now empty, then return size.
  5589. if (unparsed_size.is_empty())
  5590. return size.value();
  5591. // FIXME: If this was not the keyword auto and it was not the last item in unparsed sizes list, that is a parse error.
  5592. // 4. Parse the remaining component values in unparsed size as a <media-condition>.
  5593. // If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue.
  5594. TokenStream<ComponentValue> token_stream { unparsed_size };
  5595. auto media_condition = parse_media_condition(token_stream, MediaCondition::AllowOr::Yes);
  5596. if (media_condition && media_condition->evaluate(*m_context.window()) == MatchResult::True) {
  5597. return size.value();
  5598. } else {
  5599. continue;
  5600. }
  5601. // 5. If size is not auto, then return size.
  5602. if (size.value().is_calculated() || !size.value().value().is_auto())
  5603. return size.value();
  5604. }
  5605. return Length(100, Length::Type::Vw);
  5606. }
  5607. // https://www.w3.org/TR/css-values-4/#parse-a-calculation
  5608. OwnPtr<CalculationNode> Parser::parse_a_calculation(Vector<ComponentValue> const& original_values)
  5609. {
  5610. // 1. Discard any <whitespace-token>s from values.
  5611. // 2. An item in values is an “operator” if it’s a <delim-token> with the value "+", "-", "*", or "/". Otherwise, it’s a “value”.
  5612. struct Operator {
  5613. char delim;
  5614. };
  5615. using Value = Variant<NonnullOwnPtr<CalculationNode>, Operator>;
  5616. Vector<Value> values;
  5617. for (auto& value : original_values) {
  5618. if (value.is(Token::Type::Whitespace))
  5619. continue;
  5620. if (value.is(Token::Type::Delim)) {
  5621. if (first_is_one_of(value.token().delim(), static_cast<u32>('+'), static_cast<u32>('-'), static_cast<u32>('*'), static_cast<u32>('/'))) {
  5622. // NOTE: Sequential operators are invalid syntax.
  5623. if (!values.is_empty() && values.last().has<Operator>())
  5624. return nullptr;
  5625. values.append(Operator { static_cast<char>(value.token().delim()) });
  5626. continue;
  5627. }
  5628. }
  5629. if (value.is(Token::Type::Ident)) {
  5630. auto maybe_constant = CalculationNode::constant_type_from_string(value.token().ident());
  5631. if (maybe_constant.has_value()) {
  5632. values.append({ ConstantCalculationNode::create(maybe_constant.value()) });
  5633. continue;
  5634. }
  5635. }
  5636. if (value.is(Token::Type::Number)) {
  5637. values.append({ NumericCalculationNode::create(value.token().number()) });
  5638. continue;
  5639. }
  5640. if (auto dimension = parse_dimension(value); dimension.has_value()) {
  5641. if (dimension->is_angle())
  5642. values.append({ NumericCalculationNode::create(dimension->angle()) });
  5643. else if (dimension->is_frequency())
  5644. values.append({ NumericCalculationNode::create(dimension->frequency()) });
  5645. else if (dimension->is_length())
  5646. values.append({ NumericCalculationNode::create(dimension->length()) });
  5647. else if (dimension->is_percentage())
  5648. values.append({ NumericCalculationNode::create(dimension->percentage()) });
  5649. // FIXME: Resolutions, once calc() supports them.
  5650. else if (dimension->is_time())
  5651. values.append({ NumericCalculationNode::create(dimension->time()) });
  5652. else if (dimension->is_flex()) {
  5653. // https://www.w3.org/TR/css3-grid-layout/#fr-unit
  5654. // NOTE: <flex> values are not <length>s (nor are they compatible with <length>s, like some <percentage> values),
  5655. // so they cannot be represented in or combined with other unit types in calc() expressions.
  5656. return nullptr;
  5657. } else {
  5658. VERIFY_NOT_REACHED();
  5659. }
  5660. continue;
  5661. }
  5662. values.append({ UnparsedCalculationNode::create(value) });
  5663. }
  5664. // If we have no values, the syntax is invalid.
  5665. if (values.is_empty())
  5666. return nullptr;
  5667. // NOTE: If the first or last value is an operator, the syntax is invalid.
  5668. if (values.first().has<Operator>() || values.last().has<Operator>())
  5669. return nullptr;
  5670. // 3. Collect children into Product and Invert nodes.
  5671. // For every consecutive run of value items in values separated by "*" or "/" operators:
  5672. while (true) {
  5673. Optional<size_t> first_product_operator = values.find_first_index_if([](auto const& item) {
  5674. return item.template has<Operator>()
  5675. && first_is_one_of(item.template get<Operator>().delim, '*', '/');
  5676. });
  5677. if (!first_product_operator.has_value())
  5678. break;
  5679. auto start_of_run = first_product_operator.value() - 1;
  5680. auto end_of_run = first_product_operator.value() + 1;
  5681. for (auto i = start_of_run + 1; i < values.size(); i += 2) {
  5682. auto& item = values[i];
  5683. if (!item.has<Operator>()) {
  5684. end_of_run = i - 1;
  5685. break;
  5686. }
  5687. auto delim = item.get<Operator>().delim;
  5688. if (!first_is_one_of(delim, '*', '/')) {
  5689. end_of_run = i - 1;
  5690. break;
  5691. }
  5692. }
  5693. // 1. For each "/" operator in the run, replace its right-hand value item rhs with an Invert node containing rhs as its child.
  5694. Vector<NonnullOwnPtr<CalculationNode>> run_values;
  5695. run_values.append(move(values[start_of_run].get<NonnullOwnPtr<CalculationNode>>()));
  5696. for (auto i = start_of_run + 1; i <= end_of_run; i += 2) {
  5697. auto& operator_ = values[i].get<Operator>().delim;
  5698. auto& rhs = values[i + 1];
  5699. if (operator_ == '/') {
  5700. run_values.append(InvertCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  5701. continue;
  5702. }
  5703. VERIFY(operator_ == '*');
  5704. run_values.append(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  5705. }
  5706. // 2. Replace the entire run with a Product node containing the value items of the run as its children.
  5707. auto product_node = ProductCalculationNode::create(move(run_values));
  5708. values.remove(start_of_run, end_of_run - start_of_run + 1);
  5709. values.insert(start_of_run, { move(product_node) });
  5710. }
  5711. // 4. Collect children into Sum and Negate nodes.
  5712. Optional<NonnullOwnPtr<CalculationNode>> single_value;
  5713. {
  5714. // 1. For each "-" operator item in values, replace its right-hand value item rhs with a Negate node containing rhs as its child.
  5715. for (auto i = 0u; i < values.size(); ++i) {
  5716. auto& maybe_minus_operator = values[i];
  5717. if (!maybe_minus_operator.has<Operator>() || maybe_minus_operator.get<Operator>().delim != '-')
  5718. continue;
  5719. auto rhs_index = ++i;
  5720. auto& rhs = values[rhs_index];
  5721. NonnullOwnPtr<CalculationNode> negate_node = NegateCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  5722. values.remove(rhs_index);
  5723. values.insert(rhs_index, move(negate_node));
  5724. }
  5725. // 2. If values has only one item, and it is a Product node or a parenthesized simple block, replace values with that item.
  5726. if (values.size() == 1) {
  5727. values.first().visit(
  5728. [&](ComponentValue& component_value) {
  5729. if (component_value.is_block() && component_value.block().is_paren())
  5730. single_value = UnparsedCalculationNode::create(component_value);
  5731. },
  5732. [&](NonnullOwnPtr<CalculationNode>& node) {
  5733. if (node->type() == CalculationNode::Type::Product)
  5734. single_value = move(node);
  5735. },
  5736. [](auto&) {});
  5737. }
  5738. // Otherwise, replace values with a Sum node containing the value items of values as its children.
  5739. if (!single_value.has_value()) {
  5740. values.remove_all_matching([](Value& value) { return value.has<Operator>(); });
  5741. Vector<NonnullOwnPtr<CalculationNode>> value_items;
  5742. value_items.ensure_capacity(values.size());
  5743. for (auto& value : values) {
  5744. if (value.has<Operator>())
  5745. continue;
  5746. value_items.unchecked_append(move(value.get<NonnullOwnPtr<CalculationNode>>()));
  5747. }
  5748. single_value = SumCalculationNode::create(move(value_items));
  5749. }
  5750. }
  5751. // 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.
  5752. // For every leaf node leaf in values:
  5753. bool parsing_failed_for_child_node = false;
  5754. single_value.value()->for_each_child_node([&](NonnullOwnPtr<CalculationNode>& node) {
  5755. if (node->type() != CalculationNode::Type::Unparsed)
  5756. return;
  5757. auto& unparsed_node = static_cast<UnparsedCalculationNode&>(*node);
  5758. auto& component_value = unparsed_node.component_value();
  5759. // 1. If leaf is a parenthesized simple block, replace leaf with the result of parsing a calculation from leaf’s contents.
  5760. if (component_value.is_block() && component_value.block().is_paren()) {
  5761. auto leaf_calculation = parse_a_calculation(component_value.block().values());
  5762. if (!leaf_calculation) {
  5763. parsing_failed_for_child_node = true;
  5764. return;
  5765. }
  5766. node = leaf_calculation.release_nonnull();
  5767. return;
  5768. }
  5769. // 2. If leaf is a math function, replace leaf with the internal representation of that math function.
  5770. // NOTE: All function tokens at this point should be math functions.
  5771. else if (component_value.is_function()) {
  5772. auto& function = component_value.function();
  5773. auto leaf_calculation = parse_a_calc_function_node(function);
  5774. if (!leaf_calculation) {
  5775. parsing_failed_for_child_node = true;
  5776. return;
  5777. }
  5778. node = leaf_calculation.release_nonnull();
  5779. return;
  5780. }
  5781. // NOTE: If we get here, then we have an UnparsedCalculationNode that didn't get replaced with something else.
  5782. // So, the calc() is invalid.
  5783. 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());
  5784. parsing_failed_for_child_node = true;
  5785. return;
  5786. });
  5787. if (parsing_failed_for_child_node)
  5788. return nullptr;
  5789. // FIXME: 6. Return the result of simplifying a calculation tree from values.
  5790. return single_value.release_value();
  5791. }
  5792. bool Parser::has_ignored_vendor_prefix(StringView string)
  5793. {
  5794. if (!string.starts_with('-'))
  5795. return false;
  5796. if (string.starts_with("--"sv))
  5797. return false;
  5798. if (string.starts_with("-libweb-"sv))
  5799. return false;
  5800. return true;
  5801. }
  5802. 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)
  5803. {
  5804. // Unresolved always contains a var() or attr(), unless it is a custom property's value, in which case we shouldn't be trying
  5805. // to produce a different StyleValue from it.
  5806. VERIFY(unresolved.contains_var_or_attr());
  5807. // If the value is invalid, we fall back to `unset`: https://www.w3.org/TR/css-variables-1/#invalid-at-computed-value-time
  5808. auto parser = MUST(Parser::create(context, ""sv));
  5809. return parser.resolve_unresolved_style_value(element, pseudo_element, property_id, unresolved);
  5810. }
  5811. class PropertyDependencyNode : public RefCounted<PropertyDependencyNode> {
  5812. public:
  5813. static NonnullRefPtr<PropertyDependencyNode> create(String name)
  5814. {
  5815. return adopt_ref(*new PropertyDependencyNode(move(name)));
  5816. }
  5817. void add_child(NonnullRefPtr<PropertyDependencyNode> new_child)
  5818. {
  5819. for (auto const& child : m_children) {
  5820. if (child->m_name == new_child->m_name)
  5821. return;
  5822. }
  5823. // We detect self-reference already.
  5824. VERIFY(new_child->m_name != m_name);
  5825. m_children.append(move(new_child));
  5826. }
  5827. bool has_cycles()
  5828. {
  5829. if (m_marked)
  5830. return true;
  5831. TemporaryChange change { m_marked, true };
  5832. for (auto& child : m_children) {
  5833. if (child->has_cycles())
  5834. return true;
  5835. }
  5836. return false;
  5837. }
  5838. private:
  5839. explicit PropertyDependencyNode(String name)
  5840. : m_name(move(name))
  5841. {
  5842. }
  5843. String m_name;
  5844. Vector<NonnullRefPtr<PropertyDependencyNode>> m_children;
  5845. bool m_marked { false };
  5846. };
  5847. NonnullRefPtr<StyleValue> Parser::resolve_unresolved_style_value(DOM::Element& element, Optional<Selector::PseudoElement> pseudo_element, PropertyID property_id, UnresolvedStyleValue const& unresolved)
  5848. {
  5849. TokenStream unresolved_values_without_variables_expanded { unresolved.values() };
  5850. Vector<ComponentValue> values_with_variables_expanded;
  5851. HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>> dependencies;
  5852. if (!expand_variables(element, pseudo_element, string_from_property_id(property_id), dependencies, unresolved_values_without_variables_expanded, values_with_variables_expanded))
  5853. return UnsetStyleValue::the();
  5854. TokenStream unresolved_values_with_variables_expanded { values_with_variables_expanded };
  5855. Vector<ComponentValue> expanded_values;
  5856. if (!expand_unresolved_values(element, string_from_property_id(property_id), unresolved_values_with_variables_expanded, expanded_values))
  5857. return UnsetStyleValue::the();
  5858. auto expanded_value_tokens = TokenStream { expanded_values };
  5859. if (auto parsed_value = parse_css_value(property_id, expanded_value_tokens); !parsed_value.is_error())
  5860. return parsed_value.release_value();
  5861. return UnsetStyleValue::the();
  5862. }
  5863. static RefPtr<StyleValue const> get_custom_property(DOM::Element const& element, Optional<CSS::Selector::PseudoElement> pseudo_element, FlyString const& custom_property_name)
  5864. {
  5865. if (pseudo_element.has_value()) {
  5866. if (auto it = element.custom_properties(pseudo_element).find(custom_property_name.to_string().to_deprecated_string()); it != element.custom_properties(pseudo_element).end())
  5867. return it->value.value;
  5868. }
  5869. for (auto const* current_element = &element; current_element; current_element = current_element->parent_element()) {
  5870. if (auto it = current_element->custom_properties({}).find(custom_property_name.to_string().to_deprecated_string()); it != current_element->custom_properties({}).end())
  5871. return it->value.value;
  5872. }
  5873. return nullptr;
  5874. }
  5875. 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)
  5876. {
  5877. // Arbitrary large value chosen to avoid the billion-laughs attack.
  5878. // https://www.w3.org/TR/css-variables-1/#long-variables
  5879. size_t const MAX_VALUE_COUNT = 16384;
  5880. if (source.remaining_token_count() + dest.size() > MAX_VALUE_COUNT) {
  5881. dbgln("Stopped expanding CSS variables: maximum length reached.");
  5882. return false;
  5883. }
  5884. auto get_dependency_node = [&](FlyString name) -> NonnullRefPtr<PropertyDependencyNode> {
  5885. if (auto existing = dependencies.get(name); existing.has_value())
  5886. return *existing.value();
  5887. auto new_node = PropertyDependencyNode::create(name.to_string());
  5888. dependencies.set(name, new_node);
  5889. return new_node;
  5890. };
  5891. while (source.has_next_token()) {
  5892. auto const& value = source.next_token();
  5893. if (value.is_block()) {
  5894. auto const& source_block = value.block();
  5895. Vector<ComponentValue> block_values;
  5896. TokenStream source_block_contents { source_block.values() };
  5897. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_block_contents, block_values))
  5898. return false;
  5899. NonnullRefPtr<Block> block = Block::create(source_block.token(), move(block_values));
  5900. dest.empend(block);
  5901. continue;
  5902. }
  5903. if (!value.is_function()) {
  5904. dest.empend(value);
  5905. continue;
  5906. }
  5907. if (!value.function().name().equals_ignoring_ascii_case("var"sv)) {
  5908. auto const& source_function = value.function();
  5909. Vector<ComponentValue> function_values;
  5910. TokenStream source_function_contents { source_function.values() };
  5911. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_function_contents, function_values))
  5912. return false;
  5913. NonnullRefPtr<Function> function = Function::create(FlyString::from_utf8(source_function.name()).release_value_but_fixme_should_propagate_errors(), move(function_values));
  5914. dest.empend(function);
  5915. continue;
  5916. }
  5917. TokenStream var_contents { value.function().values() };
  5918. var_contents.skip_whitespace();
  5919. if (!var_contents.has_next_token())
  5920. return false;
  5921. auto const& custom_property_name_token = var_contents.next_token();
  5922. if (!custom_property_name_token.is(Token::Type::Ident))
  5923. return false;
  5924. auto custom_property_name = custom_property_name_token.token().ident();
  5925. if (!custom_property_name.bytes_as_string_view().starts_with("--"sv))
  5926. return false;
  5927. // Detect dependency cycles. https://www.w3.org/TR/css-variables-1/#cycles
  5928. // We do not do this by the spec, since we are not keeping a graph of var dependencies around,
  5929. // but rebuilding it every time.
  5930. if (custom_property_name == property_name)
  5931. return false;
  5932. auto parent = get_dependency_node(FlyString::from_utf8(property_name).release_value_but_fixme_should_propagate_errors());
  5933. auto child = get_dependency_node(FlyString::from_utf8(custom_property_name).release_value_but_fixme_should_propagate_errors());
  5934. parent->add_child(child);
  5935. if (parent->has_cycles())
  5936. return false;
  5937. if (auto custom_property_value = get_custom_property(element, pseudo_element, FlyString::from_utf8(custom_property_name).release_value_but_fixme_should_propagate_errors())) {
  5938. VERIFY(custom_property_value->is_unresolved());
  5939. TokenStream custom_property_tokens { custom_property_value->as_unresolved().values() };
  5940. if (!expand_variables(element, pseudo_element, custom_property_name, dependencies, custom_property_tokens, dest))
  5941. return false;
  5942. continue;
  5943. }
  5944. // Use the provided fallback value, if any.
  5945. var_contents.skip_whitespace();
  5946. if (var_contents.has_next_token()) {
  5947. auto const& comma_token = var_contents.next_token();
  5948. if (!comma_token.is(Token::Type::Comma))
  5949. return false;
  5950. var_contents.skip_whitespace();
  5951. if (!expand_variables(element, pseudo_element, property_name, dependencies, var_contents, dest))
  5952. return false;
  5953. }
  5954. }
  5955. return true;
  5956. }
  5957. bool Parser::expand_unresolved_values(DOM::Element& element, StringView property_name, TokenStream<ComponentValue>& source, Vector<ComponentValue>& dest)
  5958. {
  5959. while (source.has_next_token()) {
  5960. auto const& value = source.next_token();
  5961. if (value.is_function()) {
  5962. if (value.function().name().equals_ignoring_ascii_case("attr"sv)) {
  5963. if (!substitute_attr_function(element, property_name, value.function(), dest))
  5964. return false;
  5965. continue;
  5966. }
  5967. if (auto maybe_calc_value = parse_calculated_value(value); maybe_calc_value && maybe_calc_value->is_calculated()) {
  5968. auto& calc_value = maybe_calc_value->as_calculated();
  5969. if (calc_value.resolves_to_angle()) {
  5970. auto resolved_value = calc_value.resolve_angle();
  5971. dest.empend(Token::create_dimension(resolved_value->to_degrees(), "deg"_fly_string));
  5972. continue;
  5973. }
  5974. if (calc_value.resolves_to_frequency()) {
  5975. auto resolved_value = calc_value.resolve_frequency();
  5976. dest.empend(Token::create_dimension(resolved_value->to_hertz(), "hz"_fly_string));
  5977. continue;
  5978. }
  5979. if (calc_value.resolves_to_length()) {
  5980. // FIXME: In order to resolve lengths, we need to know the font metrics in case a font-relative unit
  5981. // is used. So... we can't do that until style is computed?
  5982. // This might be easier once we have calc-simplification implemented.
  5983. }
  5984. if (calc_value.resolves_to_percentage()) {
  5985. auto resolved_value = calc_value.resolve_percentage();
  5986. dest.empend(Token::create_percentage(resolved_value.value().value()));
  5987. continue;
  5988. }
  5989. if (calc_value.resolves_to_time()) {
  5990. auto resolved_value = calc_value.resolve_time();
  5991. dest.empend(Token::create_dimension(resolved_value->to_seconds(), "s"_fly_string));
  5992. continue;
  5993. }
  5994. if (calc_value.resolves_to_number()) {
  5995. auto resolved_value = calc_value.resolve_number();
  5996. dest.empend(Token::create_number(resolved_value.value()));
  5997. continue;
  5998. }
  5999. }
  6000. auto const& source_function = value.function();
  6001. Vector<ComponentValue> function_values;
  6002. TokenStream source_function_contents { source_function.values() };
  6003. if (!expand_unresolved_values(element, property_name, source_function_contents, function_values))
  6004. return false;
  6005. NonnullRefPtr<Function> function = Function::create(source_function.name(), move(function_values));
  6006. dest.empend(function);
  6007. continue;
  6008. }
  6009. if (value.is_block()) {
  6010. auto const& source_block = value.block();
  6011. TokenStream source_block_values { source_block.values() };
  6012. Vector<ComponentValue> block_values;
  6013. if (!expand_unresolved_values(element, property_name, source_block_values, block_values))
  6014. return false;
  6015. NonnullRefPtr<Block> block = Block::create(source_block.token(), move(block_values));
  6016. dest.empend(move(block));
  6017. continue;
  6018. }
  6019. dest.empend(value.token());
  6020. }
  6021. return true;
  6022. }
  6023. // https://drafts.csswg.org/css-values-5/#attr-substitution
  6024. bool Parser::substitute_attr_function(DOM::Element& element, StringView property_name, Function const& attr_function, Vector<ComponentValue>& dest)
  6025. {
  6026. // First, parse the arguments to attr():
  6027. // attr() = attr( <q-name> <attr-type>? , <declaration-value>?)
  6028. // <attr-type> = string | url | ident | color | number | percentage | length | angle | time | frequency | flex | <dimension-unit>
  6029. TokenStream attr_contents { attr_function.values() };
  6030. attr_contents.skip_whitespace();
  6031. if (!attr_contents.has_next_token())
  6032. return false;
  6033. // - Attribute name
  6034. // FIXME: Support optional attribute namespace
  6035. if (!attr_contents.peek_token().is(Token::Type::Ident))
  6036. return false;
  6037. auto attribute_name = attr_contents.next_token().token().ident();
  6038. attr_contents.skip_whitespace();
  6039. // - Attribute type (optional)
  6040. auto attribute_type = "string"_fly_string;
  6041. if (attr_contents.peek_token().is(Token::Type::Ident)) {
  6042. attribute_type = MUST(FlyString::from_utf8(attr_contents.next_token().token().ident()));
  6043. attr_contents.skip_whitespace();
  6044. }
  6045. // - Comma, then fallback values (optional)
  6046. bool has_fallback_values = false;
  6047. if (attr_contents.has_next_token()) {
  6048. if (!attr_contents.peek_token().is(Token::Type::Comma))
  6049. return false;
  6050. (void)attr_contents.next_token(); // Comma
  6051. has_fallback_values = true;
  6052. }
  6053. // Then, run the substitution algorithm:
  6054. // 1. If the attr() function has a substitution value, replace the attr() function by the substitution value.
  6055. // https://drafts.csswg.org/css-values-5/#attr-types
  6056. if (element.has_attribute(attribute_name)) {
  6057. auto attribute_value = element.get_attribute_value(attribute_name);
  6058. if (attribute_type.equals_ignoring_ascii_case("angle"_fly_string)) {
  6059. // Parse a component value from the attribute’s value.
  6060. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6061. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6062. // Otherwise, there is no substitution value.
  6063. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6064. if (Angle::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6065. dest.append(component_value.release_value());
  6066. return true;
  6067. }
  6068. }
  6069. } else if (attribute_type.equals_ignoring_ascii_case("color"_fly_string)) {
  6070. // Parse a component value from the attribute’s value.
  6071. // If the result is a <hex-color> or a named color ident, the substitution value is that result as a <color>.
  6072. // Otherwise there is no substitution value.
  6073. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6074. if (component_value.has_value()) {
  6075. if ((component_value->is(Token::Type::Hash)
  6076. && Color::from_string(MUST(String::formatted("#{}", component_value->token().hash_value()))).has_value())
  6077. || (component_value->is(Token::Type::Ident)
  6078. && Color::from_string(component_value->token().ident()).has_value())) {
  6079. dest.append(component_value.release_value());
  6080. return true;
  6081. }
  6082. }
  6083. } else if (attribute_type.equals_ignoring_ascii_case("flex"_fly_string)) {
  6084. // Parse a component value from the attribute’s value.
  6085. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6086. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6087. // Otherwise, there is no substitution value.
  6088. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6089. if (Flex::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6090. dest.append(component_value.release_value());
  6091. return true;
  6092. }
  6093. }
  6094. } else if (attribute_type.equals_ignoring_ascii_case("frequency"_fly_string)) {
  6095. // Parse a component value from the attribute’s value.
  6096. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6097. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6098. // Otherwise, there is no substitution value.
  6099. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6100. if (Frequency::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6101. dest.append(component_value.release_value());
  6102. return true;
  6103. }
  6104. }
  6105. } else if (attribute_type.equals_ignoring_ascii_case("ident"_fly_string)) {
  6106. // The substitution value is a CSS <custom-ident>, whose value is the literal value of the attribute,
  6107. // with leading and trailing ASCII whitespace stripped. (No CSS parsing of the value is performed.)
  6108. // If the attribute value, after trimming, is the empty string, there is instead no substitution value.
  6109. // If the <custom-ident>’s value is a CSS-wide keyword or `default`, there is instead no substitution value.
  6110. auto substitution_value = attribute_value.trim_whitespace();
  6111. if (!substitution_value.is_empty()
  6112. && !substitution_value.equals_ignoring_ascii_case("default"sv)
  6113. && !is_css_wide_keyword(substitution_value)) {
  6114. dest.empend(Token::create_ident(MUST(FlyString::from_deprecated_fly_string(substitution_value))));
  6115. return true;
  6116. }
  6117. } else if (attribute_type.equals_ignoring_ascii_case("length"_fly_string)) {
  6118. // Parse a component value from the attribute’s value.
  6119. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6120. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6121. // Otherwise, there is no substitution value.
  6122. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6123. if (Length::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6124. dest.append(component_value.release_value());
  6125. return true;
  6126. }
  6127. }
  6128. } else if (attribute_type.equals_ignoring_ascii_case("number"_fly_string)) {
  6129. // Parse a component value from the attribute’s value.
  6130. // If the result is a <number-token>, the result is the substitution value.
  6131. // Otherwise, there is no substitution value.
  6132. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6133. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  6134. dest.append(component_value.release_value());
  6135. return true;
  6136. }
  6137. } else if (attribute_type.equals_ignoring_ascii_case("percentage"_fly_string)) {
  6138. // Parse a component value from the attribute’s value.
  6139. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6140. // If the result is a <percentage-token>, the result is the substitution value.
  6141. // Otherwise, there is no substitution value.
  6142. if (component_value.has_value() && component_value->is(Token::Type::Percentage)) {
  6143. dest.append(component_value.release_value());
  6144. return true;
  6145. }
  6146. } else if (attribute_type.equals_ignoring_ascii_case("string"_fly_string)) {
  6147. // The substitution value is a CSS string, whose value is the literal value of the attribute.
  6148. // (No CSS parsing or "cleanup" of the value is performed.)
  6149. // No value triggers fallback.
  6150. dest.empend(Token::create_string(MUST(FlyString::from_deprecated_fly_string(attribute_value))));
  6151. return true;
  6152. } else if (attribute_type.equals_ignoring_ascii_case("time"_fly_string)) {
  6153. // Parse a component value from the attribute’s value.
  6154. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6155. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6156. // Otherwise, there is no substitution value.
  6157. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6158. if (Time::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6159. dest.append(component_value.release_value());
  6160. return true;
  6161. }
  6162. }
  6163. } else if (attribute_type.equals_ignoring_ascii_case("url"_fly_string)) {
  6164. // The substitution value is a CSS <url> value, whose url is the literal value of the attribute.
  6165. // (No CSS parsing or "cleanup" of the value is performed.)
  6166. // No value triggers fallback.
  6167. dest.empend(Token::create_url(MUST(FlyString::from_deprecated_fly_string(attribute_value))));
  6168. return true;
  6169. } else {
  6170. // Dimension units
  6171. // Parse a component value from the attribute’s value.
  6172. // If the result is a <number-token>, the substitution value is a dimension with the result’s value, and the given unit.
  6173. // Otherwise, there is no substitution value.
  6174. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6175. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  6176. if (attribute_value == "%"sv) {
  6177. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6178. return true;
  6179. } else if (auto angle_unit = Angle::unit_from_name(attribute_type); angle_unit.has_value()) {
  6180. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6181. return true;
  6182. } else if (auto flex_unit = Flex::unit_from_name(attribute_type); flex_unit.has_value()) {
  6183. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6184. return true;
  6185. } else if (auto frequency_unit = Frequency::unit_from_name(attribute_type); frequency_unit.has_value()) {
  6186. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6187. return true;
  6188. } else if (auto length_unit = Length::unit_from_name(attribute_type); length_unit.has_value()) {
  6189. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6190. return true;
  6191. } else if (auto time_unit = Time::unit_from_name(attribute_type); time_unit.has_value()) {
  6192. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6193. return true;
  6194. } else {
  6195. // Not a dimension unit.
  6196. return false;
  6197. }
  6198. }
  6199. }
  6200. }
  6201. // 2. Otherwise, if the attr() function has a fallback value as its last argument, replace the attr() function by the fallback value.
  6202. // If there are any var() or attr() references in the fallback, substitute them as well.
  6203. if (has_fallback_values)
  6204. return expand_unresolved_values(element, property_name, attr_contents, dest);
  6205. // 3. Otherwise, the property containing the attr() function is invalid at computed-value time.
  6206. return false;
  6207. }
  6208. }