Parser.cpp 297 KB

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