CSSParser.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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 (!peek())
  236. return {};
  237. if (consume_whitespace_or_comments())
  238. return {};
  239. if (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. if (pseudo_name == "link")
  341. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Link;
  342. else if (pseudo_name == "hover")
  343. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Hover;
  344. else if (pseudo_name == "first-child")
  345. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::FirstChild;
  346. else if (pseudo_name == "last-child")
  347. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::LastChild;
  348. else if (pseudo_name == "only-child")
  349. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::OnlyChild;
  350. else if (pseudo_name == "empty")
  351. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Empty;
  352. }
  353. return simple_selector;
  354. }
  355. Optional<Selector::ComplexSelector> parse_complex_selector()
  356. {
  357. auto relation = Selector::ComplexSelector::Relation::Descendant;
  358. if (peek() == '{' || peek() == ',')
  359. return {};
  360. if (is_combinator(peek())) {
  361. switch (peek()) {
  362. case '>':
  363. relation = Selector::ComplexSelector::Relation::ImmediateChild;
  364. break;
  365. case '+':
  366. relation = Selector::ComplexSelector::Relation::AdjacentSibling;
  367. break;
  368. case '~':
  369. relation = Selector::ComplexSelector::Relation::GeneralSibling;
  370. break;
  371. }
  372. consume_one();
  373. consume_whitespace_or_comments();
  374. }
  375. consume_whitespace_or_comments();
  376. Vector<Selector::SimpleSelector> simple_selectors;
  377. for (;;) {
  378. auto component = parse_simple_selector();
  379. if (!component.has_value())
  380. break;
  381. simple_selectors.append(component.value());
  382. // If this assert triggers, we're most likely up to no good.
  383. PARSE_ASSERT(simple_selectors.size() < 100);
  384. }
  385. return Selector::ComplexSelector { relation, move(simple_selectors) };
  386. }
  387. void parse_selector()
  388. {
  389. Vector<Selector::ComplexSelector> complex_selectors;
  390. for (;;) {
  391. auto complex_selector = parse_complex_selector();
  392. if (complex_selector.has_value())
  393. complex_selectors.append(complex_selector.value());
  394. consume_whitespace_or_comments();
  395. if (peek() == ',' || peek() == '{')
  396. break;
  397. }
  398. if (complex_selectors.is_empty())
  399. return;
  400. complex_selectors.first().relation = Selector::ComplexSelector::Relation::None;
  401. current_rule.selectors.append(Selector(move(complex_selectors)));
  402. };
  403. void parse_selector_list()
  404. {
  405. for (;;) {
  406. parse_selector();
  407. consume_whitespace_or_comments();
  408. if (peek() == ',') {
  409. consume_one();
  410. continue;
  411. }
  412. if (peek() == '{')
  413. break;
  414. }
  415. }
  416. bool is_valid_property_name_char(char ch) const
  417. {
  418. return ch && !isspace(ch) && ch != ':';
  419. }
  420. bool is_valid_property_value_char(char ch) const
  421. {
  422. return ch && ch != '!' && ch != ';' && ch != '}';
  423. }
  424. struct ValueAndImportant {
  425. String value;
  426. bool important { false };
  427. };
  428. ValueAndImportant consume_css_value()
  429. {
  430. buffer.clear();
  431. int paren_nesting_level = 0;
  432. bool important = false;
  433. for (;;) {
  434. char ch = peek();
  435. if (ch == '(') {
  436. ++paren_nesting_level;
  437. buffer.append(consume_one());
  438. continue;
  439. }
  440. if (ch == ')') {
  441. PARSE_ASSERT(paren_nesting_level > 0);
  442. --paren_nesting_level;
  443. buffer.append(consume_one());
  444. continue;
  445. }
  446. if (paren_nesting_level > 0) {
  447. buffer.append(consume_one());
  448. continue;
  449. }
  450. if (next_is("!important")) {
  451. consume_specific('!');
  452. consume_specific('i');
  453. consume_specific('m');
  454. consume_specific('p');
  455. consume_specific('o');
  456. consume_specific('r');
  457. consume_specific('t');
  458. consume_specific('a');
  459. consume_specific('n');
  460. consume_specific('t');
  461. important = true;
  462. continue;
  463. }
  464. if (next_is("/*")) {
  465. consume_whitespace_or_comments();
  466. continue;
  467. }
  468. if (!ch)
  469. break;
  470. if (ch == '}')
  471. break;
  472. if (ch == ';')
  473. break;
  474. buffer.append(consume_one());
  475. }
  476. // Remove trailing whitespace.
  477. while (!buffer.is_empty() && isspace(buffer.last()))
  478. buffer.take_last();
  479. auto string = String::copy(buffer);
  480. buffer.clear();
  481. return { string, important };
  482. }
  483. Optional<StyleProperty> parse_property()
  484. {
  485. consume_whitespace_or_comments();
  486. if (peek() == ';') {
  487. consume_one();
  488. return {};
  489. }
  490. if (peek() == '}')
  491. return {};
  492. buffer.clear();
  493. while (is_valid_property_name_char(peek()))
  494. buffer.append(consume_one());
  495. auto property_name = String::copy(buffer);
  496. buffer.clear();
  497. consume_whitespace_or_comments();
  498. consume_specific(':');
  499. consume_whitespace_or_comments();
  500. auto [property_value, important] = consume_css_value();
  501. consume_whitespace_or_comments();
  502. if (peek() && peek() != '}')
  503. consume_specific(';');
  504. auto property_id = CSS::property_id_from_string(property_name);
  505. return StyleProperty { property_id, parse_css_value(property_value), important };
  506. }
  507. void parse_declaration()
  508. {
  509. for (;;) {
  510. auto property = parse_property();
  511. if (property.has_value())
  512. current_rule.properties.append(property.value());
  513. consume_whitespace_or_comments();
  514. if (peek() == '}')
  515. break;
  516. }
  517. }
  518. void parse_rule()
  519. {
  520. consume_whitespace_or_comments();
  521. if (index >= css.length())
  522. return;
  523. // FIXME: We ignore @-rules for now.
  524. if (peek() == '@') {
  525. while (peek() != '{')
  526. consume_one();
  527. int level = 0;
  528. for (;;) {
  529. auto ch = consume_one();
  530. if (ch == '{') {
  531. ++level;
  532. } else if (ch == '}') {
  533. --level;
  534. if (level == 0)
  535. break;
  536. }
  537. }
  538. consume_whitespace_or_comments();
  539. return;
  540. }
  541. parse_selector_list();
  542. consume_specific('{');
  543. parse_declaration();
  544. consume_specific('}');
  545. rules.append(StyleRule::create(move(current_rule.selectors), StyleDeclaration::create(move(current_rule.properties))));
  546. consume_whitespace_or_comments();
  547. }
  548. RefPtr<StyleSheet> parse_sheet()
  549. {
  550. while (index < css.length()) {
  551. parse_rule();
  552. }
  553. return StyleSheet::create(move(rules));
  554. }
  555. RefPtr<StyleDeclaration> parse_standalone_declaration()
  556. {
  557. consume_whitespace_or_comments();
  558. for (;;) {
  559. auto property = parse_property();
  560. if (property.has_value())
  561. current_rule.properties.append(property.value());
  562. consume_whitespace_or_comments();
  563. if (!peek())
  564. break;
  565. }
  566. return StyleDeclaration::create(move(current_rule.properties));
  567. }
  568. private:
  569. NonnullRefPtrVector<StyleRule> rules;
  570. struct CurrentRule {
  571. Vector<Selector> selectors;
  572. Vector<StyleProperty> properties;
  573. };
  574. CurrentRule current_rule;
  575. Vector<char> buffer;
  576. size_t index = 0;
  577. StringView css;
  578. };
  579. Optional<Selector> parse_selector(const StringView& selector_text)
  580. {
  581. CSSParser parser(selector_text);
  582. auto complex_selector = parser.parse_complex_selector();
  583. if (!complex_selector.has_value())
  584. return {};
  585. complex_selector.value().relation = Selector::ComplexSelector::Relation::None;
  586. return Selector({ complex_selector.value() });
  587. }
  588. RefPtr<StyleSheet> parse_css(const StringView& css)
  589. {
  590. CSSParser parser(css);
  591. return parser.parse_sheet();
  592. }
  593. RefPtr<StyleDeclaration> parse_css_declaration(const StringView& css)
  594. {
  595. CSSParser parser(css);
  596. return parser.parse_standalone_declaration();
  597. }
  598. }