Parser.cpp 304 KB

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