Parser.cpp 300 KB

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