DeprecatedCSSParser.cpp 32 KB

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