Parser.cpp 155 KB

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