Parser.cpp 301 KB

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