Parser.cpp 260 KB

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