Parser.cpp 302 KB

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