Parser.cpp 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375
  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/CSSStyleDeclaration.h>
  14. #include <LibWeb/CSS/CSSStyleRule.h>
  15. #include <LibWeb/CSS/CSSStyleSheet.h>
  16. #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
  17. #include <LibWeb/CSS/Parser/Parser.h>
  18. #include <LibWeb/CSS/Parser/StyleBlockRule.h>
  19. #include <LibWeb/CSS/Parser/StyleComponentValueRule.h>
  20. #include <LibWeb/CSS/Parser/StyleFunctionRule.h>
  21. #include <LibWeb/CSS/Parser/StyleRule.h>
  22. #include <LibWeb/CSS/Selector.h>
  23. #include <LibWeb/DOM/Document.h>
  24. #include <LibWeb/Dump.h>
  25. static void log_parse_error(const SourceLocation& location = SourceLocation::current())
  26. {
  27. dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
  28. }
  29. namespace Web::CSS {
  30. ParsingContext::ParsingContext(DOM::Document& document)
  31. : m_document(&document)
  32. {
  33. }
  34. ParsingContext::ParsingContext(DOM::ParentNode& parent_node)
  35. : m_document(&parent_node.document())
  36. {
  37. }
  38. bool ParsingContext::in_quirks_mode() const
  39. {
  40. return m_document ? m_document->in_quirks_mode() : false;
  41. }
  42. AK::URL ParsingContext::complete_url(String const& addr) const
  43. {
  44. return m_document ? m_document->url().complete_url(addr) : AK::URL::create_with_url_or_path(addr);
  45. }
  46. template<typename T>
  47. TokenStream<T>::TokenStream(Vector<T> const& tokens)
  48. : m_tokens(tokens)
  49. , m_eof(make_eof())
  50. {
  51. }
  52. template<typename T>
  53. TokenStream<T>::~TokenStream()
  54. {
  55. }
  56. template<typename T>
  57. bool TokenStream<T>::has_next_token()
  58. {
  59. return (size_t)(m_iterator_offset + 1) < m_tokens.size();
  60. }
  61. template<typename T>
  62. T const& TokenStream<T>::peek_token(int offset)
  63. {
  64. if (!has_next_token())
  65. return m_eof;
  66. return m_tokens.at(m_iterator_offset + offset + 1);
  67. }
  68. template<typename T>
  69. T const& TokenStream<T>::next_token()
  70. {
  71. if (!has_next_token())
  72. return m_eof;
  73. ++m_iterator_offset;
  74. return m_tokens.at(m_iterator_offset);
  75. }
  76. template<typename T>
  77. T const& TokenStream<T>::current_token()
  78. {
  79. if ((size_t)m_iterator_offset >= m_tokens.size())
  80. return m_eof;
  81. return m_tokens.at(m_iterator_offset);
  82. }
  83. template<typename T>
  84. void TokenStream<T>::reconsume_current_input_token()
  85. {
  86. if (m_iterator_offset >= 0)
  87. --m_iterator_offset;
  88. }
  89. template<typename T>
  90. void TokenStream<T>::skip_whitespace()
  91. {
  92. while (peek_token().is(Token::Type::Whitespace))
  93. next_token();
  94. }
  95. template<>
  96. Token TokenStream<Token>::make_eof()
  97. {
  98. return Tokenizer::create_eof_token();
  99. }
  100. template<>
  101. StyleComponentValueRule TokenStream<StyleComponentValueRule>::make_eof()
  102. {
  103. return StyleComponentValueRule(Tokenizer::create_eof_token());
  104. }
  105. template<typename T>
  106. void TokenStream<T>::dump_all_tokens()
  107. {
  108. dbgln("Dumping all tokens:");
  109. for (size_t i = 0; i < m_tokens.size(); ++i) {
  110. auto& token = m_tokens[i];
  111. if ((i - 1) == (size_t)m_iterator_offset)
  112. dbgln("-> {}", token.to_debug_string());
  113. else
  114. dbgln(" {}", token.to_debug_string());
  115. }
  116. }
  117. Parser::Parser(ParsingContext const& context, StringView const& input, String const& encoding)
  118. : m_context(context)
  119. , m_tokenizer(input, encoding)
  120. , m_tokens(m_tokenizer.parse())
  121. , m_token_stream(TokenStream(m_tokens))
  122. {
  123. }
  124. Parser::~Parser()
  125. {
  126. }
  127. NonnullRefPtr<CSSStyleSheet> Parser::parse_as_stylesheet()
  128. {
  129. return parse_a_stylesheet(m_token_stream);
  130. }
  131. template<typename T>
  132. NonnullRefPtr<CSSStyleSheet> Parser::parse_a_stylesheet(TokenStream<T>& tokens)
  133. {
  134. auto parser_rules = consume_a_list_of_rules(tokens, true);
  135. NonnullRefPtrVector<CSSRule> rules;
  136. for (auto& raw_rule : parser_rules) {
  137. auto rule = convert_to_rule(raw_rule);
  138. if (rule)
  139. rules.append(*rule);
  140. }
  141. auto stylesheet = CSSStyleSheet::create(rules);
  142. if constexpr (CSS_PARSER_DEBUG) {
  143. dump_sheet(stylesheet);
  144. }
  145. return stylesheet;
  146. }
  147. Optional<SelectorList> Parser::parse_as_selector()
  148. {
  149. auto selector_list = parse_a_selector(m_token_stream);
  150. if (!selector_list.is_error())
  151. return selector_list.release_value();
  152. return {};
  153. }
  154. template<typename T>
  155. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_selector(TokenStream<T>& tokens)
  156. {
  157. return parse_a_selector_list(tokens);
  158. }
  159. Optional<SelectorList> Parser::parse_as_relative_selector()
  160. {
  161. auto selector_list = parse_a_relative_selector(m_token_stream);
  162. if (!selector_list.is_error())
  163. return selector_list.release_value();
  164. return {};
  165. }
  166. template<typename T>
  167. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_relative_selector(TokenStream<T>& tokens)
  168. {
  169. return parse_a_relative_selector_list(tokens);
  170. }
  171. template<typename T>
  172. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_selector_list(TokenStream<T>& tokens)
  173. {
  174. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  175. NonnullRefPtrVector<Selector> selectors;
  176. for (auto& selector_parts : comma_separated_lists) {
  177. auto stream = TokenStream(selector_parts);
  178. auto selector = parse_complex_selector(stream, false);
  179. if (selector.is_error())
  180. return selector.error();
  181. selectors.append(selector.release_value());
  182. }
  183. if (selectors.is_empty())
  184. return ParsingResult::SyntaxError;
  185. return selectors;
  186. }
  187. template<typename T>
  188. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_relative_selector_list(TokenStream<T>& tokens)
  189. {
  190. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  191. NonnullRefPtrVector<Selector> selectors;
  192. for (auto& selector_parts : comma_separated_lists) {
  193. auto stream = TokenStream(selector_parts);
  194. auto selector = parse_complex_selector(stream, true);
  195. if (selector.is_error())
  196. return selector.error();
  197. selectors.append(selector.release_value());
  198. }
  199. if (selectors.is_empty())
  200. return ParsingResult::SyntaxError;
  201. return selectors;
  202. }
  203. Result<NonnullRefPtr<Selector>, Parser::ParsingResult> Parser::parse_complex_selector(TokenStream<StyleComponentValueRule>& tokens, bool allow_starting_combinator)
  204. {
  205. Vector<Selector::CompoundSelector> compound_selectors;
  206. auto first_selector = parse_compound_selector(tokens);
  207. if (first_selector.is_error())
  208. return first_selector.error();
  209. if (!allow_starting_combinator) {
  210. if (first_selector.value().combinator != Selector::Combinator::Descendant)
  211. return ParsingResult::SyntaxError;
  212. first_selector.value().combinator = Selector::Combinator::None;
  213. }
  214. compound_selectors.append(first_selector.value());
  215. while (tokens.has_next_token()) {
  216. auto compound_selector = parse_compound_selector(tokens);
  217. if (compound_selector.is_error()) {
  218. if (compound_selector.error() == ParsingResult::Done)
  219. break;
  220. else
  221. return compound_selector.error();
  222. }
  223. compound_selectors.append(compound_selector.value());
  224. }
  225. if (compound_selectors.is_empty())
  226. return ParsingResult::SyntaxError;
  227. return Selector::create(move(compound_selectors));
  228. }
  229. Result<Selector::CompoundSelector, Parser::ParsingResult> Parser::parse_compound_selector(TokenStream<StyleComponentValueRule>& tokens)
  230. {
  231. tokens.skip_whitespace();
  232. auto combinator = parse_selector_combinator(tokens).value_or(Selector::Combinator::Descendant);
  233. tokens.skip_whitespace();
  234. Vector<Selector::SimpleSelector> simple_selectors;
  235. while (tokens.has_next_token()) {
  236. auto component = parse_simple_selector(tokens);
  237. if (component.is_error()) {
  238. if (component.error() == ParsingResult::Done)
  239. break;
  240. else
  241. return component.error();
  242. }
  243. simple_selectors.append(component.value());
  244. }
  245. if (simple_selectors.is_empty())
  246. return ParsingResult::Done;
  247. return Selector::CompoundSelector { combinator, move(simple_selectors) };
  248. }
  249. Optional<Selector::Combinator> Parser::parse_selector_combinator(TokenStream<StyleComponentValueRule>& tokens)
  250. {
  251. auto& current_value = tokens.next_token();
  252. if (current_value.is(Token::Type::Delim)) {
  253. auto delim = current_value.token().delim();
  254. if (delim == ">"sv) {
  255. return Selector::Combinator::ImmediateChild;
  256. } else if (delim == "+"sv) {
  257. return Selector::Combinator::NextSibling;
  258. } else if (delim == "~"sv) {
  259. return Selector::Combinator::SubsequentSibling;
  260. } else if (delim == "|"sv) {
  261. auto& next = tokens.peek_token();
  262. if (next.is(Token::Type::EndOfFile))
  263. return {};
  264. if (next.is(Token::Type::Delim) && next.token().delim() == "|"sv) {
  265. tokens.next_token();
  266. return Selector::Combinator::Column;
  267. }
  268. }
  269. }
  270. tokens.reconsume_current_input_token();
  271. return {};
  272. }
  273. Result<Selector::SimpleSelector, Parser::ParsingResult> Parser::parse_simple_selector(TokenStream<StyleComponentValueRule>& tokens)
  274. {
  275. auto peek_token_ends_selector = [&]() -> bool {
  276. auto& value = tokens.peek_token();
  277. return (value.is(Token::Type::EndOfFile) || value.is(Token::Type::Whitespace) || value.is(Token::Type::Comma));
  278. };
  279. if (peek_token_ends_selector())
  280. return ParsingResult::Done;
  281. auto& first_value = tokens.next_token();
  282. if (first_value.is(Token::Type::Delim) && first_value.token().delim() == "*"sv) {
  283. return Selector::SimpleSelector {
  284. .type = Selector::SimpleSelector::Type::Universal
  285. };
  286. } else if (first_value.is(Token::Type::Hash)) {
  287. if (first_value.token().hash_type() != Token::HashType::Id) {
  288. dbgln_if(CSS_PARSER_DEBUG, "Selector contains hash token that is not an id: {}", first_value.to_debug_string());
  289. return ParsingResult::SyntaxError;
  290. }
  291. return Selector::SimpleSelector {
  292. .type = Selector::SimpleSelector::Type::Id,
  293. .value = first_value.token().hash_value()
  294. };
  295. } else if (first_value.is(Token::Type::Delim) && first_value.token().delim() == "."sv) {
  296. if (peek_token_ends_selector())
  297. return ParsingResult::SyntaxError;
  298. auto& class_name_value = tokens.next_token();
  299. if (!class_name_value.is(Token::Type::Ident)) {
  300. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident after '.', got: {}", class_name_value.to_debug_string());
  301. return ParsingResult::SyntaxError;
  302. }
  303. return Selector::SimpleSelector {
  304. .type = Selector::SimpleSelector::Type::Class,
  305. .value = class_name_value.token().ident()
  306. };
  307. } else if (first_value.is(Token::Type::Ident)) {
  308. return Selector::SimpleSelector {
  309. .type = Selector::SimpleSelector::Type::TagName,
  310. .value = first_value.token().ident()
  311. };
  312. } else if (first_value.is_block() && first_value.block().is_square()) {
  313. auto& attribute_parts = first_value.block().values();
  314. if (attribute_parts.is_empty()) {
  315. dbgln_if(CSS_PARSER_DEBUG, "CSS attribute selector is empty!");
  316. return ParsingResult::SyntaxError;
  317. }
  318. // FIXME: Handle namespace prefix for attribute name.
  319. auto& attribute_part = attribute_parts.first();
  320. if (!attribute_part.is(Token::Type::Ident)) {
  321. dbgln_if(CSS_PARSER_DEBUG, "Expected ident for attribute name, got: '{}'", attribute_part.to_debug_string());
  322. return ParsingResult::SyntaxError;
  323. }
  324. Selector::SimpleSelector simple_selector {
  325. .type = Selector::SimpleSelector::Type::Attribute,
  326. .attribute = {
  327. .match_type = Selector::SimpleSelector::Attribute::MatchType::HasAttribute,
  328. // FIXME: Case-sensitivity is defined by the document language.
  329. // HTML is insensitive with attribute names, and our code generally assumes
  330. // they are converted to lowercase, so we do that here too. If we want to be
  331. // correct with XML later, we'll need to keep the original case and then do
  332. // a case-insensitive compare later.
  333. .name = attribute_part.token().ident().to_lowercase_string(),
  334. }
  335. };
  336. if (attribute_parts.size() == 1)
  337. return simple_selector;
  338. size_t attribute_index = 1;
  339. auto& delim_part = attribute_parts.at(attribute_index);
  340. if (!delim_part.is(Token::Type::Delim)) {
  341. dbgln_if(CSS_PARSER_DEBUG, "Expected a delim for attribute comparison, got: '{}'", delim_part.to_debug_string());
  342. return ParsingResult::SyntaxError;
  343. }
  344. if (delim_part.token().delim() == "="sv) {
  345. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch;
  346. attribute_index++;
  347. } else {
  348. attribute_index++;
  349. if (attribute_index >= attribute_parts.size()) {
  350. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended part way through a match type.");
  351. return ParsingResult::SyntaxError;
  352. }
  353. auto& delim_second_part = attribute_parts.at(attribute_index);
  354. if (!(delim_second_part.is(Token::Type::Delim) && delim_second_part.token().delim() == "=")) {
  355. dbgln_if(CSS_PARSER_DEBUG, "Expected a double delim for attribute comparison, got: '{}{}'", delim_part.to_debug_string(), delim_second_part.to_debug_string());
  356. return ParsingResult::SyntaxError;
  357. }
  358. if (delim_part.token().delim() == "~"sv) {
  359. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsWord;
  360. attribute_index++;
  361. } else if (delim_part.token().delim() == "*"sv) {
  362. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsString;
  363. attribute_index++;
  364. } else if (delim_part.token().delim() == "|"sv) {
  365. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment;
  366. attribute_index++;
  367. } else if (delim_part.token().delim() == "^"sv) {
  368. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithString;
  369. attribute_index++;
  370. } else if (delim_part.token().delim() == "$"sv) {
  371. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::EndsWithString;
  372. attribute_index++;
  373. }
  374. }
  375. if (attribute_index >= attribute_parts.size()) {
  376. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended without a value to match.");
  377. return ParsingResult::SyntaxError;
  378. }
  379. auto& value_part = attribute_parts.at(attribute_index);
  380. if (!value_part.is(Token::Type::Ident) && !value_part.is(Token::Type::String)) {
  381. dbgln_if(CSS_PARSER_DEBUG, "Expected a string or ident for the value to match attribute against, got: '{}'", value_part.to_debug_string());
  382. return ParsingResult::SyntaxError;
  383. }
  384. simple_selector.attribute.value = value_part.token().is(Token::Type::Ident) ? value_part.token().ident() : value_part.token().string();
  385. // FIXME: Handle case-sensitivity suffixes. https://www.w3.org/TR/selectors-4/#attribute-case
  386. return simple_selector;
  387. } else if (first_value.is(Token::Type::Colon)) {
  388. if (peek_token_ends_selector())
  389. return ParsingResult::SyntaxError;
  390. bool is_pseudo = false;
  391. if (tokens.peek_token().is(Token::Type::Colon)) {
  392. is_pseudo = true;
  393. tokens.next_token();
  394. if (peek_token_ends_selector())
  395. return ParsingResult::SyntaxError;
  396. }
  397. if (is_pseudo) {
  398. Selector::SimpleSelector simple_selector {
  399. .type = Selector::SimpleSelector::Type::PseudoElement
  400. };
  401. auto& name_token = tokens.next_token();
  402. if (!name_token.is(Token::Type::Ident)) {
  403. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident for pseudo-element, got: '{}'", name_token.to_debug_string());
  404. return ParsingResult::SyntaxError;
  405. }
  406. auto pseudo_name = name_token.token().ident();
  407. if (has_ignored_vendor_prefix(pseudo_name))
  408. return ParsingResult::IncludesIgnoredVendorPrefix;
  409. if (pseudo_name.equals_ignoring_case("after")) {
  410. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  411. } else if (pseudo_name.equals_ignoring_case("before")) {
  412. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  413. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  414. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  415. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  416. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  417. } else {
  418. dbgln("Unrecognized pseudo-element: '::{}'", pseudo_name);
  419. return ParsingResult::SyntaxError;
  420. }
  421. return simple_selector;
  422. }
  423. if (peek_token_ends_selector())
  424. return ParsingResult::SyntaxError;
  425. auto& pseudo_class_token = tokens.next_token();
  426. Selector::SimpleSelector simple_selector {
  427. .type = Selector::SimpleSelector::Type::PseudoClass
  428. };
  429. if (pseudo_class_token.is(Token::Type::Ident)) {
  430. auto pseudo_name = pseudo_class_token.token().ident();
  431. if (has_ignored_vendor_prefix(pseudo_name))
  432. return ParsingResult::IncludesIgnoredVendorPrefix;
  433. if (pseudo_name.equals_ignoring_case("active")) {
  434. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Active;
  435. } else if (pseudo_name.equals_ignoring_case("checked")) {
  436. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Checked;
  437. } else if (pseudo_name.equals_ignoring_case("disabled")) {
  438. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Disabled;
  439. } else if (pseudo_name.equals_ignoring_case("empty")) {
  440. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Empty;
  441. } else if (pseudo_name.equals_ignoring_case("enabled")) {
  442. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Enabled;
  443. } else if (pseudo_name.equals_ignoring_case("first-child")) {
  444. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstChild;
  445. } else if (pseudo_name.equals_ignoring_case("first-of-type")) {
  446. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstOfType;
  447. } else if (pseudo_name.equals_ignoring_case("focus")) {
  448. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Focus;
  449. } else if (pseudo_name.equals_ignoring_case("hover")) {
  450. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Hover;
  451. } else if (pseudo_name.equals_ignoring_case("last-child")) {
  452. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastChild;
  453. } else if (pseudo_name.equals_ignoring_case("last-of-type")) {
  454. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastOfType;
  455. } else if (pseudo_name.equals_ignoring_case("link")) {
  456. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Link;
  457. } else if (pseudo_name.equals_ignoring_case("only-child")) {
  458. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::OnlyChild;
  459. } else if (pseudo_name.equals_ignoring_case("root")) {
  460. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Root;
  461. } else if (pseudo_name.equals_ignoring_case("visited")) {
  462. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Visited;
  463. } else if (pseudo_name.equals_ignoring_case("after")) {
  464. // Single-colon syntax allowed for compatibility. https://www.w3.org/TR/selectors/#pseudo-element-syntax
  465. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  466. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  467. } else if (pseudo_name.equals_ignoring_case("before")) {
  468. // See :after
  469. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  470. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  471. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  472. // See :after
  473. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  474. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  475. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  476. // See :after
  477. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  478. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  479. } else {
  480. dbgln("Unrecognized pseudo-class: ':{}'", pseudo_name);
  481. return ParsingResult::SyntaxError;
  482. }
  483. return simple_selector;
  484. } else if (pseudo_class_token.is_function()) {
  485. auto& pseudo_function = pseudo_class_token.function();
  486. if (pseudo_function.name().equals_ignoring_case("not")) {
  487. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Not;
  488. auto function_token_stream = TokenStream(pseudo_function.values());
  489. auto not_selector = parse_a_selector(function_token_stream);
  490. if (not_selector.is_error()) {
  491. dbgln_if(CSS_PARSER_DEBUG, "Invalid selector in :not() clause");
  492. return ParsingResult::SyntaxError;
  493. }
  494. simple_selector.pseudo_class.not_selector = not_selector.release_value();
  495. } else if (pseudo_function.name().equals_ignoring_case("nth-child")) {
  496. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthChild;
  497. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  498. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  499. if (nth_child_pattern.has_value()) {
  500. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  501. } else {
  502. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  503. return ParsingResult::SyntaxError;
  504. }
  505. } else if (pseudo_function.name().equals_ignoring_case("nth-last-child")) {
  506. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthLastChild;
  507. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  508. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  509. if (nth_child_pattern.has_value()) {
  510. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  511. } else {
  512. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  513. return ParsingResult::SyntaxError;
  514. }
  515. } else {
  516. dbgln("Unrecognized pseudo-class function: ':{}'()", pseudo_function.name());
  517. return ParsingResult::SyntaxError;
  518. }
  519. return simple_selector;
  520. } else {
  521. dbgln_if(CSS_PARSER_DEBUG, "Unexpected Block in pseudo-class name, expected a function or identifier. '{}'", pseudo_class_token.to_debug_string());
  522. return ParsingResult::SyntaxError;
  523. }
  524. }
  525. // Whitespace is not required between the compound-selector and a combinator.
  526. // So, if we see a combinator, return that this compound-selector is done, instead of a syntax error.
  527. if (first_value.is(Token::Type::Delim)) {
  528. auto delim = first_value.token().delim();
  529. if ((delim == ">"sv) || (delim == "+"sv) || (delim == "~"sv) || (delim == "|"sv)) {
  530. tokens.reconsume_current_input_token();
  531. return ParsingResult::Done;
  532. }
  533. }
  534. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid simple selector!");
  535. return ParsingResult::SyntaxError;
  536. }
  537. NonnullRefPtrVector<MediaQuery> Parser::parse_as_media_query_list()
  538. {
  539. return parse_a_media_query_list(m_token_stream);
  540. }
  541. template<typename T>
  542. NonnullRefPtrVector<MediaQuery> Parser::parse_a_media_query_list(TokenStream<T>& tokens)
  543. {
  544. // https://www.w3.org/TR/mediaqueries-4/#mq-list
  545. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  546. AK::NonnullRefPtrVector<MediaQuery> media_queries;
  547. for (auto& media_query_parts : comma_separated_lists) {
  548. auto stream = TokenStream(media_query_parts);
  549. media_queries.append(parse_media_query(stream));
  550. }
  551. return media_queries;
  552. }
  553. RefPtr<MediaQuery> Parser::parse_as_media_query()
  554. {
  555. // https://www.w3.org/TR/cssom-1/#parse-a-media-query
  556. auto media_query_list = parse_as_media_query_list();
  557. if (media_query_list.is_empty())
  558. return MediaQuery::create_not_all();
  559. if (media_query_list.size() == 1)
  560. return media_query_list.first();
  561. return nullptr;
  562. }
  563. NonnullRefPtr<MediaQuery> Parser::parse_media_query(TokenStream<StyleComponentValueRule>&)
  564. {
  565. // "A media query that does not match the grammar in the previous section must be replaced by `not all`
  566. // during parsing." - https://www.w3.org/TR/mediaqueries-5/#error-handling
  567. // FIXME: Implement media queries!
  568. return MediaQuery::create_not_all();
  569. }
  570. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(bool top_level)
  571. {
  572. return consume_a_list_of_rules(m_token_stream, top_level);
  573. }
  574. template<typename T>
  575. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, bool top_level)
  576. {
  577. NonnullRefPtrVector<StyleRule> rules;
  578. for (;;) {
  579. auto& token = tokens.next_token();
  580. if (token.is(Token::Type::Whitespace)) {
  581. continue;
  582. }
  583. if (token.is(Token::Type::EndOfFile)) {
  584. break;
  585. }
  586. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  587. if (top_level) {
  588. continue;
  589. }
  590. tokens.reconsume_current_input_token();
  591. auto maybe_qualified = consume_a_qualified_rule(tokens);
  592. if (maybe_qualified) {
  593. rules.append(maybe_qualified.release_nonnull());
  594. }
  595. continue;
  596. }
  597. if (token.is(Token::Type::AtKeyword)) {
  598. tokens.reconsume_current_input_token();
  599. rules.append(consume_an_at_rule(tokens));
  600. continue;
  601. }
  602. tokens.reconsume_current_input_token();
  603. auto maybe_qualified = consume_a_qualified_rule(tokens);
  604. if (maybe_qualified) {
  605. rules.append(maybe_qualified.release_nonnull());
  606. }
  607. }
  608. return rules;
  609. }
  610. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule()
  611. {
  612. return consume_an_at_rule(m_token_stream);
  613. }
  614. template<typename T>
  615. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  616. {
  617. auto& name_ident = tokens.next_token();
  618. VERIFY(name_ident.is(Token::Type::AtKeyword));
  619. auto rule = make_ref_counted<StyleRule>(StyleRule::Type::At);
  620. rule->m_name = ((Token)name_ident).at_keyword();
  621. for (;;) {
  622. auto& token = tokens.next_token();
  623. if (token.is(Token::Type::Semicolon)) {
  624. return rule;
  625. }
  626. if (token.is(Token::Type::EndOfFile)) {
  627. log_parse_error();
  628. return rule;
  629. }
  630. if (token.is(Token::Type::OpenCurly)) {
  631. rule->m_block = consume_a_simple_block(tokens);
  632. return rule;
  633. }
  634. // how is "simple block with an associated token of <{-token>" a valid token?
  635. tokens.reconsume_current_input_token();
  636. auto value = consume_a_component_value(tokens);
  637. rule->m_prelude.append(value);
  638. }
  639. }
  640. RefPtr<StyleRule> Parser::consume_a_qualified_rule()
  641. {
  642. return consume_a_qualified_rule(m_token_stream);
  643. }
  644. template<typename T>
  645. RefPtr<StyleRule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  646. {
  647. auto rule = make_ref_counted<StyleRule>(StyleRule::Type::Qualified);
  648. for (;;) {
  649. auto& token = tokens.next_token();
  650. if (token.is(Token::Type::EndOfFile)) {
  651. log_parse_error();
  652. return {};
  653. }
  654. if (token.is(Token::Type::OpenCurly)) {
  655. rule->m_block = consume_a_simple_block(tokens);
  656. return rule;
  657. }
  658. // how is "simple block with an associated token of <{-token>" a valid token?
  659. tokens.reconsume_current_input_token();
  660. auto value = consume_a_component_value(tokens);
  661. rule->m_prelude.append(value);
  662. }
  663. return rule;
  664. }
  665. template<>
  666. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<StyleComponentValueRule>& tokens)
  667. {
  668. return tokens.next_token();
  669. }
  670. template<typename T>
  671. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<T>& tokens)
  672. {
  673. auto& token = tokens.next_token();
  674. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  675. return StyleComponentValueRule(consume_a_simple_block(tokens));
  676. if (token.is(Token::Type::Function))
  677. return StyleComponentValueRule(consume_a_function(tokens));
  678. return StyleComponentValueRule(token);
  679. }
  680. StyleComponentValueRule Parser::consume_a_component_value()
  681. {
  682. return consume_a_component_value(m_token_stream);
  683. }
  684. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block()
  685. {
  686. return consume_a_simple_block(m_token_stream);
  687. }
  688. template<typename T>
  689. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  690. {
  691. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  692. auto block = make_ref_counted<StyleBlockRule>();
  693. block->m_token = tokens.current_token();
  694. for (;;) {
  695. auto& token = tokens.next_token();
  696. if (token.is(ending_token)) {
  697. return block;
  698. }
  699. if (token.is(Token::Type::EndOfFile)) {
  700. log_parse_error();
  701. return block;
  702. }
  703. tokens.reconsume_current_input_token();
  704. auto value = consume_a_component_value(tokens);
  705. block->m_values.append(value);
  706. }
  707. }
  708. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function()
  709. {
  710. return consume_a_function(m_token_stream);
  711. }
  712. template<typename T>
  713. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function(TokenStream<T>& tokens)
  714. {
  715. auto name_ident = tokens.current_token();
  716. VERIFY(name_ident.is(Token::Type::Function));
  717. auto function = make_ref_counted<StyleFunctionRule>(((Token)name_ident).m_value.to_string());
  718. for (;;) {
  719. auto& token = tokens.next_token();
  720. if (token.is(Token::Type::CloseParen)) {
  721. return function;
  722. }
  723. if (token.is(Token::Type::EndOfFile)) {
  724. log_parse_error();
  725. return function;
  726. }
  727. tokens.reconsume_current_input_token();
  728. auto value = consume_a_component_value(tokens);
  729. function->m_values.append(value);
  730. }
  731. return function;
  732. }
  733. Optional<StyleDeclarationRule> Parser::consume_a_declaration()
  734. {
  735. return consume_a_declaration(m_token_stream);
  736. }
  737. template<typename T>
  738. Optional<StyleDeclarationRule> Parser::consume_a_declaration(TokenStream<T>& tokens)
  739. {
  740. auto& token = tokens.next_token();
  741. StyleDeclarationRule declaration;
  742. VERIFY(token.is(Token::Type::Ident));
  743. declaration.m_name = ((Token)token).ident();
  744. tokens.skip_whitespace();
  745. auto& maybe_colon = tokens.next_token();
  746. if (!maybe_colon.is(Token::Type::Colon)) {
  747. log_parse_error();
  748. return {};
  749. }
  750. tokens.skip_whitespace();
  751. for (;;) {
  752. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  753. break;
  754. }
  755. declaration.m_values.append(consume_a_component_value(tokens));
  756. }
  757. if (declaration.m_values.size() >= 2) {
  758. auto second_last = declaration.m_values.at(declaration.m_values.size() - 2);
  759. auto last = declaration.m_values.at(declaration.m_values.size() - 1);
  760. if (second_last.m_type == StyleComponentValueRule::ComponentType::Token && last.m_type == StyleComponentValueRule::ComponentType::Token) {
  761. auto last_token = last.m_token;
  762. auto second_last_token = second_last.m_token;
  763. if (second_last_token.is(Token::Type::Delim) && second_last_token.m_value.to_string().equals_ignoring_case("!")) {
  764. if (last_token.is(Token::Type::Ident) && last_token.m_value.to_string().equals_ignoring_case("important")) {
  765. declaration.m_values.remove(declaration.m_values.size() - 2);
  766. declaration.m_values.remove(declaration.m_values.size() - 1);
  767. declaration.m_important = true;
  768. }
  769. }
  770. }
  771. }
  772. while (!declaration.m_values.is_empty()) {
  773. auto maybe_whitespace = declaration.m_values.last();
  774. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  775. break;
  776. }
  777. declaration.m_values.take_last();
  778. }
  779. return declaration;
  780. }
  781. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations()
  782. {
  783. return consume_a_list_of_declarations(m_token_stream);
  784. }
  785. template<typename T>
  786. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  787. {
  788. Vector<DeclarationOrAtRule> list;
  789. for (;;) {
  790. auto& token = tokens.next_token();
  791. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  792. continue;
  793. }
  794. if (token.is(Token::Type::EndOfFile)) {
  795. return list;
  796. }
  797. if (token.is(Token::Type::AtKeyword)) {
  798. tokens.reconsume_current_input_token();
  799. list.append(DeclarationOrAtRule(consume_an_at_rule(tokens)));
  800. continue;
  801. }
  802. if (token.is(Token::Type::Ident)) {
  803. Vector<StyleComponentValueRule> temp;
  804. temp.append(token);
  805. for (;;) {
  806. auto& peek = tokens.peek_token();
  807. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile)) {
  808. break;
  809. }
  810. temp.append(consume_a_component_value(tokens));
  811. }
  812. auto token_stream = TokenStream(temp);
  813. auto maybe_declaration = consume_a_declaration(token_stream);
  814. if (maybe_declaration.has_value()) {
  815. list.append(DeclarationOrAtRule(maybe_declaration.value()));
  816. }
  817. continue;
  818. }
  819. log_parse_error();
  820. tokens.reconsume_current_input_token();
  821. for (;;) {
  822. auto& peek = tokens.peek_token();
  823. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  824. break;
  825. dbgln("Discarding token: '{}'", peek.to_debug_string());
  826. (void)consume_a_component_value(tokens);
  827. }
  828. }
  829. return list;
  830. }
  831. RefPtr<CSSRule> Parser::parse_as_rule()
  832. {
  833. return parse_a_rule(m_token_stream);
  834. }
  835. template<typename T>
  836. RefPtr<CSSRule> Parser::parse_a_rule(TokenStream<T>& tokens)
  837. {
  838. RefPtr<CSSRule> rule;
  839. tokens.skip_whitespace();
  840. auto& token = tokens.peek_token();
  841. if (token.is(Token::Type::EndOfFile)) {
  842. return {};
  843. } else if (token.is(Token::Type::AtKeyword)) {
  844. auto at_rule = consume_an_at_rule();
  845. rule = convert_to_rule(at_rule);
  846. } else {
  847. auto qualified_rule = consume_a_qualified_rule(tokens);
  848. if (!qualified_rule)
  849. return {};
  850. rule = convert_to_rule(*qualified_rule);
  851. }
  852. tokens.skip_whitespace();
  853. auto& maybe_eof = tokens.peek_token();
  854. if (maybe_eof.is(Token::Type::EndOfFile)) {
  855. return rule;
  856. }
  857. return {};
  858. }
  859. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules()
  860. {
  861. return parse_a_list_of_rules(m_token_stream);
  862. }
  863. template<typename T>
  864. NonnullRefPtrVector<CSSRule> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
  865. {
  866. auto parsed_rules = consume_a_list_of_rules(tokens, false);
  867. NonnullRefPtrVector<CSSRule> rules;
  868. for (auto& rule : parsed_rules) {
  869. auto converted_rule = convert_to_rule(rule);
  870. if (converted_rule)
  871. rules.append(*converted_rule);
  872. }
  873. return rules;
  874. }
  875. Optional<StyleProperty> Parser::parse_as_declaration()
  876. {
  877. return parse_a_declaration(m_token_stream);
  878. }
  879. template<typename T>
  880. Optional<StyleProperty> Parser::parse_a_declaration(TokenStream<T>& tokens)
  881. {
  882. tokens.skip_whitespace();
  883. auto& token = tokens.peek_token();
  884. if (!token.is(Token::Type::Ident)) {
  885. return {};
  886. }
  887. auto declaration = consume_a_declaration(tokens);
  888. if (declaration.has_value())
  889. return convert_to_style_property(declaration.value());
  890. return {};
  891. }
  892. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::parse_as_list_of_declarations()
  893. {
  894. return parse_a_list_of_declarations(m_token_stream);
  895. }
  896. template<typename T>
  897. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
  898. {
  899. auto declarations_and_at_rules = consume_a_list_of_declarations(tokens);
  900. Vector<StyleProperty> properties;
  901. HashMap<String, StyleProperty> custom_properties;
  902. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  903. if (declaration_or_at_rule.is_at_rule()) {
  904. dbgln_if(CSS_PARSER_DEBUG, "!!! CSS at-rule is not allowed here!");
  905. continue;
  906. }
  907. auto& declaration = declaration_or_at_rule.m_declaration;
  908. auto maybe_property = convert_to_style_property(declaration);
  909. if (maybe_property.has_value()) {
  910. auto property = maybe_property.value();
  911. if (property.property_id == PropertyID::Custom) {
  912. custom_properties.set(property.custom_name, property);
  913. } else {
  914. properties.append(property);
  915. }
  916. }
  917. }
  918. return PropertyOwningCSSStyleDeclaration::create(move(properties), move(custom_properties));
  919. }
  920. Optional<StyleComponentValueRule> Parser::parse_as_component_value()
  921. {
  922. return parse_a_component_value(m_token_stream);
  923. }
  924. template<typename T>
  925. Optional<StyleComponentValueRule> Parser::parse_a_component_value(TokenStream<T>& tokens)
  926. {
  927. tokens.skip_whitespace();
  928. auto& token = tokens.peek_token();
  929. if (token.is(Token::Type::EndOfFile)) {
  930. return {};
  931. }
  932. auto value = consume_a_component_value(tokens);
  933. tokens.skip_whitespace();
  934. auto& maybe_eof = tokens.peek_token();
  935. if (maybe_eof.is(Token::Type::EndOfFile)) {
  936. return value;
  937. }
  938. return {};
  939. }
  940. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values()
  941. {
  942. return parse_a_list_of_component_values(m_token_stream);
  943. }
  944. template<typename T>
  945. Vector<StyleComponentValueRule> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
  946. {
  947. Vector<StyleComponentValueRule> rules;
  948. for (;;) {
  949. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  950. break;
  951. }
  952. rules.append(consume_a_component_value(tokens));
  953. }
  954. return rules;
  955. }
  956. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values()
  957. {
  958. return parse_a_comma_separated_list_of_component_values(m_token_stream);
  959. }
  960. template<typename T>
  961. Vector<Vector<StyleComponentValueRule>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  962. {
  963. Vector<Vector<StyleComponentValueRule>> lists;
  964. lists.append({});
  965. for (;;) {
  966. auto& next = tokens.next_token();
  967. if (next.is(Token::Type::Comma)) {
  968. lists.append({});
  969. continue;
  970. } else if (next.is(Token::Type::EndOfFile)) {
  971. break;
  972. }
  973. tokens.reconsume_current_input_token();
  974. auto component_value = consume_a_component_value(tokens);
  975. lists.last().append(component_value);
  976. }
  977. return lists;
  978. }
  979. Optional<AK::URL> Parser::parse_url_function(ParsingContext const& context, StyleComponentValueRule const& component_value)
  980. {
  981. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  982. // FIXME: Handle data: urls (RFC2397)
  983. auto is_data_url = [](StringView& url_string) -> bool {
  984. return url_string.starts_with("data:", CaseSensitivity::CaseInsensitive);
  985. };
  986. if (component_value.is(Token::Type::Url)) {
  987. auto url_string = component_value.token().url();
  988. if (is_data_url(url_string))
  989. return {};
  990. return context.complete_url(url_string);
  991. }
  992. if (component_value.is_function() && component_value.function().name().equals_ignoring_case("url")) {
  993. auto& function_values = component_value.function().values();
  994. // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
  995. for (size_t i = 0; i < function_values.size(); ++i) {
  996. auto& value = function_values[i];
  997. if (value.is(Token::Type::Whitespace))
  998. continue;
  999. if (value.is(Token::Type::String)) {
  1000. auto url_string = value.token().string();
  1001. if (is_data_url(url_string))
  1002. return {};
  1003. return context.complete_url(url_string);
  1004. }
  1005. break;
  1006. }
  1007. }
  1008. return {};
  1009. }
  1010. RefPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<StyleRule> rule)
  1011. {
  1012. if (rule->m_type == StyleRule::Type::At) {
  1013. if (has_ignored_vendor_prefix(rule->m_name)) {
  1014. return {};
  1015. } else if (rule->m_name.equals_ignoring_case("import"sv) && !rule->prelude().is_empty()) {
  1016. Optional<AK::URL> url;
  1017. for (auto& token : rule->prelude()) {
  1018. if (token.is(Token::Type::Whitespace))
  1019. continue;
  1020. if (token.is(Token::Type::String)) {
  1021. url = m_context.complete_url(token.token().string());
  1022. } else {
  1023. url = parse_url_function(m_context, token);
  1024. }
  1025. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1026. if (url.has_value())
  1027. break;
  1028. }
  1029. if (url.has_value())
  1030. return CSSImportRule::create(url.value());
  1031. else
  1032. dbgln("Unable to parse url from @import rule");
  1033. } else {
  1034. dbgln("Unrecognized CSS at-rule: @{}", rule->m_name);
  1035. }
  1036. // FIXME: More at rules!
  1037. } else {
  1038. auto prelude_stream = TokenStream(rule->m_prelude);
  1039. auto selectors = parse_a_selector(prelude_stream);
  1040. if (selectors.is_error()) {
  1041. if (selectors.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1042. dbgln("CSSParser: style rule selectors invalid; discarding.");
  1043. if constexpr (CSS_PARSER_DEBUG) {
  1044. prelude_stream.dump_all_tokens();
  1045. }
  1046. }
  1047. return {};
  1048. }
  1049. if (selectors.value().is_empty()) {
  1050. dbgln("CSSParser: empty selector; discarding.");
  1051. return {};
  1052. }
  1053. auto declaration = convert_to_declaration(*rule->m_block);
  1054. if (!declaration) {
  1055. dbgln("CSSParser: style rule declaration invalid; discarding.");
  1056. return {};
  1057. }
  1058. return CSSStyleRule::create(move(selectors.value()), move(*declaration));
  1059. }
  1060. return {};
  1061. }
  1062. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::convert_to_declaration(NonnullRefPtr<StyleBlockRule> block)
  1063. {
  1064. if (!block->is_curly())
  1065. return {};
  1066. auto stream = TokenStream(block->m_values);
  1067. return parse_a_list_of_declarations(stream);
  1068. }
  1069. Optional<StyleProperty> Parser::convert_to_style_property(StyleDeclarationRule& declaration)
  1070. {
  1071. auto& property_name = declaration.m_name;
  1072. auto property_id = property_id_from_string(property_name);
  1073. if (property_id == PropertyID::Invalid) {
  1074. if (property_name.starts_with("--")) {
  1075. property_id = PropertyID::Custom;
  1076. } else if (has_ignored_vendor_prefix(property_name)) {
  1077. return {};
  1078. } else if (!property_name.starts_with("-")) {
  1079. dbgln("Unrecognized CSS property '{}'", property_name);
  1080. return {};
  1081. }
  1082. }
  1083. auto value_token_stream = TokenStream(declaration.m_values);
  1084. auto value = parse_css_value(property_id, value_token_stream);
  1085. if (value.is_error()) {
  1086. if (value.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1087. dbgln("Unable to parse value for CSS property '{}'.", property_name);
  1088. if constexpr (CSS_PARSER_DEBUG) {
  1089. value_token_stream.dump_all_tokens();
  1090. }
  1091. }
  1092. return {};
  1093. }
  1094. if (property_id == PropertyID::Custom) {
  1095. return StyleProperty { property_id, value.release_value(), declaration.m_name, declaration.m_important };
  1096. } else {
  1097. return StyleProperty { property_id, value.release_value(), {}, declaration.m_important };
  1098. }
  1099. }
  1100. Optional<float> Parser::try_parse_float(StringView string)
  1101. {
  1102. // FIXME: This is copied from DeprecatedCSSParser, so may not be to spec.
  1103. const char* str = string.characters_without_null_termination();
  1104. size_t len = string.length();
  1105. size_t weight = 1;
  1106. int exp_val = 0;
  1107. float value = 0.0f;
  1108. float fraction = 0.0f;
  1109. bool has_sign = false;
  1110. bool is_negative = false;
  1111. bool is_fractional = false;
  1112. bool is_scientific = false;
  1113. if (str[0] == '-') {
  1114. is_negative = true;
  1115. has_sign = true;
  1116. }
  1117. if (str[0] == '+') {
  1118. has_sign = true;
  1119. }
  1120. for (size_t i = has_sign; i < len; i++) {
  1121. // Looks like we're about to start working on the fractional part
  1122. if (str[i] == '.') {
  1123. is_fractional = true;
  1124. continue;
  1125. }
  1126. if (str[i] == 'e' || str[i] == 'E') {
  1127. if (str[i + 1] == '-' || str[i + 1] == '+')
  1128. exp_val = atoi(str + i + 2);
  1129. else
  1130. exp_val = atoi(str + i + 1);
  1131. is_scientific = true;
  1132. continue;
  1133. }
  1134. if (str[i] < '0' || str[i] > '9' || exp_val != 0) {
  1135. return {};
  1136. continue;
  1137. }
  1138. if (is_fractional) {
  1139. fraction *= 10;
  1140. fraction += str[i] - '0';
  1141. weight *= 10;
  1142. } else {
  1143. value = value * 10;
  1144. value += str[i] - '0';
  1145. }
  1146. }
  1147. fraction /= weight;
  1148. value += fraction;
  1149. if (is_scientific) {
  1150. bool divide = exp_val < 0;
  1151. if (divide)
  1152. exp_val *= -1;
  1153. for (int i = 0; i < exp_val; i++) {
  1154. if (divide)
  1155. value /= 10;
  1156. else
  1157. value *= 10;
  1158. }
  1159. }
  1160. return is_negative ? -value : value;
  1161. }
  1162. RefPtr<StyleValue> Parser::parse_builtin_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1163. {
  1164. if (component_value.is(Token::Type::Ident)) {
  1165. auto ident = component_value.token().ident();
  1166. if (ident.equals_ignoring_case("inherit"))
  1167. return InheritStyleValue::the();
  1168. if (ident.equals_ignoring_case("initial"))
  1169. return InitialStyleValue::the();
  1170. if (ident.equals_ignoring_case("unset"))
  1171. return UnsetStyleValue::the();
  1172. // FIXME: Implement `revert` and `revert-layer` keywords, from Cascade4 and Cascade5 respectively
  1173. }
  1174. return {};
  1175. }
  1176. RefPtr<StyleValue> Parser::parse_dynamic_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1177. {
  1178. if (component_value.is_function()) {
  1179. auto& function = component_value.function();
  1180. if (function.name().equals_ignoring_case("calc")) {
  1181. auto calc_expression = parse_calc_expression(context, function.values());
  1182. // FIXME: Either produce a string value of calc() here, or do so in CalculatedStyleValue::to_string().
  1183. if (calc_expression)
  1184. return CalculatedStyleValue::create("(FIXME:calc to string)", calc_expression.release_nonnull());
  1185. } else if (function.name().equals_ignoring_case("var")) {
  1186. // FIXME: Handle fallback value as second parameter
  1187. // https://www.w3.org/TR/css-variables-1/#using-variables
  1188. if (!component_value.function().values().is_empty()) {
  1189. auto& property_name_token = component_value.function().values().first();
  1190. if (property_name_token.is(Token::Type::Ident))
  1191. return CustomStyleValue::create(property_name_token.token().ident());
  1192. else
  1193. dbgln("First argument to var() function was not an ident: '{}'", property_name_token.to_debug_string());
  1194. }
  1195. }
  1196. }
  1197. return {};
  1198. }
  1199. Optional<Length> Parser::parse_length(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1200. {
  1201. Length::Type type = Length::Type::Undefined;
  1202. Optional<float> numeric_value;
  1203. if (component_value.is(Token::Type::Dimension)) {
  1204. auto length_string = component_value.token().m_value.string_view();
  1205. auto unit_string = component_value.token().m_unit.string_view();
  1206. if (unit_string.equals_ignoring_case("%")) {
  1207. type = Length::Type::Percentage;
  1208. } else if (unit_string.equals_ignoring_case("px")) {
  1209. type = Length::Type::Px;
  1210. } else if (unit_string.equals_ignoring_case("pt")) {
  1211. type = Length::Type::Pt;
  1212. } else if (unit_string.equals_ignoring_case("pc")) {
  1213. type = Length::Type::Pc;
  1214. } else if (unit_string.equals_ignoring_case("mm")) {
  1215. type = Length::Type::Mm;
  1216. } else if (unit_string.equals_ignoring_case("rem")) {
  1217. type = Length::Type::Rem;
  1218. } else if (unit_string.equals_ignoring_case("em")) {
  1219. type = Length::Type::Em;
  1220. } else if (unit_string.equals_ignoring_case("ex")) {
  1221. type = Length::Type::Ex;
  1222. } else if (unit_string.equals_ignoring_case("ch")) {
  1223. type = Length::Type::Ch;
  1224. } else if (unit_string.equals_ignoring_case("vw")) {
  1225. type = Length::Type::Vw;
  1226. } else if (unit_string.equals_ignoring_case("vh")) {
  1227. type = Length::Type::Vh;
  1228. } else if (unit_string.equals_ignoring_case("vmax")) {
  1229. type = Length::Type::Vmax;
  1230. } else if (unit_string.equals_ignoring_case("vmin")) {
  1231. type = Length::Type::Vmin;
  1232. } else if (unit_string.equals_ignoring_case("cm")) {
  1233. type = Length::Type::Cm;
  1234. } else if (unit_string.equals_ignoring_case("in")) {
  1235. type = Length::Type::In;
  1236. } else if (unit_string.equals_ignoring_case("Q")) {
  1237. type = Length::Type::Q;
  1238. } else {
  1239. return {};
  1240. }
  1241. numeric_value = try_parse_float(length_string);
  1242. } else if (component_value.is(Token::Type::Percentage)) {
  1243. type = Length::Type::Percentage;
  1244. auto value_string = component_value.token().m_value.string_view();
  1245. numeric_value = try_parse_float(value_string);
  1246. } else if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto")) {
  1247. return Length::make_auto();
  1248. } else if (component_value.is(Token::Type::Number)) {
  1249. auto value_string = component_value.token().m_value.string_view();
  1250. if (value_string == "0") {
  1251. type = Length::Type::Px;
  1252. numeric_value = 0;
  1253. } else if (context.in_quirks_mode() && property_has_quirk(context.current_property_id(), Quirk::UnitlessLength)) {
  1254. // https://quirks.spec.whatwg.org/#quirky-length-value
  1255. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  1256. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  1257. // expression, and must not be supported in the supports() static method of the CSS interface."
  1258. type = Length::Type::Px;
  1259. numeric_value = try_parse_float(value_string);
  1260. }
  1261. }
  1262. if (!numeric_value.has_value())
  1263. return {};
  1264. return Length(numeric_value.value(), type);
  1265. }
  1266. RefPtr<StyleValue> Parser::parse_length_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1267. {
  1268. // Numbers with no units can be lengths, in two situations:
  1269. // 1) We're in quirks mode, and it's an integer.
  1270. // 2) It's a 0.
  1271. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  1272. // FIXME: "auto" is also treated as a Length, and most of the time that is how it is used, but not always.
  1273. // Possibly it should always be an Identifier, and then quietly converted to a Length when needed, like 0 above.
  1274. // Right now, it instead is quietly converted to an Identifier when needed.
  1275. if (component_value.is(Token::Type::Dimension) || component_value.is(Token::Type::Percentage)
  1276. || (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto"sv))
  1277. || (context.in_quirks_mode() && component_value.is(Token::Type::Number) && component_value.token().m_value.string_view() != "0"sv)) {
  1278. auto length = parse_length(context, component_value);
  1279. if (length.has_value())
  1280. return LengthStyleValue::create(length.value());
  1281. }
  1282. return {};
  1283. }
  1284. RefPtr<StyleValue> Parser::parse_numeric_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1285. {
  1286. if (component_value.is(Token::Type::Number)) {
  1287. auto number = component_value.token();
  1288. if (number.m_number_type == Token::NumberType::Integer) {
  1289. return NumericStyleValue::create(number.to_integer());
  1290. } else {
  1291. auto float_value = try_parse_float(number.m_value.string_view());
  1292. if (float_value.has_value())
  1293. return NumericStyleValue::create(float_value.value());
  1294. }
  1295. }
  1296. return {};
  1297. }
  1298. RefPtr<StyleValue> Parser::parse_identifier_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1299. {
  1300. if (component_value.is(Token::Type::Ident)) {
  1301. auto value_id = value_id_from_string(component_value.token().ident());
  1302. if (value_id != ValueID::Invalid)
  1303. return IdentifierStyleValue::create(value_id);
  1304. }
  1305. return {};
  1306. }
  1307. Optional<Color> Parser::parse_color(ParsingContext const&, StyleComponentValueRule const& component_value)
  1308. {
  1309. // https://www.w3.org/TR/css-color-3/
  1310. if (component_value.is(Token::Type::Ident)) {
  1311. auto ident = component_value.token().ident();
  1312. if (ident.equals_ignoring_case("transparent"))
  1313. return Color::from_rgba(0x00000000);
  1314. auto color = Color::from_string(ident.to_string().to_lowercase());
  1315. if (color.has_value())
  1316. return color;
  1317. } else if (component_value.is(Token::Type::Hash)) {
  1318. // FIXME: Read it directly
  1319. auto color = Color::from_string(String::formatted("#{}", component_value.token().m_value.to_string().to_lowercase()));
  1320. if (color.has_value())
  1321. return color;
  1322. } else if (component_value.is_function()) {
  1323. auto& function = component_value.function();
  1324. auto& values = function.values();
  1325. Vector<Token> params;
  1326. for (size_t i = 0; i < values.size(); ++i) {
  1327. auto& value = values.at(i);
  1328. if (value.is(Token::Type::Whitespace))
  1329. continue;
  1330. if (value.is(Token::Type::Percentage) || value.is(Token::Type::Number)) {
  1331. params.append(value.token());
  1332. // Eat following comma and whitespace
  1333. while ((i + 1) < values.size()) {
  1334. auto& next = values.at(i + 1);
  1335. if (next.is(Token::Type::Whitespace))
  1336. i++;
  1337. else if (next.is(Token::Type::Comma))
  1338. break;
  1339. return {};
  1340. }
  1341. }
  1342. }
  1343. if (function.name().equals_ignoring_case("rgb")) {
  1344. if (params.size() != 3)
  1345. return {};
  1346. auto r_val = params[0];
  1347. auto g_val = params[1];
  1348. auto b_val = params[2];
  1349. if (r_val.is(Token::NumberType::Integer)
  1350. && g_val.is(Token::NumberType::Integer)
  1351. && b_val.is(Token::NumberType::Integer)) {
  1352. auto maybe_r = r_val.m_value.string_view().to_uint<u8>();
  1353. auto maybe_g = g_val.m_value.string_view().to_uint<u8>();
  1354. auto maybe_b = b_val.m_value.string_view().to_uint<u8>();
  1355. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value())
  1356. return Color(maybe_r.value(), maybe_g.value(), maybe_b.value());
  1357. } else if (r_val.is(Token::Type::Percentage)
  1358. && g_val.is(Token::Type::Percentage)
  1359. && b_val.is(Token::Type::Percentage)) {
  1360. auto maybe_r = try_parse_float(r_val.m_value.string_view());
  1361. auto maybe_g = try_parse_float(g_val.m_value.string_view());
  1362. auto maybe_b = try_parse_float(b_val.m_value.string_view());
  1363. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value()) {
  1364. u8 r = clamp(lroundf(maybe_r.value() * 2.55f), 0, 255);
  1365. u8 g = clamp(lroundf(maybe_g.value() * 2.55f), 0, 255);
  1366. u8 b = clamp(lroundf(maybe_b.value() * 2.55f), 0, 255);
  1367. return Color(r, g, b);
  1368. }
  1369. }
  1370. } else if (function.name().equals_ignoring_case("rgba")) {
  1371. if (params.size() != 4)
  1372. return {};
  1373. auto r_val = params[0];
  1374. auto g_val = params[1];
  1375. auto b_val = params[2];
  1376. auto a_val = params[3];
  1377. if (r_val.is(Token::NumberType::Integer)
  1378. && g_val.is(Token::NumberType::Integer)
  1379. && b_val.is(Token::NumberType::Integer)
  1380. && a_val.is(Token::Type::Number)) {
  1381. auto maybe_r = r_val.m_value.string_view().to_uint<u8>();
  1382. auto maybe_g = g_val.m_value.string_view().to_uint<u8>();
  1383. auto maybe_b = b_val.m_value.string_view().to_uint<u8>();
  1384. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1385. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value() && maybe_a.has_value()) {
  1386. u8 a = clamp(lroundf(maybe_a.value() * 255.0f), 0, 255);
  1387. return Color(maybe_r.value(), maybe_g.value(), maybe_b.value(), a);
  1388. }
  1389. } else if (r_val.is(Token::Type::Percentage)
  1390. && g_val.is(Token::Type::Percentage)
  1391. && b_val.is(Token::Type::Percentage)
  1392. && a_val.is(Token::Type::Number)) {
  1393. auto maybe_r = try_parse_float(r_val.m_value.string_view());
  1394. auto maybe_g = try_parse_float(g_val.m_value.string_view());
  1395. auto maybe_b = try_parse_float(b_val.m_value.string_view());
  1396. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1397. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value() && maybe_a.has_value()) {
  1398. u8 r = clamp(lroundf(maybe_r.value() * 2.55f), 0, 255);
  1399. u8 g = clamp(lroundf(maybe_g.value() * 2.55f), 0, 255);
  1400. u8 b = clamp(lroundf(maybe_b.value() * 2.55f), 0, 255);
  1401. u8 a = clamp(lroundf(maybe_a.value() * 255.0f), 0, 255);
  1402. return Color(r, g, b, a);
  1403. }
  1404. }
  1405. } else if (function.name().equals_ignoring_case("hsl")) {
  1406. if (params.size() != 3)
  1407. return {};
  1408. auto h_val = params[0];
  1409. auto s_val = params[1];
  1410. auto l_val = params[2];
  1411. if (h_val.is(Token::Type::Number)
  1412. && s_val.is(Token::Type::Percentage)
  1413. && l_val.is(Token::Type::Percentage)) {
  1414. auto maybe_h = try_parse_float(h_val.m_value.string_view());
  1415. auto maybe_s = try_parse_float(s_val.m_value.string_view());
  1416. auto maybe_l = try_parse_float(l_val.m_value.string_view());
  1417. if (maybe_h.has_value() && maybe_s.has_value() && maybe_l.has_value()) {
  1418. float h = maybe_h.value();
  1419. float s = maybe_s.value() / 100.0f;
  1420. float l = maybe_l.value() / 100.0f;
  1421. return Color::from_hsl(h, s, l);
  1422. }
  1423. }
  1424. } else if (function.name().equals_ignoring_case("hsla")) {
  1425. if (params.size() != 4)
  1426. return {};
  1427. auto h_val = params[0];
  1428. auto s_val = params[1];
  1429. auto l_val = params[2];
  1430. auto a_val = params[3];
  1431. if (h_val.is(Token::Type::Number)
  1432. && s_val.is(Token::Type::Percentage)
  1433. && l_val.is(Token::Type::Percentage)
  1434. && a_val.is(Token::Type::Number)) {
  1435. auto maybe_h = try_parse_float(h_val.m_value.string_view());
  1436. auto maybe_s = try_parse_float(s_val.m_value.string_view());
  1437. auto maybe_l = try_parse_float(l_val.m_value.string_view());
  1438. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1439. if (maybe_h.has_value() && maybe_s.has_value() && maybe_l.has_value() && maybe_a.has_value()) {
  1440. float h = maybe_h.value();
  1441. float s = maybe_s.value() / 100.0f;
  1442. float l = maybe_l.value() / 100.0f;
  1443. float a = maybe_a.value();
  1444. return Color::from_hsla(h, s, l, a);
  1445. }
  1446. }
  1447. }
  1448. return {};
  1449. }
  1450. return {};
  1451. }
  1452. RefPtr<StyleValue> Parser::parse_color_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1453. {
  1454. auto color = parse_color(context, component_value);
  1455. if (color.has_value())
  1456. return ColorStyleValue::create(color.value());
  1457. return {};
  1458. }
  1459. RefPtr<StyleValue> Parser::parse_string_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1460. {
  1461. if (component_value.is(Token::Type::String))
  1462. return StringStyleValue::create(component_value.token().string());
  1463. return {};
  1464. }
  1465. RefPtr<StyleValue> Parser::parse_image_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1466. {
  1467. auto url = parse_url_function(context, component_value);
  1468. if (url.has_value())
  1469. return ImageStyleValue::create(url.value(), context.document());
  1470. // FIXME: Handle gradients.
  1471. return {};
  1472. }
  1473. RefPtr<StyleValue> Parser::parse_background_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1474. {
  1475. RefPtr<StyleValue> background_color;
  1476. RefPtr<StyleValue> background_image;
  1477. RefPtr<StyleValue> repeat_x;
  1478. RefPtr<StyleValue> repeat_y;
  1479. // FIXME: Implement background-position.
  1480. // FIXME: Implement background-size.
  1481. // FIXME: Implement background-attachment.
  1482. // FIXME: Implement background-clip.
  1483. // FIXME: Implement background-origin.
  1484. for (size_t i = 0; i < component_values.size(); ++i) {
  1485. auto& part = component_values[i];
  1486. // FIXME: Handle multiple backgrounds, by returning a List of BackgroundStyleValues.
  1487. if (part.is(Token::Type::Comma)) {
  1488. dbgln("CSS Parser does not yet support multiple comma-separated values for background.");
  1489. break;
  1490. }
  1491. auto value = parse_css_value(context, part);
  1492. if (!value) {
  1493. return nullptr;
  1494. }
  1495. if (property_accepts_value(PropertyID::BackgroundColor, *value)) {
  1496. if (background_color)
  1497. return nullptr;
  1498. background_color = value.release_nonnull();
  1499. continue;
  1500. }
  1501. if (property_accepts_value(PropertyID::BackgroundImage, *value)) {
  1502. if (background_image)
  1503. return nullptr;
  1504. background_image = value.release_nonnull();
  1505. continue;
  1506. }
  1507. if (property_accepts_value(PropertyID::BackgroundRepeat, *value)) {
  1508. if (repeat_x)
  1509. return nullptr;
  1510. auto value_id = value->to_identifier();
  1511. if (value_id == ValueID::RepeatX || value_id == ValueID::RepeatY) {
  1512. repeat_x = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat);
  1513. repeat_y = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat);
  1514. continue;
  1515. }
  1516. // Check following value, if it's also a repeat, set both.
  1517. if (i + 1 < component_values.size()) {
  1518. auto next_value = parse_css_value(context, component_values[i + 1]);
  1519. if (next_value && property_accepts_value(PropertyID::BackgroundRepeat, *next_value)) {
  1520. ++i;
  1521. repeat_x = value.release_nonnull();
  1522. repeat_y = next_value.release_nonnull();
  1523. continue;
  1524. }
  1525. }
  1526. auto repeat = value.release_nonnull();
  1527. repeat_x = repeat;
  1528. repeat_y = repeat;
  1529. continue;
  1530. }
  1531. return nullptr;
  1532. }
  1533. if (!background_color)
  1534. background_color = property_initial_value(PropertyID::BackgroundColor);
  1535. if (!background_image)
  1536. background_image = property_initial_value(PropertyID::BackgroundImage);
  1537. if (!repeat_x)
  1538. repeat_x = property_initial_value(PropertyID::BackgroundRepeatX);
  1539. if (!repeat_y)
  1540. repeat_y = property_initial_value(PropertyID::BackgroundRepeatY);
  1541. return BackgroundStyleValue::create(background_color.release_nonnull(), background_image.release_nonnull(), repeat_x.release_nonnull(), repeat_y.release_nonnull());
  1542. }
  1543. RefPtr<StyleValue> Parser::parse_background_image_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1544. {
  1545. if (component_values.size() == 1) {
  1546. auto maybe_value = parse_css_value(context, component_values.first());
  1547. if (!maybe_value)
  1548. return nullptr;
  1549. auto value = maybe_value.release_nonnull();
  1550. if (property_accepts_value(PropertyID::BackgroundImage, *value))
  1551. return value;
  1552. return nullptr;
  1553. }
  1554. // FIXME: Handle multiple sets of comma-separated values.
  1555. dbgln("CSS Parser does not yet support multiple comma-separated values for background-image.");
  1556. return nullptr;
  1557. }
  1558. RefPtr<StyleValue> Parser::parse_background_repeat_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1559. {
  1560. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  1561. auto value_id = value.to_identifier();
  1562. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  1563. };
  1564. if (component_values.size() == 1) {
  1565. auto maybe_value = parse_css_value(context, component_values.first());
  1566. if (!maybe_value)
  1567. return nullptr;
  1568. auto value = maybe_value.release_nonnull();
  1569. if (!property_accepts_value(PropertyID::BackgroundRepeat, *value))
  1570. return nullptr;
  1571. if (is_directional_repeat(value)) {
  1572. auto value_id = value->to_identifier();
  1573. return BackgroundRepeatStyleValue::create(
  1574. IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat),
  1575. IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat));
  1576. }
  1577. return BackgroundRepeatStyleValue::create(value, value);
  1578. }
  1579. if (component_values.size() == 2) {
  1580. auto maybe_x_value = parse_css_value(context, component_values[0]);
  1581. auto maybe_y_value = parse_css_value(context, component_values[1]);
  1582. if (!maybe_x_value || !maybe_y_value)
  1583. return nullptr;
  1584. auto x_value = maybe_x_value.release_nonnull();
  1585. auto y_value = maybe_y_value.release_nonnull();
  1586. if (!property_accepts_value(PropertyID::BackgroundRepeat, x_value) || !property_accepts_value(PropertyID::BackgroundRepeat, y_value))
  1587. return nullptr;
  1588. if (is_directional_repeat(x_value) || is_directional_repeat(y_value))
  1589. return nullptr;
  1590. return BackgroundRepeatStyleValue::create(x_value, y_value);
  1591. }
  1592. // FIXME: Handle multiple sets of comma-separated values.
  1593. dbgln("CSS Parser does not yet support multiple comma-separated values for background-repeat.");
  1594. return nullptr;
  1595. }
  1596. RefPtr<StyleValue> Parser::parse_border_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1597. {
  1598. if (component_values.size() > 3)
  1599. return nullptr;
  1600. RefPtr<StyleValue> border_width;
  1601. RefPtr<StyleValue> border_color;
  1602. RefPtr<StyleValue> border_style;
  1603. for (auto& part : component_values) {
  1604. auto value = parse_css_value(context, part);
  1605. if (!value)
  1606. return nullptr;
  1607. if (property_accepts_value(PropertyID::BorderWidth, *value)) {
  1608. if (border_width)
  1609. return nullptr;
  1610. border_width = value.release_nonnull();
  1611. continue;
  1612. }
  1613. if (property_accepts_value(PropertyID::BorderColor, *value)) {
  1614. if (border_color)
  1615. return nullptr;
  1616. border_color = value.release_nonnull();
  1617. continue;
  1618. }
  1619. if (property_accepts_value(PropertyID::BorderStyle, *value)) {
  1620. if (border_style)
  1621. return nullptr;
  1622. border_style = value.release_nonnull();
  1623. continue;
  1624. }
  1625. return nullptr;
  1626. }
  1627. if (!border_width)
  1628. border_width = property_initial_value(PropertyID::BorderWidth);
  1629. if (!border_style)
  1630. border_style = property_initial_value(PropertyID::BorderStyle);
  1631. if (!border_color)
  1632. border_color = property_initial_value(PropertyID::BorderColor);
  1633. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  1634. }
  1635. RefPtr<StyleValue> Parser::parse_border_radius_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1636. {
  1637. if (component_values.size() == 2) {
  1638. auto horizontal = parse_length(context, component_values[0]);
  1639. auto vertical = parse_length(context, component_values[1]);
  1640. if (horizontal.has_value() && vertical.has_value())
  1641. return BorderRadiusStyleValue::create(horizontal.value(), vertical.value());
  1642. return nullptr;
  1643. }
  1644. if (component_values.size() == 1) {
  1645. auto radius = parse_length(context, component_values[0]);
  1646. if (radius.has_value())
  1647. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  1648. return nullptr;
  1649. }
  1650. return nullptr;
  1651. }
  1652. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1653. {
  1654. auto top_left = [&](Vector<Length>& radii) { return radii[0]; };
  1655. auto top_right = [&](Vector<Length>& radii) {
  1656. switch (radii.size()) {
  1657. case 4:
  1658. case 3:
  1659. case 2:
  1660. return radii[1];
  1661. case 1:
  1662. return radii[0];
  1663. default:
  1664. VERIFY_NOT_REACHED();
  1665. }
  1666. };
  1667. auto bottom_right = [&](Vector<Length>& radii) {
  1668. switch (radii.size()) {
  1669. case 4:
  1670. case 3:
  1671. return radii[2];
  1672. case 2:
  1673. case 1:
  1674. return radii[0];
  1675. default:
  1676. VERIFY_NOT_REACHED();
  1677. }
  1678. };
  1679. auto bottom_left = [&](Vector<Length>& radii) {
  1680. switch (radii.size()) {
  1681. case 4:
  1682. return radii[3];
  1683. case 3:
  1684. case 2:
  1685. return radii[1];
  1686. case 1:
  1687. return radii[0];
  1688. default:
  1689. VERIFY_NOT_REACHED();
  1690. }
  1691. };
  1692. Vector<Length> horizontal_radii;
  1693. Vector<Length> vertical_radii;
  1694. bool reading_vertical = false;
  1695. for (auto& value : component_values) {
  1696. if (value.is(Token::Type::Delim) && value.token().delim() == "/"sv) {
  1697. if (reading_vertical || horizontal_radii.is_empty())
  1698. return nullptr;
  1699. reading_vertical = true;
  1700. continue;
  1701. }
  1702. auto maybe_length = parse_length(context, value);
  1703. if (!maybe_length.has_value())
  1704. return nullptr;
  1705. if (reading_vertical) {
  1706. vertical_radii.append(maybe_length.value());
  1707. } else {
  1708. horizontal_radii.append(maybe_length.value());
  1709. }
  1710. }
  1711. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  1712. || horizontal_radii.is_empty()
  1713. || (reading_vertical && vertical_radii.is_empty()))
  1714. return nullptr;
  1715. NonnullRefPtrVector<StyleValue> border_radii;
  1716. border_radii.append(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  1717. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  1718. border_radii.append(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  1719. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  1720. border_radii.append(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  1721. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  1722. border_radii.append(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  1723. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  1724. return StyleValueList::create(move(border_radii));
  1725. }
  1726. RefPtr<StyleValue> Parser::parse_box_shadow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1727. {
  1728. // FIXME: Also support inset, spread-radius and multiple comma-separated box-shadows
  1729. Length offset_x {};
  1730. Length offset_y {};
  1731. Length blur_radius {};
  1732. Color color {};
  1733. if (component_values.size() < 3 || component_values.size() > 4)
  1734. return nullptr;
  1735. auto maybe_x = parse_length(context, component_values[0]);
  1736. if (!maybe_x.has_value())
  1737. return nullptr;
  1738. offset_x = maybe_x.value();
  1739. auto maybe_y = parse_length(context, component_values[1]);
  1740. if (!maybe_y.has_value())
  1741. return nullptr;
  1742. offset_y = maybe_y.value();
  1743. if (component_values.size() == 3) {
  1744. auto parsed_color = parse_color(context, component_values[2]);
  1745. if (!parsed_color.has_value())
  1746. return nullptr;
  1747. color = parsed_color.value();
  1748. } else if (component_values.size() == 4) {
  1749. auto maybe_blur_radius = parse_length(context, component_values[2]);
  1750. if (!maybe_blur_radius.has_value())
  1751. return nullptr;
  1752. blur_radius = maybe_blur_radius.value();
  1753. auto parsed_color = parse_color(context, component_values[3]);
  1754. if (!parsed_color.has_value())
  1755. return nullptr;
  1756. color = parsed_color.value();
  1757. }
  1758. return BoxShadowStyleValue::create(offset_x, offset_y, blur_radius, color);
  1759. }
  1760. RefPtr<StyleValue> Parser::parse_flex_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1761. {
  1762. if (component_values.size() == 1) {
  1763. auto value = parse_css_value(context, component_values[0]);
  1764. if (!value)
  1765. return nullptr;
  1766. switch (value->to_identifier()) {
  1767. case ValueID::Auto: {
  1768. auto one = NumericStyleValue::create(1);
  1769. return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
  1770. }
  1771. case ValueID::None: {
  1772. auto zero = NumericStyleValue::create(0);
  1773. return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  1774. }
  1775. default:
  1776. break;
  1777. }
  1778. }
  1779. RefPtr<StyleValue> flex_grow;
  1780. RefPtr<StyleValue> flex_shrink;
  1781. RefPtr<StyleValue> flex_basis;
  1782. for (size_t i = 0; i < component_values.size(); ++i) {
  1783. auto value = parse_css_value(context, component_values[i]);
  1784. if (!value)
  1785. return nullptr;
  1786. // Zero is a valid value for basis, but only if grow and shrink are already specified.
  1787. if (value->has_number() && value->to_number() == 0) {
  1788. if (flex_grow && flex_shrink && !flex_basis) {
  1789. flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
  1790. continue;
  1791. }
  1792. }
  1793. if (property_accepts_value(PropertyID::FlexGrow, *value)) {
  1794. if (flex_grow)
  1795. return nullptr;
  1796. flex_grow = value.release_nonnull();
  1797. // Flex-shrink may optionally follow directly after.
  1798. if (i + 1 < component_values.size()) {
  1799. auto second_value = parse_css_value(context, component_values[i + 1]);
  1800. if (second_value && property_accepts_value(PropertyID::FlexShrink, *second_value)) {
  1801. flex_shrink = second_value.release_nonnull();
  1802. i++;
  1803. }
  1804. }
  1805. continue;
  1806. }
  1807. if (property_accepts_value(PropertyID::FlexBasis, *value)) {
  1808. if (flex_basis)
  1809. return nullptr;
  1810. flex_basis = value.release_nonnull();
  1811. continue;
  1812. }
  1813. return nullptr;
  1814. }
  1815. if (!flex_grow)
  1816. flex_grow = property_initial_value(PropertyID::FlexGrow);
  1817. if (!flex_shrink)
  1818. flex_shrink = property_initial_value(PropertyID::FlexShrink);
  1819. if (!flex_basis)
  1820. flex_basis = property_initial_value(PropertyID::FlexBasis);
  1821. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  1822. }
  1823. RefPtr<StyleValue> Parser::parse_flex_flow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1824. {
  1825. if (component_values.size() > 2)
  1826. return nullptr;
  1827. RefPtr<StyleValue> flex_direction;
  1828. RefPtr<StyleValue> flex_wrap;
  1829. for (auto& part : component_values) {
  1830. auto value = parse_css_value(context, part);
  1831. if (!value)
  1832. return nullptr;
  1833. if (property_accepts_value(PropertyID::FlexDirection, *value)) {
  1834. if (flex_direction)
  1835. return nullptr;
  1836. flex_direction = value.release_nonnull();
  1837. continue;
  1838. }
  1839. if (property_accepts_value(PropertyID::FlexWrap, *value)) {
  1840. if (flex_wrap)
  1841. return nullptr;
  1842. flex_wrap = value.release_nonnull();
  1843. continue;
  1844. }
  1845. }
  1846. if (!flex_direction)
  1847. flex_direction = property_initial_value(PropertyID::FlexDirection);
  1848. if (!flex_wrap)
  1849. flex_wrap = property_initial_value(PropertyID::FlexWrap);
  1850. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  1851. }
  1852. RefPtr<StyleValue> Parser::parse_font_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1853. {
  1854. RefPtr<StyleValue> font_style;
  1855. RefPtr<StyleValue> font_weight;
  1856. RefPtr<StyleValue> font_size;
  1857. RefPtr<StyleValue> line_height;
  1858. RefPtr<StyleValue> font_families;
  1859. // FIXME: Implement font-stretch and font-variant.
  1860. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  1861. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  1862. // So, we have to handle that separately.
  1863. int normal_count = 0;
  1864. for (size_t i = 0; i < component_values.size(); ++i) {
  1865. auto value = parse_css_value(context, component_values[i]);
  1866. if (!value)
  1867. return nullptr;
  1868. if (value->to_identifier() == ValueID::Normal) {
  1869. normal_count++;
  1870. continue;
  1871. }
  1872. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  1873. if (property_accepts_value(PropertyID::FontStyle, *value)) {
  1874. if (font_style)
  1875. return nullptr;
  1876. font_style = value.release_nonnull();
  1877. continue;
  1878. }
  1879. if (property_accepts_value(PropertyID::FontWeight, *value)) {
  1880. if (font_weight)
  1881. return nullptr;
  1882. font_weight = value.release_nonnull();
  1883. continue;
  1884. }
  1885. if (property_accepts_value(PropertyID::FontSize, *value)) {
  1886. if (font_size)
  1887. return nullptr;
  1888. font_size = value.release_nonnull();
  1889. // Consume `/ line-height` if present
  1890. if (i + 2 < component_values.size()) {
  1891. auto maybe_solidus = component_values[i + 1];
  1892. if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == "/"sv) {
  1893. auto maybe_line_height = parse_css_value(context, component_values[i + 2]);
  1894. if (!(maybe_line_height && property_accepts_value(PropertyID::LineHeight, *maybe_line_height)))
  1895. return nullptr;
  1896. line_height = maybe_line_height.release_nonnull();
  1897. i += 2;
  1898. }
  1899. }
  1900. // Consume font-families
  1901. auto maybe_font_families = parse_font_family_value(context, component_values, i + 1);
  1902. if (!maybe_font_families)
  1903. return nullptr;
  1904. font_families = maybe_font_families.release_nonnull();
  1905. break;
  1906. }
  1907. return nullptr;
  1908. }
  1909. // Since normal is the default value for all the properties that can have it, we don't have to actually
  1910. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  1911. // We just need to make sure we were not given more normals than will fit.
  1912. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  1913. if (unset_value_count < normal_count)
  1914. return nullptr;
  1915. if (!font_size || !font_families)
  1916. return nullptr;
  1917. if (!font_style)
  1918. font_style = property_initial_value(PropertyID::FontStyle);
  1919. if (!font_weight)
  1920. font_weight = property_initial_value(PropertyID::FontWeight);
  1921. if (!line_height)
  1922. line_height = property_initial_value(PropertyID::LineHeight);
  1923. return FontStyleValue::create(font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
  1924. }
  1925. RefPtr<StyleValue> Parser::parse_font_family_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values, size_t start_index)
  1926. {
  1927. auto is_generic_font_family = [](ValueID identifier) -> bool {
  1928. switch (identifier) {
  1929. case ValueID::Cursive:
  1930. case ValueID::Fantasy:
  1931. case ValueID::Monospace:
  1932. case ValueID::Serif:
  1933. case ValueID::SansSerif:
  1934. case ValueID::UiMonospace:
  1935. case ValueID::UiRounded:
  1936. case ValueID::UiSerif:
  1937. case ValueID::UiSansSerif:
  1938. return true;
  1939. default:
  1940. return false;
  1941. }
  1942. };
  1943. auto is_comma_or_eof = [&](size_t i) -> bool {
  1944. if (i < component_values.size()) {
  1945. auto& maybe_comma = component_values[i];
  1946. if (!maybe_comma.is(Token::Type::Comma))
  1947. return false;
  1948. }
  1949. return true;
  1950. };
  1951. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  1952. // eg, these are equivalent:
  1953. // font-family: my cool font\!, serif;
  1954. // font-family: "my cool font!", serif;
  1955. NonnullRefPtrVector<StyleValue> font_families;
  1956. Vector<String> current_name_parts;
  1957. for (size_t i = start_index; i < component_values.size(); ++i) {
  1958. auto& part = component_values[i];
  1959. if (part.is(Token::Type::String)) {
  1960. // `font-family: my cool "font";` is invalid.
  1961. if (!current_name_parts.is_empty())
  1962. return nullptr;
  1963. if (!is_comma_or_eof(i + 1))
  1964. return nullptr;
  1965. font_families.append(StringStyleValue::create(part.token().string()));
  1966. i++;
  1967. continue;
  1968. }
  1969. if (part.is(Token::Type::Ident)) {
  1970. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  1971. auto maybe_ident = parse_css_value(context, part);
  1972. if (maybe_ident) {
  1973. // CSS-wide keywords are not allowed
  1974. if (maybe_ident->is_builtin())
  1975. return nullptr;
  1976. if (is_generic_font_family(maybe_ident->to_identifier())) {
  1977. // Can't have a generic-font-name as a token in an unquoted font name.
  1978. if (!current_name_parts.is_empty())
  1979. return nullptr;
  1980. if (!is_comma_or_eof(i + 1))
  1981. return nullptr;
  1982. font_families.append(maybe_ident.release_nonnull());
  1983. i++;
  1984. continue;
  1985. }
  1986. }
  1987. current_name_parts.append(part.token().ident());
  1988. continue;
  1989. }
  1990. if (part.is(Token::Type::Comma)) {
  1991. if (current_name_parts.is_empty())
  1992. return nullptr;
  1993. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  1994. current_name_parts.clear();
  1995. // Can't have a trailing comma
  1996. if (i + 1 == component_values.size())
  1997. return nullptr;
  1998. continue;
  1999. }
  2000. }
  2001. if (!current_name_parts.is_empty()) {
  2002. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2003. current_name_parts.clear();
  2004. }
  2005. if (font_families.is_empty())
  2006. return nullptr;
  2007. return StyleValueList::create(move(font_families));
  2008. }
  2009. RefPtr<StyleValue> Parser::parse_list_style_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2010. {
  2011. if (component_values.size() > 3)
  2012. return nullptr;
  2013. RefPtr<StyleValue> list_position;
  2014. RefPtr<StyleValue> list_image;
  2015. RefPtr<StyleValue> list_type;
  2016. int found_nones = 0;
  2017. for (auto& part : component_values) {
  2018. auto value = parse_css_value(context, part);
  2019. if (!value)
  2020. return nullptr;
  2021. if (value->to_identifier() == ValueID::None) {
  2022. found_nones++;
  2023. continue;
  2024. }
  2025. if (property_accepts_value(PropertyID::ListStylePosition, *value)) {
  2026. if (list_position)
  2027. return nullptr;
  2028. list_position = value.release_nonnull();
  2029. continue;
  2030. }
  2031. if (property_accepts_value(PropertyID::ListStyleImage, *value)) {
  2032. if (list_image)
  2033. return nullptr;
  2034. list_image = value.release_nonnull();
  2035. continue;
  2036. }
  2037. if (property_accepts_value(PropertyID::ListStyleType, *value)) {
  2038. if (list_type)
  2039. return nullptr;
  2040. list_type = value.release_nonnull();
  2041. continue;
  2042. }
  2043. }
  2044. if (found_nones > 2)
  2045. return nullptr;
  2046. if (found_nones == 2) {
  2047. if (list_image || list_type)
  2048. return nullptr;
  2049. auto none = IdentifierStyleValue::create(ValueID::None);
  2050. list_image = none;
  2051. list_type = none;
  2052. } else if (found_nones == 1) {
  2053. if (list_image && list_type)
  2054. return nullptr;
  2055. auto none = IdentifierStyleValue::create(ValueID::None);
  2056. if (!list_image)
  2057. list_image = none;
  2058. if (!list_type)
  2059. list_type = none;
  2060. }
  2061. if (!list_position)
  2062. list_position = property_initial_value(PropertyID::ListStylePosition);
  2063. if (!list_image)
  2064. list_image = property_initial_value(PropertyID::ListStyleImage);
  2065. if (!list_type)
  2066. list_type = property_initial_value(PropertyID::ListStyleType);
  2067. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  2068. }
  2069. RefPtr<StyleValue> Parser::parse_overflow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2070. {
  2071. if (component_values.size() == 1) {
  2072. auto maybe_value = parse_css_value(context, component_values.first());
  2073. if (!maybe_value)
  2074. return nullptr;
  2075. auto value = maybe_value.release_nonnull();
  2076. if (property_accepts_value(PropertyID::Overflow, *value))
  2077. return OverflowStyleValue::create(value, value);
  2078. return nullptr;
  2079. }
  2080. if (component_values.size() == 2) {
  2081. auto maybe_x_value = parse_css_value(context, component_values[0]);
  2082. auto maybe_y_value = parse_css_value(context, component_values[1]);
  2083. if (!maybe_x_value || !maybe_y_value)
  2084. return nullptr;
  2085. auto x_value = maybe_x_value.release_nonnull();
  2086. auto y_value = maybe_y_value.release_nonnull();
  2087. if (!property_accepts_value(PropertyID::OverflowX, x_value) || !property_accepts_value(PropertyID::OverflowY, y_value)) {
  2088. return nullptr;
  2089. }
  2090. return OverflowStyleValue::create(x_value, y_value);
  2091. }
  2092. return nullptr;
  2093. }
  2094. RefPtr<StyleValue> Parser::parse_text_decoration_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2095. {
  2096. if (component_values.size() > 3)
  2097. return nullptr;
  2098. RefPtr<StyleValue> decoration_line;
  2099. RefPtr<StyleValue> decoration_style;
  2100. RefPtr<StyleValue> decoration_color;
  2101. // FIXME: Implement 'text-decoration-thickness' parameter. https://www.w3.org/TR/css-text-decor-4/#text-decoration-width-property
  2102. for (auto& part : component_values) {
  2103. auto value = parse_css_value(context, part);
  2104. if (!value)
  2105. return nullptr;
  2106. if (property_accepts_value(PropertyID::TextDecorationColor, *value)) {
  2107. if (decoration_color)
  2108. return nullptr;
  2109. decoration_color = value.release_nonnull();
  2110. continue;
  2111. }
  2112. if (property_accepts_value(PropertyID::TextDecorationLine, *value)) {
  2113. if (decoration_line)
  2114. return nullptr;
  2115. decoration_line = value.release_nonnull();
  2116. continue;
  2117. }
  2118. if (property_accepts_value(PropertyID::TextDecorationStyle, *value)) {
  2119. if (decoration_style)
  2120. return nullptr;
  2121. decoration_style = value.release_nonnull();
  2122. continue;
  2123. }
  2124. return nullptr;
  2125. }
  2126. if (!decoration_line)
  2127. decoration_line = property_initial_value(PropertyID::TextDecorationLine);
  2128. if (!decoration_style)
  2129. decoration_style = property_initial_value(PropertyID::TextDecorationStyle);
  2130. if (!decoration_color)
  2131. decoration_color = property_initial_value(PropertyID::TextDecorationColor);
  2132. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  2133. }
  2134. static Optional<CSS::TransformFunction> parse_transform_function_name(StringView name)
  2135. {
  2136. if (name == "translateY")
  2137. return CSS::TransformFunction::TranslateY;
  2138. return {};
  2139. }
  2140. RefPtr<StyleValue> Parser::parse_transform_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2141. {
  2142. NonnullRefPtrVector<StyleValue> transformations;
  2143. for (auto& part : component_values) {
  2144. if (!part.is_function())
  2145. return nullptr;
  2146. auto maybe_function = parse_transform_function_name(part.function().name());
  2147. if (!maybe_function.has_value())
  2148. return nullptr;
  2149. NonnullRefPtrVector<StyleValue> values;
  2150. for (auto& value : part.function().values()) {
  2151. if (value.is(Token::Type::Dimension)) {
  2152. auto maybe_length = parse_length(context, value);
  2153. if (!maybe_length.has_value())
  2154. return nullptr;
  2155. values.append(LengthStyleValue::create(maybe_length.release_value()));
  2156. } else if (value.is(Token::Type::Number)) {
  2157. auto number = parse_numeric_value(context, value);
  2158. values.append(number.release_nonnull());
  2159. } else {
  2160. dbgln("FIXME: Unsupported value type for transformation!");
  2161. return nullptr;
  2162. }
  2163. }
  2164. transformations.append(TransformationStyleValue::create(maybe_function.value(), move(values)));
  2165. }
  2166. return StyleValueList::create(move(transformations));
  2167. }
  2168. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  2169. {
  2170. auto component_values = parse_as_list_of_component_values();
  2171. auto tokens = TokenStream(component_values);
  2172. auto parsed_value = parse_css_value(property_id, tokens);
  2173. if (parsed_value.is_error())
  2174. return {};
  2175. return parsed_value.release_value();
  2176. }
  2177. Result<NonnullRefPtr<StyleValue>, Parser::ParsingResult> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  2178. {
  2179. m_context.set_current_property_id(property_id);
  2180. Vector<StyleComponentValueRule> component_values;
  2181. while (tokens.has_next_token()) {
  2182. auto& token = tokens.next_token();
  2183. if (token.is(Token::Type::Semicolon)) {
  2184. tokens.reconsume_current_input_token();
  2185. break;
  2186. }
  2187. if (token.is(Token::Type::Whitespace))
  2188. continue;
  2189. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  2190. return ParsingResult::IncludesIgnoredVendorPrefix;
  2191. component_values.append(token);
  2192. }
  2193. if (component_values.is_empty())
  2194. return ParsingResult::SyntaxError;
  2195. if (component_values.size() == 1) {
  2196. if (auto parsed_value = parse_builtin_value(m_context, component_values.first()))
  2197. return parsed_value.release_nonnull();
  2198. }
  2199. // Special-case property handling
  2200. switch (property_id) {
  2201. case PropertyID::Background:
  2202. if (auto parsed_value = parse_background_value(m_context, component_values))
  2203. return parsed_value.release_nonnull();
  2204. return ParsingResult::SyntaxError;
  2205. case PropertyID::BackgroundImage:
  2206. if (auto parsed_value = parse_background_image_value(m_context, component_values))
  2207. return parsed_value.release_nonnull();
  2208. return ParsingResult::SyntaxError;
  2209. case PropertyID::BackgroundRepeat:
  2210. if (auto parsed_value = parse_background_repeat_value(m_context, component_values))
  2211. return parsed_value.release_nonnull();
  2212. return ParsingResult::SyntaxError;
  2213. case PropertyID::Border:
  2214. case PropertyID::BorderBottom:
  2215. case PropertyID::BorderLeft:
  2216. case PropertyID::BorderRight:
  2217. case PropertyID::BorderTop:
  2218. if (auto parsed_value = parse_border_value(m_context, component_values))
  2219. return parsed_value.release_nonnull();
  2220. return ParsingResult::SyntaxError;
  2221. case PropertyID::BorderTopLeftRadius:
  2222. case PropertyID::BorderTopRightRadius:
  2223. case PropertyID::BorderBottomRightRadius:
  2224. case PropertyID::BorderBottomLeftRadius:
  2225. if (auto parsed_value = parse_border_radius_value(m_context, component_values))
  2226. return parsed_value.release_nonnull();
  2227. return ParsingResult::SyntaxError;
  2228. case PropertyID::BorderRadius:
  2229. if (auto parsed_value = parse_border_radius_shorthand_value(m_context, component_values))
  2230. return parsed_value.release_nonnull();
  2231. return ParsingResult::SyntaxError;
  2232. case PropertyID::BoxShadow:
  2233. if (auto parsed_value = parse_box_shadow_value(m_context, component_values))
  2234. return parsed_value.release_nonnull();
  2235. return ParsingResult::SyntaxError;
  2236. case PropertyID::Flex:
  2237. if (auto parsed_value = parse_flex_value(m_context, component_values))
  2238. return parsed_value.release_nonnull();
  2239. return ParsingResult::SyntaxError;
  2240. case PropertyID::FlexFlow:
  2241. if (auto parsed_value = parse_flex_flow_value(m_context, component_values))
  2242. return parsed_value.release_nonnull();
  2243. return ParsingResult::SyntaxError;
  2244. case PropertyID::Font:
  2245. if (auto parsed_value = parse_font_value(m_context, component_values))
  2246. return parsed_value.release_nonnull();
  2247. return ParsingResult::SyntaxError;
  2248. case PropertyID::FontFamily:
  2249. if (auto parsed_value = parse_font_family_value(m_context, component_values))
  2250. return parsed_value.release_nonnull();
  2251. return ParsingResult::SyntaxError;
  2252. case PropertyID::ListStyle:
  2253. if (auto parsed_value = parse_list_style_value(m_context, component_values))
  2254. return parsed_value.release_nonnull();
  2255. return ParsingResult::SyntaxError;
  2256. case PropertyID::Overflow:
  2257. if (auto parsed_value = parse_overflow_value(m_context, component_values))
  2258. return parsed_value.release_nonnull();
  2259. return ParsingResult::SyntaxError;
  2260. case PropertyID::TextDecoration:
  2261. if (auto parsed_value = parse_text_decoration_value(m_context, component_values))
  2262. return parsed_value.release_nonnull();
  2263. return ParsingResult::SyntaxError;
  2264. case PropertyID::Transform:
  2265. if (auto parsed_value = parse_transform_value(m_context, component_values))
  2266. return parsed_value.release_nonnull();
  2267. return ParsingResult::SyntaxError;
  2268. default:
  2269. break;
  2270. }
  2271. if (component_values.size() == 1) {
  2272. if (auto parsed_value = parse_css_value(m_context, component_values.first())) {
  2273. if (property_accepts_value(property_id, *parsed_value))
  2274. return parsed_value.release_nonnull();
  2275. }
  2276. return ParsingResult::SyntaxError;
  2277. }
  2278. // We have multiple values, so treat them as a StyleValueList.
  2279. if (property_maximum_value_count(property_id) > 1) {
  2280. NonnullRefPtrVector<StyleValue> parsed_values;
  2281. for (auto& component_value : component_values) {
  2282. auto parsed_value = parse_css_value(m_context, component_value);
  2283. if (!parsed_value || !property_accepts_value(property_id, *parsed_value))
  2284. return ParsingResult::SyntaxError;
  2285. parsed_values.append(parsed_value.release_nonnull());
  2286. }
  2287. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  2288. return { StyleValueList::create(move(parsed_values)) };
  2289. }
  2290. return ParsingResult::SyntaxError;
  2291. }
  2292. RefPtr<StyleValue> Parser::parse_css_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  2293. {
  2294. if (auto builtin = parse_builtin_value(context, component_value))
  2295. return builtin;
  2296. if (auto dynamic = parse_dynamic_value(context, component_value))
  2297. return dynamic;
  2298. if (auto length = parse_length_value(context, component_value))
  2299. return length;
  2300. if (auto numeric = parse_numeric_value(context, component_value))
  2301. return numeric;
  2302. if (auto identifier = parse_identifier_value(context, component_value))
  2303. return identifier;
  2304. if (auto color = parse_color_value(context, component_value))
  2305. return color;
  2306. if (auto string = parse_string_value(context, component_value))
  2307. return string;
  2308. if (auto image = parse_image_value(context, component_value))
  2309. return image;
  2310. return {};
  2311. }
  2312. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values)
  2313. {
  2314. int a = 0;
  2315. int b = 0;
  2316. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2317. if constexpr (CSS_PARSER_DEBUG) {
  2318. dbgln("Invalid An+B value:");
  2319. values.dump_all_tokens();
  2320. }
  2321. return {};
  2322. };
  2323. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2324. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  2325. values.skip_whitespace();
  2326. if (values.has_next_token()) {
  2327. if constexpr (CSS_PARSER_DEBUG) {
  2328. dbgln("Extra tokens at end of An+B value:");
  2329. values.dump_all_tokens();
  2330. }
  2331. return syntax_error();
  2332. } else {
  2333. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  2334. }
  2335. };
  2336. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  2337. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  2338. };
  2339. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  2340. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  2341. };
  2342. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  2343. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  2344. };
  2345. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  2346. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  2347. };
  2348. auto is_delim = [](StyleComponentValueRule const& value, StringView const& delim) -> bool {
  2349. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  2350. };
  2351. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  2352. if (!value.is(Token::Type::Dimension))
  2353. return false;
  2354. if (value.token().number_type() != Token::NumberType::Integer)
  2355. return false;
  2356. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  2357. return false;
  2358. return true;
  2359. };
  2360. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  2361. if (!value.is(Token::Type::Dimension))
  2362. return false;
  2363. if (value.token().number_type() != Token::NumberType::Integer)
  2364. return false;
  2365. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  2366. return false;
  2367. return true;
  2368. };
  2369. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  2370. if (!value.is(Token::Type::Dimension))
  2371. return false;
  2372. if (value.token().number_type() != Token::NumberType::Integer)
  2373. return false;
  2374. auto dimension_unit = value.token().dimension_unit();
  2375. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2376. return false;
  2377. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  2378. if (!is_ascii_digit(dimension_unit[i]))
  2379. return false;
  2380. }
  2381. return true;
  2382. };
  2383. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2384. if (!value.is(Token::Type::Ident))
  2385. return false;
  2386. auto ident = value.token().ident();
  2387. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2388. return false;
  2389. for (size_t i = 2; i < ident.length(); ++i) {
  2390. if (!is_ascii_digit(ident[i]))
  2391. return false;
  2392. }
  2393. return true;
  2394. };
  2395. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2396. if (!value.is(Token::Type::Ident))
  2397. return false;
  2398. auto ident = value.token().ident();
  2399. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  2400. return false;
  2401. for (size_t i = 3; i < ident.length(); ++i) {
  2402. if (!is_ascii_digit(ident[i]))
  2403. return false;
  2404. }
  2405. return true;
  2406. };
  2407. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  2408. return value.is(Token::Type::Number) && value.token().is(Token::NumberType::Integer);
  2409. };
  2410. auto is_signed_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2411. return is_integer(value) && value.token().is_integer_value_signed();
  2412. };
  2413. auto is_signless_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2414. return is_integer(value) && !value.token().is_integer_value_signed();
  2415. };
  2416. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  2417. // Unfortunately these can't be in the same order as in the spec.
  2418. values.skip_whitespace();
  2419. auto& first_value = values.next_token();
  2420. // odd | even
  2421. if (first_value.is(Token::Type::Ident)) {
  2422. auto ident = first_value.token().ident();
  2423. if (ident.equals_ignoring_case("odd")) {
  2424. a = 2;
  2425. b = 1;
  2426. return make_return_value();
  2427. } else if (ident.equals_ignoring_case("even")) {
  2428. a = 2;
  2429. return make_return_value();
  2430. }
  2431. }
  2432. // <integer>
  2433. if (is_integer(first_value)) {
  2434. b = first_value.token().to_integer();
  2435. return make_return_value();
  2436. }
  2437. // <n-dimension>
  2438. // <n-dimension> <signed-integer>
  2439. // <n-dimension> ['+' | '-'] <signless-integer>
  2440. if (is_n_dimension(first_value)) {
  2441. a = first_value.token().dimension_value_int();
  2442. values.skip_whitespace();
  2443. auto& second_value = values.next_token();
  2444. if (second_value.is(Token::Type::EndOfFile)) {
  2445. // <n-dimension>
  2446. return make_return_value();
  2447. } else if (is_signed_integer(second_value)) {
  2448. // <n-dimension> <signed-integer>
  2449. b = second_value.token().to_integer();
  2450. return make_return_value();
  2451. }
  2452. values.skip_whitespace();
  2453. auto& third_value = values.next_token();
  2454. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2455. // <n-dimension> ['+' | '-'] <signless-integer>
  2456. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2457. return make_return_value();
  2458. }
  2459. return syntax_error();
  2460. }
  2461. // <ndash-dimension> <signless-integer>
  2462. if (is_ndash_dimension(first_value)) {
  2463. values.skip_whitespace();
  2464. auto& second_value = values.next_token();
  2465. if (is_signless_integer(second_value)) {
  2466. a = first_value.token().dimension_value_int();
  2467. b = -second_value.token().to_integer();
  2468. return make_return_value();
  2469. }
  2470. return syntax_error();
  2471. }
  2472. // <ndashdigit-dimension>
  2473. if (is_ndashdigit_dimension(first_value)) {
  2474. auto& dimension = first_value.token();
  2475. a = dimension.dimension_value_int();
  2476. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  2477. if (maybe_b.has_value()) {
  2478. b = maybe_b.value();
  2479. return make_return_value();
  2480. }
  2481. return syntax_error();
  2482. }
  2483. // <dashndashdigit-ident>
  2484. if (is_dashndashdigit_ident(first_value)) {
  2485. a = -1;
  2486. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  2487. if (maybe_b.has_value()) {
  2488. b = maybe_b.value();
  2489. return make_return_value();
  2490. }
  2491. return syntax_error();
  2492. }
  2493. // -n
  2494. // -n <signed-integer>
  2495. // -n ['+' | '-'] <signless-integer>
  2496. if (is_dashn(first_value)) {
  2497. a = -1;
  2498. values.skip_whitespace();
  2499. auto& second_value = values.next_token();
  2500. if (second_value.is(Token::Type::EndOfFile)) {
  2501. // -n
  2502. return make_return_value();
  2503. } else if (is_signed_integer(second_value)) {
  2504. // -n <signed-integer>
  2505. b = second_value.token().to_integer();
  2506. return make_return_value();
  2507. }
  2508. values.skip_whitespace();
  2509. auto& third_value = values.next_token();
  2510. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2511. // -n ['+' | '-'] <signless-integer>
  2512. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2513. return make_return_value();
  2514. }
  2515. return syntax_error();
  2516. }
  2517. // -n- <signless-integer>
  2518. if (is_dashndash(first_value)) {
  2519. values.skip_whitespace();
  2520. auto& second_value = values.next_token();
  2521. if (is_signless_integer(second_value)) {
  2522. a = -1;
  2523. b = -second_value.token().to_integer();
  2524. return make_return_value();
  2525. }
  2526. return syntax_error();
  2527. }
  2528. // All that's left now are these:
  2529. // '+'?† n
  2530. // '+'?† n <signed-integer>
  2531. // '+'?† n ['+' | '-'] <signless-integer>
  2532. // '+'?† n- <signless-integer>
  2533. // '+'?† <ndashdigit-ident>
  2534. // In all of these cases, the + is optional, and has no effect.
  2535. // So, we just skip the +, and carry on.
  2536. if (!is_delim(first_value, "+"sv)) {
  2537. values.reconsume_current_input_token();
  2538. // We do *not* skip whitespace here.
  2539. }
  2540. auto& first_after_plus = values.next_token();
  2541. // '+'?† n
  2542. // '+'?† n <signed-integer>
  2543. // '+'?† n ['+' | '-'] <signless-integer>
  2544. if (is_n(first_after_plus)) {
  2545. a = 1;
  2546. values.skip_whitespace();
  2547. auto& second_value = values.next_token();
  2548. if (second_value.is(Token::Type::EndOfFile)) {
  2549. // '+'?† n
  2550. return make_return_value();
  2551. } else if (is_signed_integer(second_value)) {
  2552. // '+'?† n <signed-integer>
  2553. b = second_value.token().to_integer();
  2554. return make_return_value();
  2555. }
  2556. values.skip_whitespace();
  2557. auto& third_value = values.next_token();
  2558. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2559. // '+'?† n ['+' | '-'] <signless-integer>
  2560. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2561. return make_return_value();
  2562. }
  2563. return syntax_error();
  2564. }
  2565. // '+'?† n- <signless-integer>
  2566. if (is_ndash(first_after_plus)) {
  2567. values.skip_whitespace();
  2568. auto& second_value = values.next_token();
  2569. if (is_signless_integer(second_value)) {
  2570. a = 1;
  2571. b = -second_value.token().to_integer();
  2572. return make_return_value();
  2573. }
  2574. return syntax_error();
  2575. }
  2576. // '+'?† <ndashdigit-ident>
  2577. if (is_ndashdigit_ident(first_after_plus)) {
  2578. a = 1;
  2579. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  2580. if (maybe_b.has_value()) {
  2581. b = maybe_b.value();
  2582. return make_return_value();
  2583. }
  2584. return syntax_error();
  2585. }
  2586. return syntax_error();
  2587. }
  2588. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(ParsingContext const& context, Vector<StyleComponentValueRule> const& values)
  2589. {
  2590. auto tokens = TokenStream(values);
  2591. return parse_calc_sum(context, tokens);
  2592. }
  2593. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2594. {
  2595. auto current_token = tokens.next_token();
  2596. if (current_token.is_block() && current_token.block().is_paren()) {
  2597. auto block_values = TokenStream(current_token.block().values());
  2598. auto parsed_calc_sum = parse_calc_sum(context, block_values);
  2599. if (!parsed_calc_sum)
  2600. return {};
  2601. return (CalculatedStyleValue::CalcValue) { parsed_calc_sum.release_nonnull() };
  2602. }
  2603. if (current_token.is(Token::Type::Number)) {
  2604. auto try_the_number = try_parse_float(current_token.token().number_string_value());
  2605. if (try_the_number.has_value())
  2606. return (CalculatedStyleValue::CalcValue) { try_the_number.value() };
  2607. return {};
  2608. }
  2609. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  2610. auto maybe_length = parse_length(context, current_token);
  2611. if (maybe_length.has_value() && !maybe_length.value().is_undefined())
  2612. return (CalculatedStyleValue::CalcValue) { maybe_length.value() };
  2613. return {};
  2614. }
  2615. return {};
  2616. }
  2617. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2618. {
  2619. // Note: The default value is not used or passed around.
  2620. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  2621. CalculatedStyleValue::CalcProductPartWithOperator::Multiply,
  2622. CalculatedStyleValue::CalcNumberValue(0));
  2623. tokens.skip_whitespace();
  2624. auto& op_token = tokens.peek_token();
  2625. if (!op_token.is(Token::Type::Delim))
  2626. return nullptr;
  2627. auto op = op_token.token().delim();
  2628. if (op == "*"sv) {
  2629. tokens.next_token();
  2630. tokens.skip_whitespace();
  2631. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Multiply;
  2632. auto parsed_calc_value = parse_calc_value(context, tokens);
  2633. if (!parsed_calc_value.has_value())
  2634. return nullptr;
  2635. product_with_operator->value = { parsed_calc_value.release_value() };
  2636. } else if (op == "/"sv) {
  2637. tokens.next_token();
  2638. tokens.skip_whitespace();
  2639. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Divide;
  2640. auto parsed_calc_number_value = parse_calc_number_value(context, tokens);
  2641. if (!parsed_calc_number_value.has_value())
  2642. return nullptr;
  2643. product_with_operator->value = { parsed_calc_number_value.release_value() };
  2644. } else {
  2645. return nullptr;
  2646. }
  2647. return product_with_operator;
  2648. }
  2649. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2650. {
  2651. // Note: The default value is not used or passed around.
  2652. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  2653. CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply,
  2654. CalculatedStyleValue::CalcNumberValue(0));
  2655. tokens.skip_whitespace();
  2656. auto& op_token = tokens.peek_token();
  2657. if (!op_token.is(Token::Type::Delim))
  2658. return nullptr;
  2659. auto op = op_token.token().delim();
  2660. if (op == "*"sv) {
  2661. tokens.next_token();
  2662. tokens.skip_whitespace();
  2663. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply;
  2664. } else if (op == "/"sv) {
  2665. tokens.next_token();
  2666. tokens.skip_whitespace();
  2667. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide;
  2668. } else {
  2669. return nullptr;
  2670. }
  2671. auto parsed_calc_value = parse_calc_number_value(context, tokens);
  2672. if (!parsed_calc_value.has_value())
  2673. return nullptr;
  2674. number_product_with_operator->value = parsed_calc_value.release_value();
  2675. return number_product_with_operator;
  2676. }
  2677. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2678. {
  2679. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  2680. CalculatedStyleValue::CalcNumberValue(0),
  2681. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  2682. auto first_calc_number_value_or_error = parse_calc_number_value(context, tokens);
  2683. if (!first_calc_number_value_or_error.has_value())
  2684. return nullptr;
  2685. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  2686. while (tokens.has_next_token()) {
  2687. auto number_product_with_operator = parse_calc_number_product_part_with_operator(context, tokens);
  2688. if (!number_product_with_operator)
  2689. break;
  2690. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  2691. }
  2692. return calc_number_product;
  2693. }
  2694. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2695. {
  2696. if (!(tokens.peek_token().is(Token::Type::Delim)
  2697. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  2698. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  2699. return nullptr;
  2700. auto& token = tokens.next_token();
  2701. tokens.skip_whitespace();
  2702. CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation op;
  2703. auto delim = token.token().delim();
  2704. if (delim == "+"sv)
  2705. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Add;
  2706. else if (delim == "-"sv)
  2707. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Subtract;
  2708. else
  2709. return nullptr;
  2710. auto calc_number_product = parse_calc_number_product(context, tokens);
  2711. if (!calc_number_product)
  2712. return nullptr;
  2713. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  2714. }
  2715. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2716. {
  2717. auto first_calc_number_product_or_error = parse_calc_number_product(context, tokens);
  2718. if (!first_calc_number_product_or_error)
  2719. return nullptr;
  2720. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  2721. while (tokens.has_next_token()) {
  2722. auto calc_sum_part = parse_calc_number_sum_part_with_operator(context, tokens);
  2723. if (!calc_sum_part)
  2724. return nullptr;
  2725. additional.append(calc_sum_part.release_nonnull());
  2726. }
  2727. tokens.skip_whitespace();
  2728. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  2729. return calc_number_sum;
  2730. }
  2731. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2732. {
  2733. auto& first = tokens.peek_token();
  2734. if (first.is_block() && first.block().is_paren()) {
  2735. tokens.next_token();
  2736. auto block_values = TokenStream(first.block().values());
  2737. auto calc_number_sum = parse_calc_number_sum(context, block_values);
  2738. if (calc_number_sum)
  2739. return { calc_number_sum.release_nonnull() };
  2740. }
  2741. if (!first.is(Token::Type::Number))
  2742. return {};
  2743. tokens.next_token();
  2744. auto try_the_number = try_parse_float(first.token().number_string_value());
  2745. if (!try_the_number.has_value())
  2746. return {};
  2747. return try_the_number.value();
  2748. }
  2749. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2750. {
  2751. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  2752. CalculatedStyleValue::CalcValue(0),
  2753. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  2754. auto first_calc_value_or_error = parse_calc_value(context, tokens);
  2755. if (!first_calc_value_or_error.has_value())
  2756. return nullptr;
  2757. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  2758. while (tokens.has_next_token()) {
  2759. auto product_with_operator = parse_calc_product_part_with_operator(context, tokens);
  2760. if (!product_with_operator)
  2761. break;
  2762. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  2763. }
  2764. return calc_product;
  2765. }
  2766. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2767. {
  2768. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  2769. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  2770. if (!(tokens.peek_token().is(Token::Type::Delim)
  2771. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  2772. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  2773. return nullptr;
  2774. auto& token = tokens.next_token();
  2775. tokens.skip_whitespace();
  2776. CalculatedStyleValue::CalcSumPartWithOperator::Operation op;
  2777. auto delim = token.token().delim();
  2778. if (delim == "+"sv)
  2779. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add;
  2780. else if (delim == "-"sv)
  2781. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract;
  2782. else
  2783. return nullptr;
  2784. auto calc_product = parse_calc_product(context, tokens);
  2785. if (!calc_product)
  2786. return nullptr;
  2787. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  2788. };
  2789. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2790. {
  2791. auto parsed_calc_product = parse_calc_product(context, tokens);
  2792. if (!parsed_calc_product)
  2793. return nullptr;
  2794. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  2795. while (tokens.has_next_token()) {
  2796. auto calc_sum_part = parse_calc_sum_part_with_operator(context, tokens);
  2797. if (!calc_sum_part)
  2798. return nullptr;
  2799. additional.append(calc_sum_part.release_nonnull());
  2800. }
  2801. tokens.skip_whitespace();
  2802. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  2803. }
  2804. bool Parser::has_ignored_vendor_prefix(StringView const& string)
  2805. {
  2806. if (!string.starts_with('-'))
  2807. return false;
  2808. if (string.starts_with("--"))
  2809. return false;
  2810. if (string.starts_with("-libweb-"))
  2811. return false;
  2812. return true;
  2813. }
  2814. }
  2815. namespace Web {
  2816. RefPtr<CSS::CSSStyleSheet> parse_css(CSS::ParsingContext const& context, StringView const& css)
  2817. {
  2818. if (css.is_empty())
  2819. return CSS::CSSStyleSheet::create({});
  2820. CSS::Parser parser(context, css);
  2821. return parser.parse_as_stylesheet();
  2822. }
  2823. RefPtr<CSS::PropertyOwningCSSStyleDeclaration> parse_css_declaration(CSS::ParsingContext const& context, StringView const& css)
  2824. {
  2825. if (css.is_empty())
  2826. return CSS::PropertyOwningCSSStyleDeclaration::create({}, {});
  2827. CSS::Parser parser(context, css);
  2828. return parser.parse_as_list_of_declarations();
  2829. }
  2830. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView const& string, CSS::PropertyID property_id)
  2831. {
  2832. if (string.is_empty())
  2833. return {};
  2834. CSS::Parser parser(context, string);
  2835. return parser.parse_as_css_value(property_id);
  2836. }
  2837. RefPtr<CSS::CSSRule> parse_css_rule(CSS::ParsingContext const& context, StringView css_text)
  2838. {
  2839. CSS::Parser parser(context, css_text);
  2840. return parser.parse_as_rule();
  2841. }
  2842. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView const& selector_text)
  2843. {
  2844. CSS::Parser parser(context, selector_text);
  2845. return parser.parse_as_selector();
  2846. }
  2847. RefPtr<CSS::MediaQuery> parse_media_query(CSS::ParsingContext const& context, StringView const& string)
  2848. {
  2849. CSS::Parser parser(context, string);
  2850. return parser.parse_as_media_query();
  2851. }
  2852. NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::ParsingContext const& context, StringView const& string)
  2853. {
  2854. CSS::Parser parser(context, string);
  2855. return parser.parse_as_media_query_list();
  2856. }
  2857. RefPtr<CSS::StyleValue> parse_html_length(DOM::Document const& document, StringView const& string)
  2858. {
  2859. auto integer = string.to_int();
  2860. if (integer.has_value())
  2861. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  2862. // FIXME: The const_cast is a hack.
  2863. return parse_css_value(CSS::ParsingContext(const_cast<DOM::Document&>(document)), string);
  2864. }
  2865. }