Parser.cpp 175 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746
  1. /*
  2. * Copyright (c) 2018-2020, 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/NonnullRefPtrVector.h>
  12. #include <AK/SourceLocation.h>
  13. #include <LibWeb/CSS/CSSImportRule.h>
  14. #include <LibWeb/CSS/CSSMediaRule.h>
  15. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  16. #include <LibWeb/CSS/CSSStyleRule.h>
  17. #include <LibWeb/CSS/CSSStyleSheet.h>
  18. #include <LibWeb/CSS/CSSSupportsRule.h>
  19. #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
  20. #include <LibWeb/CSS/Parser/Parser.h>
  21. #include <LibWeb/CSS/Parser/StyleBlockRule.h>
  22. #include <LibWeb/CSS/Parser/StyleComponentValueRule.h>
  23. #include <LibWeb/CSS/Parser/StyleFunctionRule.h>
  24. #include <LibWeb/CSS/Parser/StyleRule.h>
  25. #include <LibWeb/CSS/Selector.h>
  26. #include <LibWeb/DOM/Document.h>
  27. #include <LibWeb/Dump.h>
  28. static void log_parse_error(const SourceLocation& location = SourceLocation::current())
  29. {
  30. dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
  31. }
  32. namespace Web::CSS {
  33. ParsingContext::ParsingContext(DOM::Document const& document)
  34. : m_document(&document)
  35. {
  36. }
  37. ParsingContext::ParsingContext(DOM::ParentNode& parent_node)
  38. : m_document(&parent_node.document())
  39. {
  40. }
  41. bool ParsingContext::in_quirks_mode() const
  42. {
  43. return m_document ? m_document->in_quirks_mode() : false;
  44. }
  45. AK::URL ParsingContext::complete_url(String const& addr) const
  46. {
  47. return m_document ? m_document->url().complete_url(addr) : AK::URL::create_with_url_or_path(addr);
  48. }
  49. template<typename T>
  50. TokenStream<T>::TokenStream(Vector<T> const& tokens)
  51. : m_tokens(tokens)
  52. , m_eof(make_eof())
  53. {
  54. }
  55. template<typename T>
  56. TokenStream<T>::~TokenStream()
  57. {
  58. }
  59. template<typename T>
  60. bool TokenStream<T>::has_next_token()
  61. {
  62. return (size_t)(m_iterator_offset + 1) < m_tokens.size();
  63. }
  64. template<typename T>
  65. T const& TokenStream<T>::peek_token(int offset)
  66. {
  67. if (!has_next_token())
  68. return m_eof;
  69. return m_tokens.at(m_iterator_offset + offset + 1);
  70. }
  71. template<typename T>
  72. T const& TokenStream<T>::next_token()
  73. {
  74. if (!has_next_token())
  75. return m_eof;
  76. ++m_iterator_offset;
  77. return m_tokens.at(m_iterator_offset);
  78. }
  79. template<typename T>
  80. T const& TokenStream<T>::current_token()
  81. {
  82. if ((size_t)m_iterator_offset >= m_tokens.size())
  83. return m_eof;
  84. return m_tokens.at(m_iterator_offset);
  85. }
  86. template<typename T>
  87. void TokenStream<T>::reconsume_current_input_token()
  88. {
  89. if (m_iterator_offset >= 0)
  90. --m_iterator_offset;
  91. }
  92. template<typename T>
  93. void TokenStream<T>::rewind_to_position(int position)
  94. {
  95. VERIFY(position <= m_iterator_offset);
  96. m_iterator_offset = position;
  97. }
  98. template<typename T>
  99. void TokenStream<T>::skip_whitespace()
  100. {
  101. while (peek_token().is(Token::Type::Whitespace))
  102. next_token();
  103. }
  104. template<>
  105. Token TokenStream<Token>::make_eof()
  106. {
  107. return Tokenizer::create_eof_token();
  108. }
  109. template<>
  110. StyleComponentValueRule TokenStream<StyleComponentValueRule>::make_eof()
  111. {
  112. return StyleComponentValueRule(Tokenizer::create_eof_token());
  113. }
  114. template<typename T>
  115. void TokenStream<T>::dump_all_tokens()
  116. {
  117. dbgln("Dumping all tokens:");
  118. for (size_t i = 0; i < m_tokens.size(); ++i) {
  119. auto& token = m_tokens[i];
  120. if ((i - 1) == (size_t)m_iterator_offset)
  121. dbgln("-> {}", token.to_debug_string());
  122. else
  123. dbgln(" {}", token.to_debug_string());
  124. }
  125. }
  126. Parser::Parser(ParsingContext const& context, StringView input, String const& encoding)
  127. : m_context(context)
  128. , m_tokenizer(input, encoding)
  129. , m_tokens(m_tokenizer.parse())
  130. , m_token_stream(TokenStream(m_tokens))
  131. {
  132. }
  133. Parser::~Parser()
  134. {
  135. }
  136. NonnullRefPtr<CSSStyleSheet> Parser::parse_as_stylesheet()
  137. {
  138. return parse_a_stylesheet(m_token_stream);
  139. }
  140. template<typename T>
  141. NonnullRefPtr<CSSStyleSheet> Parser::parse_a_stylesheet(TokenStream<T>& tokens)
  142. {
  143. auto parser_rules = consume_a_list_of_rules(tokens, true);
  144. NonnullRefPtrVector<CSSRule> rules;
  145. for (auto& raw_rule : parser_rules) {
  146. auto rule = convert_to_rule(raw_rule);
  147. if (rule)
  148. rules.append(*rule);
  149. }
  150. return CSSStyleSheet::create(rules);
  151. }
  152. Optional<SelectorList> Parser::parse_as_selector()
  153. {
  154. auto selector_list = parse_a_selector(m_token_stream);
  155. if (!selector_list.is_error())
  156. return selector_list.release_value();
  157. return {};
  158. }
  159. template<typename T>
  160. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_selector(TokenStream<T>& tokens)
  161. {
  162. return parse_a_selector_list(tokens);
  163. }
  164. Optional<SelectorList> Parser::parse_as_relative_selector()
  165. {
  166. auto selector_list = parse_a_relative_selector(m_token_stream);
  167. if (!selector_list.is_error())
  168. return selector_list.release_value();
  169. return {};
  170. }
  171. template<typename T>
  172. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_relative_selector(TokenStream<T>& tokens)
  173. {
  174. return parse_a_relative_selector_list(tokens);
  175. }
  176. template<typename T>
  177. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_selector_list(TokenStream<T>& tokens)
  178. {
  179. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  180. NonnullRefPtrVector<Selector> selectors;
  181. for (auto& selector_parts : comma_separated_lists) {
  182. auto stream = TokenStream(selector_parts);
  183. auto selector = parse_complex_selector(stream, false);
  184. if (selector.is_error())
  185. return selector.error();
  186. selectors.append(selector.release_value());
  187. }
  188. if (selectors.is_empty())
  189. return ParsingResult::SyntaxError;
  190. return selectors;
  191. }
  192. template<typename T>
  193. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_relative_selector_list(TokenStream<T>& tokens)
  194. {
  195. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  196. NonnullRefPtrVector<Selector> selectors;
  197. for (auto& selector_parts : comma_separated_lists) {
  198. auto stream = TokenStream(selector_parts);
  199. auto selector = parse_complex_selector(stream, true);
  200. if (selector.is_error())
  201. return selector.error();
  202. selectors.append(selector.release_value());
  203. }
  204. if (selectors.is_empty())
  205. return ParsingResult::SyntaxError;
  206. return selectors;
  207. }
  208. Result<NonnullRefPtr<Selector>, Parser::ParsingResult> Parser::parse_complex_selector(TokenStream<StyleComponentValueRule>& tokens, bool allow_starting_combinator)
  209. {
  210. Vector<Selector::CompoundSelector> compound_selectors;
  211. auto first_selector = parse_compound_selector(tokens);
  212. if (first_selector.is_error())
  213. return first_selector.error();
  214. if (!allow_starting_combinator) {
  215. if (first_selector.value().combinator != Selector::Combinator::Descendant)
  216. return ParsingResult::SyntaxError;
  217. first_selector.value().combinator = Selector::Combinator::None;
  218. }
  219. compound_selectors.append(first_selector.value());
  220. while (tokens.has_next_token()) {
  221. auto compound_selector = parse_compound_selector(tokens);
  222. if (compound_selector.is_error()) {
  223. if (compound_selector.error() == ParsingResult::Done)
  224. break;
  225. else
  226. return compound_selector.error();
  227. }
  228. compound_selectors.append(compound_selector.value());
  229. }
  230. if (compound_selectors.is_empty())
  231. return ParsingResult::SyntaxError;
  232. return Selector::create(move(compound_selectors));
  233. }
  234. Result<Selector::CompoundSelector, Parser::ParsingResult> Parser::parse_compound_selector(TokenStream<StyleComponentValueRule>& tokens)
  235. {
  236. tokens.skip_whitespace();
  237. auto combinator = parse_selector_combinator(tokens).value_or(Selector::Combinator::Descendant);
  238. tokens.skip_whitespace();
  239. Vector<Selector::SimpleSelector> simple_selectors;
  240. while (tokens.has_next_token()) {
  241. auto component = parse_simple_selector(tokens);
  242. if (component.is_error()) {
  243. if (component.error() == ParsingResult::Done)
  244. break;
  245. else
  246. return component.error();
  247. }
  248. simple_selectors.append(component.value());
  249. }
  250. if (simple_selectors.is_empty())
  251. return ParsingResult::Done;
  252. return Selector::CompoundSelector { combinator, move(simple_selectors) };
  253. }
  254. Optional<Selector::Combinator> Parser::parse_selector_combinator(TokenStream<StyleComponentValueRule>& tokens)
  255. {
  256. auto& current_value = tokens.next_token();
  257. if (current_value.is(Token::Type::Delim)) {
  258. auto delim = current_value.token().delim();
  259. if (delim == ">"sv) {
  260. return Selector::Combinator::ImmediateChild;
  261. } else if (delim == "+"sv) {
  262. return Selector::Combinator::NextSibling;
  263. } else if (delim == "~"sv) {
  264. return Selector::Combinator::SubsequentSibling;
  265. } else if (delim == "|"sv) {
  266. auto& next = tokens.peek_token();
  267. if (next.is(Token::Type::EndOfFile))
  268. return {};
  269. if (next.is(Token::Type::Delim) && next.token().delim() == "|"sv) {
  270. tokens.next_token();
  271. return Selector::Combinator::Column;
  272. }
  273. }
  274. }
  275. tokens.reconsume_current_input_token();
  276. return {};
  277. }
  278. Result<Selector::SimpleSelector, Parser::ParsingResult> Parser::parse_simple_selector(TokenStream<StyleComponentValueRule>& tokens)
  279. {
  280. auto peek_token_ends_selector = [&]() -> bool {
  281. auto& value = tokens.peek_token();
  282. return (value.is(Token::Type::EndOfFile) || value.is(Token::Type::Whitespace) || value.is(Token::Type::Comma));
  283. };
  284. if (peek_token_ends_selector())
  285. return ParsingResult::Done;
  286. auto& first_value = tokens.next_token();
  287. if (first_value.is(Token::Type::Delim) && first_value.token().delim() == "*"sv) {
  288. return Selector::SimpleSelector {
  289. .type = Selector::SimpleSelector::Type::Universal
  290. };
  291. } else if (first_value.is(Token::Type::Hash)) {
  292. if (first_value.token().hash_type() != Token::HashType::Id) {
  293. dbgln_if(CSS_PARSER_DEBUG, "Selector contains hash token that is not an id: {}", first_value.to_debug_string());
  294. return ParsingResult::SyntaxError;
  295. }
  296. return Selector::SimpleSelector {
  297. .type = Selector::SimpleSelector::Type::Id,
  298. .value = first_value.token().hash_value()
  299. };
  300. } else if (first_value.is(Token::Type::Delim) && first_value.token().delim() == "."sv) {
  301. if (peek_token_ends_selector())
  302. return ParsingResult::SyntaxError;
  303. auto& class_name_value = tokens.next_token();
  304. if (!class_name_value.is(Token::Type::Ident)) {
  305. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident after '.', got: {}", class_name_value.to_debug_string());
  306. return ParsingResult::SyntaxError;
  307. }
  308. return Selector::SimpleSelector {
  309. .type = Selector::SimpleSelector::Type::Class,
  310. .value = class_name_value.token().ident()
  311. };
  312. } else if (first_value.is(Token::Type::Ident)) {
  313. return Selector::SimpleSelector {
  314. .type = Selector::SimpleSelector::Type::TagName,
  315. .value = first_value.token().ident()
  316. };
  317. } else if (first_value.is_block() && first_value.block().is_square()) {
  318. auto attribute_tokens = TokenStream { first_value.block().values() };
  319. attribute_tokens.skip_whitespace();
  320. if (!attribute_tokens.has_next_token()) {
  321. dbgln_if(CSS_PARSER_DEBUG, "CSS attribute selector is empty!");
  322. return ParsingResult::SyntaxError;
  323. }
  324. // FIXME: Handle namespace prefix for attribute name.
  325. auto& attribute_part = attribute_tokens.next_token();
  326. if (!attribute_part.is(Token::Type::Ident)) {
  327. dbgln_if(CSS_PARSER_DEBUG, "Expected ident for attribute name, got: '{}'", attribute_part.to_debug_string());
  328. return ParsingResult::SyntaxError;
  329. }
  330. Selector::SimpleSelector simple_selector {
  331. .type = Selector::SimpleSelector::Type::Attribute,
  332. .attribute = {
  333. .match_type = Selector::SimpleSelector::Attribute::MatchType::HasAttribute,
  334. // FIXME: Case-sensitivity is defined by the document language.
  335. // HTML is insensitive with attribute names, and our code generally assumes
  336. // they are converted to lowercase, so we do that here too. If we want to be
  337. // correct with XML later, we'll need to keep the original case and then do
  338. // a case-insensitive compare later.
  339. .name = attribute_part.token().ident().to_lowercase_string(),
  340. }
  341. };
  342. attribute_tokens.skip_whitespace();
  343. if (!attribute_tokens.has_next_token())
  344. return simple_selector;
  345. auto& delim_part = attribute_tokens.next_token();
  346. if (!delim_part.is(Token::Type::Delim)) {
  347. dbgln_if(CSS_PARSER_DEBUG, "Expected a delim for attribute comparison, got: '{}'", delim_part.to_debug_string());
  348. return ParsingResult::SyntaxError;
  349. }
  350. if (delim_part.token().delim() == "="sv) {
  351. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch;
  352. } else {
  353. if (!attribute_tokens.has_next_token()) {
  354. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended part way through a match type.");
  355. return ParsingResult::SyntaxError;
  356. }
  357. auto& delim_second_part = attribute_tokens.next_token();
  358. if (!(delim_second_part.is(Token::Type::Delim) && delim_second_part.token().delim() == "=")) {
  359. dbgln_if(CSS_PARSER_DEBUG, "Expected a double delim for attribute comparison, got: '{}{}'", delim_part.to_debug_string(), delim_second_part.to_debug_string());
  360. return ParsingResult::SyntaxError;
  361. }
  362. if (delim_part.token().delim() == "~"sv) {
  363. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsWord;
  364. } else if (delim_part.token().delim() == "*"sv) {
  365. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsString;
  366. } else if (delim_part.token().delim() == "|"sv) {
  367. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment;
  368. } else if (delim_part.token().delim() == "^"sv) {
  369. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithString;
  370. } else if (delim_part.token().delim() == "$"sv) {
  371. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::EndsWithString;
  372. } else {
  373. attribute_tokens.reconsume_current_input_token();
  374. }
  375. }
  376. attribute_tokens.skip_whitespace();
  377. if (!attribute_tokens.has_next_token()) {
  378. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended without a value to match.");
  379. return ParsingResult::SyntaxError;
  380. }
  381. auto& value_part = attribute_tokens.next_token();
  382. if (!value_part.is(Token::Type::Ident) && !value_part.is(Token::Type::String)) {
  383. dbgln_if(CSS_PARSER_DEBUG, "Expected a string or ident for the value to match attribute against, got: '{}'", value_part.to_debug_string());
  384. return ParsingResult::SyntaxError;
  385. }
  386. simple_selector.attribute.value = value_part.token().is(Token::Type::Ident) ? value_part.token().ident() : value_part.token().string();
  387. attribute_tokens.skip_whitespace();
  388. // FIXME: Handle case-sensitivity suffixes. https://www.w3.org/TR/selectors-4/#attribute-case
  389. return simple_selector;
  390. } else if (first_value.is(Token::Type::Colon)) {
  391. if (peek_token_ends_selector())
  392. return ParsingResult::SyntaxError;
  393. bool is_pseudo = false;
  394. if (tokens.peek_token().is(Token::Type::Colon)) {
  395. is_pseudo = true;
  396. tokens.next_token();
  397. if (peek_token_ends_selector())
  398. return ParsingResult::SyntaxError;
  399. }
  400. if (is_pseudo) {
  401. Selector::SimpleSelector simple_selector {
  402. .type = Selector::SimpleSelector::Type::PseudoElement
  403. };
  404. auto& name_token = tokens.next_token();
  405. if (!name_token.is(Token::Type::Ident)) {
  406. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident for pseudo-element, got: '{}'", name_token.to_debug_string());
  407. return ParsingResult::SyntaxError;
  408. }
  409. auto pseudo_name = name_token.token().ident();
  410. if (has_ignored_vendor_prefix(pseudo_name))
  411. return ParsingResult::IncludesIgnoredVendorPrefix;
  412. if (pseudo_name.equals_ignoring_case("after")) {
  413. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  414. } else if (pseudo_name.equals_ignoring_case("before")) {
  415. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  416. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  417. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  418. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  419. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  420. } else {
  421. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized pseudo-element: '::{}'", pseudo_name);
  422. return ParsingResult::SyntaxError;
  423. }
  424. return simple_selector;
  425. }
  426. if (peek_token_ends_selector())
  427. return ParsingResult::SyntaxError;
  428. auto& pseudo_class_token = tokens.next_token();
  429. Selector::SimpleSelector simple_selector {
  430. .type = Selector::SimpleSelector::Type::PseudoClass
  431. };
  432. if (pseudo_class_token.is(Token::Type::Ident)) {
  433. auto pseudo_name = pseudo_class_token.token().ident();
  434. if (has_ignored_vendor_prefix(pseudo_name))
  435. return ParsingResult::IncludesIgnoredVendorPrefix;
  436. if (pseudo_name.equals_ignoring_case("active")) {
  437. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Active;
  438. } else if (pseudo_name.equals_ignoring_case("checked")) {
  439. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Checked;
  440. } else if (pseudo_name.equals_ignoring_case("disabled")) {
  441. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Disabled;
  442. } else if (pseudo_name.equals_ignoring_case("empty")) {
  443. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Empty;
  444. } else if (pseudo_name.equals_ignoring_case("enabled")) {
  445. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Enabled;
  446. } else if (pseudo_name.equals_ignoring_case("first-child")) {
  447. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstChild;
  448. } else if (pseudo_name.equals_ignoring_case("first-of-type")) {
  449. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstOfType;
  450. } else if (pseudo_name.equals_ignoring_case("focus")) {
  451. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Focus;
  452. } else if (pseudo_name.equals_ignoring_case("hover")) {
  453. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Hover;
  454. } else if (pseudo_name.equals_ignoring_case("last-child")) {
  455. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastChild;
  456. } else if (pseudo_name.equals_ignoring_case("last-of-type")) {
  457. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastOfType;
  458. } else if (pseudo_name.equals_ignoring_case("link")) {
  459. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Link;
  460. } else if (pseudo_name.equals_ignoring_case("only-child")) {
  461. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::OnlyChild;
  462. } else if (pseudo_name.equals_ignoring_case("only-of-type")) {
  463. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::OnlyOfType;
  464. } else if (pseudo_name.equals_ignoring_case("root")) {
  465. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Root;
  466. } else if (pseudo_name.equals_ignoring_case("visited")) {
  467. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Visited;
  468. } else if (pseudo_name.equals_ignoring_case("after")) {
  469. // Single-colon syntax allowed for compatibility. https://www.w3.org/TR/selectors/#pseudo-element-syntax
  470. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  471. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  472. } else if (pseudo_name.equals_ignoring_case("before")) {
  473. // See :after
  474. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  475. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  476. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  477. // See :after
  478. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  479. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  480. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  481. // See :after
  482. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  483. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  484. } else {
  485. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized pseudo-class: ':{}'", pseudo_name);
  486. return ParsingResult::SyntaxError;
  487. }
  488. return simple_selector;
  489. } else if (pseudo_class_token.is_function()) {
  490. auto& pseudo_function = pseudo_class_token.function();
  491. if (pseudo_function.name().equals_ignoring_case("not")) {
  492. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Not;
  493. auto function_token_stream = TokenStream(pseudo_function.values());
  494. auto not_selector = parse_a_selector(function_token_stream);
  495. if (not_selector.is_error()) {
  496. dbgln_if(CSS_PARSER_DEBUG, "Invalid selector in :not() clause");
  497. return ParsingResult::SyntaxError;
  498. }
  499. simple_selector.pseudo_class.not_selector = not_selector.release_value();
  500. } else if (pseudo_function.name().equals_ignoring_case("nth-child")) {
  501. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthChild;
  502. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  503. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  504. if (nth_child_pattern.has_value()) {
  505. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  506. } else {
  507. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  508. return ParsingResult::SyntaxError;
  509. }
  510. } else if (pseudo_function.name().equals_ignoring_case("nth-last-child")) {
  511. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthLastChild;
  512. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  513. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  514. if (nth_child_pattern.has_value()) {
  515. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  516. } else {
  517. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  518. return ParsingResult::SyntaxError;
  519. }
  520. } else {
  521. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized pseudo-class function: ':{}'()", pseudo_function.name());
  522. return ParsingResult::SyntaxError;
  523. }
  524. return simple_selector;
  525. } else {
  526. dbgln_if(CSS_PARSER_DEBUG, "Unexpected Block in pseudo-class name, expected a function or identifier. '{}'", pseudo_class_token.to_debug_string());
  527. return ParsingResult::SyntaxError;
  528. }
  529. }
  530. // Whitespace is not required between the compound-selector and a combinator.
  531. // So, if we see a combinator, return that this compound-selector is done, instead of a syntax error.
  532. if (first_value.is(Token::Type::Delim)) {
  533. auto delim = first_value.token().delim();
  534. if ((delim == ">"sv) || (delim == "+"sv) || (delim == "~"sv) || (delim == "|"sv)) {
  535. tokens.reconsume_current_input_token();
  536. return ParsingResult::Done;
  537. }
  538. }
  539. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid simple selector!");
  540. return ParsingResult::SyntaxError;
  541. }
  542. NonnullRefPtrVector<MediaQuery> Parser::parse_as_media_query_list()
  543. {
  544. return parse_a_media_query_list(m_token_stream);
  545. }
  546. template<typename T>
  547. NonnullRefPtrVector<MediaQuery> Parser::parse_a_media_query_list(TokenStream<T>& tokens)
  548. {
  549. // https://www.w3.org/TR/mediaqueries-4/#mq-list
  550. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  551. AK::NonnullRefPtrVector<MediaQuery> media_queries;
  552. for (auto& media_query_parts : comma_separated_lists) {
  553. auto stream = TokenStream(media_query_parts);
  554. media_queries.append(parse_media_query(stream));
  555. }
  556. return media_queries;
  557. }
  558. RefPtr<MediaQuery> Parser::parse_as_media_query()
  559. {
  560. // https://www.w3.org/TR/cssom-1/#parse-a-media-query
  561. auto media_query_list = parse_as_media_query_list();
  562. if (media_query_list.is_empty())
  563. return MediaQuery::create_not_all();
  564. if (media_query_list.size() == 1)
  565. return media_query_list.first();
  566. return nullptr;
  567. }
  568. // `<media-query>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-query
  569. NonnullRefPtr<MediaQuery> Parser::parse_media_query(TokenStream<StyleComponentValueRule>& tokens)
  570. {
  571. // `<media-query> = <media-condition>
  572. // | [ not | only ]? <media-type> [ and <media-condition-without-or> ]?`
  573. auto position = tokens.position();
  574. tokens.skip_whitespace();
  575. // `[ not | only ]?`, Returns whether to negate the query
  576. auto parse_initial_modifier = [](auto& tokens) -> Optional<bool> {
  577. auto position = tokens.position();
  578. tokens.skip_whitespace();
  579. auto& token = tokens.next_token();
  580. if (!token.is(Token::Type::Ident)) {
  581. tokens.rewind_to_position(position);
  582. return {};
  583. }
  584. auto ident = token.token().ident();
  585. if (ident.equals_ignoring_case("not")) {
  586. return true;
  587. } else if (ident.equals_ignoring_case("only")) {
  588. return false;
  589. }
  590. tokens.rewind_to_position(position);
  591. return {};
  592. };
  593. auto invalid_media_query = [&]() {
  594. // "A media query that does not match the grammar in the previous section must be replaced by `not all`
  595. // during parsing." - https://www.w3.org/TR/mediaqueries-5/#error-handling
  596. if constexpr (CSS_PARSER_DEBUG) {
  597. dbgln("Invalid media query:");
  598. tokens.dump_all_tokens();
  599. }
  600. tokens.rewind_to_position(position);
  601. return MediaQuery::create_not_all();
  602. };
  603. auto media_query = MediaQuery::create();
  604. tokens.skip_whitespace();
  605. // `<media-condition>`
  606. if (auto media_condition = parse_media_condition(tokens, MediaCondition::AllowOr::Yes)) {
  607. tokens.skip_whitespace();
  608. if (tokens.has_next_token())
  609. return invalid_media_query();
  610. media_query->m_media_condition = move(media_condition);
  611. return media_query;
  612. }
  613. // `[ not | only ]?`
  614. if (auto modifier = parse_initial_modifier(tokens); modifier.has_value()) {
  615. media_query->m_negated = modifier.value();
  616. tokens.skip_whitespace();
  617. }
  618. // `<media-type>`
  619. if (auto media_type = parse_media_type(tokens); media_type.has_value()) {
  620. media_query->m_media_type = media_type.value();
  621. tokens.skip_whitespace();
  622. } else {
  623. return invalid_media_query();
  624. }
  625. if (!tokens.has_next_token())
  626. return media_query;
  627. // `[ and <media-condition-without-or> ]?`
  628. if (auto maybe_and = tokens.next_token(); maybe_and.is(Token::Type::Ident) && maybe_and.token().ident().equals_ignoring_case("and")) {
  629. if (auto media_condition = parse_media_condition(tokens, MediaCondition::AllowOr::No)) {
  630. tokens.skip_whitespace();
  631. if (tokens.has_next_token())
  632. return invalid_media_query();
  633. media_query->m_media_condition = move(media_condition);
  634. return media_query;
  635. }
  636. return invalid_media_query();
  637. }
  638. return invalid_media_query();
  639. }
  640. // `<media-condition>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-condition
  641. // `<media-condition-widthout-or>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-condition-without-or
  642. // (We distinguish between these two with the `allow_or` parameter.)
  643. OwnPtr<MediaCondition> Parser::parse_media_condition(TokenStream<StyleComponentValueRule>& tokens, MediaCondition::AllowOr allow_or)
  644. {
  645. // `<media-not> | <media-in-parens> [ <media-and>* | <media-or>* ]`
  646. auto position = tokens.position();
  647. tokens.skip_whitespace();
  648. // `<media-not> = not <media-in-parens>`
  649. auto parse_media_not = [&](auto& tokens) -> OwnPtr<MediaCondition> {
  650. auto position = tokens.position();
  651. tokens.skip_whitespace();
  652. auto& first_token = tokens.next_token();
  653. if (first_token.is(Token::Type::Ident) && first_token.token().ident().equals_ignoring_case("not"sv)) {
  654. if (auto child_condition = parse_media_condition(tokens, MediaCondition::AllowOr::Yes))
  655. return MediaCondition::from_not(child_condition.release_nonnull());
  656. }
  657. tokens.rewind_to_position(position);
  658. return {};
  659. };
  660. auto parse_media_with_combinator = [&](auto& tokens, StringView combinator) -> OwnPtr<MediaCondition> {
  661. auto position = tokens.position();
  662. tokens.skip_whitespace();
  663. auto& first = tokens.next_token();
  664. if (first.is(Token::Type::Ident) && first.token().ident().equals_ignoring_case(combinator)) {
  665. tokens.skip_whitespace();
  666. if (auto media_in_parens = parse_media_in_parens(tokens))
  667. return media_in_parens;
  668. }
  669. tokens.rewind_to_position(position);
  670. return {};
  671. };
  672. // `<media-and> = and <media-in-parens>`
  673. auto parse_media_and = [&](auto& tokens) { return parse_media_with_combinator(tokens, "and"sv); };
  674. // `<media-or> = or <media-in-parens>`
  675. auto parse_media_or = [&](auto& tokens) { return parse_media_with_combinator(tokens, "or"sv); };
  676. // `<media-not>`
  677. if (auto maybe_media_not = parse_media_not(tokens))
  678. return maybe_media_not.release_nonnull();
  679. // `<media-in-parens> [ <media-and>* | <media-or>* ]`
  680. if (auto maybe_media_in_parens = parse_media_in_parens(tokens)) {
  681. tokens.skip_whitespace();
  682. // Only `<media-in-parens>`
  683. if (!tokens.has_next_token())
  684. return maybe_media_in_parens.release_nonnull();
  685. NonnullOwnPtrVector<MediaCondition> child_conditions;
  686. child_conditions.append(maybe_media_in_parens.release_nonnull());
  687. // `<media-and>*`
  688. if (auto media_and = parse_media_and(tokens)) {
  689. child_conditions.append(media_and.release_nonnull());
  690. tokens.skip_whitespace();
  691. while (tokens.has_next_token()) {
  692. if (auto next_media_and = parse_media_and(tokens)) {
  693. child_conditions.append(next_media_and.release_nonnull());
  694. tokens.skip_whitespace();
  695. continue;
  696. }
  697. // We failed - invalid syntax!
  698. tokens.rewind_to_position(position);
  699. return {};
  700. }
  701. return MediaCondition::from_and_list(move(child_conditions));
  702. }
  703. // `<media-or>*`
  704. if (allow_or == MediaCondition::AllowOr::Yes) {
  705. if (auto media_or = parse_media_or(tokens)) {
  706. child_conditions.append(media_or.release_nonnull());
  707. tokens.skip_whitespace();
  708. while (tokens.has_next_token()) {
  709. if (auto next_media_or = parse_media_or(tokens)) {
  710. child_conditions.append(next_media_or.release_nonnull());
  711. tokens.skip_whitespace();
  712. continue;
  713. }
  714. // We failed - invalid syntax!
  715. tokens.rewind_to_position(position);
  716. return {};
  717. }
  718. return MediaCondition::from_or_list(move(child_conditions));
  719. }
  720. }
  721. }
  722. tokens.rewind_to_position(position);
  723. return {};
  724. }
  725. // `<media-feature>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-feature
  726. Optional<MediaFeature> Parser::parse_media_feature(TokenStream<StyleComponentValueRule>& tokens)
  727. {
  728. // `[ <mf-plain> | <mf-boolean> | <mf-range> ]`
  729. auto position = tokens.position();
  730. tokens.skip_whitespace();
  731. // `<mf-name> = <ident>`
  732. auto parse_mf_name = [](auto& tokens, bool allow_min_max_prefix) -> Optional<String> {
  733. auto& token = tokens.peek_token();
  734. if (token.is(Token::Type::Ident)) {
  735. auto name = token.token().ident();
  736. if (is_media_feature_name(name)) {
  737. tokens.next_token();
  738. return name;
  739. }
  740. if (allow_min_max_prefix && (name.starts_with("min-", CaseSensitivity::CaseInsensitive) || name.starts_with("max-", CaseSensitivity::CaseInsensitive))) {
  741. auto adjusted_name = name.substring_view(4);
  742. if (is_media_feature_name(adjusted_name)) {
  743. tokens.next_token();
  744. return name;
  745. }
  746. }
  747. }
  748. return {};
  749. };
  750. // `<mf-boolean> = <mf-name>`
  751. auto parse_mf_boolean = [&](auto& tokens) -> Optional<MediaFeature> {
  752. auto position = tokens.position();
  753. tokens.skip_whitespace();
  754. auto maybe_name = parse_mf_name(tokens, false);
  755. if (maybe_name.has_value()) {
  756. tokens.skip_whitespace();
  757. if (!tokens.has_next_token())
  758. return MediaFeature::boolean(maybe_name.release_value());
  759. }
  760. tokens.rewind_to_position(position);
  761. return {};
  762. };
  763. // `<mf-plain> = <mf-name> : <mf-value>`
  764. auto parse_mf_plain = [&](auto& tokens) -> Optional<MediaFeature> {
  765. auto position = tokens.position();
  766. tokens.skip_whitespace();
  767. if (auto maybe_name = parse_mf_name(tokens, true); maybe_name.has_value()) {
  768. tokens.skip_whitespace();
  769. if (tokens.next_token().is(Token::Type::Colon)) {
  770. tokens.skip_whitespace();
  771. if (auto maybe_value = parse_media_feature_value(tokens); maybe_value.has_value()) {
  772. tokens.skip_whitespace();
  773. if (!tokens.has_next_token())
  774. return MediaFeature::plain(maybe_name.release_value(), maybe_value.release_value());
  775. }
  776. }
  777. }
  778. tokens.rewind_to_position(position);
  779. return {};
  780. };
  781. // `<mf-lt> = '<' '='?
  782. // <mf-gt> = '>' '='?
  783. // <mf-eq> = '='
  784. // <mf-comparison> = <mf-lt> | <mf-gt> | <mf-eq>`
  785. auto parse_comparison = [](auto& tokens) -> Optional<MediaFeature::Comparison> {
  786. auto position = tokens.position();
  787. tokens.skip_whitespace();
  788. auto& first = tokens.next_token();
  789. if (first.is(Token::Type::Delim)) {
  790. auto first_delim = first.token().delim();
  791. if (first_delim == "="sv)
  792. return MediaFeature::Comparison::Equal;
  793. if (first_delim == "<"sv) {
  794. auto& second = tokens.peek_token();
  795. if (second.is(Token::Type::Delim) && second.token().delim() == "="sv) {
  796. tokens.next_token();
  797. return MediaFeature::Comparison::LessThanOrEqual;
  798. }
  799. return MediaFeature::Comparison::LessThan;
  800. }
  801. if (first_delim == ">"sv) {
  802. auto& second = tokens.peek_token();
  803. if (second.is(Token::Type::Delim) && second.token().delim() == "="sv) {
  804. tokens.next_token();
  805. return MediaFeature::Comparison::GreaterThanOrEqual;
  806. }
  807. return MediaFeature::Comparison::GreaterThan;
  808. }
  809. }
  810. tokens.rewind_to_position(position);
  811. return {};
  812. };
  813. auto flip = [](MediaFeature::Comparison comparison) {
  814. switch (comparison) {
  815. case MediaFeature::Comparison::Equal:
  816. return MediaFeature::Comparison::Equal;
  817. case MediaFeature::Comparison::LessThan:
  818. return MediaFeature::Comparison::GreaterThan;
  819. case MediaFeature::Comparison::LessThanOrEqual:
  820. return MediaFeature::Comparison::GreaterThanOrEqual;
  821. case MediaFeature::Comparison::GreaterThan:
  822. return MediaFeature::Comparison::LessThan;
  823. case MediaFeature::Comparison::GreaterThanOrEqual:
  824. return MediaFeature::Comparison::LessThanOrEqual;
  825. }
  826. VERIFY_NOT_REACHED();
  827. };
  828. auto comparisons_match = [](MediaFeature::Comparison a, MediaFeature::Comparison b) -> bool {
  829. switch (a) {
  830. case MediaFeature::Comparison::Equal:
  831. return b == MediaFeature::Comparison::Equal;
  832. case MediaFeature::Comparison::LessThan:
  833. case MediaFeature::Comparison::LessThanOrEqual:
  834. return b == MediaFeature::Comparison::LessThan || b == MediaFeature::Comparison::LessThanOrEqual;
  835. case MediaFeature::Comparison::GreaterThan:
  836. case MediaFeature::Comparison::GreaterThanOrEqual:
  837. return b == MediaFeature::Comparison::GreaterThan || b == MediaFeature::Comparison::GreaterThanOrEqual;
  838. }
  839. VERIFY_NOT_REACHED();
  840. };
  841. // `<mf-range> = <mf-name> <mf-comparison> <mf-value>
  842. // | <mf-value> <mf-comparison> <mf-name>
  843. // | <mf-value> <mf-lt> <mf-name> <mf-lt> <mf-value>
  844. // | <mf-value> <mf-gt> <mf-name> <mf-gt> <mf-value>`
  845. auto parse_mf_range = [&](auto& tokens) -> Optional<MediaFeature> {
  846. auto position = tokens.position();
  847. tokens.skip_whitespace();
  848. // `<mf-name> <mf-comparison> <mf-value>`
  849. // NOTE: We have to check for <mf-name> first, since all <mf-name>s will also parse as <mf-value>.
  850. if (auto maybe_name = parse_mf_name(tokens, false); maybe_name.has_value()) {
  851. tokens.skip_whitespace();
  852. if (auto maybe_comparison = parse_comparison(tokens); maybe_comparison.has_value()) {
  853. tokens.skip_whitespace();
  854. if (auto maybe_value = parse_media_feature_value(tokens); maybe_value.has_value()) {
  855. tokens.skip_whitespace();
  856. if (!tokens.has_next_token() && !maybe_value->is_ident())
  857. return MediaFeature::half_range(maybe_value.release_value(), flip(maybe_comparison.release_value()), maybe_name.release_value());
  858. }
  859. }
  860. }
  861. // `<mf-value> <mf-comparison> <mf-name>
  862. // | <mf-value> <mf-lt> <mf-name> <mf-lt> <mf-value>
  863. // | <mf-value> <mf-gt> <mf-name> <mf-gt> <mf-value>`
  864. if (auto maybe_left_value = parse_media_feature_value(tokens); maybe_left_value.has_value()) {
  865. tokens.skip_whitespace();
  866. if (auto maybe_left_comparison = parse_comparison(tokens); maybe_left_comparison.has_value()) {
  867. tokens.skip_whitespace();
  868. if (auto maybe_name = parse_mf_name(tokens, false); maybe_name.has_value()) {
  869. tokens.skip_whitespace();
  870. if (!tokens.has_next_token())
  871. return MediaFeature::half_range(maybe_left_value.release_value(), maybe_left_comparison.release_value(), maybe_name.release_value());
  872. if (auto maybe_right_comparison = parse_comparison(tokens); maybe_right_comparison.has_value()) {
  873. tokens.skip_whitespace();
  874. if (auto maybe_right_value = parse_media_feature_value(tokens); maybe_right_value.has_value()) {
  875. tokens.skip_whitespace();
  876. // For this to be valid, the following must be true:
  877. // - Comparisons must either both be >/>= or both be </<=.
  878. // - Neither comparison can be `=`.
  879. // - Neither value can be an ident.
  880. auto left_comparison = maybe_left_comparison.release_value();
  881. auto right_comparison = maybe_right_comparison.release_value();
  882. if (!tokens.has_next_token()
  883. && comparisons_match(left_comparison, right_comparison)
  884. && left_comparison != MediaFeature::Comparison::Equal
  885. && !maybe_left_value->is_ident() && !maybe_right_value->is_ident()) {
  886. return MediaFeature::range(maybe_left_value.release_value(), left_comparison, maybe_name.release_value(), right_comparison, maybe_right_value.release_value());
  887. }
  888. }
  889. }
  890. }
  891. }
  892. }
  893. tokens.rewind_to_position(position);
  894. return {};
  895. };
  896. if (auto maybe_mf_boolean = parse_mf_boolean(tokens); maybe_mf_boolean.has_value())
  897. return maybe_mf_boolean.release_value();
  898. if (auto maybe_mf_plain = parse_mf_plain(tokens); maybe_mf_plain.has_value())
  899. return maybe_mf_plain.release_value();
  900. if (auto maybe_mf_range = parse_mf_range(tokens); maybe_mf_range.has_value())
  901. return maybe_mf_range.release_value();
  902. tokens.rewind_to_position(position);
  903. return {};
  904. }
  905. Optional<MediaQuery::MediaType> Parser::parse_media_type(TokenStream<StyleComponentValueRule>& tokens)
  906. {
  907. auto position = tokens.position();
  908. tokens.skip_whitespace();
  909. auto& token = tokens.next_token();
  910. if (!token.is(Token::Type::Ident)) {
  911. tokens.rewind_to_position(position);
  912. return {};
  913. }
  914. auto ident = token.token().ident();
  915. if (ident.equals_ignoring_case("all")) {
  916. return MediaQuery::MediaType::All;
  917. } else if (ident.equals_ignoring_case("aural")) {
  918. return MediaQuery::MediaType::Aural;
  919. } else if (ident.equals_ignoring_case("braille")) {
  920. return MediaQuery::MediaType::Braille;
  921. } else if (ident.equals_ignoring_case("embossed")) {
  922. return MediaQuery::MediaType::Embossed;
  923. } else if (ident.equals_ignoring_case("handheld")) {
  924. return MediaQuery::MediaType::Handheld;
  925. } else if (ident.equals_ignoring_case("print")) {
  926. return MediaQuery::MediaType::Print;
  927. } else if (ident.equals_ignoring_case("projection")) {
  928. return MediaQuery::MediaType::Projection;
  929. } else if (ident.equals_ignoring_case("screen")) {
  930. return MediaQuery::MediaType::Screen;
  931. } else if (ident.equals_ignoring_case("speech")) {
  932. return MediaQuery::MediaType::Speech;
  933. } else if (ident.equals_ignoring_case("tty")) {
  934. return MediaQuery::MediaType::TTY;
  935. } else if (ident.equals_ignoring_case("tv")) {
  936. return MediaQuery::MediaType::TV;
  937. }
  938. tokens.rewind_to_position(position);
  939. return {};
  940. }
  941. // `<media-in-parens>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-in-parens
  942. OwnPtr<MediaCondition> Parser::parse_media_in_parens(TokenStream<StyleComponentValueRule>& tokens)
  943. {
  944. // `<media-in-parens> = ( <media-condition> ) | ( <media-feature> ) | <general-enclosed>`
  945. auto position = tokens.position();
  946. tokens.skip_whitespace();
  947. // `( <media-condition> ) | ( <media-feature> )`
  948. auto& first_token = tokens.peek_token();
  949. if (first_token.is_block() && first_token.block().is_paren()) {
  950. TokenStream inner_token_stream { first_token.block().values() };
  951. if (auto maybe_media_condition = parse_media_condition(inner_token_stream, MediaCondition::AllowOr::Yes)) {
  952. tokens.next_token();
  953. return maybe_media_condition.release_nonnull();
  954. }
  955. if (auto maybe_media_feature = parse_media_feature(inner_token_stream); maybe_media_feature.has_value()) {
  956. tokens.next_token();
  957. return MediaCondition::from_feature(maybe_media_feature.release_value());
  958. }
  959. }
  960. // `<general-enclosed>`
  961. // FIXME: We should only be taking this branch if the grammar doesn't match the above options.
  962. // Currently we take it if the above fail to parse, which is different.
  963. // eg, `@media (min-width: 76yaks)` is valid grammar, but does not parse because `yaks` isn't a unit.
  964. if (auto maybe_general_enclosed = parse_general_enclosed(tokens); maybe_general_enclosed.has_value())
  965. return MediaCondition::from_general_enclosed(maybe_general_enclosed.release_value());
  966. tokens.rewind_to_position(position);
  967. return {};
  968. }
  969. // `<mf-value>`, https://www.w3.org/TR/mediaqueries-4/#typedef-mf-value
  970. Optional<MediaFeatureValue> Parser::parse_media_feature_value(TokenStream<StyleComponentValueRule>& tokens)
  971. {
  972. // `<number> | <dimension> | <ident> | <ratio>`
  973. auto position = tokens.position();
  974. tokens.skip_whitespace();
  975. auto& first = tokens.next_token();
  976. // `<number>`
  977. if (first.is(Token::Type::Number))
  978. return MediaFeatureValue(first.token().number_value());
  979. // `<dimension>`
  980. if (auto dimension = parse_dimension(first); dimension.has_value()) {
  981. if (dimension->is_length())
  982. return MediaFeatureValue(dimension->length());
  983. if (dimension->is_resolution())
  984. return MediaFeatureValue(dimension->resolution());
  985. }
  986. // `<ident>`
  987. if (first.is(Token::Type::Ident))
  988. return MediaFeatureValue(first.token().ident());
  989. // FIXME: `<ratio>`, once we have ratios.
  990. tokens.rewind_to_position(position);
  991. return {};
  992. }
  993. RefPtr<Supports> Parser::parse_as_supports()
  994. {
  995. return parse_a_supports(m_token_stream);
  996. }
  997. template<typename T>
  998. RefPtr<Supports> Parser::parse_a_supports(TokenStream<T>& tokens)
  999. {
  1000. auto component_values = parse_a_list_of_component_values(tokens);
  1001. TokenStream<StyleComponentValueRule> token_stream { component_values };
  1002. auto maybe_condition = parse_supports_condition(token_stream);
  1003. token_stream.skip_whitespace();
  1004. if (maybe_condition && !token_stream.has_next_token())
  1005. return Supports::create(maybe_condition.release_nonnull());
  1006. return {};
  1007. }
  1008. OwnPtr<Supports::Condition> Parser::parse_supports_condition(TokenStream<StyleComponentValueRule>& tokens)
  1009. {
  1010. tokens.skip_whitespace();
  1011. auto start_position = tokens.position();
  1012. auto& peeked_token = tokens.peek_token();
  1013. // `not <supports-in-parens>`
  1014. if (peeked_token.is(Token::Type::Ident) && peeked_token.token().ident().equals_ignoring_case("not")) {
  1015. tokens.next_token();
  1016. tokens.skip_whitespace();
  1017. auto child = parse_supports_in_parens(tokens);
  1018. if (child.has_value()) {
  1019. auto* condition = new Supports::Condition;
  1020. condition->type = Supports::Condition::Type::Not;
  1021. condition->children.append(child.release_value());
  1022. return adopt_own(*condition);
  1023. }
  1024. tokens.rewind_to_position(start_position);
  1025. return {};
  1026. }
  1027. // ` <supports-in-parens> [ and <supports-in-parens> ]*
  1028. // | <supports-in-parens> [ or <supports-in-parens> ]*`
  1029. Vector<Supports::InParens> children;
  1030. Optional<Supports::Condition::Type> condition_type {};
  1031. auto as_condition_type = [](auto& token) -> Optional<Supports::Condition::Type> {
  1032. if (!token.is(Token::Type::Ident))
  1033. return {};
  1034. auto ident = token.token().ident();
  1035. if (ident.equals_ignoring_case("and"))
  1036. return Supports::Condition::Type::And;
  1037. if (ident.equals_ignoring_case("or"))
  1038. return Supports::Condition::Type::Or;
  1039. return {};
  1040. };
  1041. bool is_invalid = false;
  1042. while (tokens.has_next_token()) {
  1043. if (!children.is_empty()) {
  1044. // Expect `and` or `or` here
  1045. auto maybe_combination = as_condition_type(tokens.next_token());
  1046. if (!maybe_combination.has_value()) {
  1047. is_invalid = true;
  1048. break;
  1049. }
  1050. if (!condition_type.has_value()) {
  1051. condition_type = maybe_combination.value();
  1052. } else if (maybe_combination != condition_type) {
  1053. is_invalid = true;
  1054. break;
  1055. }
  1056. }
  1057. tokens.skip_whitespace();
  1058. if (auto in_parens = parse_supports_in_parens(tokens); in_parens.has_value()) {
  1059. children.append(in_parens.release_value());
  1060. } else {
  1061. is_invalid = true;
  1062. break;
  1063. }
  1064. tokens.skip_whitespace();
  1065. }
  1066. if (!is_invalid && !children.is_empty()) {
  1067. auto* condition = new Supports::Condition;
  1068. condition->type = condition_type.value_or(Supports::Condition::Type::Or);
  1069. condition->children = move(children);
  1070. return adopt_own(*condition);
  1071. }
  1072. tokens.rewind_to_position(start_position);
  1073. return {};
  1074. }
  1075. Optional<Supports::InParens> Parser::parse_supports_in_parens(TokenStream<StyleComponentValueRule>& tokens)
  1076. {
  1077. tokens.skip_whitespace();
  1078. auto start_position = tokens.position();
  1079. auto& first_token = tokens.peek_token();
  1080. // `( <supports-condition> )`
  1081. if (first_token.is_block() && first_token.block().is_paren()) {
  1082. tokens.next_token();
  1083. tokens.skip_whitespace();
  1084. TokenStream child_tokens { first_token.block().values() };
  1085. if (auto condition = parse_supports_condition(child_tokens)) {
  1086. if (child_tokens.has_next_token()) {
  1087. tokens.rewind_to_position(start_position);
  1088. return {};
  1089. }
  1090. return Supports::InParens {
  1091. .value = { condition.release_nonnull() }
  1092. };
  1093. }
  1094. tokens.rewind_to_position(start_position);
  1095. }
  1096. // `<supports-feature>`
  1097. if (auto feature = parse_supports_feature(tokens); feature.has_value()) {
  1098. return Supports::InParens {
  1099. .value = { feature.release_value() }
  1100. };
  1101. }
  1102. // `<general-enclosed>`
  1103. if (auto general_enclosed = parse_general_enclosed(tokens); general_enclosed.has_value()) {
  1104. return Supports::InParens {
  1105. .value = general_enclosed.release_value()
  1106. };
  1107. }
  1108. tokens.rewind_to_position(start_position);
  1109. return {};
  1110. }
  1111. Optional<Supports::Feature> Parser::parse_supports_feature(TokenStream<StyleComponentValueRule>& tokens)
  1112. {
  1113. tokens.skip_whitespace();
  1114. auto start_position = tokens.position();
  1115. auto& first_token = tokens.next_token();
  1116. // `<supports-decl>`
  1117. if (first_token.is_block() && first_token.block().is_paren()) {
  1118. TokenStream block_tokens { first_token.block().values() };
  1119. // FIXME: Parsing and then converting back to a string is weird.
  1120. if (auto declaration = consume_a_declaration(block_tokens); declaration.has_value()) {
  1121. return Supports::Feature {
  1122. Supports::Declaration { declaration->to_string() }
  1123. };
  1124. }
  1125. }
  1126. // `<supports-selector-fn>`
  1127. if (first_token.is_function() && first_token.function().name().equals_ignoring_case("selector"sv)) {
  1128. // FIXME: Parsing and then converting back to a string is weird.
  1129. StringBuilder builder;
  1130. for (auto const& item : first_token.function().values())
  1131. builder.append(item.to_string());
  1132. return Supports::Feature {
  1133. Supports::Selector { builder.to_string() }
  1134. };
  1135. }
  1136. tokens.rewind_to_position(start_position);
  1137. return {};
  1138. }
  1139. // https://www.w3.org/TR/mediaqueries-4/#typedef-general-enclosed
  1140. Optional<GeneralEnclosed> Parser::parse_general_enclosed(TokenStream<StyleComponentValueRule>& tokens)
  1141. {
  1142. tokens.skip_whitespace();
  1143. auto start_position = tokens.position();
  1144. auto& first_token = tokens.next_token();
  1145. // `[ <function-token> <any-value>? ) ]`
  1146. if (first_token.is_function())
  1147. return GeneralEnclosed { first_token.to_string() };
  1148. // `( <any-value>? )`
  1149. if (first_token.is_block() && first_token.block().is_paren())
  1150. return GeneralEnclosed { first_token.to_string() };
  1151. tokens.rewind_to_position(start_position);
  1152. return {};
  1153. }
  1154. template<typename T>
  1155. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, bool top_level)
  1156. {
  1157. NonnullRefPtrVector<StyleRule> rules;
  1158. for (;;) {
  1159. auto& token = tokens.next_token();
  1160. if (token.is(Token::Type::Whitespace)) {
  1161. continue;
  1162. }
  1163. if (token.is(Token::Type::EndOfFile)) {
  1164. break;
  1165. }
  1166. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  1167. if (top_level) {
  1168. continue;
  1169. }
  1170. tokens.reconsume_current_input_token();
  1171. auto maybe_qualified = consume_a_qualified_rule(tokens);
  1172. if (maybe_qualified) {
  1173. rules.append(maybe_qualified.release_nonnull());
  1174. }
  1175. continue;
  1176. }
  1177. if (token.is(Token::Type::AtKeyword)) {
  1178. tokens.reconsume_current_input_token();
  1179. rules.append(consume_an_at_rule(tokens));
  1180. continue;
  1181. }
  1182. tokens.reconsume_current_input_token();
  1183. auto maybe_qualified = consume_a_qualified_rule(tokens);
  1184. if (maybe_qualified) {
  1185. rules.append(maybe_qualified.release_nonnull());
  1186. }
  1187. }
  1188. return rules;
  1189. }
  1190. template<typename T>
  1191. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  1192. {
  1193. auto& name_ident = tokens.next_token();
  1194. VERIFY(name_ident.is(Token::Type::AtKeyword));
  1195. auto rule = make_ref_counted<StyleRule>(StyleRule::Type::At);
  1196. rule->m_name = ((Token)name_ident).at_keyword();
  1197. for (;;) {
  1198. auto& token = tokens.next_token();
  1199. if (token.is(Token::Type::Semicolon)) {
  1200. return rule;
  1201. }
  1202. if (token.is(Token::Type::EndOfFile)) {
  1203. log_parse_error();
  1204. return rule;
  1205. }
  1206. if (token.is(Token::Type::OpenCurly)) {
  1207. rule->m_block = consume_a_simple_block(tokens);
  1208. return rule;
  1209. }
  1210. if constexpr (IsSame<T, StyleComponentValueRule>) {
  1211. StyleComponentValueRule const& component_value = token;
  1212. if (component_value.is_block() && component_value.block().is_curly()) {
  1213. rule->m_block = component_value.block();
  1214. return rule;
  1215. }
  1216. }
  1217. tokens.reconsume_current_input_token();
  1218. auto value = consume_a_component_value(tokens);
  1219. rule->m_prelude.append(value);
  1220. }
  1221. }
  1222. template<typename T>
  1223. RefPtr<StyleRule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  1224. {
  1225. auto rule = make_ref_counted<StyleRule>(StyleRule::Type::Qualified);
  1226. for (;;) {
  1227. auto& token = tokens.next_token();
  1228. if (token.is(Token::Type::EndOfFile)) {
  1229. log_parse_error();
  1230. return {};
  1231. }
  1232. if (token.is(Token::Type::OpenCurly)) {
  1233. rule->m_block = consume_a_simple_block(tokens);
  1234. return rule;
  1235. }
  1236. if constexpr (IsSame<T, StyleComponentValueRule>) {
  1237. StyleComponentValueRule const& component_value = token;
  1238. if (component_value.is_block() && component_value.block().is_curly()) {
  1239. rule->m_block = component_value.block();
  1240. return rule;
  1241. }
  1242. }
  1243. tokens.reconsume_current_input_token();
  1244. auto value = consume_a_component_value(tokens);
  1245. rule->m_prelude.append(value);
  1246. }
  1247. return rule;
  1248. }
  1249. template<>
  1250. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<StyleComponentValueRule>& tokens)
  1251. {
  1252. return tokens.next_token();
  1253. }
  1254. template<typename T>
  1255. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<T>& tokens)
  1256. {
  1257. auto& token = tokens.next_token();
  1258. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  1259. return StyleComponentValueRule(consume_a_simple_block(tokens));
  1260. if (token.is(Token::Type::Function))
  1261. return StyleComponentValueRule(consume_a_function(tokens));
  1262. return StyleComponentValueRule(token);
  1263. }
  1264. template<typename T>
  1265. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  1266. {
  1267. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  1268. auto block = make_ref_counted<StyleBlockRule>();
  1269. block->m_token = tokens.current_token();
  1270. for (;;) {
  1271. auto& token = tokens.next_token();
  1272. if (token.is(ending_token)) {
  1273. return block;
  1274. }
  1275. if (token.is(Token::Type::EndOfFile)) {
  1276. log_parse_error();
  1277. return block;
  1278. }
  1279. tokens.reconsume_current_input_token();
  1280. auto value = consume_a_component_value(tokens);
  1281. block->m_values.append(value);
  1282. }
  1283. }
  1284. template<typename T>
  1285. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function(TokenStream<T>& tokens)
  1286. {
  1287. auto name_ident = tokens.current_token();
  1288. VERIFY(name_ident.is(Token::Type::Function));
  1289. auto function = make_ref_counted<StyleFunctionRule>(((Token)name_ident).function());
  1290. for (;;) {
  1291. auto& token = tokens.next_token();
  1292. if (token.is(Token::Type::CloseParen)) {
  1293. return function;
  1294. }
  1295. if (token.is(Token::Type::EndOfFile)) {
  1296. log_parse_error();
  1297. return function;
  1298. }
  1299. tokens.reconsume_current_input_token();
  1300. auto value = consume_a_component_value(tokens);
  1301. function->m_values.append(value);
  1302. }
  1303. return function;
  1304. }
  1305. // https://www.w3.org/TR/css-syntax-3/#consume-declaration
  1306. template<typename T>
  1307. Optional<StyleDeclarationRule> Parser::consume_a_declaration(TokenStream<T>& tokens)
  1308. {
  1309. // Note: This algorithm assumes that the next input token has already been checked to
  1310. // be an <ident-token>.
  1311. // To consume a declaration:
  1312. // Consume the next input token.
  1313. tokens.skip_whitespace();
  1314. auto start_position = tokens.position();
  1315. auto& token = tokens.next_token();
  1316. if (!token.is(Token::Type::Ident)) {
  1317. tokens.rewind_to_position(start_position);
  1318. return {};
  1319. }
  1320. // Create a new declaration with its name set to the value of the current input token
  1321. // and its value initially set to the empty list.
  1322. StyleDeclarationRule declaration;
  1323. declaration.m_name = ((Token)token).ident();
  1324. // 1. While the next input token is a <whitespace-token>, consume the next input token.
  1325. tokens.skip_whitespace();
  1326. // 2. If the next input token is anything other than a <colon-token>, this is a parse error.
  1327. // Return nothing.
  1328. auto& maybe_colon = tokens.peek_token();
  1329. if (!maybe_colon.is(Token::Type::Colon)) {
  1330. log_parse_error();
  1331. tokens.rewind_to_position(start_position);
  1332. return {};
  1333. }
  1334. // Otherwise, consume the next input token.
  1335. tokens.next_token();
  1336. // 3. While the next input token is a <whitespace-token>, consume the next input token.
  1337. tokens.skip_whitespace();
  1338. // 4. As long as the next input token is anything other than an <EOF-token>, consume a
  1339. // component value and append it to the declaration’s value.
  1340. for (;;) {
  1341. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  1342. break;
  1343. }
  1344. declaration.m_values.append(consume_a_component_value(tokens));
  1345. }
  1346. // 5. If the last two non-<whitespace-token>s in the declaration’s value are a <delim-token>
  1347. // with the value "!" followed by an <ident-token> with a value that is an ASCII case-insensitive
  1348. // match for "important", remove them from the declaration’s value and set the declaration’s
  1349. // important flag to true.
  1350. if (declaration.m_values.size() >= 2) {
  1351. // Walk backwards from the end until we find "important"
  1352. Optional<size_t> important_index;
  1353. for (size_t i = declaration.m_values.size() - 1; i > 0; i--) {
  1354. auto value = declaration.m_values[i];
  1355. if (value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("important")) {
  1356. important_index = i;
  1357. break;
  1358. }
  1359. if (value.is(Token::Type::Whitespace))
  1360. continue;
  1361. break;
  1362. }
  1363. // Walk backwards from important until we find "!"
  1364. if (important_index.has_value()) {
  1365. Optional<size_t> bang_index;
  1366. for (size_t i = important_index.value() - 1; i > 0; i--) {
  1367. auto value = declaration.m_values[i];
  1368. if (value.is(Token::Type::Delim) && value.token().delim() == "!"sv) {
  1369. bang_index = i;
  1370. break;
  1371. }
  1372. if (value.is(Token::Type::Whitespace))
  1373. continue;
  1374. break;
  1375. }
  1376. if (bang_index.has_value()) {
  1377. declaration.m_values.remove(important_index.value());
  1378. declaration.m_values.remove(bang_index.value());
  1379. declaration.m_important = Important::Yes;
  1380. }
  1381. }
  1382. }
  1383. // 6. While the last token in the declaration’s value is a <whitespace-token>, remove that token.
  1384. while (!declaration.m_values.is_empty()) {
  1385. auto maybe_whitespace = declaration.m_values.last();
  1386. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  1387. break;
  1388. }
  1389. declaration.m_values.take_last();
  1390. }
  1391. // 7. Return the declaration.
  1392. return declaration;
  1393. }
  1394. template<typename T>
  1395. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  1396. {
  1397. Vector<DeclarationOrAtRule> list;
  1398. for (;;) {
  1399. auto& token = tokens.next_token();
  1400. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  1401. continue;
  1402. }
  1403. if (token.is(Token::Type::EndOfFile)) {
  1404. return list;
  1405. }
  1406. if (token.is(Token::Type::AtKeyword)) {
  1407. tokens.reconsume_current_input_token();
  1408. list.append(DeclarationOrAtRule(consume_an_at_rule(tokens)));
  1409. continue;
  1410. }
  1411. if (token.is(Token::Type::Ident)) {
  1412. Vector<StyleComponentValueRule> temp;
  1413. temp.append(token);
  1414. for (;;) {
  1415. auto& peek = tokens.peek_token();
  1416. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile)) {
  1417. break;
  1418. }
  1419. temp.append(consume_a_component_value(tokens));
  1420. }
  1421. auto token_stream = TokenStream(temp);
  1422. auto maybe_declaration = consume_a_declaration(token_stream);
  1423. if (maybe_declaration.has_value()) {
  1424. list.append(DeclarationOrAtRule(maybe_declaration.value()));
  1425. }
  1426. continue;
  1427. }
  1428. log_parse_error();
  1429. tokens.reconsume_current_input_token();
  1430. for (;;) {
  1431. auto& peek = tokens.peek_token();
  1432. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  1433. break;
  1434. dbgln_if(CSS_PARSER_DEBUG, "Discarding token: '{}'", peek.to_debug_string());
  1435. (void)consume_a_component_value(tokens);
  1436. }
  1437. }
  1438. return list;
  1439. }
  1440. RefPtr<CSSRule> Parser::parse_as_rule()
  1441. {
  1442. return parse_a_rule(m_token_stream);
  1443. }
  1444. template<typename T>
  1445. RefPtr<CSSRule> Parser::parse_a_rule(TokenStream<T>& tokens)
  1446. {
  1447. RefPtr<CSSRule> rule;
  1448. tokens.skip_whitespace();
  1449. auto& token = tokens.peek_token();
  1450. if (token.is(Token::Type::EndOfFile)) {
  1451. return {};
  1452. } else if (token.is(Token::Type::AtKeyword)) {
  1453. auto at_rule = consume_an_at_rule(m_token_stream);
  1454. rule = convert_to_rule(at_rule);
  1455. } else {
  1456. auto qualified_rule = consume_a_qualified_rule(tokens);
  1457. if (!qualified_rule)
  1458. return {};
  1459. rule = convert_to_rule(*qualified_rule);
  1460. }
  1461. tokens.skip_whitespace();
  1462. auto& maybe_eof = tokens.peek_token();
  1463. if (maybe_eof.is(Token::Type::EndOfFile)) {
  1464. return rule;
  1465. }
  1466. return {};
  1467. }
  1468. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules()
  1469. {
  1470. return parse_a_list_of_rules(m_token_stream);
  1471. }
  1472. template<typename T>
  1473. NonnullRefPtrVector<CSSRule> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
  1474. {
  1475. auto parsed_rules = consume_a_list_of_rules(tokens, false);
  1476. NonnullRefPtrVector<CSSRule> rules;
  1477. for (auto& rule : parsed_rules) {
  1478. auto converted_rule = convert_to_rule(rule);
  1479. if (converted_rule)
  1480. rules.append(*converted_rule);
  1481. }
  1482. return rules;
  1483. }
  1484. Optional<StyleProperty> Parser::parse_as_declaration()
  1485. {
  1486. return parse_a_declaration(m_token_stream);
  1487. }
  1488. template<typename T>
  1489. Optional<StyleProperty> Parser::parse_a_declaration(TokenStream<T>& tokens)
  1490. {
  1491. tokens.skip_whitespace();
  1492. auto& token = tokens.peek_token();
  1493. if (!token.is(Token::Type::Ident)) {
  1494. return {};
  1495. }
  1496. auto declaration = consume_a_declaration(tokens);
  1497. if (declaration.has_value())
  1498. return convert_to_style_property(declaration.value());
  1499. return {};
  1500. }
  1501. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::parse_as_list_of_declarations()
  1502. {
  1503. return parse_a_list_of_declarations(m_token_stream);
  1504. }
  1505. template<typename T>
  1506. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
  1507. {
  1508. auto declarations_and_at_rules = consume_a_list_of_declarations(tokens);
  1509. Vector<StyleProperty> properties;
  1510. HashMap<String, StyleProperty> custom_properties;
  1511. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  1512. if (declaration_or_at_rule.is_at_rule()) {
  1513. dbgln_if(CSS_PARSER_DEBUG, "!!! CSS at-rule is not allowed here!");
  1514. continue;
  1515. }
  1516. auto& declaration = declaration_or_at_rule.m_declaration;
  1517. auto maybe_property = convert_to_style_property(declaration);
  1518. if (maybe_property.has_value()) {
  1519. auto property = maybe_property.value();
  1520. if (property.property_id == PropertyID::Custom) {
  1521. custom_properties.set(property.custom_name, property);
  1522. } else {
  1523. properties.append(property);
  1524. }
  1525. }
  1526. }
  1527. return PropertyOwningCSSStyleDeclaration::create(move(properties), move(custom_properties));
  1528. }
  1529. Optional<StyleComponentValueRule> Parser::parse_as_component_value()
  1530. {
  1531. return parse_a_component_value(m_token_stream);
  1532. }
  1533. template<typename T>
  1534. Optional<StyleComponentValueRule> Parser::parse_a_component_value(TokenStream<T>& tokens)
  1535. {
  1536. tokens.skip_whitespace();
  1537. auto& token = tokens.peek_token();
  1538. if (token.is(Token::Type::EndOfFile)) {
  1539. return {};
  1540. }
  1541. auto value = consume_a_component_value(tokens);
  1542. tokens.skip_whitespace();
  1543. auto& maybe_eof = tokens.peek_token();
  1544. if (maybe_eof.is(Token::Type::EndOfFile)) {
  1545. return value;
  1546. }
  1547. return {};
  1548. }
  1549. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values()
  1550. {
  1551. return parse_a_list_of_component_values(m_token_stream);
  1552. }
  1553. template<typename T>
  1554. Vector<StyleComponentValueRule> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
  1555. {
  1556. Vector<StyleComponentValueRule> rules;
  1557. for (;;) {
  1558. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  1559. break;
  1560. }
  1561. rules.append(consume_a_component_value(tokens));
  1562. }
  1563. return rules;
  1564. }
  1565. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values()
  1566. {
  1567. return parse_a_comma_separated_list_of_component_values(m_token_stream);
  1568. }
  1569. template<typename T>
  1570. Vector<Vector<StyleComponentValueRule>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  1571. {
  1572. Vector<Vector<StyleComponentValueRule>> lists;
  1573. lists.append({});
  1574. for (;;) {
  1575. auto& next = tokens.next_token();
  1576. if (next.is(Token::Type::Comma)) {
  1577. lists.append({});
  1578. continue;
  1579. } else if (next.is(Token::Type::EndOfFile)) {
  1580. break;
  1581. }
  1582. tokens.reconsume_current_input_token();
  1583. auto component_value = consume_a_component_value(tokens);
  1584. lists.last().append(component_value);
  1585. }
  1586. return lists;
  1587. }
  1588. Optional<AK::URL> Parser::parse_url_function(StyleComponentValueRule const& component_value, AllowedDataUrlType allowed_data_url_type)
  1589. {
  1590. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1591. // FIXME: Handle data: urls (RFC2397)
  1592. auto convert_string_to_url = [&](StringView& url_string) -> Optional<AK::URL> {
  1593. if (url_string.starts_with("data:", CaseSensitivity::CaseInsensitive)) {
  1594. auto data_url = AK::URL(url_string);
  1595. switch (allowed_data_url_type) {
  1596. case AllowedDataUrlType::Image:
  1597. if (data_url.data_mime_type().starts_with("image"sv, CaseSensitivity::CaseInsensitive))
  1598. return data_url;
  1599. break;
  1600. default:
  1601. break;
  1602. }
  1603. return {};
  1604. }
  1605. return m_context.complete_url(url_string);
  1606. };
  1607. if (component_value.is(Token::Type::Url)) {
  1608. auto url_string = component_value.token().url();
  1609. return convert_string_to_url(url_string);
  1610. }
  1611. if (component_value.is_function() && component_value.function().name().equals_ignoring_case("url")) {
  1612. auto& function_values = component_value.function().values();
  1613. // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
  1614. for (size_t i = 0; i < function_values.size(); ++i) {
  1615. auto& value = function_values[i];
  1616. if (value.is(Token::Type::Whitespace))
  1617. continue;
  1618. if (value.is(Token::Type::String)) {
  1619. auto url_string = value.token().string();
  1620. return convert_string_to_url(url_string);
  1621. }
  1622. break;
  1623. }
  1624. }
  1625. return {};
  1626. }
  1627. RefPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<StyleRule> rule)
  1628. {
  1629. if (rule->m_type == StyleRule::Type::At) {
  1630. if (has_ignored_vendor_prefix(rule->m_name)) {
  1631. return {};
  1632. } else if (rule->m_name.equals_ignoring_case("media"sv)) {
  1633. auto media_query_tokens = TokenStream { rule->prelude() };
  1634. auto media_query_list = parse_a_media_query_list(media_query_tokens);
  1635. if (media_query_list.is_empty() || !rule->block())
  1636. return {};
  1637. auto child_tokens = TokenStream { rule->block()->values() };
  1638. auto parser_rules = consume_a_list_of_rules(child_tokens, false);
  1639. NonnullRefPtrVector<CSSRule> child_rules;
  1640. for (auto& raw_rule : parser_rules) {
  1641. if (auto child_rule = convert_to_rule(raw_rule))
  1642. child_rules.append(*child_rule);
  1643. }
  1644. return CSSMediaRule::create(MediaList::create(move(media_query_list)), move(child_rules));
  1645. } else if (rule->m_name.equals_ignoring_case("import"sv) && !rule->prelude().is_empty()) {
  1646. Optional<AK::URL> url;
  1647. for (auto& token : rule->prelude()) {
  1648. if (token.is(Token::Type::Whitespace))
  1649. continue;
  1650. if (token.is(Token::Type::String)) {
  1651. url = m_context.complete_url(token.token().string());
  1652. } else {
  1653. url = parse_url_function(token);
  1654. }
  1655. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1656. if (url.has_value())
  1657. break;
  1658. }
  1659. if (url.has_value())
  1660. return CSSImportRule::create(url.value(), const_cast<DOM::Document&>(*m_context.document()));
  1661. else
  1662. dbgln_if(CSS_PARSER_DEBUG, "Unable to parse url from @import rule");
  1663. } else if (rule->m_name.equals_ignoring_case("supports"sv)) {
  1664. auto supports_tokens = TokenStream { rule->prelude() };
  1665. auto supports = parse_a_supports(supports_tokens);
  1666. if (!supports) {
  1667. if constexpr (CSS_PARSER_DEBUG) {
  1668. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @supports rule invalid; discarding.");
  1669. supports_tokens.dump_all_tokens();
  1670. }
  1671. return {};
  1672. }
  1673. if (!rule->block())
  1674. return {};
  1675. auto child_tokens = TokenStream { rule->block()->values() };
  1676. auto parser_rules = consume_a_list_of_rules(child_tokens, false);
  1677. NonnullRefPtrVector<CSSRule> child_rules;
  1678. for (auto& raw_rule : parser_rules) {
  1679. if (auto child_rule = convert_to_rule(raw_rule))
  1680. child_rules.append(*child_rule);
  1681. }
  1682. return CSSSupportsRule::create(supports.release_nonnull(), move(child_rules));
  1683. } else {
  1684. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS at-rule: @{}", rule->m_name);
  1685. }
  1686. // FIXME: More at rules!
  1687. } else {
  1688. auto prelude_stream = TokenStream(rule->m_prelude);
  1689. auto selectors = parse_a_selector(prelude_stream);
  1690. if (selectors.is_error()) {
  1691. if (selectors.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1692. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule selectors invalid; discarding.");
  1693. if constexpr (CSS_PARSER_DEBUG) {
  1694. prelude_stream.dump_all_tokens();
  1695. }
  1696. }
  1697. return {};
  1698. }
  1699. if (selectors.value().is_empty()) {
  1700. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: empty selector; discarding.");
  1701. return {};
  1702. }
  1703. auto declaration = convert_to_declaration(*rule->m_block);
  1704. if (!declaration) {
  1705. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule declaration invalid; discarding.");
  1706. return {};
  1707. }
  1708. return CSSStyleRule::create(move(selectors.value()), move(*declaration));
  1709. }
  1710. return {};
  1711. }
  1712. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::convert_to_declaration(NonnullRefPtr<StyleBlockRule> block)
  1713. {
  1714. if (!block->is_curly())
  1715. return {};
  1716. auto stream = TokenStream(block->m_values);
  1717. return parse_a_list_of_declarations(stream);
  1718. }
  1719. Optional<StyleProperty> Parser::convert_to_style_property(StyleDeclarationRule const& declaration)
  1720. {
  1721. auto& property_name = declaration.m_name;
  1722. auto property_id = property_id_from_string(property_name);
  1723. if (property_id == PropertyID::Invalid) {
  1724. if (property_name.starts_with("--")) {
  1725. property_id = PropertyID::Custom;
  1726. } else if (has_ignored_vendor_prefix(property_name)) {
  1727. return {};
  1728. } else if (!property_name.starts_with("-")) {
  1729. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS property '{}'", property_name);
  1730. return {};
  1731. }
  1732. }
  1733. auto value_token_stream = TokenStream(declaration.m_values);
  1734. auto value = parse_css_value(property_id, value_token_stream);
  1735. if (value.is_error()) {
  1736. if (value.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1737. dbgln_if(CSS_PARSER_DEBUG, "Unable to parse value for CSS property '{}'.", property_name);
  1738. if constexpr (CSS_PARSER_DEBUG) {
  1739. value_token_stream.dump_all_tokens();
  1740. }
  1741. }
  1742. return {};
  1743. }
  1744. if (property_id == PropertyID::Custom) {
  1745. return StyleProperty { declaration.m_important, property_id, value.release_value(), declaration.m_name };
  1746. } else {
  1747. return StyleProperty { declaration.m_important, property_id, value.release_value(), {} };
  1748. }
  1749. }
  1750. RefPtr<StyleValue> Parser::parse_builtin_value(StyleComponentValueRule const& component_value)
  1751. {
  1752. if (component_value.is(Token::Type::Ident)) {
  1753. auto ident = component_value.token().ident();
  1754. if (ident.equals_ignoring_case("inherit"))
  1755. return InheritStyleValue::the();
  1756. if (ident.equals_ignoring_case("initial"))
  1757. return InitialStyleValue::the();
  1758. if (ident.equals_ignoring_case("unset"))
  1759. return UnsetStyleValue::the();
  1760. // FIXME: Implement `revert` and `revert-layer` keywords, from Cascade4 and Cascade5 respectively
  1761. }
  1762. return {};
  1763. }
  1764. RefPtr<StyleValue> Parser::parse_calculated_value(Vector<StyleComponentValueRule> const& component_values)
  1765. {
  1766. auto calc_expression = parse_calc_expression(component_values);
  1767. if (calc_expression == nullptr)
  1768. return nullptr;
  1769. auto calc_type = calc_expression->resolved_type();
  1770. if (!calc_type.has_value()) {
  1771. dbgln_if(CSS_PARSER_DEBUG, "calc() resolved as invalid!!!");
  1772. return nullptr;
  1773. }
  1774. [[maybe_unused]] auto to_string = [](CalculatedStyleValue::ResolvedType type) {
  1775. switch (type) {
  1776. case CalculatedStyleValue::ResolvedType::Angle:
  1777. return "Angle"sv;
  1778. case CalculatedStyleValue::ResolvedType::Frequency:
  1779. return "Frequency"sv;
  1780. case CalculatedStyleValue::ResolvedType::Integer:
  1781. return "Integer"sv;
  1782. case CalculatedStyleValue::ResolvedType::Length:
  1783. return "Length"sv;
  1784. case CalculatedStyleValue::ResolvedType::Number:
  1785. return "Number"sv;
  1786. case CalculatedStyleValue::ResolvedType::Percentage:
  1787. return "Percentage"sv;
  1788. case CalculatedStyleValue::ResolvedType::Time:
  1789. return "Time"sv;
  1790. }
  1791. VERIFY_NOT_REACHED();
  1792. };
  1793. dbgln_if(CSS_PARSER_DEBUG, "Deduced calc() resolved type as: {}", to_string(calc_type.value()));
  1794. return CalculatedStyleValue::create(calc_expression.release_nonnull(), calc_type.release_value());
  1795. }
  1796. RefPtr<StyleValue> Parser::parse_dynamic_value(StyleComponentValueRule const& component_value)
  1797. {
  1798. if (component_value.is_function()) {
  1799. auto& function = component_value.function();
  1800. if (function.name().equals_ignoring_case("calc"))
  1801. return parse_calculated_value(function.values());
  1802. if (function.name().equals_ignoring_case("var")) {
  1803. // Declarations using `var()` should already be parsed as an UnresolvedStyleValue before this point.
  1804. VERIFY_NOT_REACHED();
  1805. }
  1806. }
  1807. return {};
  1808. }
  1809. Optional<Parser::Dimension> Parser::parse_dimension(StyleComponentValueRule const& component_value)
  1810. {
  1811. if (component_value.is(Token::Type::Dimension)) {
  1812. float numeric_value = component_value.token().dimension_value();
  1813. auto unit_string = component_value.token().dimension_unit();
  1814. if (auto length_type = Length::unit_from_name(unit_string); length_type.has_value())
  1815. return Length { numeric_value, length_type.release_value() };
  1816. if (auto angle_type = Angle::unit_from_name(unit_string); angle_type.has_value())
  1817. return Angle { numeric_value, angle_type.release_value() };
  1818. if (auto frequency_type = Frequency::unit_from_name(unit_string); frequency_type.has_value())
  1819. return Frequency { numeric_value, frequency_type.release_value() };
  1820. if (auto resolution_type = Resolution::unit_from_name(unit_string); resolution_type.has_value())
  1821. return Resolution { numeric_value, resolution_type.release_value() };
  1822. if (auto time_type = Time::unit_from_name(unit_string); time_type.has_value())
  1823. return Time { numeric_value, time_type.release_value() };
  1824. }
  1825. if (component_value.is(Token::Type::Percentage))
  1826. return Percentage { static_cast<float>(component_value.token().percentage()) };
  1827. if (component_value.is(Token::Type::Number)) {
  1828. float numeric_value = component_value.token().number_value();
  1829. if (numeric_value == 0)
  1830. return Length::make_px(0);
  1831. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
  1832. // https://quirks.spec.whatwg.org/#quirky-length-value
  1833. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  1834. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  1835. // expression, and must not be supported in the supports() static method of the CSS interface."
  1836. return Length::make_px(numeric_value);
  1837. }
  1838. }
  1839. return {};
  1840. }
  1841. Optional<Length> Parser::parse_length(StyleComponentValueRule const& component_value)
  1842. {
  1843. auto dimension = parse_dimension(component_value);
  1844. if (!dimension.has_value())
  1845. return {};
  1846. if (dimension->is_length())
  1847. return dimension->length();
  1848. // FIXME: auto isn't a length!
  1849. if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto"))
  1850. return Length::make_auto();
  1851. return {};
  1852. }
  1853. RefPtr<StyleValue> Parser::parse_dimension_value(StyleComponentValueRule const& component_value)
  1854. {
  1855. // Numbers with no units can be lengths, in two situations:
  1856. // 1) We're in quirks mode, and it's an integer.
  1857. // 2) It's a 0.
  1858. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  1859. if (component_value.is(Token::Type::Number) && !(m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)))
  1860. return {};
  1861. if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto"))
  1862. return LengthStyleValue::create(Length::make_auto());
  1863. auto dimension = parse_dimension(component_value);
  1864. if (!dimension.has_value())
  1865. return {};
  1866. if (dimension->is_angle())
  1867. return AngleStyleValue::create(dimension->angle());
  1868. if (dimension->is_frequency())
  1869. return FrequencyStyleValue::create(dimension->frequency());
  1870. if (dimension->is_length())
  1871. return LengthStyleValue::create(dimension->length());
  1872. if (dimension->is_percentage())
  1873. return PercentageStyleValue::create(dimension->percentage());
  1874. if (dimension->is_resolution())
  1875. return ResolutionStyleValue::create(dimension->resolution());
  1876. if (dimension->is_time())
  1877. return TimeStyleValue::create(dimension->time());
  1878. VERIFY_NOT_REACHED();
  1879. }
  1880. RefPtr<StyleValue> Parser::parse_numeric_value(StyleComponentValueRule const& component_value)
  1881. {
  1882. if (component_value.is(Token::Type::Number)) {
  1883. auto number = component_value.token();
  1884. if (number.number_type() == Token::NumberType::Integer) {
  1885. return NumericStyleValue::create_integer(number.to_integer());
  1886. } else {
  1887. return NumericStyleValue::create_float(number.number_value());
  1888. }
  1889. }
  1890. return {};
  1891. }
  1892. RefPtr<StyleValue> Parser::parse_identifier_value(StyleComponentValueRule const& component_value)
  1893. {
  1894. if (component_value.is(Token::Type::Ident)) {
  1895. auto value_id = value_id_from_string(component_value.token().ident());
  1896. if (value_id != ValueID::Invalid)
  1897. return IdentifierStyleValue::create(value_id);
  1898. }
  1899. return {};
  1900. }
  1901. Optional<Color> Parser::parse_color(StyleComponentValueRule const& component_value)
  1902. {
  1903. // https://www.w3.org/TR/css-color-3/
  1904. if (component_value.is(Token::Type::Ident)) {
  1905. auto ident = component_value.token().ident();
  1906. auto color = Color::from_string(ident);
  1907. if (color.has_value())
  1908. return color;
  1909. } else if (component_value.is(Token::Type::Hash)) {
  1910. auto color = Color::from_string(String::formatted("#{}", component_value.token().hash_value()));
  1911. if (color.has_value())
  1912. return color;
  1913. return {};
  1914. } else if (component_value.is_function()) {
  1915. auto& function = component_value.function();
  1916. auto& values = function.values();
  1917. Vector<Token> params;
  1918. for (size_t i = 0; i < values.size(); ++i) {
  1919. auto& value = values.at(i);
  1920. if (value.is(Token::Type::Whitespace))
  1921. continue;
  1922. if (value.is(Token::Type::Percentage) || value.is(Token::Type::Number)) {
  1923. params.append(value.token());
  1924. // Eat following comma and whitespace
  1925. while ((i + 1) < values.size()) {
  1926. auto& next = values.at(i + 1);
  1927. if (next.is(Token::Type::Whitespace))
  1928. i++;
  1929. else if (next.is(Token::Type::Comma))
  1930. break;
  1931. return {};
  1932. }
  1933. }
  1934. }
  1935. if (function.name().equals_ignoring_case("rgb")) {
  1936. if (params.size() != 3)
  1937. return {};
  1938. auto r_val = params[0];
  1939. auto g_val = params[1];
  1940. auto b_val = params[2];
  1941. if (r_val.is(Token::NumberType::Integer)
  1942. && g_val.is(Token::NumberType::Integer)
  1943. && b_val.is(Token::NumberType::Integer)) {
  1944. auto r = r_val.to_integer();
  1945. auto g = g_val.to_integer();
  1946. auto b = b_val.to_integer();
  1947. if (AK::is_within_range<u8>(r) && AK::is_within_range<u8>(g) && AK::is_within_range<u8>(b))
  1948. return Color(r, g, b);
  1949. } else if (r_val.is(Token::Type::Percentage)
  1950. && g_val.is(Token::Type::Percentage)
  1951. && b_val.is(Token::Type::Percentage)) {
  1952. u8 r = clamp(lroundf(r_val.percentage() * 2.55), 0, 255);
  1953. u8 g = clamp(lroundf(g_val.percentage() * 2.55), 0, 255);
  1954. u8 b = clamp(lroundf(b_val.percentage() * 2.55), 0, 255);
  1955. return Color(r, g, b);
  1956. }
  1957. } else if (function.name().equals_ignoring_case("rgba")) {
  1958. if (params.size() != 4)
  1959. return {};
  1960. auto r_val = params[0];
  1961. auto g_val = params[1];
  1962. auto b_val = params[2];
  1963. auto a_val = params[3];
  1964. if (r_val.is(Token::NumberType::Integer)
  1965. && g_val.is(Token::NumberType::Integer)
  1966. && b_val.is(Token::NumberType::Integer)
  1967. && a_val.is(Token::Type::Number)) {
  1968. auto r = r_val.to_integer();
  1969. auto g = g_val.to_integer();
  1970. auto b = b_val.to_integer();
  1971. auto a = clamp(lroundf(a_val.number_value() * 255.0), 0, 255);
  1972. if (AK::is_within_range<u8>(r) && AK::is_within_range<u8>(g) && AK::is_within_range<u8>(b))
  1973. return Color(r, g, b, a);
  1974. } else if (r_val.is(Token::Type::Percentage)
  1975. && g_val.is(Token::Type::Percentage)
  1976. && b_val.is(Token::Type::Percentage)
  1977. && a_val.is(Token::Type::Number)) {
  1978. auto r = r_val.percentage();
  1979. auto g = g_val.percentage();
  1980. auto b = b_val.percentage();
  1981. auto a = a_val.number_value();
  1982. u8 r_255 = clamp(lroundf(r * 2.55), 0, 255);
  1983. u8 g_255 = clamp(lroundf(g * 2.55), 0, 255);
  1984. u8 b_255 = clamp(lroundf(b * 2.55), 0, 255);
  1985. u8 a_255 = clamp(lroundf(a * 255.0), 0, 255);
  1986. return Color(r_255, g_255, b_255, a_255);
  1987. }
  1988. } else if (function.name().equals_ignoring_case("hsl")) {
  1989. if (params.size() != 3)
  1990. return {};
  1991. auto h_val = params[0];
  1992. auto s_val = params[1];
  1993. auto l_val = params[2];
  1994. if (h_val.is(Token::Type::Number)
  1995. && s_val.is(Token::Type::Percentage)
  1996. && l_val.is(Token::Type::Percentage)) {
  1997. auto h = h_val.number_value();
  1998. auto s = s_val.percentage() / 100.0;
  1999. auto l = l_val.percentage() / 100.0;
  2000. return Color::from_hsl(h, s, l);
  2001. }
  2002. } else if (function.name().equals_ignoring_case("hsla")) {
  2003. if (params.size() != 4)
  2004. return {};
  2005. auto h_val = params[0];
  2006. auto s_val = params[1];
  2007. auto l_val = params[2];
  2008. auto a_val = params[3];
  2009. if (h_val.is(Token::Type::Number)
  2010. && s_val.is(Token::Type::Percentage)
  2011. && l_val.is(Token::Type::Percentage)
  2012. && a_val.is(Token::Type::Number)) {
  2013. auto h = h_val.number_value();
  2014. auto s = s_val.percentage() / 100.0;
  2015. auto l = l_val.percentage() / 100.0;
  2016. auto a = a_val.number_value();
  2017. return Color::from_hsla(h, s, l, a);
  2018. }
  2019. }
  2020. return {};
  2021. }
  2022. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  2023. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  2024. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  2025. // aborting on the first step that returns a value:
  2026. // 1. Let cv be the component value.
  2027. auto& cv = component_value;
  2028. String serialization;
  2029. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  2030. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  2031. // 1. If cv’s type flag is not "integer", return an error.
  2032. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  2033. if (cv.token().number_type() != Token::NumberType::Integer)
  2034. return {};
  2035. // 2. If cv’s value is less than zero, return an error.
  2036. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  2037. if (value < 0)
  2038. return {};
  2039. // 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.
  2040. StringBuilder serialization_builder;
  2041. serialization_builder.appendff("{}", value);
  2042. // 4. If cv is a <dimension-token>, append the unit to serialization.
  2043. if (cv.is(Token::Type::Dimension))
  2044. serialization_builder.append(cv.token().dimension_unit());
  2045. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  2046. serialization = serialization_builder.to_string();
  2047. if (serialization_builder.length() < 6) {
  2048. StringBuilder builder;
  2049. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  2050. builder.append('0');
  2051. builder.append(serialization_builder.string_view());
  2052. serialization = builder.to_string();
  2053. }
  2054. }
  2055. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  2056. else {
  2057. if (!cv.is(Token::Type::Ident))
  2058. return {};
  2059. serialization = cv.token().ident();
  2060. }
  2061. // 4. If serialization does not consist of three or six characters, return an error.
  2062. if (serialization.length() != 3 && serialization.length() != 6)
  2063. return {};
  2064. // 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.
  2065. for (auto c : serialization) {
  2066. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  2067. return {};
  2068. }
  2069. // 6. Return the concatenation of "#" (U+0023) and serialization.
  2070. String concatenation = String::formatted("#{}", serialization);
  2071. return Color::from_string(concatenation);
  2072. }
  2073. return {};
  2074. }
  2075. RefPtr<StyleValue> Parser::parse_color_value(StyleComponentValueRule const& component_value)
  2076. {
  2077. auto color = parse_color(component_value);
  2078. if (color.has_value())
  2079. return ColorStyleValue::create(color.value());
  2080. return {};
  2081. }
  2082. RefPtr<StyleValue> Parser::parse_string_value(StyleComponentValueRule const& component_value)
  2083. {
  2084. if (component_value.is(Token::Type::String))
  2085. return StringStyleValue::create(component_value.token().string());
  2086. return {};
  2087. }
  2088. RefPtr<StyleValue> Parser::parse_image_value(StyleComponentValueRule const& component_value)
  2089. {
  2090. auto url = parse_url_function(component_value, AllowedDataUrlType::Image);
  2091. if (url.has_value())
  2092. return ImageStyleValue::create(url.value());
  2093. // FIXME: Handle gradients.
  2094. return {};
  2095. }
  2096. template<typename ParseFunction>
  2097. RefPtr<StyleValue> Parser::parse_comma_separated_value_list(Vector<StyleComponentValueRule> const& component_values, ParseFunction parse_one_value)
  2098. {
  2099. auto tokens = TokenStream { component_values };
  2100. auto first = parse_one_value(tokens);
  2101. if (!first || !tokens.has_next_token())
  2102. return first;
  2103. NonnullRefPtrVector<StyleValue> values;
  2104. values.append(first.release_nonnull());
  2105. while (tokens.has_next_token()) {
  2106. if (!tokens.next_token().is(Token::Type::Comma))
  2107. return {};
  2108. if (auto maybe_value = parse_one_value(tokens)) {
  2109. values.append(maybe_value.release_nonnull());
  2110. continue;
  2111. }
  2112. return {};
  2113. }
  2114. return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
  2115. }
  2116. RefPtr<StyleValue> Parser::parse_simple_comma_separated_value_list(Vector<StyleComponentValueRule> const& component_values)
  2117. {
  2118. return parse_comma_separated_value_list(component_values, [=, this](auto& tokens) -> RefPtr<StyleValue> {
  2119. auto& token = tokens.next_token();
  2120. if (auto value = parse_css_value(token); value && property_accepts_value(m_context.current_property_id(), *value))
  2121. return value;
  2122. tokens.reconsume_current_input_token();
  2123. return nullptr;
  2124. });
  2125. }
  2126. RefPtr<StyleValue> Parser::parse_background_value(Vector<StyleComponentValueRule> const& component_values)
  2127. {
  2128. NonnullRefPtrVector<StyleValue> background_images;
  2129. NonnullRefPtrVector<StyleValue> background_positions;
  2130. NonnullRefPtrVector<StyleValue> background_sizes;
  2131. NonnullRefPtrVector<StyleValue> background_repeats;
  2132. NonnullRefPtrVector<StyleValue> background_attachments;
  2133. NonnullRefPtrVector<StyleValue> background_clips;
  2134. NonnullRefPtrVector<StyleValue> background_origins;
  2135. RefPtr<StyleValue> background_color;
  2136. // Per-layer values
  2137. RefPtr<StyleValue> background_image;
  2138. RefPtr<StyleValue> background_position;
  2139. RefPtr<StyleValue> background_size;
  2140. RefPtr<StyleValue> background_repeat;
  2141. RefPtr<StyleValue> background_attachment;
  2142. RefPtr<StyleValue> background_clip;
  2143. RefPtr<StyleValue> background_origin;
  2144. bool has_multiple_layers = false;
  2145. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  2146. if (allow_background_color) {
  2147. if (background_color)
  2148. return true;
  2149. } else {
  2150. if (background_color)
  2151. return false;
  2152. }
  2153. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  2154. };
  2155. auto complete_background_layer = [&]() {
  2156. background_images.append(background_image ? background_image.release_nonnull() : property_initial_value(PropertyID::BackgroundImage));
  2157. background_positions.append(background_position ? background_position.release_nonnull() : property_initial_value(PropertyID::BackgroundPosition));
  2158. background_sizes.append(background_size ? background_size.release_nonnull() : property_initial_value(PropertyID::BackgroundSize));
  2159. background_repeats.append(background_repeat ? background_repeat.release_nonnull() : property_initial_value(PropertyID::BackgroundRepeat));
  2160. background_attachments.append(background_attachment ? background_attachment.release_nonnull() : property_initial_value(PropertyID::BackgroundAttachment));
  2161. if (!background_origin && !background_clip) {
  2162. background_origin = property_initial_value(PropertyID::BackgroundOrigin);
  2163. background_clip = property_initial_value(PropertyID::BackgroundClip);
  2164. } else if (!background_clip) {
  2165. background_clip = background_origin;
  2166. }
  2167. background_origins.append(background_origin.release_nonnull());
  2168. background_clips.append(background_clip.release_nonnull());
  2169. background_image = nullptr;
  2170. background_position = nullptr;
  2171. background_size = nullptr;
  2172. background_repeat = nullptr;
  2173. background_attachment = nullptr;
  2174. background_clip = nullptr;
  2175. background_origin = nullptr;
  2176. };
  2177. auto tokens = TokenStream { component_values };
  2178. while (tokens.has_next_token()) {
  2179. auto& part = tokens.next_token();
  2180. if (part.is(Token::Type::Comma)) {
  2181. has_multiple_layers = true;
  2182. if (!background_layer_is_valid(false))
  2183. return nullptr;
  2184. complete_background_layer();
  2185. continue;
  2186. }
  2187. auto value = parse_css_value(part);
  2188. if (!value)
  2189. return nullptr;
  2190. if (property_accepts_value(PropertyID::BackgroundAttachment, *value)) {
  2191. if (background_attachment)
  2192. return nullptr;
  2193. background_attachment = value.release_nonnull();
  2194. continue;
  2195. }
  2196. if (property_accepts_value(PropertyID::BackgroundColor, *value)) {
  2197. if (background_color)
  2198. return nullptr;
  2199. background_color = value.release_nonnull();
  2200. continue;
  2201. }
  2202. if (property_accepts_value(PropertyID::BackgroundImage, *value)) {
  2203. if (background_image)
  2204. return nullptr;
  2205. background_image = value.release_nonnull();
  2206. continue;
  2207. }
  2208. if (property_accepts_value(PropertyID::BackgroundOrigin, *value)) {
  2209. // background-origin and background-clip accept the same values. From the spec:
  2210. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  2211. // If two values are present, then the first sets background-origin and the second background-clip."
  2212. // - https://www.w3.org/TR/css-backgrounds-3/#background
  2213. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  2214. // If we only get one, we copy the value before creating the BackgroundStyleValue.
  2215. if (!background_origin) {
  2216. background_origin = value.release_nonnull();
  2217. continue;
  2218. }
  2219. if (!background_clip) {
  2220. background_clip = value.release_nonnull();
  2221. continue;
  2222. }
  2223. return nullptr;
  2224. }
  2225. if (property_accepts_value(PropertyID::BackgroundPosition, *value)) {
  2226. if (background_position)
  2227. return nullptr;
  2228. tokens.reconsume_current_input_token();
  2229. if (auto maybe_background_position = parse_single_background_position_value(tokens)) {
  2230. background_position = maybe_background_position.release_nonnull();
  2231. // Attempt to parse `/ <background-size>`
  2232. auto before_slash = tokens.position();
  2233. auto& maybe_slash = tokens.next_token();
  2234. if (maybe_slash.is(Token::Type::Delim) && maybe_slash.token().delim() == "/"sv) {
  2235. if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
  2236. background_size = maybe_background_size.release_nonnull();
  2237. continue;
  2238. }
  2239. return nullptr;
  2240. }
  2241. tokens.rewind_to_position(before_slash);
  2242. continue;
  2243. }
  2244. return nullptr;
  2245. }
  2246. if (property_accepts_value(PropertyID::BackgroundRepeat, *value)) {
  2247. if (background_repeat)
  2248. return nullptr;
  2249. tokens.reconsume_current_input_token();
  2250. if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
  2251. background_repeat = maybe_repeat.release_nonnull();
  2252. continue;
  2253. }
  2254. return nullptr;
  2255. }
  2256. return nullptr;
  2257. }
  2258. if (!background_layer_is_valid(true))
  2259. return nullptr;
  2260. // We only need to create StyleValueLists if there are multiple layers.
  2261. // Otherwise, we can pass the single StyleValues directly.
  2262. if (has_multiple_layers) {
  2263. complete_background_layer();
  2264. if (!background_color)
  2265. background_color = property_initial_value(PropertyID::BackgroundColor);
  2266. return BackgroundStyleValue::create(
  2267. background_color.release_nonnull(),
  2268. StyleValueList::create(move(background_images), StyleValueList::Separator::Comma),
  2269. StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma),
  2270. StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma),
  2271. StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma),
  2272. StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma),
  2273. StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma),
  2274. StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma));
  2275. }
  2276. if (!background_color)
  2277. background_color = property_initial_value(PropertyID::BackgroundColor);
  2278. if (!background_image)
  2279. background_image = property_initial_value(PropertyID::BackgroundImage);
  2280. if (!background_position)
  2281. background_position = property_initial_value(PropertyID::BackgroundPosition);
  2282. if (!background_size)
  2283. background_size = property_initial_value(PropertyID::BackgroundSize);
  2284. if (!background_repeat)
  2285. background_repeat = property_initial_value(PropertyID::BackgroundRepeat);
  2286. if (!background_attachment)
  2287. background_attachment = property_initial_value(PropertyID::BackgroundAttachment);
  2288. if (!background_origin && !background_clip) {
  2289. background_origin = property_initial_value(PropertyID::BackgroundOrigin);
  2290. background_clip = property_initial_value(PropertyID::BackgroundClip);
  2291. } else if (!background_clip) {
  2292. background_clip = background_origin;
  2293. }
  2294. return BackgroundStyleValue::create(
  2295. background_color.release_nonnull(),
  2296. background_image.release_nonnull(),
  2297. background_position.release_nonnull(),
  2298. background_size.release_nonnull(),
  2299. background_repeat.release_nonnull(),
  2300. background_attachment.release_nonnull(),
  2301. background_origin.release_nonnull(),
  2302. background_clip.release_nonnull());
  2303. }
  2304. RefPtr<StyleValue> Parser::parse_single_background_position_value(TokenStream<StyleComponentValueRule>& tokens)
  2305. {
  2306. // NOTE: This *looks* like it parses a <position>, but it doesn't. From the spec:
  2307. // "Note: The background-position property also accepts a three-value syntax.
  2308. // This has been disallowed generically because it creates parsing ambiguities
  2309. // when combined with other length or percentage components in a property value."
  2310. // - https://www.w3.org/TR/css-values-4/#typedef-position
  2311. // So, we'll need a separate function to parse <position> later.
  2312. auto start_position = tokens.position();
  2313. auto error = [&]() {
  2314. tokens.rewind_to_position(start_position);
  2315. return nullptr;
  2316. };
  2317. auto to_edge = [](ValueID identifier) -> Optional<PositionEdge> {
  2318. switch (identifier) {
  2319. case ValueID::Top:
  2320. return PositionEdge::Top;
  2321. case ValueID::Bottom:
  2322. return PositionEdge::Bottom;
  2323. case ValueID::Left:
  2324. return PositionEdge::Left;
  2325. case ValueID::Right:
  2326. return PositionEdge::Right;
  2327. default:
  2328. return {};
  2329. }
  2330. };
  2331. auto is_horizontal = [](ValueID identifier) -> bool {
  2332. switch (identifier) {
  2333. case ValueID::Left:
  2334. case ValueID::Right:
  2335. return true;
  2336. default:
  2337. return false;
  2338. }
  2339. };
  2340. auto is_vertical = [](ValueID identifier) -> bool {
  2341. switch (identifier) {
  2342. case ValueID::Top:
  2343. case ValueID::Bottom:
  2344. return true;
  2345. default:
  2346. return false;
  2347. }
  2348. };
  2349. LengthPercentage zero_offset = Length::make_px(0);
  2350. LengthPercentage center_offset = Percentage { 50 };
  2351. struct EdgeOffset {
  2352. PositionEdge edge;
  2353. LengthPercentage offset;
  2354. bool edge_provided;
  2355. bool offset_provided;
  2356. };
  2357. Optional<EdgeOffset> horizontal;
  2358. Optional<EdgeOffset> vertical;
  2359. bool found_center = false;
  2360. while (tokens.has_next_token()) {
  2361. // Check if we're done
  2362. auto seen_items = (horizontal.has_value() ? 1 : 0) + (vertical.has_value() ? 1 : 0) + (found_center ? 1 : 0);
  2363. if (seen_items == 2)
  2364. break;
  2365. auto& token = tokens.peek_token();
  2366. auto maybe_value = parse_css_value(token);
  2367. if (!maybe_value || !property_accepts_value(PropertyID::BackgroundPosition, *maybe_value))
  2368. break;
  2369. tokens.next_token();
  2370. auto value = maybe_value.release_nonnull();
  2371. if (value->is_percentage()) {
  2372. if (!horizontal.has_value()) {
  2373. horizontal = EdgeOffset { PositionEdge::Left, value->as_percentage().percentage(), false, true };
  2374. } else if (!vertical.has_value()) {
  2375. vertical = EdgeOffset { PositionEdge::Top, value->as_percentage().percentage(), false, true };
  2376. } else {
  2377. return error();
  2378. }
  2379. continue;
  2380. }
  2381. if (value->has_length()) {
  2382. if (!horizontal.has_value()) {
  2383. horizontal = EdgeOffset { PositionEdge::Left, value->to_length(), false, true };
  2384. } else if (!vertical.has_value()) {
  2385. vertical = EdgeOffset { PositionEdge::Top, value->to_length(), false, true };
  2386. } else {
  2387. return error();
  2388. }
  2389. continue;
  2390. }
  2391. if (value->has_identifier()) {
  2392. auto identifier = value->to_identifier();
  2393. if (is_horizontal(identifier)) {
  2394. LengthPercentage offset = zero_offset;
  2395. bool offset_provided = false;
  2396. if (tokens.has_next_token()) {
  2397. auto maybe_offset = parse_dimension(tokens.peek_token());
  2398. if (maybe_offset.has_value() && maybe_offset.value().is_length_percentage()) {
  2399. offset = maybe_offset.value().length_percentage();
  2400. offset_provided = true;
  2401. tokens.next_token();
  2402. }
  2403. }
  2404. horizontal = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
  2405. } else if (is_vertical(identifier)) {
  2406. LengthPercentage offset = zero_offset;
  2407. bool offset_provided = false;
  2408. if (tokens.has_next_token()) {
  2409. auto maybe_offset = parse_dimension(tokens.peek_token());
  2410. if (maybe_offset.has_value() && maybe_offset.value().is_length_percentage()) {
  2411. offset = maybe_offset.value().length_percentage();
  2412. offset_provided = true;
  2413. tokens.next_token();
  2414. }
  2415. }
  2416. vertical = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
  2417. } else if (identifier == ValueID::Center) {
  2418. found_center = true;
  2419. } else {
  2420. return error();
  2421. }
  2422. continue;
  2423. }
  2424. tokens.reconsume_current_input_token();
  2425. break;
  2426. }
  2427. if (found_center) {
  2428. if (horizontal.has_value() && vertical.has_value())
  2429. return error();
  2430. if (!horizontal.has_value())
  2431. horizontal = EdgeOffset { PositionEdge::Left, center_offset, true, false };
  2432. if (!vertical.has_value())
  2433. vertical = EdgeOffset { PositionEdge::Top, center_offset, true, false };
  2434. }
  2435. if (!horizontal.has_value() && !vertical.has_value())
  2436. return error();
  2437. // Unpack `<edge> <length>`:
  2438. // The loop above reads this pattern as a single EdgeOffset, when actually, it should be treated
  2439. // as `x y` if the edge is horizontal, and `y` (with the second token reconsumed) otherwise.
  2440. if (!vertical.has_value() && horizontal->edge_provided && horizontal->offset_provided) {
  2441. // Split into `x y`
  2442. vertical = EdgeOffset { PositionEdge::Top, horizontal->offset, false, true };
  2443. horizontal->offset = zero_offset;
  2444. horizontal->offset_provided = false;
  2445. } else if (!horizontal.has_value() && vertical->edge_provided && vertical->offset_provided) {
  2446. // `y`, reconsume
  2447. vertical->offset = zero_offset;
  2448. vertical->offset_provided = false;
  2449. tokens.reconsume_current_input_token();
  2450. }
  2451. // If only one value is specified, the second value is assumed to be center.
  2452. if (!horizontal.has_value())
  2453. horizontal = EdgeOffset { PositionEdge::Left, center_offset, false, false };
  2454. if (!vertical.has_value())
  2455. vertical = EdgeOffset { PositionEdge::Top, center_offset, false, false };
  2456. return PositionStyleValue::create(
  2457. horizontal->edge, horizontal->offset,
  2458. vertical->edge, vertical->offset);
  2459. }
  2460. RefPtr<StyleValue> Parser::parse_single_background_repeat_value(TokenStream<StyleComponentValueRule>& tokens)
  2461. {
  2462. auto start_position = tokens.position();
  2463. auto error = [&]() {
  2464. tokens.rewind_to_position(start_position);
  2465. return nullptr;
  2466. };
  2467. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  2468. auto value_id = value.to_identifier();
  2469. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  2470. };
  2471. auto as_repeat = [](ValueID identifier) {
  2472. switch (identifier) {
  2473. case ValueID::NoRepeat:
  2474. return Repeat::NoRepeat;
  2475. case ValueID::Repeat:
  2476. return Repeat::Repeat;
  2477. case ValueID::Round:
  2478. return Repeat::Round;
  2479. case ValueID::Space:
  2480. return Repeat::Space;
  2481. default:
  2482. VERIFY_NOT_REACHED();
  2483. }
  2484. };
  2485. auto& token = tokens.next_token();
  2486. auto maybe_x_value = parse_css_value(token);
  2487. if (!maybe_x_value || !property_accepts_value(PropertyID::BackgroundRepeat, *maybe_x_value))
  2488. return error();
  2489. auto x_value = maybe_x_value.release_nonnull();
  2490. if (is_directional_repeat(*x_value)) {
  2491. auto value_id = x_value->to_identifier();
  2492. return BackgroundRepeatStyleValue::create(
  2493. value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  2494. value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  2495. }
  2496. // See if we have a second value for Y
  2497. auto& second_token = tokens.peek_token();
  2498. auto maybe_y_value = parse_css_value(second_token);
  2499. if (!maybe_y_value || !property_accepts_value(PropertyID::BackgroundRepeat, *maybe_y_value)) {
  2500. // We don't have a second value, so use x for both
  2501. return BackgroundRepeatStyleValue::create(as_repeat(x_value->to_identifier()), as_repeat(x_value->to_identifier()));
  2502. }
  2503. tokens.next_token();
  2504. auto y_value = maybe_y_value.release_nonnull();
  2505. if (is_directional_repeat(*y_value))
  2506. return error();
  2507. return BackgroundRepeatStyleValue::create(as_repeat(x_value->to_identifier()), as_repeat(y_value->to_identifier()));
  2508. }
  2509. RefPtr<StyleValue> Parser::parse_single_background_size_value(TokenStream<StyleComponentValueRule>& tokens)
  2510. {
  2511. auto start_position = tokens.position();
  2512. auto error = [&]() {
  2513. tokens.rewind_to_position(start_position);
  2514. return nullptr;
  2515. };
  2516. auto get_length_percentage = [](StyleValue& style_value) -> Optional<LengthPercentage> {
  2517. if (style_value.is_percentage())
  2518. return LengthPercentage { style_value.as_percentage().percentage() };
  2519. if (style_value.has_length())
  2520. return LengthPercentage { style_value.to_length() };
  2521. return {};
  2522. };
  2523. auto maybe_x_value = parse_css_value(tokens.next_token());
  2524. if (!maybe_x_value || !property_accepts_value(PropertyID::BackgroundSize, *maybe_x_value))
  2525. return error();
  2526. auto x_value = maybe_x_value.release_nonnull();
  2527. if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain)
  2528. return x_value;
  2529. auto maybe_y_value = parse_css_value(tokens.peek_token());
  2530. if (!maybe_y_value || !property_accepts_value(PropertyID::BackgroundSize, *maybe_y_value)) {
  2531. auto x_size = get_length_percentage(*x_value);
  2532. if (!x_size.has_value())
  2533. return error();
  2534. return BackgroundSizeStyleValue::create(x_size.value(), x_size.value());
  2535. }
  2536. tokens.next_token();
  2537. auto y_value = maybe_y_value.release_nonnull();
  2538. auto x_size = get_length_percentage(*x_value);
  2539. auto y_size = get_length_percentage(*y_value);
  2540. if (x_size.has_value() && y_size.has_value())
  2541. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  2542. return error();
  2543. }
  2544. RefPtr<StyleValue> Parser::parse_border_value(Vector<StyleComponentValueRule> const& component_values)
  2545. {
  2546. if (component_values.size() > 3)
  2547. return nullptr;
  2548. RefPtr<StyleValue> border_width;
  2549. RefPtr<StyleValue> border_color;
  2550. RefPtr<StyleValue> border_style;
  2551. for (auto& part : component_values) {
  2552. auto value = parse_css_value(part);
  2553. if (!value)
  2554. return nullptr;
  2555. if (property_accepts_value(PropertyID::BorderWidth, *value)) {
  2556. if (border_width)
  2557. return nullptr;
  2558. border_width = value.release_nonnull();
  2559. continue;
  2560. }
  2561. if (property_accepts_value(PropertyID::BorderColor, *value)) {
  2562. if (border_color)
  2563. return nullptr;
  2564. border_color = value.release_nonnull();
  2565. continue;
  2566. }
  2567. if (property_accepts_value(PropertyID::BorderStyle, *value)) {
  2568. if (border_style)
  2569. return nullptr;
  2570. border_style = value.release_nonnull();
  2571. continue;
  2572. }
  2573. return nullptr;
  2574. }
  2575. if (!border_width)
  2576. border_width = property_initial_value(PropertyID::BorderWidth);
  2577. if (!border_style)
  2578. border_style = property_initial_value(PropertyID::BorderStyle);
  2579. if (!border_color)
  2580. border_color = property_initial_value(PropertyID::BorderColor);
  2581. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  2582. }
  2583. RefPtr<StyleValue> Parser::parse_border_radius_value(Vector<StyleComponentValueRule> const& component_values)
  2584. {
  2585. if (component_values.size() == 2) {
  2586. auto horizontal = parse_dimension(component_values[0]);
  2587. auto vertical = parse_dimension(component_values[1]);
  2588. if (horizontal.has_value() && horizontal->is_length_percentage() && vertical.has_value() && vertical->is_length_percentage())
  2589. return BorderRadiusStyleValue::create(horizontal->length_percentage(), vertical->length_percentage());
  2590. return nullptr;
  2591. }
  2592. if (component_values.size() == 1) {
  2593. auto radius = parse_dimension(component_values[0]);
  2594. if (radius.has_value() && radius->is_length_percentage())
  2595. return BorderRadiusStyleValue::create(radius->length_percentage(), radius->length_percentage());
  2596. return nullptr;
  2597. }
  2598. return nullptr;
  2599. }
  2600. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(Vector<StyleComponentValueRule> const& component_values)
  2601. {
  2602. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  2603. auto top_right = [&](Vector<LengthPercentage>& radii) {
  2604. switch (radii.size()) {
  2605. case 4:
  2606. case 3:
  2607. case 2:
  2608. return radii[1];
  2609. case 1:
  2610. return radii[0];
  2611. default:
  2612. VERIFY_NOT_REACHED();
  2613. }
  2614. };
  2615. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  2616. switch (radii.size()) {
  2617. case 4:
  2618. case 3:
  2619. return radii[2];
  2620. case 2:
  2621. case 1:
  2622. return radii[0];
  2623. default:
  2624. VERIFY_NOT_REACHED();
  2625. }
  2626. };
  2627. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  2628. switch (radii.size()) {
  2629. case 4:
  2630. return radii[3];
  2631. case 3:
  2632. case 2:
  2633. return radii[1];
  2634. case 1:
  2635. return radii[0];
  2636. default:
  2637. VERIFY_NOT_REACHED();
  2638. }
  2639. };
  2640. Vector<LengthPercentage> horizontal_radii;
  2641. Vector<LengthPercentage> vertical_radii;
  2642. bool reading_vertical = false;
  2643. for (auto& value : component_values) {
  2644. if (value.is(Token::Type::Delim) && value.token().delim() == "/"sv) {
  2645. if (reading_vertical || horizontal_radii.is_empty())
  2646. return nullptr;
  2647. reading_vertical = true;
  2648. continue;
  2649. }
  2650. auto maybe_dimension = parse_dimension(value);
  2651. if (!maybe_dimension.has_value() || !maybe_dimension->is_length_percentage())
  2652. return nullptr;
  2653. if (reading_vertical) {
  2654. vertical_radii.append(maybe_dimension->length_percentage());
  2655. } else {
  2656. horizontal_radii.append(maybe_dimension->length_percentage());
  2657. }
  2658. }
  2659. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  2660. || horizontal_radii.is_empty()
  2661. || (reading_vertical && vertical_radii.is_empty()))
  2662. return nullptr;
  2663. NonnullRefPtrVector<StyleValue> border_radii;
  2664. border_radii.append(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  2665. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  2666. border_radii.append(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  2667. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  2668. border_radii.append(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  2669. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  2670. border_radii.append(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  2671. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  2672. return StyleValueList::create(move(border_radii), StyleValueList::Separator::Space);
  2673. }
  2674. RefPtr<StyleValue> Parser::parse_box_shadow_value(Vector<StyleComponentValueRule> const& component_values)
  2675. {
  2676. // "none"
  2677. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  2678. auto ident = parse_identifier_value(component_values.first());
  2679. if (ident && ident->to_identifier() == ValueID::None)
  2680. return ident;
  2681. }
  2682. return parse_comma_separated_value_list(component_values, [this](auto& tokens) {
  2683. return parse_single_box_shadow_value(tokens);
  2684. });
  2685. }
  2686. RefPtr<StyleValue> Parser::parse_single_box_shadow_value(TokenStream<StyleComponentValueRule>& tokens)
  2687. {
  2688. auto start_position = tokens.position();
  2689. auto error = [&]() {
  2690. tokens.rewind_to_position(start_position);
  2691. return nullptr;
  2692. };
  2693. Optional<Color> color;
  2694. Optional<Length> offset_x;
  2695. Optional<Length> offset_y;
  2696. Optional<Length> blur_radius;
  2697. Optional<Length> spread_distance;
  2698. Optional<BoxShadowPlacement> placement;
  2699. while (tokens.has_next_token()) {
  2700. auto& token = tokens.peek_token();
  2701. if (auto maybe_color = parse_color(token); maybe_color.has_value()) {
  2702. if (color.has_value())
  2703. return error();
  2704. color = maybe_color.release_value();
  2705. tokens.next_token();
  2706. continue;
  2707. }
  2708. if (auto maybe_offset_x = parse_length(token); maybe_offset_x.has_value()) {
  2709. // horizontal offset
  2710. if (offset_x.has_value())
  2711. return error();
  2712. offset_x = maybe_offset_x.release_value();
  2713. tokens.next_token();
  2714. // vertical offset
  2715. if (!tokens.has_next_token())
  2716. return error();
  2717. auto maybe_offset_y = parse_length(tokens.peek_token());
  2718. if (!maybe_offset_y.has_value())
  2719. return error();
  2720. offset_y = maybe_offset_y.release_value();
  2721. tokens.next_token();
  2722. // blur radius (optional)
  2723. if (!tokens.has_next_token())
  2724. break;
  2725. auto maybe_blur_radius = parse_length(tokens.peek_token());
  2726. if (!maybe_blur_radius.has_value())
  2727. continue;
  2728. blur_radius = maybe_blur_radius.release_value();
  2729. tokens.next_token();
  2730. // spread distance (optional)
  2731. if (!tokens.has_next_token())
  2732. break;
  2733. auto maybe_spread_distance = parse_length(tokens.peek_token());
  2734. if (!maybe_spread_distance.has_value())
  2735. continue;
  2736. spread_distance = maybe_spread_distance.release_value();
  2737. tokens.next_token();
  2738. continue;
  2739. }
  2740. if (token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_case("inset"sv)) {
  2741. if (placement.has_value())
  2742. return error();
  2743. placement = BoxShadowPlacement::Inner;
  2744. tokens.next_token();
  2745. continue;
  2746. }
  2747. if (token.is(Token::Type::Comma))
  2748. break;
  2749. return error();
  2750. }
  2751. // FIXME: If color is absent, default to `currentColor`
  2752. if (!color.has_value())
  2753. color = Color::NamedColor::Black;
  2754. // x/y offsets are required
  2755. if (!offset_x.has_value() || !offset_y.has_value())
  2756. return error();
  2757. // Other lengths default to 0
  2758. if (!blur_radius.has_value())
  2759. blur_radius = Length::make_px(0);
  2760. if (!spread_distance.has_value())
  2761. spread_distance = Length::make_px(0);
  2762. // Placement is outer by default
  2763. if (!placement.has_value())
  2764. placement = BoxShadowPlacement::Outer;
  2765. return BoxShadowStyleValue::create(color.release_value(), offset_x.release_value(), offset_y.release_value(), blur_radius.release_value(), spread_distance.release_value(), placement.release_value());
  2766. }
  2767. RefPtr<StyleValue> Parser::parse_flex_value(Vector<StyleComponentValueRule> const& component_values)
  2768. {
  2769. if (component_values.size() == 1) {
  2770. auto value = parse_css_value(component_values[0]);
  2771. if (!value)
  2772. return nullptr;
  2773. switch (value->to_identifier()) {
  2774. case ValueID::Auto: {
  2775. auto one = NumericStyleValue::create_integer(1);
  2776. return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
  2777. }
  2778. case ValueID::None: {
  2779. auto zero = NumericStyleValue::create_integer(0);
  2780. return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  2781. }
  2782. default:
  2783. break;
  2784. }
  2785. }
  2786. RefPtr<StyleValue> flex_grow;
  2787. RefPtr<StyleValue> flex_shrink;
  2788. RefPtr<StyleValue> flex_basis;
  2789. for (size_t i = 0; i < component_values.size(); ++i) {
  2790. auto value = parse_css_value(component_values[i]);
  2791. if (!value)
  2792. return nullptr;
  2793. // Zero is a valid value for basis, but only if grow and shrink are already specified.
  2794. if (value->has_number() && value->to_number() == 0) {
  2795. if (flex_grow && flex_shrink && !flex_basis) {
  2796. flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
  2797. continue;
  2798. }
  2799. }
  2800. if (property_accepts_value(PropertyID::FlexGrow, *value)) {
  2801. if (flex_grow)
  2802. return nullptr;
  2803. flex_grow = value.release_nonnull();
  2804. // Flex-shrink may optionally follow directly after.
  2805. if (i + 1 < component_values.size()) {
  2806. auto second_value = parse_css_value(component_values[i + 1]);
  2807. if (second_value && property_accepts_value(PropertyID::FlexShrink, *second_value)) {
  2808. flex_shrink = second_value.release_nonnull();
  2809. i++;
  2810. }
  2811. }
  2812. continue;
  2813. }
  2814. if (property_accepts_value(PropertyID::FlexBasis, *value)) {
  2815. if (flex_basis)
  2816. return nullptr;
  2817. flex_basis = value.release_nonnull();
  2818. continue;
  2819. }
  2820. return nullptr;
  2821. }
  2822. if (!flex_grow)
  2823. flex_grow = property_initial_value(PropertyID::FlexGrow);
  2824. if (!flex_shrink)
  2825. flex_shrink = property_initial_value(PropertyID::FlexShrink);
  2826. if (!flex_basis)
  2827. flex_basis = property_initial_value(PropertyID::FlexBasis);
  2828. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  2829. }
  2830. RefPtr<StyleValue> Parser::parse_flex_flow_value(Vector<StyleComponentValueRule> const& component_values)
  2831. {
  2832. if (component_values.size() > 2)
  2833. return nullptr;
  2834. RefPtr<StyleValue> flex_direction;
  2835. RefPtr<StyleValue> flex_wrap;
  2836. for (auto& part : component_values) {
  2837. auto value = parse_css_value(part);
  2838. if (!value)
  2839. return nullptr;
  2840. if (property_accepts_value(PropertyID::FlexDirection, *value)) {
  2841. if (flex_direction)
  2842. return nullptr;
  2843. flex_direction = value.release_nonnull();
  2844. continue;
  2845. }
  2846. if (property_accepts_value(PropertyID::FlexWrap, *value)) {
  2847. if (flex_wrap)
  2848. return nullptr;
  2849. flex_wrap = value.release_nonnull();
  2850. continue;
  2851. }
  2852. }
  2853. if (!flex_direction)
  2854. flex_direction = property_initial_value(PropertyID::FlexDirection);
  2855. if (!flex_wrap)
  2856. flex_wrap = property_initial_value(PropertyID::FlexWrap);
  2857. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  2858. }
  2859. RefPtr<StyleValue> Parser::parse_font_value(Vector<StyleComponentValueRule> const& component_values)
  2860. {
  2861. RefPtr<StyleValue> font_style;
  2862. RefPtr<StyleValue> font_weight;
  2863. RefPtr<StyleValue> font_size;
  2864. RefPtr<StyleValue> line_height;
  2865. RefPtr<StyleValue> font_families;
  2866. // FIXME: Implement font-stretch and font-variant.
  2867. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  2868. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  2869. // So, we have to handle that separately.
  2870. int normal_count = 0;
  2871. for (size_t i = 0; i < component_values.size(); ++i) {
  2872. auto value = parse_css_value(component_values[i]);
  2873. if (!value)
  2874. return nullptr;
  2875. if (value->to_identifier() == ValueID::Normal) {
  2876. normal_count++;
  2877. continue;
  2878. }
  2879. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  2880. if (property_accepts_value(PropertyID::FontStyle, *value)) {
  2881. if (font_style)
  2882. return nullptr;
  2883. font_style = value.release_nonnull();
  2884. continue;
  2885. }
  2886. if (property_accepts_value(PropertyID::FontWeight, *value)) {
  2887. if (font_weight)
  2888. return nullptr;
  2889. font_weight = value.release_nonnull();
  2890. continue;
  2891. }
  2892. if (property_accepts_value(PropertyID::FontSize, *value)) {
  2893. if (font_size)
  2894. return nullptr;
  2895. font_size = value.release_nonnull();
  2896. // Consume `/ line-height` if present
  2897. if (i + 2 < component_values.size()) {
  2898. auto maybe_solidus = component_values[i + 1];
  2899. if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == "/"sv) {
  2900. auto maybe_line_height = parse_css_value(component_values[i + 2]);
  2901. if (!(maybe_line_height && property_accepts_value(PropertyID::LineHeight, *maybe_line_height)))
  2902. return nullptr;
  2903. line_height = maybe_line_height.release_nonnull();
  2904. i += 2;
  2905. }
  2906. }
  2907. // Consume font-families
  2908. auto maybe_font_families = parse_font_family_value(component_values, i + 1);
  2909. if (!maybe_font_families)
  2910. return nullptr;
  2911. font_families = maybe_font_families.release_nonnull();
  2912. break;
  2913. }
  2914. return nullptr;
  2915. }
  2916. // Since normal is the default value for all the properties that can have it, we don't have to actually
  2917. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  2918. // We just need to make sure we were not given more normals than will fit.
  2919. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  2920. if (unset_value_count < normal_count)
  2921. return nullptr;
  2922. if (!font_size || !font_families)
  2923. return nullptr;
  2924. if (!font_style)
  2925. font_style = property_initial_value(PropertyID::FontStyle);
  2926. if (!font_weight)
  2927. font_weight = property_initial_value(PropertyID::FontWeight);
  2928. if (!line_height)
  2929. line_height = property_initial_value(PropertyID::LineHeight);
  2930. return FontStyleValue::create(font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
  2931. }
  2932. RefPtr<StyleValue> Parser::parse_font_family_value(Vector<StyleComponentValueRule> const& component_values, size_t start_index)
  2933. {
  2934. auto is_generic_font_family = [](ValueID identifier) -> bool {
  2935. switch (identifier) {
  2936. case ValueID::Cursive:
  2937. case ValueID::Fantasy:
  2938. case ValueID::Monospace:
  2939. case ValueID::Serif:
  2940. case ValueID::SansSerif:
  2941. case ValueID::UiMonospace:
  2942. case ValueID::UiRounded:
  2943. case ValueID::UiSerif:
  2944. case ValueID::UiSansSerif:
  2945. return true;
  2946. default:
  2947. return false;
  2948. }
  2949. };
  2950. auto is_comma_or_eof = [&](size_t i) -> bool {
  2951. if (i < component_values.size()) {
  2952. auto& maybe_comma = component_values[i];
  2953. if (!maybe_comma.is(Token::Type::Comma))
  2954. return false;
  2955. }
  2956. return true;
  2957. };
  2958. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  2959. // eg, these are equivalent:
  2960. // font-family: my cool font\!, serif;
  2961. // font-family: "my cool font!", serif;
  2962. NonnullRefPtrVector<StyleValue> font_families;
  2963. Vector<String> current_name_parts;
  2964. for (size_t i = start_index; i < component_values.size(); ++i) {
  2965. auto& part = component_values[i];
  2966. if (part.is(Token::Type::String)) {
  2967. // `font-family: my cool "font";` is invalid.
  2968. if (!current_name_parts.is_empty())
  2969. return nullptr;
  2970. if (!is_comma_or_eof(i + 1))
  2971. return nullptr;
  2972. font_families.append(StringStyleValue::create(part.token().string()));
  2973. i++;
  2974. continue;
  2975. }
  2976. if (part.is(Token::Type::Ident)) {
  2977. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  2978. auto maybe_ident = parse_css_value(part);
  2979. if (maybe_ident) {
  2980. // CSS-wide keywords are not allowed
  2981. if (maybe_ident->is_builtin())
  2982. return nullptr;
  2983. if (is_generic_font_family(maybe_ident->to_identifier())) {
  2984. // Can't have a generic-font-name as a token in an unquoted font name.
  2985. if (!current_name_parts.is_empty())
  2986. return nullptr;
  2987. if (!is_comma_or_eof(i + 1))
  2988. return nullptr;
  2989. font_families.append(maybe_ident.release_nonnull());
  2990. i++;
  2991. continue;
  2992. }
  2993. }
  2994. current_name_parts.append(part.token().ident());
  2995. continue;
  2996. }
  2997. if (part.is(Token::Type::Comma)) {
  2998. if (current_name_parts.is_empty())
  2999. return nullptr;
  3000. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  3001. current_name_parts.clear();
  3002. // Can't have a trailing comma
  3003. if (i + 1 == component_values.size())
  3004. return nullptr;
  3005. continue;
  3006. }
  3007. }
  3008. if (!current_name_parts.is_empty()) {
  3009. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  3010. current_name_parts.clear();
  3011. }
  3012. if (font_families.is_empty())
  3013. return nullptr;
  3014. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  3015. }
  3016. RefPtr<StyleValue> Parser::parse_list_style_value(Vector<StyleComponentValueRule> const& component_values)
  3017. {
  3018. if (component_values.size() > 3)
  3019. return nullptr;
  3020. RefPtr<StyleValue> list_position;
  3021. RefPtr<StyleValue> list_image;
  3022. RefPtr<StyleValue> list_type;
  3023. int found_nones = 0;
  3024. for (auto& part : component_values) {
  3025. auto value = parse_css_value(part);
  3026. if (!value)
  3027. return nullptr;
  3028. if (value->to_identifier() == ValueID::None) {
  3029. found_nones++;
  3030. continue;
  3031. }
  3032. if (property_accepts_value(PropertyID::ListStylePosition, *value)) {
  3033. if (list_position)
  3034. return nullptr;
  3035. list_position = value.release_nonnull();
  3036. continue;
  3037. }
  3038. if (property_accepts_value(PropertyID::ListStyleImage, *value)) {
  3039. if (list_image)
  3040. return nullptr;
  3041. list_image = value.release_nonnull();
  3042. continue;
  3043. }
  3044. if (property_accepts_value(PropertyID::ListStyleType, *value)) {
  3045. if (list_type)
  3046. return nullptr;
  3047. list_type = value.release_nonnull();
  3048. continue;
  3049. }
  3050. }
  3051. if (found_nones > 2)
  3052. return nullptr;
  3053. if (found_nones == 2) {
  3054. if (list_image || list_type)
  3055. return nullptr;
  3056. auto none = IdentifierStyleValue::create(ValueID::None);
  3057. list_image = none;
  3058. list_type = none;
  3059. } else if (found_nones == 1) {
  3060. if (list_image && list_type)
  3061. return nullptr;
  3062. auto none = IdentifierStyleValue::create(ValueID::None);
  3063. if (!list_image)
  3064. list_image = none;
  3065. if (!list_type)
  3066. list_type = none;
  3067. }
  3068. if (!list_position)
  3069. list_position = property_initial_value(PropertyID::ListStylePosition);
  3070. if (!list_image)
  3071. list_image = property_initial_value(PropertyID::ListStyleImage);
  3072. if (!list_type)
  3073. list_type = property_initial_value(PropertyID::ListStyleType);
  3074. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  3075. }
  3076. RefPtr<StyleValue> Parser::parse_overflow_value(Vector<StyleComponentValueRule> const& component_values)
  3077. {
  3078. if (component_values.size() == 1) {
  3079. auto maybe_value = parse_css_value(component_values.first());
  3080. if (!maybe_value)
  3081. return nullptr;
  3082. auto value = maybe_value.release_nonnull();
  3083. if (property_accepts_value(PropertyID::Overflow, *value))
  3084. return OverflowStyleValue::create(value, value);
  3085. return nullptr;
  3086. }
  3087. if (component_values.size() == 2) {
  3088. auto maybe_x_value = parse_css_value(component_values[0]);
  3089. auto maybe_y_value = parse_css_value(component_values[1]);
  3090. if (!maybe_x_value || !maybe_y_value)
  3091. return nullptr;
  3092. auto x_value = maybe_x_value.release_nonnull();
  3093. auto y_value = maybe_y_value.release_nonnull();
  3094. if (!property_accepts_value(PropertyID::OverflowX, x_value) || !property_accepts_value(PropertyID::OverflowY, y_value)) {
  3095. return nullptr;
  3096. }
  3097. return OverflowStyleValue::create(x_value, y_value);
  3098. }
  3099. return nullptr;
  3100. }
  3101. RefPtr<StyleValue> Parser::parse_text_decoration_value(Vector<StyleComponentValueRule> const& component_values)
  3102. {
  3103. if (component_values.size() > 3)
  3104. return nullptr;
  3105. RefPtr<StyleValue> decoration_line;
  3106. RefPtr<StyleValue> decoration_style;
  3107. RefPtr<StyleValue> decoration_color;
  3108. // FIXME: Implement 'text-decoration-thickness' parameter. https://www.w3.org/TR/css-text-decor-4/#text-decoration-width-property
  3109. for (auto& part : component_values) {
  3110. auto value = parse_css_value(part);
  3111. if (!value)
  3112. return nullptr;
  3113. if (property_accepts_value(PropertyID::TextDecorationColor, *value)) {
  3114. if (decoration_color)
  3115. return nullptr;
  3116. decoration_color = value.release_nonnull();
  3117. continue;
  3118. }
  3119. if (property_accepts_value(PropertyID::TextDecorationLine, *value)) {
  3120. if (decoration_line)
  3121. return nullptr;
  3122. decoration_line = value.release_nonnull();
  3123. continue;
  3124. }
  3125. if (property_accepts_value(PropertyID::TextDecorationStyle, *value)) {
  3126. if (decoration_style)
  3127. return nullptr;
  3128. decoration_style = value.release_nonnull();
  3129. continue;
  3130. }
  3131. return nullptr;
  3132. }
  3133. if (!decoration_line)
  3134. decoration_line = property_initial_value(PropertyID::TextDecorationLine);
  3135. if (!decoration_style)
  3136. decoration_style = property_initial_value(PropertyID::TextDecorationStyle);
  3137. if (!decoration_color)
  3138. decoration_color = property_initial_value(PropertyID::TextDecorationColor);
  3139. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  3140. }
  3141. static Optional<CSS::TransformFunction> parse_transform_function_name(StringView name)
  3142. {
  3143. if (name == "translateY")
  3144. return CSS::TransformFunction::TranslateY;
  3145. return {};
  3146. }
  3147. RefPtr<StyleValue> Parser::parse_transform_value(Vector<StyleComponentValueRule> const& component_values)
  3148. {
  3149. NonnullRefPtrVector<StyleValue> transformations;
  3150. for (auto& part : component_values) {
  3151. if (part.is(Token::Type::Ident) && part.token().ident().equals_ignoring_case("none")) {
  3152. if (!transformations.is_empty())
  3153. return nullptr;
  3154. return IdentifierStyleValue::create(ValueID::None);
  3155. }
  3156. if (!part.is_function())
  3157. return nullptr;
  3158. auto maybe_function = parse_transform_function_name(part.function().name());
  3159. if (!maybe_function.has_value())
  3160. return nullptr;
  3161. NonnullRefPtrVector<StyleValue> values;
  3162. for (auto& value : part.function().values()) {
  3163. if (value.is(Token::Type::Dimension)) {
  3164. auto maybe_length = parse_length(value);
  3165. if (!maybe_length.has_value())
  3166. return nullptr;
  3167. values.append(LengthStyleValue::create(maybe_length.release_value()));
  3168. } else if (value.is(Token::Type::Number)) {
  3169. auto number = parse_numeric_value(value);
  3170. values.append(number.release_nonnull());
  3171. } else {
  3172. dbgln_if(CSS_PARSER_DEBUG, "FIXME: Unsupported value type for transformation!");
  3173. return nullptr;
  3174. }
  3175. }
  3176. transformations.append(TransformationStyleValue::create(maybe_function.value(), move(values)));
  3177. }
  3178. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  3179. }
  3180. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  3181. {
  3182. auto component_values = parse_as_list_of_component_values();
  3183. auto tokens = TokenStream(component_values);
  3184. auto parsed_value = parse_css_value(property_id, tokens);
  3185. if (parsed_value.is_error())
  3186. return {};
  3187. return parsed_value.release_value();
  3188. }
  3189. Result<NonnullRefPtr<StyleValue>, Parser::ParsingResult> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  3190. {
  3191. auto block_contains_var = [](StyleBlockRule const& block, auto&& recurse) -> bool {
  3192. for (auto const& token : block.values()) {
  3193. if (token.is_function() && token.function().name().equals_ignoring_case("var"sv))
  3194. return true;
  3195. if (token.is_block() && recurse(token.block(), recurse))
  3196. return true;
  3197. }
  3198. return false;
  3199. };
  3200. m_context.set_current_property_id(property_id);
  3201. Vector<StyleComponentValueRule> component_values;
  3202. bool contains_var = false;
  3203. while (tokens.has_next_token()) {
  3204. auto& token = tokens.next_token();
  3205. if (token.is(Token::Type::Semicolon)) {
  3206. tokens.reconsume_current_input_token();
  3207. break;
  3208. }
  3209. if (property_id != PropertyID::Custom) {
  3210. if (token.is(Token::Type::Whitespace))
  3211. continue;
  3212. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  3213. return ParsingResult::IncludesIgnoredVendorPrefix;
  3214. }
  3215. if (!contains_var) {
  3216. if (token.is_function() && token.function().name().equals_ignoring_case("var"sv))
  3217. contains_var = true;
  3218. else if (token.is_block() && block_contains_var(token.block(), block_contains_var))
  3219. contains_var = true;
  3220. }
  3221. component_values.append(token);
  3222. }
  3223. if (property_id == PropertyID::Custom || contains_var)
  3224. return { UnresolvedStyleValue::create(move(component_values), contains_var) };
  3225. if (component_values.is_empty())
  3226. return ParsingResult::SyntaxError;
  3227. if (component_values.size() == 1) {
  3228. if (auto parsed_value = parse_builtin_value(component_values.first()))
  3229. return parsed_value.release_nonnull();
  3230. }
  3231. // Special-case property handling
  3232. switch (property_id) {
  3233. case PropertyID::Background:
  3234. if (auto parsed_value = parse_background_value(component_values))
  3235. return parsed_value.release_nonnull();
  3236. return ParsingResult::SyntaxError;
  3237. case PropertyID::BackgroundAttachment:
  3238. case PropertyID::BackgroundClip:
  3239. case PropertyID::BackgroundImage:
  3240. case PropertyID::BackgroundOrigin:
  3241. if (auto parsed_value = parse_simple_comma_separated_value_list(component_values))
  3242. return parsed_value.release_nonnull();
  3243. return ParsingResult::SyntaxError;
  3244. case PropertyID::BackgroundPosition:
  3245. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_position_value(tokens); }))
  3246. return parsed_value.release_nonnull();
  3247. return ParsingResult::SyntaxError;
  3248. case PropertyID::BackgroundRepeat:
  3249. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
  3250. return parsed_value.release_nonnull();
  3251. return ParsingResult::SyntaxError;
  3252. case PropertyID::BackgroundSize:
  3253. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
  3254. return parsed_value.release_nonnull();
  3255. return ParsingResult::SyntaxError;
  3256. case PropertyID::Border:
  3257. case PropertyID::BorderBottom:
  3258. case PropertyID::BorderLeft:
  3259. case PropertyID::BorderRight:
  3260. case PropertyID::BorderTop:
  3261. if (auto parsed_value = parse_border_value(component_values))
  3262. return parsed_value.release_nonnull();
  3263. return ParsingResult::SyntaxError;
  3264. case PropertyID::BorderTopLeftRadius:
  3265. case PropertyID::BorderTopRightRadius:
  3266. case PropertyID::BorderBottomRightRadius:
  3267. case PropertyID::BorderBottomLeftRadius:
  3268. if (auto parsed_value = parse_border_radius_value(component_values))
  3269. return parsed_value.release_nonnull();
  3270. return ParsingResult::SyntaxError;
  3271. case PropertyID::BorderRadius:
  3272. if (auto parsed_value = parse_border_radius_shorthand_value(component_values))
  3273. return parsed_value.release_nonnull();
  3274. return ParsingResult::SyntaxError;
  3275. case PropertyID::BoxShadow:
  3276. if (auto parsed_value = parse_box_shadow_value(component_values))
  3277. return parsed_value.release_nonnull();
  3278. return ParsingResult::SyntaxError;
  3279. case PropertyID::Flex:
  3280. if (auto parsed_value = parse_flex_value(component_values))
  3281. return parsed_value.release_nonnull();
  3282. return ParsingResult::SyntaxError;
  3283. case PropertyID::FlexFlow:
  3284. if (auto parsed_value = parse_flex_flow_value(component_values))
  3285. return parsed_value.release_nonnull();
  3286. return ParsingResult::SyntaxError;
  3287. case PropertyID::Font:
  3288. if (auto parsed_value = parse_font_value(component_values))
  3289. return parsed_value.release_nonnull();
  3290. return ParsingResult::SyntaxError;
  3291. case PropertyID::FontFamily:
  3292. if (auto parsed_value = parse_font_family_value(component_values))
  3293. return parsed_value.release_nonnull();
  3294. return ParsingResult::SyntaxError;
  3295. case PropertyID::ListStyle:
  3296. if (auto parsed_value = parse_list_style_value(component_values))
  3297. return parsed_value.release_nonnull();
  3298. return ParsingResult::SyntaxError;
  3299. case PropertyID::Overflow:
  3300. if (auto parsed_value = parse_overflow_value(component_values))
  3301. return parsed_value.release_nonnull();
  3302. return ParsingResult::SyntaxError;
  3303. case PropertyID::TextDecoration:
  3304. if (auto parsed_value = parse_text_decoration_value(component_values))
  3305. return parsed_value.release_nonnull();
  3306. return ParsingResult::SyntaxError;
  3307. case PropertyID::Transform:
  3308. if (auto parsed_value = parse_transform_value(component_values))
  3309. return parsed_value.release_nonnull();
  3310. return ParsingResult::SyntaxError;
  3311. default:
  3312. break;
  3313. }
  3314. if (component_values.size() == 1) {
  3315. if (auto parsed_value = parse_css_value(component_values.first())) {
  3316. if (property_accepts_value(property_id, *parsed_value))
  3317. return parsed_value.release_nonnull();
  3318. }
  3319. return ParsingResult::SyntaxError;
  3320. }
  3321. // We have multiple values, so treat them as a StyleValueList.
  3322. if (property_maximum_value_count(property_id) > 1) {
  3323. NonnullRefPtrVector<StyleValue> parsed_values;
  3324. for (auto& component_value : component_values) {
  3325. auto parsed_value = parse_css_value(component_value);
  3326. if (!parsed_value || !property_accepts_value(property_id, *parsed_value))
  3327. return ParsingResult::SyntaxError;
  3328. parsed_values.append(parsed_value.release_nonnull());
  3329. }
  3330. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  3331. return { StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space) };
  3332. }
  3333. return ParsingResult::SyntaxError;
  3334. }
  3335. RefPtr<StyleValue> Parser::parse_css_value(StyleComponentValueRule const& component_value)
  3336. {
  3337. if (auto builtin = parse_builtin_value(component_value))
  3338. return builtin;
  3339. if (auto dynamic = parse_dynamic_value(component_value))
  3340. return dynamic;
  3341. // We parse colors before numbers, to catch hashless hex colors.
  3342. if (auto color = parse_color_value(component_value))
  3343. return color;
  3344. if (auto dimension = parse_dimension_value(component_value))
  3345. return dimension;
  3346. if (auto numeric = parse_numeric_value(component_value))
  3347. return numeric;
  3348. if (auto identifier = parse_identifier_value(component_value))
  3349. return identifier;
  3350. if (auto string = parse_string_value(component_value))
  3351. return string;
  3352. if (auto image = parse_image_value(component_value))
  3353. return image;
  3354. return {};
  3355. }
  3356. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values)
  3357. {
  3358. int a = 0;
  3359. int b = 0;
  3360. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  3361. if constexpr (CSS_PARSER_DEBUG) {
  3362. dbgln_if(CSS_PARSER_DEBUG, "Invalid An+B value:");
  3363. values.dump_all_tokens();
  3364. }
  3365. return {};
  3366. };
  3367. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  3368. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  3369. values.skip_whitespace();
  3370. if (values.has_next_token()) {
  3371. if constexpr (CSS_PARSER_DEBUG) {
  3372. dbgln_if(CSS_PARSER_DEBUG, "Extra tokens at end of An+B value:");
  3373. values.dump_all_tokens();
  3374. }
  3375. return syntax_error();
  3376. } else {
  3377. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  3378. }
  3379. };
  3380. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  3381. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  3382. };
  3383. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  3384. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  3385. };
  3386. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  3387. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  3388. };
  3389. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  3390. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  3391. };
  3392. auto is_delim = [](StyleComponentValueRule const& value, StringView delim) -> bool {
  3393. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  3394. };
  3395. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  3396. if (!value.is(Token::Type::Dimension))
  3397. return false;
  3398. if (value.token().number_type() != Token::NumberType::Integer)
  3399. return false;
  3400. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  3401. return false;
  3402. return true;
  3403. };
  3404. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  3405. if (!value.is(Token::Type::Dimension))
  3406. return false;
  3407. if (value.token().number_type() != Token::NumberType::Integer)
  3408. return false;
  3409. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  3410. return false;
  3411. return true;
  3412. };
  3413. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  3414. if (!value.is(Token::Type::Dimension))
  3415. return false;
  3416. if (value.token().number_type() != Token::NumberType::Integer)
  3417. return false;
  3418. auto dimension_unit = value.token().dimension_unit();
  3419. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  3420. return false;
  3421. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  3422. if (!is_ascii_digit(dimension_unit[i]))
  3423. return false;
  3424. }
  3425. return true;
  3426. };
  3427. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  3428. if (!value.is(Token::Type::Ident))
  3429. return false;
  3430. auto ident = value.token().ident();
  3431. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  3432. return false;
  3433. for (size_t i = 2; i < ident.length(); ++i) {
  3434. if (!is_ascii_digit(ident[i]))
  3435. return false;
  3436. }
  3437. return true;
  3438. };
  3439. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  3440. if (!value.is(Token::Type::Ident))
  3441. return false;
  3442. auto ident = value.token().ident();
  3443. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  3444. return false;
  3445. for (size_t i = 3; i < ident.length(); ++i) {
  3446. if (!is_ascii_digit(ident[i]))
  3447. return false;
  3448. }
  3449. return true;
  3450. };
  3451. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  3452. return value.is(Token::Type::Number) && value.token().is(Token::NumberType::Integer);
  3453. };
  3454. auto is_signed_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  3455. return is_integer(value) && value.token().is_integer_value_signed();
  3456. };
  3457. auto is_signless_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  3458. return is_integer(value) && !value.token().is_integer_value_signed();
  3459. };
  3460. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  3461. // Unfortunately these can't be in the same order as in the spec.
  3462. values.skip_whitespace();
  3463. auto& first_value = values.next_token();
  3464. // odd | even
  3465. if (first_value.is(Token::Type::Ident)) {
  3466. auto ident = first_value.token().ident();
  3467. if (ident.equals_ignoring_case("odd")) {
  3468. a = 2;
  3469. b = 1;
  3470. return make_return_value();
  3471. } else if (ident.equals_ignoring_case("even")) {
  3472. a = 2;
  3473. return make_return_value();
  3474. }
  3475. }
  3476. // <integer>
  3477. if (is_integer(first_value)) {
  3478. b = first_value.token().to_integer();
  3479. return make_return_value();
  3480. }
  3481. // <n-dimension>
  3482. // <n-dimension> <signed-integer>
  3483. // <n-dimension> ['+' | '-'] <signless-integer>
  3484. if (is_n_dimension(first_value)) {
  3485. a = first_value.token().dimension_value_int();
  3486. values.skip_whitespace();
  3487. auto& second_value = values.next_token();
  3488. if (second_value.is(Token::Type::EndOfFile)) {
  3489. // <n-dimension>
  3490. return make_return_value();
  3491. } else if (is_signed_integer(second_value)) {
  3492. // <n-dimension> <signed-integer>
  3493. b = second_value.token().to_integer();
  3494. return make_return_value();
  3495. }
  3496. values.skip_whitespace();
  3497. auto& third_value = values.next_token();
  3498. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3499. // <n-dimension> ['+' | '-'] <signless-integer>
  3500. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3501. return make_return_value();
  3502. }
  3503. return syntax_error();
  3504. }
  3505. // <ndash-dimension> <signless-integer>
  3506. if (is_ndash_dimension(first_value)) {
  3507. values.skip_whitespace();
  3508. auto& second_value = values.next_token();
  3509. if (is_signless_integer(second_value)) {
  3510. a = first_value.token().dimension_value_int();
  3511. b = -second_value.token().to_integer();
  3512. return make_return_value();
  3513. }
  3514. return syntax_error();
  3515. }
  3516. // <ndashdigit-dimension>
  3517. if (is_ndashdigit_dimension(first_value)) {
  3518. auto& dimension = first_value.token();
  3519. a = dimension.dimension_value_int();
  3520. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  3521. if (maybe_b.has_value()) {
  3522. b = maybe_b.value();
  3523. return make_return_value();
  3524. }
  3525. return syntax_error();
  3526. }
  3527. // <dashndashdigit-ident>
  3528. if (is_dashndashdigit_ident(first_value)) {
  3529. a = -1;
  3530. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  3531. if (maybe_b.has_value()) {
  3532. b = maybe_b.value();
  3533. return make_return_value();
  3534. }
  3535. return syntax_error();
  3536. }
  3537. // -n
  3538. // -n <signed-integer>
  3539. // -n ['+' | '-'] <signless-integer>
  3540. if (is_dashn(first_value)) {
  3541. a = -1;
  3542. values.skip_whitespace();
  3543. auto& second_value = values.next_token();
  3544. if (second_value.is(Token::Type::EndOfFile)) {
  3545. // -n
  3546. return make_return_value();
  3547. } else if (is_signed_integer(second_value)) {
  3548. // -n <signed-integer>
  3549. b = second_value.token().to_integer();
  3550. return make_return_value();
  3551. }
  3552. values.skip_whitespace();
  3553. auto& third_value = values.next_token();
  3554. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3555. // -n ['+' | '-'] <signless-integer>
  3556. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3557. return make_return_value();
  3558. }
  3559. return syntax_error();
  3560. }
  3561. // -n- <signless-integer>
  3562. if (is_dashndash(first_value)) {
  3563. values.skip_whitespace();
  3564. auto& second_value = values.next_token();
  3565. if (is_signless_integer(second_value)) {
  3566. a = -1;
  3567. b = -second_value.token().to_integer();
  3568. return make_return_value();
  3569. }
  3570. return syntax_error();
  3571. }
  3572. // All that's left now are these:
  3573. // '+'?† n
  3574. // '+'?† n <signed-integer>
  3575. // '+'?† n ['+' | '-'] <signless-integer>
  3576. // '+'?† n- <signless-integer>
  3577. // '+'?† <ndashdigit-ident>
  3578. // In all of these cases, the + is optional, and has no effect.
  3579. // So, we just skip the +, and carry on.
  3580. if (!is_delim(first_value, "+"sv)) {
  3581. values.reconsume_current_input_token();
  3582. // We do *not* skip whitespace here.
  3583. }
  3584. auto& first_after_plus = values.next_token();
  3585. // '+'?† n
  3586. // '+'?† n <signed-integer>
  3587. // '+'?† n ['+' | '-'] <signless-integer>
  3588. if (is_n(first_after_plus)) {
  3589. a = 1;
  3590. values.skip_whitespace();
  3591. auto& second_value = values.next_token();
  3592. if (second_value.is(Token::Type::EndOfFile)) {
  3593. // '+'?† n
  3594. return make_return_value();
  3595. } else if (is_signed_integer(second_value)) {
  3596. // '+'?† n <signed-integer>
  3597. b = second_value.token().to_integer();
  3598. return make_return_value();
  3599. }
  3600. values.skip_whitespace();
  3601. auto& third_value = values.next_token();
  3602. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3603. // '+'?† n ['+' | '-'] <signless-integer>
  3604. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3605. return make_return_value();
  3606. }
  3607. return syntax_error();
  3608. }
  3609. // '+'?† n- <signless-integer>
  3610. if (is_ndash(first_after_plus)) {
  3611. values.skip_whitespace();
  3612. auto& second_value = values.next_token();
  3613. if (is_signless_integer(second_value)) {
  3614. a = 1;
  3615. b = -second_value.token().to_integer();
  3616. return make_return_value();
  3617. }
  3618. return syntax_error();
  3619. }
  3620. // '+'?† <ndashdigit-ident>
  3621. if (is_ndashdigit_ident(first_after_plus)) {
  3622. a = 1;
  3623. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  3624. if (maybe_b.has_value()) {
  3625. b = maybe_b.value();
  3626. return make_return_value();
  3627. }
  3628. return syntax_error();
  3629. }
  3630. return syntax_error();
  3631. }
  3632. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(Vector<StyleComponentValueRule> const& values)
  3633. {
  3634. auto tokens = TokenStream(values);
  3635. return parse_calc_sum(tokens);
  3636. }
  3637. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(TokenStream<StyleComponentValueRule>& tokens)
  3638. {
  3639. auto current_token = tokens.next_token();
  3640. if (current_token.is_block() && current_token.block().is_paren()) {
  3641. auto block_values = TokenStream(current_token.block().values());
  3642. auto parsed_calc_sum = parse_calc_sum(block_values);
  3643. if (!parsed_calc_sum)
  3644. return {};
  3645. return CalculatedStyleValue::CalcValue { parsed_calc_sum.release_nonnull() };
  3646. }
  3647. if (current_token.is(Token::Type::Number))
  3648. return CalculatedStyleValue::CalcValue {
  3649. CalculatedStyleValue::Number {
  3650. .is_integer = current_token.token().number_type() == Token::NumberType::Integer,
  3651. .value = static_cast<float>(current_token.token().number_value()) }
  3652. };
  3653. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  3654. auto maybe_dimension = parse_dimension(current_token);
  3655. if (!maybe_dimension.has_value())
  3656. return {};
  3657. auto& dimension = maybe_dimension.value();
  3658. if (dimension.is_angle())
  3659. return CalculatedStyleValue::CalcValue { dimension.angle() };
  3660. if (dimension.is_frequency())
  3661. return CalculatedStyleValue::CalcValue { dimension.frequency() };
  3662. if (dimension.is_length())
  3663. return CalculatedStyleValue::CalcValue { dimension.length() };
  3664. if (dimension.is_percentage())
  3665. return CalculatedStyleValue::CalcValue { dimension.percentage() };
  3666. if (dimension.is_resolution()) {
  3667. // Resolution is not allowed in calc()
  3668. return {};
  3669. }
  3670. if (dimension.is_time())
  3671. return CalculatedStyleValue::CalcValue { dimension.time() };
  3672. VERIFY_NOT_REACHED();
  3673. }
  3674. return {};
  3675. }
  3676. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3677. {
  3678. // Note: The default value is not used or passed around.
  3679. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  3680. CalculatedStyleValue::ProductOperation::Multiply,
  3681. CalculatedStyleValue::CalcNumberValue { CalculatedStyleValue::Number { false, 0 } });
  3682. tokens.skip_whitespace();
  3683. auto& op_token = tokens.peek_token();
  3684. if (!op_token.is(Token::Type::Delim))
  3685. return nullptr;
  3686. auto op = op_token.token().delim();
  3687. if (op == "*"sv) {
  3688. tokens.next_token();
  3689. tokens.skip_whitespace();
  3690. product_with_operator->op = CalculatedStyleValue::ProductOperation::Multiply;
  3691. auto parsed_calc_value = parse_calc_value(tokens);
  3692. if (!parsed_calc_value.has_value())
  3693. return nullptr;
  3694. product_with_operator->value = { parsed_calc_value.release_value() };
  3695. } else if (op == "/"sv) {
  3696. // FIXME: Detect divide-by-zero if possible
  3697. tokens.next_token();
  3698. tokens.skip_whitespace();
  3699. product_with_operator->op = CalculatedStyleValue::ProductOperation::Divide;
  3700. auto parsed_calc_number_value = parse_calc_number_value(tokens);
  3701. if (!parsed_calc_number_value.has_value())
  3702. return nullptr;
  3703. product_with_operator->value = { parsed_calc_number_value.release_value() };
  3704. } else {
  3705. return nullptr;
  3706. }
  3707. return product_with_operator;
  3708. }
  3709. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3710. {
  3711. // Note: The default value is not used or passed around.
  3712. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  3713. CalculatedStyleValue::ProductOperation::Multiply,
  3714. CalculatedStyleValue::CalcNumberValue { CalculatedStyleValue::Number { false, 0 } });
  3715. tokens.skip_whitespace();
  3716. auto& op_token = tokens.peek_token();
  3717. if (!op_token.is(Token::Type::Delim))
  3718. return nullptr;
  3719. auto op = op_token.token().delim();
  3720. if (op == "*"sv) {
  3721. tokens.next_token();
  3722. tokens.skip_whitespace();
  3723. number_product_with_operator->op = CalculatedStyleValue::ProductOperation::Multiply;
  3724. } else if (op == "/"sv) {
  3725. // FIXME: Detect divide-by-zero if possible
  3726. tokens.next_token();
  3727. tokens.skip_whitespace();
  3728. number_product_with_operator->op = CalculatedStyleValue::ProductOperation::Divide;
  3729. } else {
  3730. return nullptr;
  3731. }
  3732. auto parsed_calc_value = parse_calc_number_value(tokens);
  3733. if (!parsed_calc_value.has_value())
  3734. return nullptr;
  3735. number_product_with_operator->value = parsed_calc_value.release_value();
  3736. return number_product_with_operator;
  3737. }
  3738. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(TokenStream<StyleComponentValueRule>& tokens)
  3739. {
  3740. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  3741. CalculatedStyleValue::CalcNumberValue { CalculatedStyleValue::Number { false, 0 } },
  3742. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  3743. auto first_calc_number_value_or_error = parse_calc_number_value(tokens);
  3744. if (!first_calc_number_value_or_error.has_value())
  3745. return nullptr;
  3746. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  3747. while (tokens.has_next_token()) {
  3748. auto number_product_with_operator = parse_calc_number_product_part_with_operator(tokens);
  3749. if (!number_product_with_operator)
  3750. break;
  3751. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  3752. }
  3753. return calc_number_product;
  3754. }
  3755. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3756. {
  3757. if (!(tokens.peek_token().is(Token::Type::Delim)
  3758. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3759. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3760. return nullptr;
  3761. auto& token = tokens.next_token();
  3762. tokens.skip_whitespace();
  3763. CalculatedStyleValue::SumOperation op;
  3764. auto delim = token.token().delim();
  3765. if (delim == "+"sv)
  3766. op = CalculatedStyleValue::SumOperation::Add;
  3767. else if (delim == "-"sv)
  3768. op = CalculatedStyleValue::SumOperation::Subtract;
  3769. else
  3770. return nullptr;
  3771. auto calc_number_product = parse_calc_number_product(tokens);
  3772. if (!calc_number_product)
  3773. return nullptr;
  3774. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  3775. }
  3776. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(TokenStream<StyleComponentValueRule>& tokens)
  3777. {
  3778. auto first_calc_number_product_or_error = parse_calc_number_product(tokens);
  3779. if (!first_calc_number_product_or_error)
  3780. return nullptr;
  3781. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  3782. while (tokens.has_next_token()) {
  3783. auto calc_sum_part = parse_calc_number_sum_part_with_operator(tokens);
  3784. if (!calc_sum_part)
  3785. return nullptr;
  3786. additional.append(calc_sum_part.release_nonnull());
  3787. }
  3788. tokens.skip_whitespace();
  3789. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  3790. return calc_number_sum;
  3791. }
  3792. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(TokenStream<StyleComponentValueRule>& tokens)
  3793. {
  3794. auto& first = tokens.peek_token();
  3795. if (first.is_block() && first.block().is_paren()) {
  3796. tokens.next_token();
  3797. auto block_values = TokenStream(first.block().values());
  3798. auto calc_number_sum = parse_calc_number_sum(block_values);
  3799. if (calc_number_sum)
  3800. return CalculatedStyleValue::CalcNumberValue { calc_number_sum.release_nonnull() };
  3801. }
  3802. if (!first.is(Token::Type::Number))
  3803. return {};
  3804. tokens.next_token();
  3805. return CalculatedStyleValue::CalcNumberValue {
  3806. CalculatedStyleValue::Number {
  3807. .is_integer = first.token().number_type() == Token::NumberType::Integer,
  3808. .value = static_cast<float>(first.token().number_value()) }
  3809. };
  3810. }
  3811. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(TokenStream<StyleComponentValueRule>& tokens)
  3812. {
  3813. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  3814. CalculatedStyleValue::CalcValue { CalculatedStyleValue::Number { false, 0 } },
  3815. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  3816. auto first_calc_value_or_error = parse_calc_value(tokens);
  3817. if (!first_calc_value_or_error.has_value())
  3818. return nullptr;
  3819. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  3820. while (tokens.has_next_token()) {
  3821. auto product_with_operator = parse_calc_product_part_with_operator(tokens);
  3822. if (!product_with_operator)
  3823. break;
  3824. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  3825. }
  3826. return calc_product;
  3827. }
  3828. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3829. {
  3830. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  3831. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  3832. if (!(tokens.peek_token().is(Token::Type::Delim)
  3833. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3834. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3835. return nullptr;
  3836. auto& token = tokens.next_token();
  3837. tokens.skip_whitespace();
  3838. CalculatedStyleValue::SumOperation op;
  3839. auto delim = token.token().delim();
  3840. if (delim == "+"sv)
  3841. op = CalculatedStyleValue::SumOperation::Add;
  3842. else if (delim == "-"sv)
  3843. op = CalculatedStyleValue::SumOperation::Subtract;
  3844. else
  3845. return nullptr;
  3846. auto calc_product = parse_calc_product(tokens);
  3847. if (!calc_product)
  3848. return nullptr;
  3849. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  3850. };
  3851. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(TokenStream<StyleComponentValueRule>& tokens)
  3852. {
  3853. auto parsed_calc_product = parse_calc_product(tokens);
  3854. if (!parsed_calc_product)
  3855. return nullptr;
  3856. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  3857. while (tokens.has_next_token()) {
  3858. auto calc_sum_part = parse_calc_sum_part_with_operator(tokens);
  3859. if (!calc_sum_part)
  3860. return nullptr;
  3861. additional.append(calc_sum_part.release_nonnull());
  3862. }
  3863. tokens.skip_whitespace();
  3864. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  3865. }
  3866. bool Parser::has_ignored_vendor_prefix(StringView string)
  3867. {
  3868. if (!string.starts_with('-'))
  3869. return false;
  3870. if (string.starts_with("--"))
  3871. return false;
  3872. if (string.starts_with("-libweb-"))
  3873. return false;
  3874. return true;
  3875. }
  3876. RefPtr<StyleValue> Parser::parse_css_value(Badge<StyleComputer>, ParsingContext const& context, PropertyID property_id, Vector<StyleComponentValueRule> const& tokens)
  3877. {
  3878. if (tokens.is_empty() || property_id == CSS::PropertyID::Invalid || property_id == CSS::PropertyID::Custom)
  3879. return {};
  3880. CSS::Parser parser(context, "");
  3881. CSS::TokenStream<CSS::StyleComponentValueRule> token_stream { tokens };
  3882. auto result = parser.parse_css_value(property_id, token_stream);
  3883. if (result.is_error())
  3884. return {};
  3885. return result.release_value();
  3886. }
  3887. bool Parser::Dimension::is_angle() const
  3888. {
  3889. return m_value.has<Angle>();
  3890. }
  3891. Angle Parser::Dimension::angle() const
  3892. {
  3893. return m_value.get<Angle>();
  3894. }
  3895. bool Parser::Dimension::is_angle_percentage() const
  3896. {
  3897. return is_angle() || is_percentage();
  3898. }
  3899. AnglePercentage Parser::Dimension::angle_percentage() const
  3900. {
  3901. if (is_angle())
  3902. return angle();
  3903. if (is_percentage())
  3904. return percentage();
  3905. VERIFY_NOT_REACHED();
  3906. }
  3907. bool Parser::Dimension::is_frequency() const
  3908. {
  3909. return m_value.has<Frequency>();
  3910. }
  3911. Frequency Parser::Dimension::frequency() const
  3912. {
  3913. return m_value.get<Frequency>();
  3914. }
  3915. bool Parser::Dimension::is_frequency_percentage() const
  3916. {
  3917. return is_frequency() || is_percentage();
  3918. }
  3919. FrequencyPercentage Parser::Dimension::frequency_percentage() const
  3920. {
  3921. if (is_frequency())
  3922. return frequency();
  3923. if (is_percentage())
  3924. return percentage();
  3925. VERIFY_NOT_REACHED();
  3926. }
  3927. bool Parser::Dimension::is_length() const
  3928. {
  3929. return m_value.has<Length>();
  3930. }
  3931. Length Parser::Dimension::length() const
  3932. {
  3933. return m_value.get<Length>();
  3934. }
  3935. bool Parser::Dimension::is_length_percentage() const
  3936. {
  3937. return is_length() || is_percentage();
  3938. }
  3939. LengthPercentage Parser::Dimension::length_percentage() const
  3940. {
  3941. if (is_length())
  3942. return length();
  3943. if (is_percentage())
  3944. return percentage();
  3945. VERIFY_NOT_REACHED();
  3946. }
  3947. bool Parser::Dimension::is_percentage() const
  3948. {
  3949. return m_value.has<Percentage>();
  3950. }
  3951. Percentage Parser::Dimension::percentage() const
  3952. {
  3953. return m_value.get<Percentage>();
  3954. }
  3955. bool Parser::Dimension::is_resolution() const
  3956. {
  3957. return m_value.has<Resolution>();
  3958. }
  3959. Resolution Parser::Dimension::resolution() const
  3960. {
  3961. return m_value.get<Resolution>();
  3962. }
  3963. bool Parser::Dimension::is_time() const
  3964. {
  3965. return m_value.has<Time>();
  3966. }
  3967. Time Parser::Dimension::time() const
  3968. {
  3969. return m_value.get<Time>();
  3970. }
  3971. bool Parser::Dimension::is_time_percentage() const
  3972. {
  3973. return is_time() || is_percentage();
  3974. }
  3975. TimePercentage Parser::Dimension::time_percentage() const
  3976. {
  3977. if (is_time())
  3978. return time();
  3979. if (is_percentage())
  3980. return percentage();
  3981. VERIFY_NOT_REACHED();
  3982. }
  3983. }
  3984. namespace Web {
  3985. RefPtr<CSS::CSSStyleSheet> parse_css(CSS::ParsingContext const& context, StringView css)
  3986. {
  3987. if (css.is_empty())
  3988. return CSS::CSSStyleSheet::create({});
  3989. CSS::Parser parser(context, css);
  3990. return parser.parse_as_stylesheet();
  3991. }
  3992. RefPtr<CSS::PropertyOwningCSSStyleDeclaration> parse_css_declaration(CSS::ParsingContext const& context, StringView css)
  3993. {
  3994. if (css.is_empty())
  3995. return CSS::PropertyOwningCSSStyleDeclaration::create({}, {});
  3996. CSS::Parser parser(context, css);
  3997. return parser.parse_as_list_of_declarations();
  3998. }
  3999. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView string, CSS::PropertyID property_id)
  4000. {
  4001. if (string.is_empty())
  4002. return {};
  4003. CSS::Parser parser(context, string);
  4004. return parser.parse_as_css_value(property_id);
  4005. }
  4006. RefPtr<CSS::CSSRule> parse_css_rule(CSS::ParsingContext const& context, StringView css_text)
  4007. {
  4008. CSS::Parser parser(context, css_text);
  4009. return parser.parse_as_rule();
  4010. }
  4011. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView selector_text)
  4012. {
  4013. CSS::Parser parser(context, selector_text);
  4014. return parser.parse_as_selector();
  4015. }
  4016. RefPtr<CSS::MediaQuery> parse_media_query(CSS::ParsingContext const& context, StringView string)
  4017. {
  4018. CSS::Parser parser(context, string);
  4019. return parser.parse_as_media_query();
  4020. }
  4021. NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::ParsingContext const& context, StringView string)
  4022. {
  4023. CSS::Parser parser(context, string);
  4024. return parser.parse_as_media_query_list();
  4025. }
  4026. RefPtr<CSS::Supports> parse_css_supports(CSS::ParsingContext const& context, StringView string)
  4027. {
  4028. if (string.is_empty())
  4029. return {};
  4030. CSS::Parser parser(context, string);
  4031. return parser.parse_as_supports();
  4032. }
  4033. RefPtr<CSS::StyleValue> parse_html_length(DOM::Document const& document, StringView string)
  4034. {
  4035. auto integer = string.to_int();
  4036. if (integer.has_value())
  4037. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  4038. return parse_css_value(CSS::ParsingContext(document), string);
  4039. }
  4040. }