CSSParser.cpp 20 KB

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