Parser.cpp 251 KB

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