Parser.cpp 305 KB

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