Parser.cpp 301 KB

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