CSSParser.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  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/Parser/CSSParser.h>
  28. #include <LibWeb/CSS/PropertyID.h>
  29. #include <LibWeb/CSS/StyleSheet.h>
  30. #include <LibWeb/DOM/Document.h>
  31. #include <ctype.h>
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <string.h>
  35. #define PARSE_ASSERT(x) \
  36. if (!(x)) { \
  37. dbgln("CSS PARSER ASSERTION FAILED: {}", #x); \
  38. dbgln("At character# {} in CSS: _{}_", index, css); \
  39. ASSERT_NOT_REACHED(); \
  40. }
  41. #define PARSE_ERROR() \
  42. do { \
  43. dbgln("CSS parse error"); \
  44. } while (0)
  45. namespace Web {
  46. namespace CSS {
  47. ParsingContext::ParsingContext()
  48. {
  49. }
  50. ParsingContext::ParsingContext(const DOM::Document& document)
  51. : m_document(&document)
  52. {
  53. }
  54. ParsingContext::ParsingContext(const DOM::ParentNode& parent_node)
  55. : m_document(&parent_node.document())
  56. {
  57. }
  58. bool ParsingContext::in_quirks_mode() const
  59. {
  60. return m_document ? m_document->in_quirks_mode() : false;
  61. }
  62. }
  63. static Optional<Color> parse_css_color(const CSS::ParsingContext&, const StringView& view)
  64. {
  65. if (view.equals_ignoring_case("transparent"))
  66. return Color::from_rgba(0x00000000);
  67. auto color = Color::from_string(view.to_string().to_lowercase());
  68. if (color.has_value())
  69. return color;
  70. return {};
  71. }
  72. static Optional<float> try_parse_float(const StringView& string)
  73. {
  74. const char* str = string.characters_without_null_termination();
  75. size_t len = string.length();
  76. size_t weight = 1;
  77. int exp_val = 0;
  78. float value = 0.0f;
  79. float fraction = 0.0f;
  80. bool has_sign = false;
  81. bool is_negative = false;
  82. bool is_fractional = false;
  83. bool is_scientific = false;
  84. if (str[0] == '-') {
  85. is_negative = true;
  86. has_sign = true;
  87. }
  88. if (str[0] == '+') {
  89. has_sign = true;
  90. }
  91. for (size_t i = has_sign; i < len; i++) {
  92. // Looks like we're about to start working on the fractional part
  93. if (str[i] == '.') {
  94. is_fractional = true;
  95. continue;
  96. }
  97. if (str[i] == 'e' || str[i] == 'E') {
  98. if (str[i + 1] == '-' || str[i + 1] == '+')
  99. exp_val = atoi(str + i + 2);
  100. else
  101. exp_val = atoi(str + i + 1);
  102. is_scientific = true;
  103. continue;
  104. }
  105. if (str[i] < '0' || str[i] > '9' || exp_val != 0) {
  106. return {};
  107. continue;
  108. }
  109. if (is_fractional) {
  110. fraction *= 10;
  111. fraction += str[i] - '0';
  112. weight *= 10;
  113. } else {
  114. value = value * 10;
  115. value += str[i] - '0';
  116. }
  117. }
  118. fraction /= weight;
  119. value += fraction;
  120. if (is_scientific) {
  121. bool divide = exp_val < 0;
  122. if (divide)
  123. exp_val *= -1;
  124. for (int i = 0; i < exp_val; i++) {
  125. if (divide)
  126. value /= 10;
  127. else
  128. value *= 10;
  129. }
  130. }
  131. return is_negative ? -value : value;
  132. }
  133. static CSS::Length parse_length(const CSS::ParsingContext& context, const StringView& view, bool& is_bad_length)
  134. {
  135. CSS::Length::Type type = CSS::Length::Type::Undefined;
  136. Optional<float> value;
  137. if (view.ends_with('%')) {
  138. type = CSS::Length::Type::Percentage;
  139. value = try_parse_float(view.substring_view(0, view.length() - 1));
  140. } else if (view.ends_with("px", CaseSensitivity::CaseInsensitive)) {
  141. type = CSS::Length::Type::Px;
  142. value = try_parse_float(view.substring_view(0, view.length() - 2));
  143. } else if (view.ends_with("pt", CaseSensitivity::CaseInsensitive)) {
  144. type = CSS::Length::Type::Pt;
  145. value = try_parse_float(view.substring_view(0, view.length() - 2));
  146. } else if (view.ends_with("pc", CaseSensitivity::CaseInsensitive)) {
  147. type = CSS::Length::Type::Pc;
  148. value = try_parse_float(view.substring_view(0, view.length() - 2));
  149. } else if (view.ends_with("mm", CaseSensitivity::CaseInsensitive)) {
  150. type = CSS::Length::Type::Mm;
  151. value = try_parse_float(view.substring_view(0, view.length() - 2));
  152. } else if (view.ends_with("rem", CaseSensitivity::CaseInsensitive)) {
  153. type = CSS::Length::Type::Rem;
  154. value = try_parse_float(view.substring_view(0, view.length() - 3));
  155. } else if (view.ends_with("em", CaseSensitivity::CaseInsensitive)) {
  156. type = CSS::Length::Type::Em;
  157. value = try_parse_float(view.substring_view(0, view.length() - 2));
  158. } else if (view.ends_with("ex", CaseSensitivity::CaseInsensitive)) {
  159. type = CSS::Length::Type::Ex;
  160. value = try_parse_float(view.substring_view(0, view.length() - 2));
  161. } else if (view.ends_with("vw", CaseSensitivity::CaseInsensitive)) {
  162. type = CSS::Length::Type::Vw;
  163. value = try_parse_float(view.substring_view(0, view.length() - 2));
  164. } else if (view.ends_with("vh", CaseSensitivity::CaseInsensitive)) {
  165. type = CSS::Length::Type::Vh;
  166. value = try_parse_float(view.substring_view(0, view.length() - 2));
  167. } else if (view.ends_with("vmax", CaseSensitivity::CaseInsensitive)) {
  168. type = CSS::Length::Type::Vmax;
  169. value = try_parse_float(view.substring_view(0, view.length() - 4));
  170. } else if (view.ends_with("vmin", CaseSensitivity::CaseInsensitive)) {
  171. type = CSS::Length::Type::Vmin;
  172. value = try_parse_float(view.substring_view(0, view.length() - 4));
  173. } else if (view.ends_with("cm", CaseSensitivity::CaseInsensitive)) {
  174. type = CSS::Length::Type::Cm;
  175. value = try_parse_float(view.substring_view(0, view.length() - 2));
  176. } else if (view.ends_with("in", CaseSensitivity::CaseInsensitive)) {
  177. type = CSS::Length::Type::In;
  178. value = try_parse_float(view.substring_view(0, view.length() - 2));
  179. } else if (view.ends_with("Q", CaseSensitivity::CaseInsensitive)) {
  180. type = CSS::Length::Type::Q;
  181. value = try_parse_float(view.substring_view(0, view.length() - 1));
  182. } else if (view == "0") {
  183. type = CSS::Length::Type::Px;
  184. value = 0;
  185. } else if (context.in_quirks_mode()) {
  186. type = CSS::Length::Type::Px;
  187. value = try_parse_float(view);
  188. } else {
  189. value = try_parse_float(view);
  190. if (value.has_value())
  191. is_bad_length = true;
  192. }
  193. if (!value.has_value())
  194. return {};
  195. return CSS::Length(value.value(), type);
  196. }
  197. static bool takes_integer_value(CSS::PropertyID property_id)
  198. {
  199. return property_id == CSS::PropertyID::ZIndex || property_id == CSS::PropertyID::FontWeight;
  200. }
  201. RefPtr<CSS::StyleValue> parse_css_value(const CSS::ParsingContext& context, const StringView& string, CSS::PropertyID property_id)
  202. {
  203. bool is_bad_length = false;
  204. if (takes_integer_value(property_id)) {
  205. auto integer = string.to_int();
  206. if (integer.has_value())
  207. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  208. }
  209. auto length = parse_length(context, string, is_bad_length);
  210. if (is_bad_length)
  211. return nullptr;
  212. if (!length.is_undefined())
  213. return CSS::LengthStyleValue::create(length);
  214. if (string.equals_ignoring_case("inherit"))
  215. return CSS::InheritStyleValue::create();
  216. if (string.equals_ignoring_case("initial"))
  217. return CSS::InitialStyleValue::create();
  218. if (string.equals_ignoring_case("auto"))
  219. return CSS::LengthStyleValue::create(CSS::Length::make_auto());
  220. auto value_id = CSS::value_id_from_string(string);
  221. if (value_id != CSS::ValueID::Invalid)
  222. return CSS::IdentifierStyleValue::create(value_id);
  223. auto color = parse_css_color(context, string);
  224. if (color.has_value())
  225. return CSS::ColorStyleValue::create(color.value());
  226. return CSS::StringStyleValue::create(string);
  227. }
  228. RefPtr<CSS::LengthStyleValue> parse_line_width(const CSS::ParsingContext& context, const StringView& part)
  229. {
  230. auto value = parse_css_value(context, part);
  231. if (value && value->is_length())
  232. return static_ptr_cast<CSS::LengthStyleValue>(value);
  233. return nullptr;
  234. }
  235. RefPtr<CSS::ColorStyleValue> parse_color(const CSS::ParsingContext& context, const StringView& part)
  236. {
  237. auto value = parse_css_value(context, part);
  238. if (value && value->is_color())
  239. return static_ptr_cast<CSS::ColorStyleValue>(value);
  240. return nullptr;
  241. }
  242. RefPtr<CSS::StringStyleValue> parse_line_style(const CSS::ParsingContext& context, const StringView& part)
  243. {
  244. auto parsed_value = parse_css_value(context, part);
  245. if (!parsed_value || !parsed_value->is_string())
  246. return nullptr;
  247. auto value = static_ptr_cast<CSS::StringStyleValue>(parsed_value);
  248. if (value->to_string() == "dotted")
  249. return value;
  250. if (value->to_string() == "dashed")
  251. return value;
  252. if (value->to_string() == "solid")
  253. return value;
  254. if (value->to_string() == "double")
  255. return value;
  256. if (value->to_string() == "groove")
  257. return value;
  258. if (value->to_string() == "ridge")
  259. return value;
  260. return nullptr;
  261. }
  262. class CSSParser {
  263. public:
  264. CSSParser(const CSS::ParsingContext& context, const StringView& input)
  265. : m_context(context)
  266. , css(input)
  267. {
  268. }
  269. bool next_is(const char* str) const
  270. {
  271. size_t len = strlen(str);
  272. for (size_t i = 0; i < len; ++i) {
  273. if (peek(i) != str[i])
  274. return false;
  275. }
  276. return true;
  277. }
  278. char peek(size_t offset = 0) const
  279. {
  280. if ((index + offset) < css.length())
  281. return css[index + offset];
  282. return 0;
  283. }
  284. bool consume_specific(char ch)
  285. {
  286. if (peek() != ch) {
  287. dbgln("CSSParser: Peeked '{:c}' wanted specific '{:c}'", peek(), ch);
  288. }
  289. if (!peek()) {
  290. PARSE_ERROR();
  291. return false;
  292. }
  293. if (peek() != ch) {
  294. PARSE_ERROR();
  295. ++index;
  296. return false;
  297. }
  298. ++index;
  299. return true;
  300. }
  301. char consume_one()
  302. {
  303. PARSE_ASSERT(index < css.length());
  304. return css[index++];
  305. };
  306. bool consume_whitespace_or_comments()
  307. {
  308. size_t original_index = index;
  309. bool in_comment = false;
  310. for (; index < css.length(); ++index) {
  311. char ch = peek();
  312. if (isspace(ch))
  313. continue;
  314. if (!in_comment && ch == '/' && peek(1) == '*') {
  315. in_comment = true;
  316. ++index;
  317. continue;
  318. }
  319. if (in_comment && ch == '*' && peek(1) == '/') {
  320. in_comment = false;
  321. ++index;
  322. continue;
  323. }
  324. if (in_comment)
  325. continue;
  326. break;
  327. }
  328. return original_index != index;
  329. }
  330. bool is_valid_selector_char(char ch) const
  331. {
  332. return isalnum(ch) || ch == '-' || ch == '_' || ch == '(' || ch == ')' || ch == '@';
  333. }
  334. bool is_combinator(char ch) const
  335. {
  336. return ch == '~' || ch == '>' || ch == '+';
  337. }
  338. Optional<CSS::Selector::SimpleSelector> parse_simple_selector()
  339. {
  340. auto index_at_start = index;
  341. if (consume_whitespace_or_comments())
  342. return {};
  343. if (!peek() || peek() == '{' || peek() == ',' || is_combinator(peek()))
  344. return {};
  345. CSS::Selector::SimpleSelector::Type type;
  346. if (peek() == '*') {
  347. type = CSS::Selector::SimpleSelector::Type::Universal;
  348. consume_one();
  349. return CSS::Selector::SimpleSelector {
  350. type,
  351. CSS::Selector::SimpleSelector::PseudoClass::None,
  352. CSS::Selector::SimpleSelector::PseudoElement::None,
  353. String(),
  354. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  355. String(),
  356. String()
  357. };
  358. }
  359. if (peek() == '.') {
  360. type = CSS::Selector::SimpleSelector::Type::Class;
  361. consume_one();
  362. } else if (peek() == '#') {
  363. type = CSS::Selector::SimpleSelector::Type::Id;
  364. consume_one();
  365. } else if (isalpha(peek())) {
  366. type = CSS::Selector::SimpleSelector::Type::TagName;
  367. } else {
  368. type = CSS::Selector::SimpleSelector::Type::Universal;
  369. }
  370. if (type != CSS::Selector::SimpleSelector::Type::Universal) {
  371. while (is_valid_selector_char(peek()))
  372. buffer.append(consume_one());
  373. PARSE_ASSERT(!buffer.is_null());
  374. }
  375. auto value = String::copy(buffer);
  376. if (type == CSS::Selector::SimpleSelector::Type::TagName) {
  377. // Some stylesheets use uppercase tag names, so here's a hack to just lowercase them internally.
  378. value = value.to_lowercase();
  379. }
  380. CSS::Selector::SimpleSelector simple_selector {
  381. type,
  382. CSS::Selector::SimpleSelector::PseudoClass::None,
  383. CSS::Selector::SimpleSelector::PseudoElement::None,
  384. value,
  385. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  386. String(),
  387. String()
  388. };
  389. buffer.clear();
  390. if (peek() == '[') {
  391. CSS::Selector::SimpleSelector::AttributeMatchType attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::HasAttribute;
  392. String attribute_name;
  393. String attribute_value;
  394. bool in_value = false;
  395. consume_specific('[');
  396. char expected_end_of_attribute_selector = ']';
  397. while (peek() != expected_end_of_attribute_selector) {
  398. char ch = consume_one();
  399. if (ch == '=' || (ch == '~' && peek() == '=')) {
  400. if (ch == '=') {
  401. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::ExactValueMatch;
  402. } else if (ch == '~') {
  403. consume_one();
  404. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::Contains;
  405. }
  406. attribute_name = String::copy(buffer);
  407. buffer.clear();
  408. in_value = true;
  409. consume_whitespace_or_comments();
  410. if (peek() == '\'') {
  411. expected_end_of_attribute_selector = '\'';
  412. consume_one();
  413. } else if (peek() == '"') {
  414. expected_end_of_attribute_selector = '"';
  415. consume_one();
  416. }
  417. continue;
  418. }
  419. // FIXME: This is a hack that will go away when we replace this with a big boy CSS parser.
  420. if (ch == '\\')
  421. ch = consume_one();
  422. buffer.append(ch);
  423. }
  424. if (in_value)
  425. attribute_value = String::copy(buffer);
  426. else
  427. attribute_name = String::copy(buffer);
  428. buffer.clear();
  429. simple_selector.attribute_match_type = attribute_match_type;
  430. simple_selector.attribute_name = attribute_name;
  431. simple_selector.attribute_value = attribute_value;
  432. if (expected_end_of_attribute_selector != ']') {
  433. if (!consume_specific(expected_end_of_attribute_selector))
  434. return {};
  435. }
  436. consume_whitespace_or_comments();
  437. if (!consume_specific(']'))
  438. return {};
  439. }
  440. if (peek() == ':') {
  441. // FIXME: Implement pseudo elements.
  442. [[maybe_unused]] bool is_pseudo_element = false;
  443. consume_one();
  444. if (peek() == ':') {
  445. is_pseudo_element = true;
  446. consume_one();
  447. }
  448. if (next_is("not")) {
  449. buffer.append(consume_one());
  450. buffer.append(consume_one());
  451. buffer.append(consume_one());
  452. if (!consume_specific('('))
  453. return {};
  454. buffer.append('(');
  455. while (peek() != ')')
  456. buffer.append(consume_one());
  457. if (!consume_specific(')'))
  458. return {};
  459. buffer.append(')');
  460. } else {
  461. while (is_valid_selector_char(peek()))
  462. buffer.append(consume_one());
  463. }
  464. auto pseudo_name = String::copy(buffer);
  465. buffer.clear();
  466. // Ignore for now, otherwise we produce a "false positive" selector
  467. // and apply styles to the element itself, not its pseudo element
  468. if (is_pseudo_element)
  469. return {};
  470. if (pseudo_name.equals_ignoring_case("link"))
  471. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Link;
  472. else if (pseudo_name.equals_ignoring_case("visited"))
  473. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Visited;
  474. else if (pseudo_name.equals_ignoring_case("hover"))
  475. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Hover;
  476. else if (pseudo_name.equals_ignoring_case("focus"))
  477. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Focus;
  478. else if (pseudo_name.equals_ignoring_case("first-child"))
  479. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::FirstChild;
  480. else if (pseudo_name.equals_ignoring_case("last-child"))
  481. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::LastChild;
  482. else if (pseudo_name.equals_ignoring_case("only-child"))
  483. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::OnlyChild;
  484. else if (pseudo_name.equals_ignoring_case("empty"))
  485. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Empty;
  486. else if (pseudo_name.equals_ignoring_case("root"))
  487. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Root;
  488. else if (pseudo_name.equals_ignoring_case("before"))
  489. simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::Before;
  490. else if (pseudo_name.equals_ignoring_case("after"))
  491. simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::After;
  492. }
  493. if (index == index_at_start) {
  494. // We consumed nothing.
  495. return {};
  496. }
  497. return simple_selector;
  498. }
  499. Optional<CSS::Selector::ComplexSelector> parse_complex_selector()
  500. {
  501. auto relation = CSS::Selector::ComplexSelector::Relation::Descendant;
  502. if (peek() == '{' || peek() == ',')
  503. return {};
  504. if (is_combinator(peek())) {
  505. switch (peek()) {
  506. case '>':
  507. relation = CSS::Selector::ComplexSelector::Relation::ImmediateChild;
  508. break;
  509. case '+':
  510. relation = CSS::Selector::ComplexSelector::Relation::AdjacentSibling;
  511. break;
  512. case '~':
  513. relation = CSS::Selector::ComplexSelector::Relation::GeneralSibling;
  514. break;
  515. }
  516. consume_one();
  517. consume_whitespace_or_comments();
  518. }
  519. consume_whitespace_or_comments();
  520. Vector<CSS::Selector::SimpleSelector> simple_selectors;
  521. for (;;) {
  522. auto component = parse_simple_selector();
  523. if (!component.has_value())
  524. break;
  525. simple_selectors.append(component.value());
  526. // If this assert triggers, we're most likely up to no good.
  527. PARSE_ASSERT(simple_selectors.size() < 100);
  528. }
  529. if (simple_selectors.is_empty())
  530. return {};
  531. return CSS::Selector::ComplexSelector { relation, move(simple_selectors) };
  532. }
  533. void parse_selector()
  534. {
  535. Vector<CSS::Selector::ComplexSelector> complex_selectors;
  536. for (;;) {
  537. auto index_before = index;
  538. auto complex_selector = parse_complex_selector();
  539. if (complex_selector.has_value())
  540. complex_selectors.append(complex_selector.value());
  541. consume_whitespace_or_comments();
  542. if (!peek() || peek() == ',' || peek() == '{')
  543. break;
  544. // HACK: If we didn't move forward, just let go.
  545. if (index == index_before)
  546. break;
  547. }
  548. if (complex_selectors.is_empty())
  549. return;
  550. complex_selectors.first().relation = CSS::Selector::ComplexSelector::Relation::None;
  551. current_rule.selectors.append(CSS::Selector(move(complex_selectors)));
  552. }
  553. Optional<CSS::Selector> parse_individual_selector()
  554. {
  555. parse_selector();
  556. if (current_rule.selectors.is_empty())
  557. return {};
  558. return current_rule.selectors.last();
  559. }
  560. void parse_selector_list()
  561. {
  562. for (;;) {
  563. auto index_before = index;
  564. parse_selector();
  565. consume_whitespace_or_comments();
  566. if (peek() == ',') {
  567. consume_one();
  568. continue;
  569. }
  570. if (peek() == '{')
  571. break;
  572. // HACK: If we didn't move forward, just let go.
  573. if (index_before == index)
  574. break;
  575. }
  576. }
  577. bool is_valid_property_name_char(char ch) const
  578. {
  579. return ch && !isspace(ch) && ch != ':';
  580. }
  581. bool is_valid_property_value_char(char ch) const
  582. {
  583. return ch && ch != '!' && ch != ';' && ch != '}';
  584. }
  585. struct ValueAndImportant {
  586. String value;
  587. bool important { false };
  588. };
  589. ValueAndImportant consume_css_value()
  590. {
  591. buffer.clear();
  592. int paren_nesting_level = 0;
  593. bool important = false;
  594. for (;;) {
  595. char ch = peek();
  596. if (ch == '(') {
  597. ++paren_nesting_level;
  598. buffer.append(consume_one());
  599. continue;
  600. }
  601. if (ch == ')') {
  602. PARSE_ASSERT(paren_nesting_level > 0);
  603. --paren_nesting_level;
  604. buffer.append(consume_one());
  605. continue;
  606. }
  607. if (paren_nesting_level > 0) {
  608. buffer.append(consume_one());
  609. continue;
  610. }
  611. if (next_is("!important")) {
  612. consume_specific('!');
  613. consume_specific('i');
  614. consume_specific('m');
  615. consume_specific('p');
  616. consume_specific('o');
  617. consume_specific('r');
  618. consume_specific('t');
  619. consume_specific('a');
  620. consume_specific('n');
  621. consume_specific('t');
  622. important = true;
  623. continue;
  624. }
  625. if (next_is("/*")) {
  626. consume_whitespace_or_comments();
  627. continue;
  628. }
  629. if (!ch)
  630. break;
  631. if (ch == '\\') {
  632. consume_one();
  633. buffer.append(consume_one());
  634. continue;
  635. }
  636. if (ch == '}')
  637. break;
  638. if (ch == ';')
  639. break;
  640. buffer.append(consume_one());
  641. }
  642. // Remove trailing whitespace.
  643. while (!buffer.is_empty() && isspace(buffer.last()))
  644. buffer.take_last();
  645. auto string = String::copy(buffer);
  646. buffer.clear();
  647. return { string, important };
  648. }
  649. Optional<CSS::StyleProperty> parse_property()
  650. {
  651. consume_whitespace_or_comments();
  652. if (peek() == ';') {
  653. consume_one();
  654. return {};
  655. }
  656. if (peek() == '}')
  657. return {};
  658. buffer.clear();
  659. while (is_valid_property_name_char(peek()))
  660. buffer.append(consume_one());
  661. auto property_name = String::copy(buffer);
  662. buffer.clear();
  663. consume_whitespace_or_comments();
  664. if (!consume_specific(':'))
  665. return {};
  666. consume_whitespace_or_comments();
  667. auto [property_value, important] = consume_css_value();
  668. consume_whitespace_or_comments();
  669. if (peek() && peek() != '}') {
  670. if (!consume_specific(';'))
  671. return {};
  672. }
  673. auto property_id = CSS::property_id_from_string(property_name);
  674. if (property_id == CSS::PropertyID::Invalid) {
  675. dbgln("CSSParser: Unrecognized property '{}'", property_name);
  676. }
  677. auto value = parse_css_value(m_context, property_value, property_id);
  678. if (!value)
  679. return {};
  680. return CSS::StyleProperty { property_id, value.release_nonnull(), important };
  681. }
  682. void parse_declaration()
  683. {
  684. for (;;) {
  685. auto property = parse_property();
  686. if (property.has_value())
  687. current_rule.properties.append(property.value());
  688. consume_whitespace_or_comments();
  689. if (!peek() || peek() == '}')
  690. break;
  691. }
  692. }
  693. void parse_rule()
  694. {
  695. consume_whitespace_or_comments();
  696. if (!peek())
  697. return;
  698. // FIXME: We ignore @-rules for now.
  699. if (peek() == '@') {
  700. while (peek() != '{')
  701. consume_one();
  702. int level = 0;
  703. for (;;) {
  704. auto ch = consume_one();
  705. if (ch == '{') {
  706. ++level;
  707. } else if (ch == '}') {
  708. --level;
  709. if (level == 0)
  710. break;
  711. }
  712. }
  713. consume_whitespace_or_comments();
  714. return;
  715. }
  716. parse_selector_list();
  717. if (!consume_specific('{')) {
  718. PARSE_ERROR();
  719. return;
  720. }
  721. parse_declaration();
  722. if (!consume_specific('}')) {
  723. PARSE_ERROR();
  724. return;
  725. }
  726. rules.append(CSS::StyleRule::create(move(current_rule.selectors), CSS::StyleDeclaration::create(move(current_rule.properties))));
  727. consume_whitespace_or_comments();
  728. }
  729. RefPtr<CSS::StyleSheet> parse_sheet()
  730. {
  731. if (peek(0) == (char)0xef && peek(1) == (char)0xbb && peek(2) == (char)0xbf) {
  732. // HACK: Skip UTF-8 BOM.
  733. index += 3;
  734. }
  735. while (peek()) {
  736. parse_rule();
  737. }
  738. return CSS::StyleSheet::create(move(rules));
  739. }
  740. RefPtr<CSS::StyleDeclaration> parse_standalone_declaration()
  741. {
  742. consume_whitespace_or_comments();
  743. for (;;) {
  744. auto property = parse_property();
  745. if (property.has_value())
  746. current_rule.properties.append(property.value());
  747. consume_whitespace_or_comments();
  748. if (!peek())
  749. break;
  750. }
  751. return CSS::StyleDeclaration::create(move(current_rule.properties));
  752. }
  753. private:
  754. CSS::ParsingContext m_context;
  755. NonnullRefPtrVector<CSS::StyleRule> rules;
  756. struct CurrentRule {
  757. Vector<CSS::Selector> selectors;
  758. Vector<CSS::StyleProperty> properties;
  759. };
  760. CurrentRule current_rule;
  761. Vector<char> buffer;
  762. size_t index = 0;
  763. StringView css;
  764. };
  765. Optional<CSS::Selector> parse_selector(const CSS::ParsingContext& context, const StringView& selector_text)
  766. {
  767. CSSParser parser(context, selector_text);
  768. return parser.parse_individual_selector();
  769. }
  770. RefPtr<CSS::StyleSheet> parse_css(const CSS::ParsingContext& context, const StringView& css)
  771. {
  772. if (css.is_empty())
  773. return CSS::StyleSheet::create({});
  774. CSSParser parser(context, css);
  775. return parser.parse_sheet();
  776. }
  777. RefPtr<CSS::StyleDeclaration> parse_css_declaration(const CSS::ParsingContext& context, const StringView& css)
  778. {
  779. if (css.is_empty())
  780. return CSS::StyleDeclaration::create({});
  781. CSSParser parser(context, css);
  782. return parser.parse_standalone_declaration();
  783. }
  784. RefPtr<CSS::StyleValue> parse_html_length(const DOM::Document& document, const StringView& string)
  785. {
  786. auto integer = string.to_int();
  787. if (integer.has_value())
  788. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  789. return parse_css_value(CSS::ParsingContext(document), string);
  790. }
  791. }