Parser.cpp 302 KB

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