CSSParser.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/HashMap.h>
  27. #include <LibWeb/CSS/CSSRule.h>
  28. #include <LibWeb/CSS/Parser/CSSParser.h>
  29. #include <LibWeb/CSS/PropertyID.h>
  30. #include <LibWeb/CSS/StyleRule.h>
  31. #include <LibWeb/CSS/StyleSheet.h>
  32. #include <LibWeb/DOM/Document.h>
  33. #include <ctype.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #define PARSE_VERIFY(x) \
  37. if (!(x)) { \
  38. dbgln("CSS PARSER ASSERTION FAILED: {}", #x); \
  39. dbgln("At character# {} in CSS: _{}_", index, css); \
  40. VERIFY_NOT_REACHED(); \
  41. }
  42. #define PARSE_ERROR() \
  43. do { \
  44. dbgln("CSS parse error"); \
  45. } while (0)
  46. namespace Web {
  47. namespace CSS {
  48. ParsingContext::ParsingContext()
  49. {
  50. }
  51. ParsingContext::ParsingContext(const DOM::Document& document)
  52. : m_document(&document)
  53. {
  54. }
  55. ParsingContext::ParsingContext(const DOM::ParentNode& parent_node)
  56. : m_document(&parent_node.document())
  57. {
  58. }
  59. bool ParsingContext::in_quirks_mode() const
  60. {
  61. return m_document ? m_document->in_quirks_mode() : false;
  62. }
  63. }
  64. static Optional<Color> parse_css_color(const CSS::ParsingContext&, const StringView& view)
  65. {
  66. if (view.equals_ignoring_case("transparent"))
  67. return Color::from_rgba(0x00000000);
  68. auto color = Color::from_string(view.to_string().to_lowercase());
  69. if (color.has_value())
  70. return color;
  71. return {};
  72. }
  73. static Optional<float> try_parse_float(const StringView& string)
  74. {
  75. const char* str = string.characters_without_null_termination();
  76. size_t len = string.length();
  77. size_t weight = 1;
  78. int exp_val = 0;
  79. float value = 0.0f;
  80. float fraction = 0.0f;
  81. bool has_sign = false;
  82. bool is_negative = false;
  83. bool is_fractional = false;
  84. bool is_scientific = false;
  85. if (str[0] == '-') {
  86. is_negative = true;
  87. has_sign = true;
  88. }
  89. if (str[0] == '+') {
  90. has_sign = true;
  91. }
  92. for (size_t i = has_sign; i < len; i++) {
  93. // Looks like we're about to start working on the fractional part
  94. if (str[i] == '.') {
  95. is_fractional = true;
  96. continue;
  97. }
  98. if (str[i] == 'e' || str[i] == 'E') {
  99. if (str[i + 1] == '-' || str[i + 1] == '+')
  100. exp_val = atoi(str + i + 2);
  101. else
  102. exp_val = atoi(str + i + 1);
  103. is_scientific = true;
  104. continue;
  105. }
  106. if (str[i] < '0' || str[i] > '9' || exp_val != 0) {
  107. return {};
  108. continue;
  109. }
  110. if (is_fractional) {
  111. fraction *= 10;
  112. fraction += str[i] - '0';
  113. weight *= 10;
  114. } else {
  115. value = value * 10;
  116. value += str[i] - '0';
  117. }
  118. }
  119. fraction /= weight;
  120. value += fraction;
  121. if (is_scientific) {
  122. bool divide = exp_val < 0;
  123. if (divide)
  124. exp_val *= -1;
  125. for (int i = 0; i < exp_val; i++) {
  126. if (divide)
  127. value /= 10;
  128. else
  129. value *= 10;
  130. }
  131. }
  132. return is_negative ? -value : value;
  133. }
  134. static CSS::Length parse_length(const CSS::ParsingContext& context, const StringView& view, bool& is_bad_length)
  135. {
  136. CSS::Length::Type type = CSS::Length::Type::Undefined;
  137. Optional<float> value;
  138. if (view.ends_with('%')) {
  139. type = CSS::Length::Type::Percentage;
  140. value = try_parse_float(view.substring_view(0, view.length() - 1));
  141. } else if (view.ends_with("px", CaseSensitivity::CaseInsensitive)) {
  142. type = CSS::Length::Type::Px;
  143. value = try_parse_float(view.substring_view(0, view.length() - 2));
  144. } else if (view.ends_with("pt", CaseSensitivity::CaseInsensitive)) {
  145. type = CSS::Length::Type::Pt;
  146. value = try_parse_float(view.substring_view(0, view.length() - 2));
  147. } else if (view.ends_with("pc", CaseSensitivity::CaseInsensitive)) {
  148. type = CSS::Length::Type::Pc;
  149. value = try_parse_float(view.substring_view(0, view.length() - 2));
  150. } else if (view.ends_with("mm", CaseSensitivity::CaseInsensitive)) {
  151. type = CSS::Length::Type::Mm;
  152. value = try_parse_float(view.substring_view(0, view.length() - 2));
  153. } else if (view.ends_with("rem", CaseSensitivity::CaseInsensitive)) {
  154. type = CSS::Length::Type::Rem;
  155. value = try_parse_float(view.substring_view(0, view.length() - 3));
  156. } else if (view.ends_with("em", CaseSensitivity::CaseInsensitive)) {
  157. type = CSS::Length::Type::Em;
  158. value = try_parse_float(view.substring_view(0, view.length() - 2));
  159. } else if (view.ends_with("ex", CaseSensitivity::CaseInsensitive)) {
  160. type = CSS::Length::Type::Ex;
  161. value = try_parse_float(view.substring_view(0, view.length() - 2));
  162. } else if (view.ends_with("vw", CaseSensitivity::CaseInsensitive)) {
  163. type = CSS::Length::Type::Vw;
  164. value = try_parse_float(view.substring_view(0, view.length() - 2));
  165. } else if (view.ends_with("vh", CaseSensitivity::CaseInsensitive)) {
  166. type = CSS::Length::Type::Vh;
  167. value = try_parse_float(view.substring_view(0, view.length() - 2));
  168. } else if (view.ends_with("vmax", CaseSensitivity::CaseInsensitive)) {
  169. type = CSS::Length::Type::Vmax;
  170. value = try_parse_float(view.substring_view(0, view.length() - 4));
  171. } else if (view.ends_with("vmin", CaseSensitivity::CaseInsensitive)) {
  172. type = CSS::Length::Type::Vmin;
  173. value = try_parse_float(view.substring_view(0, view.length() - 4));
  174. } else if (view.ends_with("cm", CaseSensitivity::CaseInsensitive)) {
  175. type = CSS::Length::Type::Cm;
  176. value = try_parse_float(view.substring_view(0, view.length() - 2));
  177. } else if (view.ends_with("in", CaseSensitivity::CaseInsensitive)) {
  178. type = CSS::Length::Type::In;
  179. value = try_parse_float(view.substring_view(0, view.length() - 2));
  180. } else if (view.ends_with("Q", CaseSensitivity::CaseInsensitive)) {
  181. type = CSS::Length::Type::Q;
  182. value = try_parse_float(view.substring_view(0, view.length() - 1));
  183. } else if (view == "0") {
  184. type = CSS::Length::Type::Px;
  185. value = 0;
  186. } else if (context.in_quirks_mode()) {
  187. type = CSS::Length::Type::Px;
  188. value = try_parse_float(view);
  189. } else {
  190. value = try_parse_float(view);
  191. if (value.has_value())
  192. is_bad_length = true;
  193. }
  194. if (!value.has_value())
  195. return {};
  196. return CSS::Length(value.value(), type);
  197. }
  198. static bool takes_integer_value(CSS::PropertyID property_id)
  199. {
  200. return property_id == CSS::PropertyID::ZIndex || property_id == CSS::PropertyID::FontWeight;
  201. }
  202. RefPtr<CSS::StyleValue> parse_css_value(const CSS::ParsingContext& context, const StringView& string, CSS::PropertyID property_id)
  203. {
  204. bool is_bad_length = false;
  205. if (takes_integer_value(property_id)) {
  206. auto integer = string.to_int();
  207. if (integer.has_value())
  208. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  209. }
  210. auto length = parse_length(context, string, is_bad_length);
  211. if (is_bad_length)
  212. return nullptr;
  213. if (!length.is_undefined())
  214. return CSS::LengthStyleValue::create(length);
  215. if (string.equals_ignoring_case("inherit"))
  216. return CSS::InheritStyleValue::create();
  217. if (string.equals_ignoring_case("initial"))
  218. return CSS::InitialStyleValue::create();
  219. if (string.equals_ignoring_case("auto"))
  220. return CSS::LengthStyleValue::create(CSS::Length::make_auto());
  221. auto value_id = CSS::value_id_from_string(string);
  222. if (value_id != CSS::ValueID::Invalid)
  223. return CSS::IdentifierStyleValue::create(value_id);
  224. auto color = parse_css_color(context, string);
  225. if (color.has_value())
  226. return CSS::ColorStyleValue::create(color.value());
  227. return CSS::StringStyleValue::create(string);
  228. }
  229. RefPtr<CSS::LengthStyleValue> parse_line_width(const CSS::ParsingContext& context, const StringView& part)
  230. {
  231. auto value = parse_css_value(context, part);
  232. if (value && value->is_length())
  233. return static_ptr_cast<CSS::LengthStyleValue>(value);
  234. return nullptr;
  235. }
  236. RefPtr<CSS::ColorStyleValue> parse_color(const CSS::ParsingContext& context, const StringView& part)
  237. {
  238. auto value = parse_css_value(context, part);
  239. if (value && value->is_color())
  240. return static_ptr_cast<CSS::ColorStyleValue>(value);
  241. return nullptr;
  242. }
  243. RefPtr<CSS::StringStyleValue> parse_line_style(const CSS::ParsingContext& context, const StringView& part)
  244. {
  245. auto parsed_value = parse_css_value(context, part);
  246. if (!parsed_value || !parsed_value->is_string())
  247. return nullptr;
  248. auto value = static_ptr_cast<CSS::StringStyleValue>(parsed_value);
  249. if (value->to_string() == "dotted")
  250. return value;
  251. if (value->to_string() == "dashed")
  252. return value;
  253. if (value->to_string() == "solid")
  254. return value;
  255. if (value->to_string() == "double")
  256. return value;
  257. if (value->to_string() == "groove")
  258. return value;
  259. if (value->to_string() == "ridge")
  260. return value;
  261. return nullptr;
  262. }
  263. class CSSParser {
  264. public:
  265. CSSParser(const CSS::ParsingContext& context, const StringView& input)
  266. : m_context(context)
  267. , css(input)
  268. {
  269. }
  270. bool next_is(const char* str) const
  271. {
  272. size_t len = strlen(str);
  273. for (size_t i = 0; i < len; ++i) {
  274. if (peek(i) != str[i])
  275. return false;
  276. }
  277. return true;
  278. }
  279. char peek(size_t offset = 0) const
  280. {
  281. if ((index + offset) < css.length())
  282. return css[index + offset];
  283. return 0;
  284. }
  285. bool consume_specific(char ch)
  286. {
  287. if (peek() != ch) {
  288. dbgln("CSSParser: Peeked '{:c}' wanted specific '{:c}'", peek(), ch);
  289. }
  290. if (!peek()) {
  291. PARSE_ERROR();
  292. return false;
  293. }
  294. if (peek() != ch) {
  295. PARSE_ERROR();
  296. ++index;
  297. return false;
  298. }
  299. ++index;
  300. return true;
  301. }
  302. char consume_one()
  303. {
  304. PARSE_VERIFY(index < css.length());
  305. return css[index++];
  306. };
  307. bool consume_whitespace_or_comments()
  308. {
  309. size_t original_index = index;
  310. bool in_comment = false;
  311. for (; index < css.length(); ++index) {
  312. char ch = peek();
  313. if (isspace(ch))
  314. continue;
  315. if (!in_comment && ch == '/' && peek(1) == '*') {
  316. in_comment = true;
  317. ++index;
  318. continue;
  319. }
  320. if (in_comment && ch == '*' && peek(1) == '/') {
  321. in_comment = false;
  322. ++index;
  323. continue;
  324. }
  325. if (in_comment)
  326. continue;
  327. break;
  328. }
  329. return original_index != index;
  330. }
  331. bool is_valid_selector_char(char ch) const
  332. {
  333. return isalnum(ch) || ch == '-' || ch == '_' || ch == '(' || ch == ')' || ch == '@';
  334. }
  335. bool is_combinator(char ch) const
  336. {
  337. return ch == '~' || ch == '>' || ch == '+';
  338. }
  339. Optional<CSS::Selector::SimpleSelector> parse_simple_selector()
  340. {
  341. auto index_at_start = index;
  342. if (consume_whitespace_or_comments())
  343. return {};
  344. if (!peek() || peek() == '{' || peek() == ',' || is_combinator(peek()))
  345. return {};
  346. CSS::Selector::SimpleSelector::Type type;
  347. if (peek() == '*') {
  348. type = CSS::Selector::SimpleSelector::Type::Universal;
  349. consume_one();
  350. return CSS::Selector::SimpleSelector {
  351. type,
  352. CSS::Selector::SimpleSelector::PseudoClass::None,
  353. CSS::Selector::SimpleSelector::PseudoElement::None,
  354. String(),
  355. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  356. String(),
  357. String()
  358. };
  359. }
  360. if (peek() == '.') {
  361. type = CSS::Selector::SimpleSelector::Type::Class;
  362. consume_one();
  363. } else if (peek() == '#') {
  364. type = CSS::Selector::SimpleSelector::Type::Id;
  365. consume_one();
  366. } else if (isalpha(peek())) {
  367. type = CSS::Selector::SimpleSelector::Type::TagName;
  368. } else {
  369. type = CSS::Selector::SimpleSelector::Type::Universal;
  370. }
  371. if (type != CSS::Selector::SimpleSelector::Type::Universal) {
  372. while (is_valid_selector_char(peek()))
  373. buffer.append(consume_one());
  374. PARSE_VERIFY(!buffer.is_null());
  375. }
  376. auto value = String::copy(buffer);
  377. if (type == CSS::Selector::SimpleSelector::Type::TagName) {
  378. // Some stylesheets use uppercase tag names, so here's a hack to just lowercase them internally.
  379. value = value.to_lowercase();
  380. }
  381. CSS::Selector::SimpleSelector simple_selector {
  382. type,
  383. CSS::Selector::SimpleSelector::PseudoClass::None,
  384. CSS::Selector::SimpleSelector::PseudoElement::None,
  385. value,
  386. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  387. String(),
  388. String()
  389. };
  390. buffer.clear();
  391. if (peek() == '[') {
  392. CSS::Selector::SimpleSelector::AttributeMatchType attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::HasAttribute;
  393. String attribute_name;
  394. String attribute_value;
  395. bool in_value = false;
  396. consume_specific('[');
  397. char expected_end_of_attribute_selector = ']';
  398. while (peek() != expected_end_of_attribute_selector) {
  399. char ch = consume_one();
  400. if (ch == '=' || (ch == '~' && peek() == '=')) {
  401. if (ch == '=') {
  402. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::ExactValueMatch;
  403. } else if (ch == '~') {
  404. consume_one();
  405. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::Contains;
  406. }
  407. attribute_name = String::copy(buffer);
  408. buffer.clear();
  409. in_value = true;
  410. consume_whitespace_or_comments();
  411. if (peek() == '\'') {
  412. expected_end_of_attribute_selector = '\'';
  413. consume_one();
  414. } else if (peek() == '"') {
  415. expected_end_of_attribute_selector = '"';
  416. consume_one();
  417. }
  418. continue;
  419. }
  420. // FIXME: This is a hack that will go away when we replace this with a big boy CSS parser.
  421. if (ch == '\\')
  422. ch = consume_one();
  423. buffer.append(ch);
  424. }
  425. if (in_value)
  426. attribute_value = String::copy(buffer);
  427. else
  428. attribute_name = String::copy(buffer);
  429. buffer.clear();
  430. simple_selector.attribute_match_type = attribute_match_type;
  431. simple_selector.attribute_name = attribute_name;
  432. simple_selector.attribute_value = attribute_value;
  433. if (expected_end_of_attribute_selector != ']') {
  434. if (!consume_specific(expected_end_of_attribute_selector))
  435. return {};
  436. }
  437. consume_whitespace_or_comments();
  438. if (!consume_specific(']'))
  439. return {};
  440. }
  441. if (peek() == ':') {
  442. // FIXME: Implement pseudo elements.
  443. [[maybe_unused]] bool is_pseudo_element = false;
  444. consume_one();
  445. if (peek() == ':') {
  446. is_pseudo_element = true;
  447. consume_one();
  448. }
  449. if (next_is("not")) {
  450. buffer.append(consume_one());
  451. buffer.append(consume_one());
  452. buffer.append(consume_one());
  453. if (!consume_specific('('))
  454. return {};
  455. buffer.append('(');
  456. while (peek() != ')')
  457. buffer.append(consume_one());
  458. if (!consume_specific(')'))
  459. return {};
  460. buffer.append(')');
  461. } else {
  462. while (is_valid_selector_char(peek()))
  463. buffer.append(consume_one());
  464. }
  465. auto pseudo_name = String::copy(buffer);
  466. buffer.clear();
  467. // Ignore for now, otherwise we produce a "false positive" selector
  468. // and apply styles to the element itself, not its pseudo element
  469. if (is_pseudo_element)
  470. return {};
  471. if (pseudo_name.equals_ignoring_case("link"))
  472. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Link;
  473. else if (pseudo_name.equals_ignoring_case("visited"))
  474. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Visited;
  475. else if (pseudo_name.equals_ignoring_case("hover"))
  476. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Hover;
  477. else if (pseudo_name.equals_ignoring_case("focus"))
  478. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Focus;
  479. else if (pseudo_name.equals_ignoring_case("first-child"))
  480. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::FirstChild;
  481. else if (pseudo_name.equals_ignoring_case("last-child"))
  482. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::LastChild;
  483. else if (pseudo_name.equals_ignoring_case("only-child"))
  484. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::OnlyChild;
  485. else if (pseudo_name.equals_ignoring_case("empty"))
  486. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Empty;
  487. else if (pseudo_name.equals_ignoring_case("root"))
  488. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Root;
  489. else if (pseudo_name.equals_ignoring_case("before"))
  490. simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::Before;
  491. else if (pseudo_name.equals_ignoring_case("after"))
  492. simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::After;
  493. }
  494. if (index == index_at_start) {
  495. // We consumed nothing.
  496. return {};
  497. }
  498. return simple_selector;
  499. }
  500. Optional<CSS::Selector::ComplexSelector> parse_complex_selector()
  501. {
  502. auto relation = CSS::Selector::ComplexSelector::Relation::Descendant;
  503. if (peek() == '{' || peek() == ',')
  504. return {};
  505. if (is_combinator(peek())) {
  506. switch (peek()) {
  507. case '>':
  508. relation = CSS::Selector::ComplexSelector::Relation::ImmediateChild;
  509. break;
  510. case '+':
  511. relation = CSS::Selector::ComplexSelector::Relation::AdjacentSibling;
  512. break;
  513. case '~':
  514. relation = CSS::Selector::ComplexSelector::Relation::GeneralSibling;
  515. break;
  516. }
  517. consume_one();
  518. consume_whitespace_or_comments();
  519. }
  520. consume_whitespace_or_comments();
  521. Vector<CSS::Selector::SimpleSelector> simple_selectors;
  522. for (;;) {
  523. auto component = parse_simple_selector();
  524. if (!component.has_value())
  525. break;
  526. simple_selectors.append(component.value());
  527. // If this assert triggers, we're most likely up to no good.
  528. PARSE_VERIFY(simple_selectors.size() < 100);
  529. }
  530. if (simple_selectors.is_empty())
  531. return {};
  532. return CSS::Selector::ComplexSelector { relation, move(simple_selectors) };
  533. }
  534. void parse_selector()
  535. {
  536. Vector<CSS::Selector::ComplexSelector> complex_selectors;
  537. for (;;) {
  538. auto index_before = index;
  539. auto complex_selector = parse_complex_selector();
  540. if (complex_selector.has_value())
  541. complex_selectors.append(complex_selector.value());
  542. consume_whitespace_or_comments();
  543. if (!peek() || peek() == ',' || peek() == '{')
  544. break;
  545. // HACK: If we didn't move forward, just let go.
  546. if (index == index_before)
  547. break;
  548. }
  549. if (complex_selectors.is_empty())
  550. return;
  551. complex_selectors.first().relation = CSS::Selector::ComplexSelector::Relation::None;
  552. current_rule.selectors.append(CSS::Selector(move(complex_selectors)));
  553. }
  554. Optional<CSS::Selector> parse_individual_selector()
  555. {
  556. parse_selector();
  557. if (current_rule.selectors.is_empty())
  558. return {};
  559. return current_rule.selectors.last();
  560. }
  561. void parse_selector_list()
  562. {
  563. for (;;) {
  564. auto index_before = index;
  565. parse_selector();
  566. consume_whitespace_or_comments();
  567. if (peek() == ',') {
  568. consume_one();
  569. continue;
  570. }
  571. if (peek() == '{')
  572. break;
  573. // HACK: If we didn't move forward, just let go.
  574. if (index_before == index)
  575. break;
  576. }
  577. }
  578. bool is_valid_property_name_char(char ch) const
  579. {
  580. return ch && !isspace(ch) && ch != ':';
  581. }
  582. bool is_valid_property_value_char(char ch) const
  583. {
  584. return ch && ch != '!' && ch != ';' && ch != '}';
  585. }
  586. struct ValueAndImportant {
  587. String value;
  588. bool important { false };
  589. };
  590. ValueAndImportant consume_css_value()
  591. {
  592. buffer.clear();
  593. int paren_nesting_level = 0;
  594. bool important = false;
  595. for (;;) {
  596. char ch = peek();
  597. if (ch == '(') {
  598. ++paren_nesting_level;
  599. buffer.append(consume_one());
  600. continue;
  601. }
  602. if (ch == ')') {
  603. PARSE_VERIFY(paren_nesting_level > 0);
  604. --paren_nesting_level;
  605. buffer.append(consume_one());
  606. continue;
  607. }
  608. if (paren_nesting_level > 0) {
  609. buffer.append(consume_one());
  610. continue;
  611. }
  612. if (next_is("!important")) {
  613. consume_specific('!');
  614. consume_specific('i');
  615. consume_specific('m');
  616. consume_specific('p');
  617. consume_specific('o');
  618. consume_specific('r');
  619. consume_specific('t');
  620. consume_specific('a');
  621. consume_specific('n');
  622. consume_specific('t');
  623. important = true;
  624. continue;
  625. }
  626. if (next_is("/*")) {
  627. consume_whitespace_or_comments();
  628. continue;
  629. }
  630. if (!ch)
  631. break;
  632. if (ch == '\\') {
  633. consume_one();
  634. buffer.append(consume_one());
  635. continue;
  636. }
  637. if (ch == '}')
  638. break;
  639. if (ch == ';')
  640. break;
  641. buffer.append(consume_one());
  642. }
  643. // Remove trailing whitespace.
  644. while (!buffer.is_empty() && isspace(buffer.last()))
  645. buffer.take_last();
  646. auto string = String::copy(buffer);
  647. buffer.clear();
  648. return { string, important };
  649. }
  650. Optional<CSS::StyleProperty> parse_property()
  651. {
  652. consume_whitespace_or_comments();
  653. if (peek() == ';') {
  654. consume_one();
  655. return {};
  656. }
  657. if (peek() == '}')
  658. return {};
  659. buffer.clear();
  660. while (is_valid_property_name_char(peek()))
  661. buffer.append(consume_one());
  662. auto property_name = String::copy(buffer);
  663. buffer.clear();
  664. consume_whitespace_or_comments();
  665. if (!consume_specific(':'))
  666. return {};
  667. consume_whitespace_or_comments();
  668. auto [property_value, important] = consume_css_value();
  669. consume_whitespace_or_comments();
  670. if (peek() && peek() != '}') {
  671. if (!consume_specific(';'))
  672. return {};
  673. }
  674. auto property_id = CSS::property_id_from_string(property_name);
  675. if (property_id == CSS::PropertyID::Invalid) {
  676. dbgln("CSSParser: Unrecognized property '{}'", property_name);
  677. }
  678. auto value = parse_css_value(m_context, property_value, property_id);
  679. if (!value)
  680. return {};
  681. return CSS::StyleProperty { property_id, value.release_nonnull(), important };
  682. }
  683. void parse_declaration()
  684. {
  685. for (;;) {
  686. auto property = parse_property();
  687. if (property.has_value())
  688. current_rule.properties.append(property.value());
  689. consume_whitespace_or_comments();
  690. if (!peek() || peek() == '}')
  691. break;
  692. }
  693. }
  694. void parse_rule()
  695. {
  696. consume_whitespace_or_comments();
  697. if (!peek())
  698. return;
  699. // FIXME: We ignore @-rules for now.
  700. if (peek() == '@') {
  701. while (peek() != '{')
  702. consume_one();
  703. int level = 0;
  704. for (;;) {
  705. auto ch = consume_one();
  706. if (ch == '{') {
  707. ++level;
  708. } else if (ch == '}') {
  709. --level;
  710. if (level == 0)
  711. break;
  712. }
  713. }
  714. consume_whitespace_or_comments();
  715. return;
  716. }
  717. parse_selector_list();
  718. if (!consume_specific('{')) {
  719. PARSE_ERROR();
  720. return;
  721. }
  722. parse_declaration();
  723. if (!consume_specific('}')) {
  724. PARSE_ERROR();
  725. return;
  726. }
  727. rules.append(CSS::StyleRule::create(move(current_rule.selectors), CSS::StyleDeclaration::create(move(current_rule.properties))));
  728. consume_whitespace_or_comments();
  729. }
  730. RefPtr<CSS::StyleSheet> parse_sheet()
  731. {
  732. if (peek(0) == (char)0xef && peek(1) == (char)0xbb && peek(2) == (char)0xbf) {
  733. // HACK: Skip UTF-8 BOM.
  734. index += 3;
  735. }
  736. while (peek()) {
  737. parse_rule();
  738. }
  739. return CSS::StyleSheet::create(move(rules));
  740. }
  741. RefPtr<CSS::StyleDeclaration> parse_standalone_declaration()
  742. {
  743. consume_whitespace_or_comments();
  744. for (;;) {
  745. auto property = parse_property();
  746. if (property.has_value())
  747. current_rule.properties.append(property.value());
  748. consume_whitespace_or_comments();
  749. if (!peek())
  750. break;
  751. }
  752. return CSS::StyleDeclaration::create(move(current_rule.properties));
  753. }
  754. private:
  755. CSS::ParsingContext m_context;
  756. NonnullRefPtrVector<CSS::CSSRule> rules;
  757. struct CurrentRule {
  758. Vector<CSS::Selector> selectors;
  759. Vector<CSS::StyleProperty> properties;
  760. };
  761. CurrentRule current_rule;
  762. Vector<char> buffer;
  763. size_t index = 0;
  764. StringView css;
  765. };
  766. Optional<CSS::Selector> parse_selector(const CSS::ParsingContext& context, const StringView& selector_text)
  767. {
  768. CSSParser parser(context, selector_text);
  769. return parser.parse_individual_selector();
  770. }
  771. RefPtr<CSS::StyleSheet> parse_css(const CSS::ParsingContext& context, const StringView& css)
  772. {
  773. if (css.is_empty())
  774. return CSS::StyleSheet::create({});
  775. CSSParser parser(context, css);
  776. return parser.parse_sheet();
  777. }
  778. RefPtr<CSS::StyleDeclaration> parse_css_declaration(const CSS::ParsingContext& context, const StringView& css)
  779. {
  780. if (css.is_empty())
  781. return CSS::StyleDeclaration::create({});
  782. CSSParser parser(context, css);
  783. return parser.parse_standalone_declaration();
  784. }
  785. RefPtr<CSS::StyleValue> parse_html_length(const DOM::Document& document, const StringView& string)
  786. {
  787. auto integer = string.to_int();
  788. if (integer.has_value())
  789. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  790. return parse_css_value(CSS::ParsingContext(document), string);
  791. }
  792. }