Parser.cpp 229 KB

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