Parser.cpp 301 KB

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