Parser.cpp 301 KB

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