Parser.cpp 309 KB

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