DeprecatedCSSParser.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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_first_of(",");
  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("hover")) {
  498. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Hover;
  499. } else if (pseudo_name.equals_ignoring_case("focus")) {
  500. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Focus;
  501. } else if (pseudo_name.equals_ignoring_case("first-child")) {
  502. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::FirstChild;
  503. } else if (pseudo_name.equals_ignoring_case("last-child")) {
  504. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::LastChild;
  505. } else if (pseudo_name.equals_ignoring_case("only-child")) {
  506. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::OnlyChild;
  507. } else if (pseudo_name.equals_ignoring_case("empty")) {
  508. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Empty;
  509. } else if (pseudo_name.equals_ignoring_case("root")) {
  510. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Root;
  511. } else if (pseudo_name.equals_ignoring_case("first-of-type")) {
  512. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::FirstOfType;
  513. } else if (pseudo_name.equals_ignoring_case("last-of-type")) {
  514. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::LastOfType;
  515. } else if (pseudo_name.starts_with("nth-child", CaseSensitivity::CaseInsensitive)) {
  516. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::NthChild;
  517. simple_selector.nth_child_pattern = CSS::Selector::SimpleSelector::NthChildPattern::parse(capture_selector_args(pseudo_name));
  518. } else if (pseudo_name.starts_with("nth-last-child", CaseSensitivity::CaseInsensitive)) {
  519. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::NthLastChild;
  520. simple_selector.nth_child_pattern = CSS::Selector::SimpleSelector::NthChildPattern::parse(capture_selector_args(pseudo_name));
  521. } else if (pseudo_name.equals_ignoring_case("before")) {
  522. simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::Before;
  523. } else if (pseudo_name.equals_ignoring_case("after")) {
  524. simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::After;
  525. } else if (pseudo_name.equals_ignoring_case("disabled")) {
  526. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Disabled;
  527. } else if (pseudo_name.equals_ignoring_case("enabled")) {
  528. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Enabled;
  529. } else if (pseudo_name.equals_ignoring_case("checked")) {
  530. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Checked;
  531. } else if (pseudo_name.starts_with("not", CaseSensitivity::CaseInsensitive)) {
  532. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Not;
  533. simple_selector.not_selector = capture_selector_args(pseudo_name);
  534. } else {
  535. dbgln("Unknown pseudo class: '{}'", pseudo_name);
  536. return {};
  537. }
  538. }
  539. if (index == index_at_start) {
  540. // We consumed nothing.
  541. return {};
  542. }
  543. return simple_selector;
  544. }
  545. Optional<CSS::Selector::ComplexSelector> parse_complex_selector()
  546. {
  547. auto relation = CSS::Selector::ComplexSelector::Relation::Descendant;
  548. if (peek() == '{' || peek() == ',')
  549. return {};
  550. if (is_combinator(peek())) {
  551. switch (peek()) {
  552. case '>':
  553. relation = CSS::Selector::ComplexSelector::Relation::ImmediateChild;
  554. break;
  555. case '+':
  556. relation = CSS::Selector::ComplexSelector::Relation::AdjacentSibling;
  557. break;
  558. case '~':
  559. relation = CSS::Selector::ComplexSelector::Relation::GeneralSibling;
  560. break;
  561. }
  562. consume_one();
  563. consume_whitespace_or_comments();
  564. }
  565. consume_whitespace_or_comments();
  566. Vector<CSS::Selector::SimpleSelector> simple_selectors;
  567. for (;;) {
  568. auto component = parse_simple_selector();
  569. if (!component.has_value())
  570. break;
  571. simple_selectors.append(component.value());
  572. // If this assert triggers, we're most likely up to no good.
  573. PARSE_VERIFY(simple_selectors.size() < 100);
  574. }
  575. if (simple_selectors.is_empty())
  576. return {};
  577. return CSS::Selector::ComplexSelector { relation, move(simple_selectors) };
  578. }
  579. void parse_selector()
  580. {
  581. Vector<CSS::Selector::ComplexSelector> complex_selectors;
  582. for (;;) {
  583. auto index_before = index;
  584. auto complex_selector = parse_complex_selector();
  585. if (complex_selector.has_value())
  586. complex_selectors.append(complex_selector.value());
  587. consume_whitespace_or_comments();
  588. if (!peek() || peek() == ',' || peek() == '{')
  589. break;
  590. // HACK: If we didn't move forward, just let go.
  591. if (index == index_before)
  592. break;
  593. }
  594. if (complex_selectors.is_empty())
  595. return;
  596. complex_selectors.first().relation = CSS::Selector::ComplexSelector::Relation::None;
  597. current_rule.selectors.append(CSS::Selector(move(complex_selectors)));
  598. }
  599. Optional<CSS::Selector> parse_individual_selector()
  600. {
  601. parse_selector();
  602. if (current_rule.selectors.is_empty())
  603. return {};
  604. return current_rule.selectors.last();
  605. }
  606. void parse_selector_list()
  607. {
  608. for (;;) {
  609. auto index_before = index;
  610. parse_selector();
  611. consume_whitespace_or_comments();
  612. if (peek() == ',') {
  613. consume_one();
  614. continue;
  615. }
  616. if (peek() == '{')
  617. break;
  618. // HACK: If we didn't move forward, just let go.
  619. if (index_before == index)
  620. break;
  621. }
  622. }
  623. bool is_valid_property_name_char(char ch) const
  624. {
  625. return ch && !isspace(ch) && ch != ':';
  626. }
  627. bool is_valid_property_value_char(char ch) const
  628. {
  629. return ch && ch != '!' && ch != ';' && ch != '}';
  630. }
  631. bool is_valid_string_quotes_char(char ch) const
  632. {
  633. return ch == '\'' || ch == '\"';
  634. }
  635. struct ValueAndImportant {
  636. String value;
  637. bool important { false };
  638. };
  639. ValueAndImportant consume_css_value()
  640. {
  641. buffer.clear();
  642. int paren_nesting_level = 0;
  643. bool important = false;
  644. for (;;) {
  645. char ch = peek();
  646. if (ch == '(') {
  647. ++paren_nesting_level;
  648. buffer.append(consume_one());
  649. continue;
  650. }
  651. if (ch == ')') {
  652. PARSE_VERIFY(paren_nesting_level > 0);
  653. --paren_nesting_level;
  654. buffer.append(consume_one());
  655. continue;
  656. }
  657. if (paren_nesting_level > 0) {
  658. buffer.append(consume_one());
  659. continue;
  660. }
  661. if (next_is("!important")) {
  662. consume_specific('!');
  663. consume_specific('i');
  664. consume_specific('m');
  665. consume_specific('p');
  666. consume_specific('o');
  667. consume_specific('r');
  668. consume_specific('t');
  669. consume_specific('a');
  670. consume_specific('n');
  671. consume_specific('t');
  672. important = true;
  673. continue;
  674. }
  675. if (next_is("/*")) {
  676. consume_whitespace_or_comments();
  677. continue;
  678. }
  679. if (!ch)
  680. break;
  681. if (ch == '\\') {
  682. consume_one();
  683. buffer.append(consume_one());
  684. continue;
  685. }
  686. if (ch == '}')
  687. break;
  688. if (ch == ';')
  689. break;
  690. buffer.append(consume_one());
  691. }
  692. // Remove trailing whitespace.
  693. while (!buffer.is_empty() && isspace(buffer.last()))
  694. buffer.take_last();
  695. auto string = String::copy(buffer);
  696. buffer.clear();
  697. return { string, important };
  698. }
  699. Optional<CSS::StyleProperty> parse_property()
  700. {
  701. consume_whitespace_or_comments();
  702. if (peek() == ';') {
  703. consume_one();
  704. return {};
  705. }
  706. if (peek() == '}')
  707. return {};
  708. buffer.clear();
  709. while (is_valid_property_name_char(peek()))
  710. buffer.append(consume_one());
  711. auto property_name = String::copy(buffer);
  712. buffer.clear();
  713. consume_whitespace_or_comments();
  714. if (!consume_specific(':'))
  715. return {};
  716. consume_whitespace_or_comments();
  717. auto [property_value, important] = consume_css_value();
  718. consume_whitespace_or_comments();
  719. if (peek() && peek() != '}') {
  720. if (!consume_specific(';'))
  721. return {};
  722. }
  723. auto property_id = CSS::property_id_from_string(property_name);
  724. if (property_id == CSS::PropertyID::Invalid && property_name.starts_with("--"))
  725. property_id = CSS::PropertyID::Custom;
  726. if (property_id == CSS::PropertyID::Invalid && !property_name.starts_with("-")) {
  727. dbgln("CSSParser: Unrecognized property '{}'", property_name);
  728. }
  729. auto value = parse_css_value(m_context, property_value, property_id);
  730. if (!value)
  731. return {};
  732. if (property_id == CSS::PropertyID::Custom) {
  733. return CSS::StyleProperty { property_id, value.release_nonnull(), property_name, important };
  734. }
  735. return CSS::StyleProperty { property_id, value.release_nonnull(), {}, important };
  736. }
  737. void parse_declaration()
  738. {
  739. for (;;) {
  740. auto property = parse_property();
  741. if (property.has_value()) {
  742. auto property_value = property.value();
  743. if (property_value.property_id == CSS::PropertyID::Custom)
  744. current_rule.custom_properties.set(property_value.custom_name, property_value);
  745. else
  746. current_rule.properties.append(property_value);
  747. }
  748. consume_whitespace_or_comments();
  749. if (!peek() || peek() == '}')
  750. break;
  751. }
  752. }
  753. void parse_style_rule()
  754. {
  755. parse_selector_list();
  756. if (!consume_specific('{')) {
  757. log_parse_error();
  758. return;
  759. }
  760. parse_declaration();
  761. if (!consume_specific('}')) {
  762. log_parse_error();
  763. return;
  764. }
  765. rules.append(CSS::CSSStyleRule::create(move(current_rule.selectors), CSS::CSSStyleDeclaration::create(move(current_rule.properties), move(current_rule.custom_properties))));
  766. }
  767. Optional<String> parse_string()
  768. {
  769. if (!is_valid_string_quotes_char(peek())) {
  770. log_parse_error();
  771. return {};
  772. }
  773. char end_char = consume_one();
  774. buffer.clear();
  775. while (peek() && peek() != end_char) {
  776. if (peek() == '\\') {
  777. consume_specific('\\');
  778. if (peek() == 0)
  779. break;
  780. }
  781. buffer.append(consume_one());
  782. }
  783. String string_value(String::copy(buffer));
  784. buffer.clear();
  785. if (consume_specific(end_char)) {
  786. return { string_value };
  787. }
  788. return {};
  789. }
  790. Optional<String> parse_url()
  791. {
  792. if (is_valid_string_quotes_char(peek()))
  793. return parse_string();
  794. buffer.clear();
  795. while (peek() && peek() != ')')
  796. buffer.append(consume_one());
  797. String url_value(String::copy(buffer));
  798. buffer.clear();
  799. if (peek() == ')')
  800. return { url_value };
  801. return {};
  802. }
  803. void parse_at_import_rule()
  804. {
  805. consume_whitespace_or_comments();
  806. Optional<String> imported_address;
  807. if (is_valid_string_quotes_char(peek())) {
  808. imported_address = parse_string();
  809. } else if (next_is("url")) {
  810. consume_specific('u');
  811. consume_specific('r');
  812. consume_specific('l');
  813. consume_whitespace_or_comments();
  814. if (!consume_specific('('))
  815. return;
  816. imported_address = parse_url();
  817. if (!consume_specific(')'))
  818. return;
  819. } else {
  820. log_parse_error();
  821. return;
  822. }
  823. if (imported_address.has_value())
  824. rules.append(CSS::CSSImportRule::create(m_context.complete_url(imported_address.value())));
  825. // FIXME: We ignore possible media query list
  826. while (peek() && peek() != ';')
  827. consume_one();
  828. consume_specific(';');
  829. }
  830. void parse_at_rule()
  831. {
  832. HashMap<String, void (CSSParser::*)()> at_rules_parsers({ { "@import", &CSSParser::parse_at_import_rule } });
  833. for (const auto& rule_parser_pair : at_rules_parsers) {
  834. if (next_is(rule_parser_pair.key.characters())) {
  835. for (char c : rule_parser_pair.key) {
  836. consume_specific(c);
  837. }
  838. (this->*(rule_parser_pair.value))();
  839. return;
  840. }
  841. }
  842. // FIXME: We ignore other @-rules completely for now.
  843. while (peek() != 0 && peek() != '{')
  844. consume_one();
  845. int level = 0;
  846. for (;;) {
  847. auto ch = consume_one();
  848. if (ch == '{') {
  849. ++level;
  850. } else if (ch == '}') {
  851. --level;
  852. if (level == 0)
  853. break;
  854. }
  855. }
  856. }
  857. void parse_rule()
  858. {
  859. consume_whitespace_or_comments();
  860. if (!peek())
  861. return;
  862. if (peek() == '@') {
  863. parse_at_rule();
  864. } else {
  865. parse_style_rule();
  866. }
  867. consume_whitespace_or_comments();
  868. }
  869. RefPtr<CSS::CSSStyleSheet> parse_sheet()
  870. {
  871. if (peek(0) == (char)0xef && peek(1) == (char)0xbb && peek(2) == (char)0xbf) {
  872. // HACK: Skip UTF-8 BOM.
  873. index += 3;
  874. }
  875. while (peek()) {
  876. parse_rule();
  877. }
  878. return CSS::CSSStyleSheet::create(move(rules));
  879. }
  880. RefPtr<CSS::CSSStyleDeclaration> parse_standalone_declaration()
  881. {
  882. consume_whitespace_or_comments();
  883. for (;;) {
  884. auto property = parse_property();
  885. if (property.has_value()) {
  886. auto property_value = property.value();
  887. if (property_value.property_id == CSS::PropertyID::Custom)
  888. current_rule.custom_properties.set(property_value.custom_name, property_value);
  889. else
  890. current_rule.properties.append(property_value);
  891. }
  892. consume_whitespace_or_comments();
  893. if (!peek())
  894. break;
  895. }
  896. return CSS::CSSStyleDeclaration::create(move(current_rule.properties), move(current_rule.custom_properties));
  897. }
  898. private:
  899. CSS::ParsingContext m_context;
  900. NonnullRefPtrVector<CSS::CSSRule> rules;
  901. struct CurrentRule {
  902. Vector<CSS::Selector> selectors;
  903. Vector<CSS::StyleProperty> properties;
  904. HashMap<String, CSS::StyleProperty> custom_properties;
  905. };
  906. CurrentRule current_rule;
  907. Vector<char> buffer;
  908. size_t index = 0;
  909. StringView css;
  910. };
  911. Optional<CSS::Selector> parse_selector(const CSS::ParsingContext& context, const StringView& selector_text)
  912. {
  913. CSSParser parser(context, selector_text);
  914. return parser.parse_individual_selector();
  915. }
  916. RefPtr<CSS::CSSStyleSheet> parse_css(const CSS::ParsingContext& context, const StringView& css)
  917. {
  918. if (css.is_empty())
  919. return CSS::CSSStyleSheet::create({});
  920. CSSParser parser(context, css);
  921. return parser.parse_sheet();
  922. }
  923. RefPtr<CSS::CSSStyleDeclaration> parse_css_declaration(const CSS::ParsingContext& context, const StringView& css)
  924. {
  925. if (css.is_empty())
  926. return CSS::CSSStyleDeclaration::create({}, {});
  927. CSSParser parser(context, css);
  928. return parser.parse_standalone_declaration();
  929. }
  930. RefPtr<CSS::StyleValue> parse_html_length(const DOM::Document& document, const StringView& string)
  931. {
  932. auto integer = string.to_int();
  933. if (integer.has_value())
  934. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  935. return parse_css_value(CSS::ParsingContext(document), string);
  936. }
  937. }