CSSParser.cpp 30 KB

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