Parser.cpp 300 KB

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