CSSParser.cpp 18 KB

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