Parser.cpp 252 KB

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