CSSParser.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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/PropertyID.h>
  28. #include <LibWeb/CSS/StyleSheet.h>
  29. #include <LibWeb/Parser/CSSParser.h>
  30. #include <ctype.h>
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #define PARSE_ASSERT(x) \
  34. if (!(x)) { \
  35. dbg() << "CSS PARSER ASSERTION FAILED: " << #x; \
  36. dbg() << "At character# " << index << " in CSS: _" << css << "_"; \
  37. ASSERT_NOT_REACHED(); \
  38. }
  39. namespace Web {
  40. static Optional<Color> parse_css_color(const StringView& view)
  41. {
  42. auto color = Color::from_string(view.to_string().to_lowercase());
  43. if (color.has_value())
  44. return color;
  45. return {};
  46. }
  47. static Optional<float> try_parse_float(const StringView& string)
  48. {
  49. const char* str = string.characters_without_null_termination();
  50. size_t len = string.length();
  51. size_t weight = 1;
  52. int exp_val = 0;
  53. float value = 0.0f;
  54. float fraction = 0.0f;
  55. bool has_sign = false;
  56. bool is_negative = false;
  57. bool is_fractional = false;
  58. bool is_scientific = false;
  59. if (str[0] == '-') {
  60. is_negative = true;
  61. has_sign = true;
  62. }
  63. if (str[0] == '+') {
  64. has_sign = true;
  65. }
  66. for (size_t i = has_sign; i < len; i++) {
  67. // Looks like we're about to start working on the fractional part
  68. if (str[i] == '.') {
  69. is_fractional = true;
  70. continue;
  71. }
  72. if (str[i] == 'e' || str[i] == 'E') {
  73. if (str[i + 1] == '-' || str[i + 1] == '+')
  74. exp_val = atoi(str + i + 2);
  75. else
  76. exp_val = atoi(str + i + 1);
  77. is_scientific = true;
  78. continue;
  79. }
  80. if (str[i] < '0' || str[i] > '9' || exp_val != 0) {
  81. return {};
  82. continue;
  83. }
  84. if (is_fractional) {
  85. fraction *= 10;
  86. fraction += str[i] - '0';
  87. weight *= 10;
  88. } else {
  89. value = value * 10;
  90. value += str[i] - '0';
  91. }
  92. }
  93. fraction /= weight;
  94. value += fraction;
  95. if (is_scientific) {
  96. bool divide = exp_val < 0;
  97. if (divide)
  98. exp_val *= -1;
  99. for (int i = 0; i < exp_val; i++) {
  100. if (divide)
  101. value /= 10;
  102. else
  103. value *= 10;
  104. }
  105. }
  106. return is_negative ? -value : value;
  107. }
  108. static Optional<float> parse_number(const StringView& view)
  109. {
  110. if (view.ends_with('%'))
  111. return parse_number(view.substring_view(0, view.length() - 1));
  112. // FIXME: Maybe we should have "ends_with_ignoring_case()" ?
  113. if (view.to_string().to_lowercase().ends_with("px"))
  114. return parse_number(view.substring_view(0, view.length() - 2));
  115. return try_parse_float(view);
  116. }
  117. NonnullRefPtr<StyleValue> parse_css_value(const StringView& string)
  118. {
  119. auto number = parse_number(string);
  120. if (number.has_value()) {
  121. if (string.ends_with('%'))
  122. return PercentageStyleValue::create(number.value());
  123. return LengthStyleValue::create(Length(number.value(), Length::Type::Absolute));
  124. }
  125. if (string.equals_ignoring_case("inherit"))
  126. return InheritStyleValue::create();
  127. if (string.equals_ignoring_case("initial"))
  128. return InitialStyleValue::create();
  129. if (string.equals_ignoring_case("auto"))
  130. return LengthStyleValue::create(Length());
  131. auto color = parse_css_color(string);
  132. if (color.has_value())
  133. return ColorStyleValue::create(color.value());
  134. if (string == "-libhtml-link")
  135. return IdentifierStyleValue::create(CSS::ValueID::VendorSpecificLink);
  136. return StringStyleValue::create(string);
  137. }
  138. RefPtr<LengthStyleValue> parse_line_width(const StringView& part)
  139. {
  140. NonnullRefPtr<StyleValue> value = parse_css_value(part);
  141. if (value->is_length())
  142. return static_ptr_cast<LengthStyleValue>(value);
  143. return nullptr;
  144. }
  145. RefPtr<ColorStyleValue> parse_color(const StringView& part)
  146. {
  147. NonnullRefPtr<StyleValue> value = parse_css_value(part);
  148. if (value->is_color())
  149. return static_ptr_cast<ColorStyleValue>(value);
  150. return nullptr;
  151. }
  152. RefPtr<StringStyleValue> parse_line_style(const StringView& part)
  153. {
  154. NonnullRefPtr<StyleValue> parsed_value = parse_css_value(part);
  155. if (!parsed_value->is_string())
  156. return nullptr;
  157. auto value = static_ptr_cast<StringStyleValue>(parsed_value);
  158. if (value->to_string() == "dotted")
  159. return value;
  160. if (value->to_string() == "dashed")
  161. return value;
  162. if (value->to_string() == "solid")
  163. return value;
  164. if (value->to_string() == "double")
  165. return value;
  166. if (value->to_string() == "groove")
  167. return value;
  168. if (value->to_string() == "ridge")
  169. return value;
  170. return nullptr;
  171. }
  172. class CSSParser {
  173. public:
  174. CSSParser(const StringView& input)
  175. : css(input)
  176. {
  177. }
  178. bool next_is(const char* str) const
  179. {
  180. size_t len = strlen(str);
  181. for (size_t i = 0; i < len; ++i) {
  182. if (peek(i) != str[i])
  183. return false;
  184. }
  185. return true;
  186. }
  187. char peek(size_t offset = 0) const
  188. {
  189. if ((index + offset) < css.length())
  190. return css[index + offset];
  191. return 0;
  192. }
  193. char consume_specific(char ch)
  194. {
  195. if (peek() != ch) {
  196. dbg() << "peek() != '" << ch << "'";
  197. }
  198. PARSE_ASSERT(peek() == ch);
  199. PARSE_ASSERT(index < css.length());
  200. ++index;
  201. return ch;
  202. }
  203. char consume_one()
  204. {
  205. PARSE_ASSERT(index < css.length());
  206. return css[index++];
  207. };
  208. bool consume_whitespace_or_comments()
  209. {
  210. size_t original_index = index;
  211. bool in_comment = false;
  212. for (; index < css.length(); ++index) {
  213. char ch = peek();
  214. if (isspace(ch))
  215. continue;
  216. if (!in_comment && ch == '/' && peek(1) == '*') {
  217. in_comment = true;
  218. ++index;
  219. continue;
  220. }
  221. if (in_comment && ch == '*' && peek(1) == '/') {
  222. in_comment = false;
  223. ++index;
  224. continue;
  225. }
  226. if (in_comment)
  227. continue;
  228. break;
  229. }
  230. return original_index != index;
  231. }
  232. bool is_valid_selector_char(char ch) const
  233. {
  234. return isalnum(ch) || ch == '-' || ch == '_' || ch == '(' || ch == ')' || ch == '@';
  235. }
  236. bool is_combinator(char ch) const
  237. {
  238. return ch == '~' || ch == '>' || ch == '+';
  239. }
  240. Optional<Selector::SimpleSelector> parse_simple_selector()
  241. {
  242. auto index_at_start = index;
  243. if (consume_whitespace_or_comments())
  244. return {};
  245. if (!peek() || peek() == '{' || peek() == ',' || is_combinator(peek()))
  246. return {};
  247. Selector::SimpleSelector::Type type;
  248. if (peek() == '*') {
  249. type = Selector::SimpleSelector::Type::Universal;
  250. consume_one();
  251. return Selector::SimpleSelector {
  252. type,
  253. Selector::SimpleSelector::PseudoClass::None,
  254. String(),
  255. Selector::SimpleSelector::AttributeMatchType::None,
  256. String(),
  257. String()
  258. };
  259. }
  260. if (peek() == '.') {
  261. type = Selector::SimpleSelector::Type::Class;
  262. consume_one();
  263. } else if (peek() == '#') {
  264. type = Selector::SimpleSelector::Type::Id;
  265. consume_one();
  266. } else if (isalpha(peek())) {
  267. type = Selector::SimpleSelector::Type::TagName;
  268. } else {
  269. type = Selector::SimpleSelector::Type::Universal;
  270. }
  271. if (type != Selector::SimpleSelector::Type::Universal) {
  272. while (is_valid_selector_char(peek()))
  273. buffer.append(consume_one());
  274. PARSE_ASSERT(!buffer.is_null());
  275. }
  276. Selector::SimpleSelector simple_selector {
  277. type,
  278. Selector::SimpleSelector::PseudoClass::None,
  279. String::copy(buffer),
  280. Selector::SimpleSelector::AttributeMatchType::None,
  281. String(),
  282. String()
  283. };
  284. buffer.clear();
  285. if (peek() == '[') {
  286. Selector::SimpleSelector::AttributeMatchType attribute_match_type = Selector::SimpleSelector::AttributeMatchType::HasAttribute;
  287. String attribute_name;
  288. String attribute_value;
  289. bool in_value = false;
  290. consume_specific('[');
  291. char expected_end_of_attribute_selector = ']';
  292. while (peek() != expected_end_of_attribute_selector) {
  293. char ch = consume_one();
  294. if (ch == '=') {
  295. attribute_match_type = Selector::SimpleSelector::AttributeMatchType::ExactValueMatch;
  296. attribute_name = String::copy(buffer);
  297. buffer.clear();
  298. in_value = true;
  299. consume_whitespace_or_comments();
  300. if (peek() == '\'') {
  301. expected_end_of_attribute_selector = '\'';
  302. consume_one();
  303. } else if (peek() == '"') {
  304. expected_end_of_attribute_selector = '"';
  305. consume_one();
  306. }
  307. continue;
  308. }
  309. buffer.append(ch);
  310. }
  311. if (in_value)
  312. attribute_value = String::copy(buffer);
  313. else
  314. attribute_name = String::copy(buffer);
  315. buffer.clear();
  316. simple_selector.attribute_match_type = attribute_match_type;
  317. simple_selector.attribute_name = attribute_name;
  318. simple_selector.attribute_value = attribute_value;
  319. if (expected_end_of_attribute_selector != ']')
  320. consume_specific(expected_end_of_attribute_selector);
  321. consume_whitespace_or_comments();
  322. consume_specific(']');
  323. }
  324. if (peek() == ':') {
  325. // FIXME: Implement pseudo elements.
  326. [[maybe_unused]] bool is_pseudo_element = false;
  327. consume_one();
  328. if (peek() == ':') {
  329. is_pseudo_element = true;
  330. consume_one();
  331. }
  332. if (next_is("not")) {
  333. buffer.append(consume_one());
  334. buffer.append(consume_one());
  335. buffer.append(consume_one());
  336. buffer.append(consume_specific('('));
  337. while (peek() != ')')
  338. buffer.append(consume_one());
  339. buffer.append(consume_specific(')'));
  340. } else {
  341. while (is_valid_selector_char(peek()))
  342. buffer.append(consume_one());
  343. }
  344. auto pseudo_name = String::copy(buffer);
  345. buffer.clear();
  346. // Ignore for now, otherwise we produce a "false positive" selector
  347. // and apply styles to the element itself, not its pseudo element
  348. if (is_pseudo_element)
  349. return {};
  350. if (pseudo_name == "link")
  351. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Link;
  352. else if (pseudo_name == "hover")
  353. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Hover;
  354. else if (pseudo_name == "focus")
  355. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Focus;
  356. else if (pseudo_name == "first-child")
  357. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::FirstChild;
  358. else if (pseudo_name == "last-child")
  359. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::LastChild;
  360. else if (pseudo_name == "only-child")
  361. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::OnlyChild;
  362. else if (pseudo_name == "empty")
  363. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Empty;
  364. }
  365. if (index == index_at_start) {
  366. // We consumed nothing.
  367. return {};
  368. }
  369. return simple_selector;
  370. }
  371. Optional<Selector::ComplexSelector> parse_complex_selector()
  372. {
  373. auto relation = Selector::ComplexSelector::Relation::Descendant;
  374. if (peek() == '{' || peek() == ',')
  375. return {};
  376. if (is_combinator(peek())) {
  377. switch (peek()) {
  378. case '>':
  379. relation = Selector::ComplexSelector::Relation::ImmediateChild;
  380. break;
  381. case '+':
  382. relation = Selector::ComplexSelector::Relation::AdjacentSibling;
  383. break;
  384. case '~':
  385. relation = Selector::ComplexSelector::Relation::GeneralSibling;
  386. break;
  387. }
  388. consume_one();
  389. consume_whitespace_or_comments();
  390. }
  391. consume_whitespace_or_comments();
  392. Vector<Selector::SimpleSelector> simple_selectors;
  393. for (;;) {
  394. auto component = parse_simple_selector();
  395. if (!component.has_value())
  396. break;
  397. simple_selectors.append(component.value());
  398. // If this assert triggers, we're most likely up to no good.
  399. PARSE_ASSERT(simple_selectors.size() < 100);
  400. }
  401. if (simple_selectors.is_empty())
  402. return {};
  403. return Selector::ComplexSelector { relation, move(simple_selectors) };
  404. }
  405. void parse_selector()
  406. {
  407. Vector<Selector::ComplexSelector> complex_selectors;
  408. for (;;) {
  409. auto complex_selector = parse_complex_selector();
  410. if (complex_selector.has_value())
  411. complex_selectors.append(complex_selector.value());
  412. consume_whitespace_or_comments();
  413. if (!peek() || peek() == ',' || peek() == '{')
  414. break;
  415. }
  416. if (complex_selectors.is_empty())
  417. return;
  418. complex_selectors.first().relation = Selector::ComplexSelector::Relation::None;
  419. current_rule.selectors.append(Selector(move(complex_selectors)));
  420. }
  421. Optional<Selector> parse_individual_selector()
  422. {
  423. parse_selector();
  424. if (current_rule.selectors.is_empty())
  425. return {};
  426. return current_rule.selectors.last();
  427. }
  428. void parse_selector_list()
  429. {
  430. for (;;) {
  431. parse_selector();
  432. consume_whitespace_or_comments();
  433. if (peek() == ',') {
  434. consume_one();
  435. continue;
  436. }
  437. if (peek() == '{')
  438. break;
  439. }
  440. }
  441. bool is_valid_property_name_char(char ch) const
  442. {
  443. return ch && !isspace(ch) && ch != ':';
  444. }
  445. bool is_valid_property_value_char(char ch) const
  446. {
  447. return ch && ch != '!' && ch != ';' && ch != '}';
  448. }
  449. struct ValueAndImportant {
  450. String value;
  451. bool important { false };
  452. };
  453. ValueAndImportant consume_css_value()
  454. {
  455. buffer.clear();
  456. int paren_nesting_level = 0;
  457. bool important = false;
  458. for (;;) {
  459. char ch = peek();
  460. if (ch == '(') {
  461. ++paren_nesting_level;
  462. buffer.append(consume_one());
  463. continue;
  464. }
  465. if (ch == ')') {
  466. PARSE_ASSERT(paren_nesting_level > 0);
  467. --paren_nesting_level;
  468. buffer.append(consume_one());
  469. continue;
  470. }
  471. if (paren_nesting_level > 0) {
  472. buffer.append(consume_one());
  473. continue;
  474. }
  475. if (next_is("!important")) {
  476. consume_specific('!');
  477. consume_specific('i');
  478. consume_specific('m');
  479. consume_specific('p');
  480. consume_specific('o');
  481. consume_specific('r');
  482. consume_specific('t');
  483. consume_specific('a');
  484. consume_specific('n');
  485. consume_specific('t');
  486. important = true;
  487. continue;
  488. }
  489. if (next_is("/*")) {
  490. consume_whitespace_or_comments();
  491. continue;
  492. }
  493. if (!ch)
  494. break;
  495. if (ch == '}')
  496. break;
  497. if (ch == ';')
  498. break;
  499. buffer.append(consume_one());
  500. }
  501. // Remove trailing whitespace.
  502. while (!buffer.is_empty() && isspace(buffer.last()))
  503. buffer.take_last();
  504. auto string = String::copy(buffer);
  505. buffer.clear();
  506. return { string, important };
  507. }
  508. Optional<StyleProperty> parse_property()
  509. {
  510. consume_whitespace_or_comments();
  511. if (peek() == ';') {
  512. consume_one();
  513. return {};
  514. }
  515. if (peek() == '}')
  516. return {};
  517. buffer.clear();
  518. while (is_valid_property_name_char(peek()))
  519. buffer.append(consume_one());
  520. auto property_name = String::copy(buffer);
  521. buffer.clear();
  522. consume_whitespace_or_comments();
  523. consume_specific(':');
  524. consume_whitespace_or_comments();
  525. auto [property_value, important] = consume_css_value();
  526. consume_whitespace_or_comments();
  527. if (peek() && peek() != '}')
  528. consume_specific(';');
  529. auto property_id = CSS::property_id_from_string(property_name);
  530. return StyleProperty { property_id, parse_css_value(property_value), important };
  531. }
  532. void parse_declaration()
  533. {
  534. for (;;) {
  535. auto property = parse_property();
  536. if (property.has_value())
  537. current_rule.properties.append(property.value());
  538. consume_whitespace_or_comments();
  539. if (peek() == '}')
  540. break;
  541. }
  542. }
  543. void parse_rule()
  544. {
  545. consume_whitespace_or_comments();
  546. if (index >= css.length())
  547. return;
  548. // FIXME: We ignore @-rules for now.
  549. if (peek() == '@') {
  550. while (peek() != '{')
  551. consume_one();
  552. int level = 0;
  553. for (;;) {
  554. auto ch = consume_one();
  555. if (ch == '{') {
  556. ++level;
  557. } else if (ch == '}') {
  558. --level;
  559. if (level == 0)
  560. break;
  561. }
  562. }
  563. consume_whitespace_or_comments();
  564. return;
  565. }
  566. parse_selector_list();
  567. consume_specific('{');
  568. parse_declaration();
  569. consume_specific('}');
  570. rules.append(StyleRule::create(move(current_rule.selectors), StyleDeclaration::create(move(current_rule.properties))));
  571. consume_whitespace_or_comments();
  572. }
  573. RefPtr<StyleSheet> parse_sheet()
  574. {
  575. while (index < css.length()) {
  576. parse_rule();
  577. }
  578. return StyleSheet::create(move(rules));
  579. }
  580. RefPtr<StyleDeclaration> parse_standalone_declaration()
  581. {
  582. consume_whitespace_or_comments();
  583. for (;;) {
  584. auto property = parse_property();
  585. if (property.has_value())
  586. current_rule.properties.append(property.value());
  587. consume_whitespace_or_comments();
  588. if (!peek())
  589. break;
  590. }
  591. return StyleDeclaration::create(move(current_rule.properties));
  592. }
  593. private:
  594. NonnullRefPtrVector<StyleRule> rules;
  595. struct CurrentRule {
  596. Vector<Selector> selectors;
  597. Vector<StyleProperty> properties;
  598. };
  599. CurrentRule current_rule;
  600. Vector<char> buffer;
  601. size_t index = 0;
  602. StringView css;
  603. };
  604. Optional<Selector> parse_selector(const StringView& selector_text)
  605. {
  606. CSSParser parser(selector_text);
  607. return parser.parse_individual_selector();
  608. }
  609. RefPtr<StyleSheet> parse_css(const StringView& css)
  610. {
  611. CSSParser parser(css);
  612. return parser.parse_sheet();
  613. }
  614. RefPtr<StyleDeclaration> parse_css_declaration(const StringView& css)
  615. {
  616. CSSParser parser(css);
  617. return parser.parse_standalone_declaration();
  618. }
  619. }