Parser.cpp 290 KB

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