CSSParser.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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. if (consume_whitespace_or_comments())
  237. return {};
  238. if (!peek() || peek() == '{' || peek() == ',' || is_combinator(peek()))
  239. return {};
  240. Selector::SimpleSelector::Type type;
  241. if (peek() == '*') {
  242. type = Selector::SimpleSelector::Type::Universal;
  243. consume_one();
  244. return Selector::SimpleSelector {
  245. type,
  246. Selector::SimpleSelector::PseudoClass::None,
  247. String(),
  248. Selector::SimpleSelector::AttributeMatchType::None,
  249. String(),
  250. String()
  251. };
  252. }
  253. if (peek() == '.') {
  254. type = Selector::SimpleSelector::Type::Class;
  255. consume_one();
  256. } else if (peek() == '#') {
  257. type = Selector::SimpleSelector::Type::Id;
  258. consume_one();
  259. } else if (isalpha(peek())) {
  260. type = Selector::SimpleSelector::Type::TagName;
  261. } else {
  262. type = Selector::SimpleSelector::Type::Universal;
  263. }
  264. if (type != Selector::SimpleSelector::Type::Universal) {
  265. while (is_valid_selector_char(peek()))
  266. buffer.append(consume_one());
  267. PARSE_ASSERT(!buffer.is_null());
  268. }
  269. Selector::SimpleSelector simple_selector {
  270. type,
  271. Selector::SimpleSelector::PseudoClass::None,
  272. String::copy(buffer),
  273. Selector::SimpleSelector::AttributeMatchType::None,
  274. String(),
  275. String()
  276. };
  277. buffer.clear();
  278. if (peek() == '[') {
  279. Selector::SimpleSelector::AttributeMatchType attribute_match_type = Selector::SimpleSelector::AttributeMatchType::HasAttribute;
  280. String attribute_name;
  281. String attribute_value;
  282. bool in_value = false;
  283. consume_specific('[');
  284. char expected_end_of_attribute_selector = ']';
  285. while (peek() != expected_end_of_attribute_selector) {
  286. char ch = consume_one();
  287. if (ch == '=') {
  288. attribute_match_type = Selector::SimpleSelector::AttributeMatchType::ExactValueMatch;
  289. attribute_name = String::copy(buffer);
  290. buffer.clear();
  291. in_value = true;
  292. consume_whitespace_or_comments();
  293. if (peek() == '\'') {
  294. expected_end_of_attribute_selector = '\'';
  295. consume_one();
  296. } else if (peek() == '"') {
  297. expected_end_of_attribute_selector = '"';
  298. consume_one();
  299. }
  300. continue;
  301. }
  302. buffer.append(ch);
  303. }
  304. if (in_value)
  305. attribute_value = String::copy(buffer);
  306. else
  307. attribute_name = String::copy(buffer);
  308. buffer.clear();
  309. simple_selector.attribute_match_type = attribute_match_type;
  310. simple_selector.attribute_name = attribute_name;
  311. simple_selector.attribute_value = attribute_value;
  312. if (expected_end_of_attribute_selector != ']')
  313. consume_specific(expected_end_of_attribute_selector);
  314. consume_whitespace_or_comments();
  315. consume_specific(']');
  316. }
  317. if (peek() == ':') {
  318. // FIXME: Implement pseudo elements.
  319. [[maybe_unused]] bool is_pseudo_element = false;
  320. consume_one();
  321. if (peek() == ':') {
  322. is_pseudo_element = true;
  323. consume_one();
  324. }
  325. if (next_is("not")) {
  326. buffer.append(consume_one());
  327. buffer.append(consume_one());
  328. buffer.append(consume_one());
  329. buffer.append(consume_specific('('));
  330. while (peek() != ')')
  331. buffer.append(consume_one());
  332. buffer.append(consume_specific(')'));
  333. } else {
  334. while (is_valid_selector_char(peek()))
  335. buffer.append(consume_one());
  336. }
  337. auto pseudo_name = String::copy(buffer);
  338. buffer.clear();
  339. if (pseudo_name == "link")
  340. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Link;
  341. else if (pseudo_name == "hover")
  342. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Hover;
  343. else if (pseudo_name == "first-child")
  344. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::FirstChild;
  345. else if (pseudo_name == "last-child")
  346. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::LastChild;
  347. else if (pseudo_name == "only-child")
  348. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::OnlyChild;
  349. else if (pseudo_name == "empty")
  350. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Empty;
  351. }
  352. return simple_selector;
  353. }
  354. Optional<Selector::ComplexSelector> parse_complex_selector()
  355. {
  356. auto relation = Selector::ComplexSelector::Relation::Descendant;
  357. if (peek() == '{' || peek() == ',')
  358. return {};
  359. if (is_combinator(peek())) {
  360. switch (peek()) {
  361. case '>':
  362. relation = Selector::ComplexSelector::Relation::ImmediateChild;
  363. break;
  364. case '+':
  365. relation = Selector::ComplexSelector::Relation::AdjacentSibling;
  366. break;
  367. case '~':
  368. relation = Selector::ComplexSelector::Relation::GeneralSibling;
  369. break;
  370. }
  371. consume_one();
  372. consume_whitespace_or_comments();
  373. }
  374. consume_whitespace_or_comments();
  375. Vector<Selector::SimpleSelector> simple_selectors;
  376. for (;;) {
  377. auto component = parse_simple_selector();
  378. if (!component.has_value())
  379. break;
  380. simple_selectors.append(component.value());
  381. // If this assert triggers, we're most likely up to no good.
  382. PARSE_ASSERT(simple_selectors.size() < 100);
  383. }
  384. return Selector::ComplexSelector { relation, move(simple_selectors) };
  385. }
  386. void parse_selector()
  387. {
  388. Vector<Selector::ComplexSelector> complex_selectors;
  389. for (;;) {
  390. auto complex_selector = parse_complex_selector();
  391. if (complex_selector.has_value())
  392. complex_selectors.append(complex_selector.value());
  393. consume_whitespace_or_comments();
  394. if (!peek() || peek() == ',' || peek() == '{')
  395. break;
  396. }
  397. if (complex_selectors.is_empty())
  398. return;
  399. complex_selectors.first().relation = Selector::ComplexSelector::Relation::None;
  400. current_rule.selectors.append(Selector(move(complex_selectors)));
  401. }
  402. Optional<Selector> parse_individual_selector()
  403. {
  404. parse_selector();
  405. if (current_rule.selectors.is_empty())
  406. return {};
  407. return current_rule.selectors.last();
  408. }
  409. void parse_selector_list()
  410. {
  411. for (;;) {
  412. parse_selector();
  413. consume_whitespace_or_comments();
  414. if (peek() == ',') {
  415. consume_one();
  416. continue;
  417. }
  418. if (peek() == '{')
  419. break;
  420. }
  421. }
  422. bool is_valid_property_name_char(char ch) const
  423. {
  424. return ch && !isspace(ch) && ch != ':';
  425. }
  426. bool is_valid_property_value_char(char ch) const
  427. {
  428. return ch && ch != '!' && ch != ';' && ch != '}';
  429. }
  430. struct ValueAndImportant {
  431. String value;
  432. bool important { false };
  433. };
  434. ValueAndImportant consume_css_value()
  435. {
  436. buffer.clear();
  437. int paren_nesting_level = 0;
  438. bool important = false;
  439. for (;;) {
  440. char ch = peek();
  441. if (ch == '(') {
  442. ++paren_nesting_level;
  443. buffer.append(consume_one());
  444. continue;
  445. }
  446. if (ch == ')') {
  447. PARSE_ASSERT(paren_nesting_level > 0);
  448. --paren_nesting_level;
  449. buffer.append(consume_one());
  450. continue;
  451. }
  452. if (paren_nesting_level > 0) {
  453. buffer.append(consume_one());
  454. continue;
  455. }
  456. if (next_is("!important")) {
  457. consume_specific('!');
  458. consume_specific('i');
  459. consume_specific('m');
  460. consume_specific('p');
  461. consume_specific('o');
  462. consume_specific('r');
  463. consume_specific('t');
  464. consume_specific('a');
  465. consume_specific('n');
  466. consume_specific('t');
  467. important = true;
  468. continue;
  469. }
  470. if (next_is("/*")) {
  471. consume_whitespace_or_comments();
  472. continue;
  473. }
  474. if (!ch)
  475. break;
  476. if (ch == '}')
  477. break;
  478. if (ch == ';')
  479. break;
  480. buffer.append(consume_one());
  481. }
  482. // Remove trailing whitespace.
  483. while (!buffer.is_empty() && isspace(buffer.last()))
  484. buffer.take_last();
  485. auto string = String::copy(buffer);
  486. buffer.clear();
  487. return { string, important };
  488. }
  489. Optional<StyleProperty> parse_property()
  490. {
  491. consume_whitespace_or_comments();
  492. if (peek() == ';') {
  493. consume_one();
  494. return {};
  495. }
  496. if (peek() == '}')
  497. return {};
  498. buffer.clear();
  499. while (is_valid_property_name_char(peek()))
  500. buffer.append(consume_one());
  501. auto property_name = String::copy(buffer);
  502. buffer.clear();
  503. consume_whitespace_or_comments();
  504. consume_specific(':');
  505. consume_whitespace_or_comments();
  506. auto [property_value, important] = consume_css_value();
  507. consume_whitespace_or_comments();
  508. if (peek() && peek() != '}')
  509. consume_specific(';');
  510. auto property_id = CSS::property_id_from_string(property_name);
  511. return StyleProperty { property_id, parse_css_value(property_value), important };
  512. }
  513. void parse_declaration()
  514. {
  515. for (;;) {
  516. auto property = parse_property();
  517. if (property.has_value())
  518. current_rule.properties.append(property.value());
  519. consume_whitespace_or_comments();
  520. if (peek() == '}')
  521. break;
  522. }
  523. }
  524. void parse_rule()
  525. {
  526. consume_whitespace_or_comments();
  527. if (index >= css.length())
  528. return;
  529. // FIXME: We ignore @-rules for now.
  530. if (peek() == '@') {
  531. while (peek() != '{')
  532. consume_one();
  533. int level = 0;
  534. for (;;) {
  535. auto ch = consume_one();
  536. if (ch == '{') {
  537. ++level;
  538. } else if (ch == '}') {
  539. --level;
  540. if (level == 0)
  541. break;
  542. }
  543. }
  544. consume_whitespace_or_comments();
  545. return;
  546. }
  547. parse_selector_list();
  548. consume_specific('{');
  549. parse_declaration();
  550. consume_specific('}');
  551. rules.append(StyleRule::create(move(current_rule.selectors), StyleDeclaration::create(move(current_rule.properties))));
  552. consume_whitespace_or_comments();
  553. }
  554. RefPtr<StyleSheet> parse_sheet()
  555. {
  556. while (index < css.length()) {
  557. parse_rule();
  558. }
  559. return StyleSheet::create(move(rules));
  560. }
  561. RefPtr<StyleDeclaration> parse_standalone_declaration()
  562. {
  563. consume_whitespace_or_comments();
  564. for (;;) {
  565. auto property = parse_property();
  566. if (property.has_value())
  567. current_rule.properties.append(property.value());
  568. consume_whitespace_or_comments();
  569. if (!peek())
  570. break;
  571. }
  572. return StyleDeclaration::create(move(current_rule.properties));
  573. }
  574. private:
  575. NonnullRefPtrVector<StyleRule> rules;
  576. struct CurrentRule {
  577. Vector<Selector> selectors;
  578. Vector<StyleProperty> properties;
  579. };
  580. CurrentRule current_rule;
  581. Vector<char> buffer;
  582. size_t index = 0;
  583. StringView css;
  584. };
  585. Optional<Selector> parse_selector(const StringView& selector_text)
  586. {
  587. CSSParser parser(selector_text);
  588. return parser.parse_individual_selector();
  589. }
  590. RefPtr<StyleSheet> parse_css(const StringView& css)
  591. {
  592. CSSParser parser(css);
  593. return parser.parse_sheet();
  594. }
  595. RefPtr<StyleDeclaration> parse_css_declaration(const StringView& css)
  596. {
  597. CSSParser parser(css);
  598. return parser.parse_standalone_declaration();
  599. }
  600. }