DeprecatedCSSParser.cpp 36 KB

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