CSSParser.cpp 21 KB

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