CSSParser.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/HashMap.h>
  27. #include <LibWeb/CSS/Parser/CSSParser.h>
  28. #include <LibWeb/CSS/PropertyID.h>
  29. #include <LibWeb/CSS/StyleSheet.h>
  30. #include <LibWeb/DOM/Document.h>
  31. #include <ctype.h>
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #define PARSE_ASSERT(x) \
  35. if (!(x)) { \
  36. dbg() << "CSS PARSER ASSERTION FAILED: " << #x; \
  37. dbg() << "At character# " << index << " in CSS: _" << css << "_"; \
  38. ASSERT_NOT_REACHED(); \
  39. }
  40. #define PARSE_ERROR() \
  41. do { \
  42. dbg() << "CSS parse error"; \
  43. } while (0)
  44. namespace Web {
  45. namespace CSS {
  46. ParsingContext::ParsingContext()
  47. {
  48. }
  49. ParsingContext::ParsingContext(const DOM::Document& document)
  50. : m_document(&document)
  51. {
  52. }
  53. ParsingContext::ParsingContext(const DOM::ParentNode& parent_node)
  54. : m_document(&parent_node.document())
  55. {
  56. }
  57. bool ParsingContext::in_quirks_mode() const
  58. {
  59. return m_document ? m_document->in_quirks_mode() : false;
  60. }
  61. }
  62. static CSS::ValueID value_id_for_palette_string(const StringView& string)
  63. {
  64. if (string == "desktop-background")
  65. return CSS::ValueID::VendorSpecificPaletteDesktopBackground;
  66. else if (string == "active-window-border1")
  67. return CSS::ValueID::VendorSpecificPaletteActiveWindowBorder1;
  68. else if (string == "active-window-border2")
  69. return CSS::ValueID::VendorSpecificPaletteActiveWindowBorder2;
  70. else if (string == "active-window-title")
  71. return CSS::ValueID::VendorSpecificPaletteActiveWindowTitle;
  72. else if (string == "inactive-window-border1")
  73. return CSS::ValueID::VendorSpecificPaletteInactiveWindowBorder1;
  74. else if (string == "inactive-window-border2")
  75. return CSS::ValueID::VendorSpecificPaletteInactiveWindowBorder2;
  76. else if (string == "inactive-window-title")
  77. return CSS::ValueID::VendorSpecificPaletteInactiveWindowTitle;
  78. else if (string == "moving-window-border1")
  79. return CSS::ValueID::VendorSpecificPaletteMovingWindowBorder1;
  80. else if (string == "moving-window-border2")
  81. return CSS::ValueID::VendorSpecificPaletteMovingWindowBorder2;
  82. else if (string == "moving-window-title")
  83. return CSS::ValueID::VendorSpecificPaletteMovingWindowTitle;
  84. else if (string == "highlight-window-border1")
  85. return CSS::ValueID::VendorSpecificPaletteHighlightWindowBorder1;
  86. else if (string == "highlight-window-border2")
  87. return CSS::ValueID::VendorSpecificPaletteHighlightWindowBorder2;
  88. else if (string == "highlight-window-title")
  89. return CSS::ValueID::VendorSpecificPaletteHighlightWindowTitle;
  90. else if (string == "menu-stripe")
  91. return CSS::ValueID::VendorSpecificPaletteMenuStripe;
  92. else if (string == "menu-base")
  93. return CSS::ValueID::VendorSpecificPaletteMenuBase;
  94. else if (string == "menu-base-text")
  95. return CSS::ValueID::VendorSpecificPaletteMenuBaseText;
  96. else if (string == "menu-selection")
  97. return CSS::ValueID::VendorSpecificPaletteMenuSelection;
  98. else if (string == "menu-selection-text")
  99. return CSS::ValueID::VendorSpecificPaletteMenuSelectionText;
  100. else if (string == "window")
  101. return CSS::ValueID::VendorSpecificPaletteWindow;
  102. else if (string == "window-text")
  103. return CSS::ValueID::VendorSpecificPaletteWindowText;
  104. else if (string == "button")
  105. return CSS::ValueID::VendorSpecificPaletteButton;
  106. else if (string == "button-text")
  107. return CSS::ValueID::VendorSpecificPaletteButtonText;
  108. else if (string == "base")
  109. return CSS::ValueID::VendorSpecificPaletteBase;
  110. else if (string == "base-text")
  111. return CSS::ValueID::VendorSpecificPaletteBaseText;
  112. else if (string == "threed-highlight")
  113. return CSS::ValueID::VendorSpecificPaletteThreedHighlight;
  114. else if (string == "threed-shadow1")
  115. return CSS::ValueID::VendorSpecificPaletteThreedShadow1;
  116. else if (string == "threed-shadow2")
  117. return CSS::ValueID::VendorSpecificPaletteThreedShadow2;
  118. else if (string == "hover-highlight")
  119. return CSS::ValueID::VendorSpecificPaletteHoverHighlight;
  120. else if (string == "selection")
  121. return CSS::ValueID::VendorSpecificPaletteSelection;
  122. else if (string == "selection-text")
  123. return CSS::ValueID::VendorSpecificPaletteSelectionText;
  124. else if (string == "inactive-selection")
  125. return CSS::ValueID::VendorSpecificPaletteInactiveSelection;
  126. else if (string == "inactive-selection-text")
  127. return CSS::ValueID::VendorSpecificPaletteInactiveSelectionText;
  128. else if (string == "rubber-band-fill")
  129. return CSS::ValueID::VendorSpecificPaletteRubberBandFill;
  130. else if (string == "rubber-band-border")
  131. return CSS::ValueID::VendorSpecificPaletteRubberBandBorder;
  132. else if (string == "link")
  133. return CSS::ValueID::VendorSpecificPaletteLink;
  134. else if (string == "active-link")
  135. return CSS::ValueID::VendorSpecificPaletteActiveLink;
  136. else if (string == "visited-link")
  137. return CSS::ValueID::VendorSpecificPaletteVisitedLink;
  138. else if (string == "ruler")
  139. return CSS::ValueID::VendorSpecificPaletteRuler;
  140. else if (string == "ruler-border")
  141. return CSS::ValueID::VendorSpecificPaletteRulerBorder;
  142. else if (string == "ruler-active-text")
  143. return CSS::ValueID::VendorSpecificPaletteRulerActiveText;
  144. else if (string == "ruler-inactive-text")
  145. return CSS::ValueID::VendorSpecificPaletteRulerInactiveText;
  146. else if (string == "text-cursor")
  147. return CSS::ValueID::VendorSpecificPaletteTextCursor;
  148. else if (string == "focus-outline")
  149. return CSS::ValueID::VendorSpecificPaletteFocusOutline;
  150. else if (string == "syntax-comment")
  151. return CSS::ValueID::VendorSpecificPaletteSyntaxComment;
  152. else if (string == "syntax-number")
  153. return CSS::ValueID::VendorSpecificPaletteSyntaxNumber;
  154. else if (string == "syntax-string")
  155. return CSS::ValueID::VendorSpecificPaletteSyntaxString;
  156. else if (string == "syntax-type")
  157. return CSS::ValueID::VendorSpecificPaletteSyntaxType;
  158. else if (string == "syntax-punctuation")
  159. return CSS::ValueID::VendorSpecificPaletteSyntaxPunctuation;
  160. else if (string == "syntax-operator")
  161. return CSS::ValueID::VendorSpecificPaletteSyntaxOperator;
  162. else if (string == "syntax-keyword")
  163. return CSS::ValueID::VendorSpecificPaletteSyntaxKeyword;
  164. else if (string == "syntax-control-keyword")
  165. return CSS::ValueID::VendorSpecificPaletteSyntaxControlKeyword;
  166. else if (string == "syntax-identifier")
  167. return CSS::ValueID::VendorSpecificPaletteSyntaxIdentifier;
  168. else if (string == "syntax-preprocessor-statement")
  169. return CSS::ValueID::VendorSpecificPaletteSyntaxPreprocessorStatement;
  170. else if (string == "syntax-preprocessor-value")
  171. return CSS::ValueID::VendorSpecificPaletteSyntaxPreprocessorValue;
  172. else
  173. return CSS::ValueID::Invalid;
  174. }
  175. static Optional<Color> parse_css_color(const CSS::ParsingContext&, const StringView& view)
  176. {
  177. if (view.equals_ignoring_case("transparent"))
  178. return Color::from_rgba(0x00000000);
  179. auto color = Color::from_string(view.to_string().to_lowercase());
  180. if (color.has_value())
  181. return color;
  182. return {};
  183. }
  184. static Optional<float> try_parse_float(const StringView& string)
  185. {
  186. const char* str = string.characters_without_null_termination();
  187. size_t len = string.length();
  188. size_t weight = 1;
  189. int exp_val = 0;
  190. float value = 0.0f;
  191. float fraction = 0.0f;
  192. bool has_sign = false;
  193. bool is_negative = false;
  194. bool is_fractional = false;
  195. bool is_scientific = false;
  196. if (str[0] == '-') {
  197. is_negative = true;
  198. has_sign = true;
  199. }
  200. if (str[0] == '+') {
  201. has_sign = true;
  202. }
  203. for (size_t i = has_sign; i < len; i++) {
  204. // Looks like we're about to start working on the fractional part
  205. if (str[i] == '.') {
  206. is_fractional = true;
  207. continue;
  208. }
  209. if (str[i] == 'e' || str[i] == 'E') {
  210. if (str[i + 1] == '-' || str[i + 1] == '+')
  211. exp_val = atoi(str + i + 2);
  212. else
  213. exp_val = atoi(str + i + 1);
  214. is_scientific = true;
  215. continue;
  216. }
  217. if (str[i] < '0' || str[i] > '9' || exp_val != 0) {
  218. return {};
  219. continue;
  220. }
  221. if (is_fractional) {
  222. fraction *= 10;
  223. fraction += str[i] - '0';
  224. weight *= 10;
  225. } else {
  226. value = value * 10;
  227. value += str[i] - '0';
  228. }
  229. }
  230. fraction /= weight;
  231. value += fraction;
  232. if (is_scientific) {
  233. bool divide = exp_val < 0;
  234. if (divide)
  235. exp_val *= -1;
  236. for (int i = 0; i < exp_val; i++) {
  237. if (divide)
  238. value /= 10;
  239. else
  240. value *= 10;
  241. }
  242. }
  243. return is_negative ? -value : value;
  244. }
  245. static CSS::Length parse_length(const CSS::ParsingContext& context, const StringView& view, bool& is_bad_length)
  246. {
  247. CSS::Length::Type type = CSS::Length::Type::Undefined;
  248. Optional<float> value;
  249. if (view.ends_with('%')) {
  250. type = CSS::Length::Type::Percentage;
  251. value = try_parse_float(view.substring_view(0, view.length() - 1));
  252. } else if (view.ends_with("px", CaseSensitivity::CaseInsensitive)) {
  253. type = CSS::Length::Type::Px;
  254. value = try_parse_float(view.substring_view(0, view.length() - 2));
  255. } else if (view.ends_with("pt", CaseSensitivity::CaseInsensitive)) {
  256. type = CSS::Length::Type::Pt;
  257. value = try_parse_float(view.substring_view(0, view.length() - 2));
  258. } else if (view.ends_with("rem", CaseSensitivity::CaseInsensitive)) {
  259. type = CSS::Length::Type::Rem;
  260. value = try_parse_float(view.substring_view(0, view.length() - 3));
  261. } else if (view.ends_with("em", CaseSensitivity::CaseInsensitive)) {
  262. type = CSS::Length::Type::Em;
  263. value = try_parse_float(view.substring_view(0, view.length() - 2));
  264. } else if (view.ends_with("ex", CaseSensitivity::CaseInsensitive)) {
  265. type = CSS::Length::Type::Ex;
  266. value = try_parse_float(view.substring_view(0, view.length() - 2));
  267. } else if (view == "0") {
  268. type = CSS::Length::Type::Px;
  269. value = 0;
  270. } else if (context.in_quirks_mode()) {
  271. type = CSS::Length::Type::Px;
  272. value = try_parse_float(view);
  273. } else {
  274. value = try_parse_float(view);
  275. if (value.has_value())
  276. is_bad_length = true;
  277. }
  278. if (!value.has_value())
  279. return {};
  280. return CSS::Length(value.value(), type);
  281. }
  282. RefPtr<CSS::StyleValue> parse_css_value(const CSS::ParsingContext& context, const StringView& string)
  283. {
  284. bool is_bad_length = false;
  285. auto length = parse_length(context, string, is_bad_length);
  286. if (is_bad_length)
  287. return nullptr;
  288. if (!length.is_undefined())
  289. return CSS::LengthStyleValue::create(length);
  290. if (string.equals_ignoring_case("inherit"))
  291. return CSS::InheritStyleValue::create();
  292. if (string.equals_ignoring_case("initial"))
  293. return CSS::InitialStyleValue::create();
  294. if (string.equals_ignoring_case("auto"))
  295. return CSS::LengthStyleValue::create(CSS::Length::make_auto());
  296. auto color = parse_css_color(context, string);
  297. if (color.has_value())
  298. return CSS::ColorStyleValue::create(color.value());
  299. if (string == "-libweb-link")
  300. return CSS::IdentifierStyleValue::create(CSS::ValueID::VendorSpecificLink);
  301. else if (string.starts_with("-libweb-palette-")) {
  302. auto value_id = value_id_for_palette_string(string.substring_view(16, string.length() - 16));
  303. return CSS::IdentifierStyleValue::create(value_id);
  304. }
  305. return CSS::StringStyleValue::create(string);
  306. }
  307. RefPtr<CSS::LengthStyleValue> parse_line_width(const CSS::ParsingContext& context, const StringView& part)
  308. {
  309. auto value = parse_css_value(context, part);
  310. if (value && value->is_length())
  311. return static_ptr_cast<CSS::LengthStyleValue>(value);
  312. return nullptr;
  313. }
  314. RefPtr<CSS::ColorStyleValue> parse_color(const CSS::ParsingContext& context, const StringView& part)
  315. {
  316. auto value = parse_css_value(context, part);
  317. if (value && value->is_color())
  318. return static_ptr_cast<CSS::ColorStyleValue>(value);
  319. return nullptr;
  320. }
  321. RefPtr<CSS::StringStyleValue> parse_line_style(const CSS::ParsingContext& context, const StringView& part)
  322. {
  323. auto parsed_value = parse_css_value(context, part);
  324. if (!parsed_value || !parsed_value->is_string())
  325. return nullptr;
  326. auto value = static_ptr_cast<CSS::StringStyleValue>(parsed_value);
  327. if (value->to_string() == "dotted")
  328. return value;
  329. if (value->to_string() == "dashed")
  330. return value;
  331. if (value->to_string() == "solid")
  332. return value;
  333. if (value->to_string() == "double")
  334. return value;
  335. if (value->to_string() == "groove")
  336. return value;
  337. if (value->to_string() == "ridge")
  338. return value;
  339. return nullptr;
  340. }
  341. class CSSParser {
  342. public:
  343. CSSParser(const CSS::ParsingContext& context, const StringView& input)
  344. : m_context(context)
  345. , css(input)
  346. {
  347. }
  348. bool next_is(const char* str) const
  349. {
  350. size_t len = strlen(str);
  351. for (size_t i = 0; i < len; ++i) {
  352. if (peek(i) != str[i])
  353. return false;
  354. }
  355. return true;
  356. }
  357. char peek(size_t offset = 0) const
  358. {
  359. if ((index + offset) < css.length())
  360. return css[index + offset];
  361. return 0;
  362. }
  363. char consume_specific(char ch)
  364. {
  365. if (peek() != ch) {
  366. dbg() << "peek() != '" << ch << "'";
  367. }
  368. if (peek() != ch) {
  369. PARSE_ERROR();
  370. }
  371. PARSE_ASSERT(index < css.length());
  372. ++index;
  373. return ch;
  374. }
  375. char consume_one()
  376. {
  377. PARSE_ASSERT(index < css.length());
  378. return css[index++];
  379. };
  380. bool consume_whitespace_or_comments()
  381. {
  382. size_t original_index = index;
  383. bool in_comment = false;
  384. for (; index < css.length(); ++index) {
  385. char ch = peek();
  386. if (isspace(ch))
  387. continue;
  388. if (!in_comment && ch == '/' && peek(1) == '*') {
  389. in_comment = true;
  390. ++index;
  391. continue;
  392. }
  393. if (in_comment && ch == '*' && peek(1) == '/') {
  394. in_comment = false;
  395. ++index;
  396. continue;
  397. }
  398. if (in_comment)
  399. continue;
  400. break;
  401. }
  402. return original_index != index;
  403. }
  404. bool is_valid_selector_char(char ch) const
  405. {
  406. return isalnum(ch) || ch == '-' || ch == '_' || ch == '(' || ch == ')' || ch == '@';
  407. }
  408. bool is_combinator(char ch) const
  409. {
  410. return ch == '~' || ch == '>' || ch == '+';
  411. }
  412. Optional<CSS::Selector::SimpleSelector> parse_simple_selector()
  413. {
  414. auto index_at_start = index;
  415. if (consume_whitespace_or_comments())
  416. return {};
  417. if (!peek() || peek() == '{' || peek() == ',' || is_combinator(peek()))
  418. return {};
  419. CSS::Selector::SimpleSelector::Type type;
  420. if (peek() == '*') {
  421. type = CSS::Selector::SimpleSelector::Type::Universal;
  422. consume_one();
  423. return CSS::Selector::SimpleSelector {
  424. type,
  425. CSS::Selector::SimpleSelector::PseudoClass::None,
  426. String(),
  427. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  428. String(),
  429. String()
  430. };
  431. }
  432. if (peek() == '.') {
  433. type = CSS::Selector::SimpleSelector::Type::Class;
  434. consume_one();
  435. } else if (peek() == '#') {
  436. type = CSS::Selector::SimpleSelector::Type::Id;
  437. consume_one();
  438. } else if (isalpha(peek())) {
  439. type = CSS::Selector::SimpleSelector::Type::TagName;
  440. } else {
  441. type = CSS::Selector::SimpleSelector::Type::Universal;
  442. }
  443. if (type != CSS::Selector::SimpleSelector::Type::Universal) {
  444. while (is_valid_selector_char(peek()))
  445. buffer.append(consume_one());
  446. PARSE_ASSERT(!buffer.is_null());
  447. }
  448. auto value = String::copy(buffer);
  449. if (type == CSS::Selector::SimpleSelector::Type::TagName) {
  450. // Some stylesheets use uppercase tag names, so here's a hack to just lowercase them internally.
  451. value = value.to_lowercase();
  452. }
  453. CSS::Selector::SimpleSelector simple_selector {
  454. type,
  455. CSS::Selector::SimpleSelector::PseudoClass::None,
  456. value,
  457. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  458. String(),
  459. String()
  460. };
  461. buffer.clear();
  462. if (peek() == '[') {
  463. CSS::Selector::SimpleSelector::AttributeMatchType attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::HasAttribute;
  464. String attribute_name;
  465. String attribute_value;
  466. bool in_value = false;
  467. consume_specific('[');
  468. char expected_end_of_attribute_selector = ']';
  469. while (peek() != expected_end_of_attribute_selector) {
  470. char ch = consume_one();
  471. if (ch == '=' || (ch == '~' && peek() == '=')) {
  472. if (ch == '=') {
  473. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::ExactValueMatch;
  474. } else if (ch == '~') {
  475. consume_one();
  476. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::Contains;
  477. }
  478. attribute_name = String::copy(buffer);
  479. buffer.clear();
  480. in_value = true;
  481. consume_whitespace_or_comments();
  482. if (peek() == '\'') {
  483. expected_end_of_attribute_selector = '\'';
  484. consume_one();
  485. } else if (peek() == '"') {
  486. expected_end_of_attribute_selector = '"';
  487. consume_one();
  488. }
  489. continue;
  490. }
  491. // FIXME: This is a hack that will go away when we replace this with a big boy CSS parser.
  492. if (ch == '\\')
  493. ch = consume_one();
  494. buffer.append(ch);
  495. }
  496. if (in_value)
  497. attribute_value = String::copy(buffer);
  498. else
  499. attribute_name = String::copy(buffer);
  500. buffer.clear();
  501. simple_selector.attribute_match_type = attribute_match_type;
  502. simple_selector.attribute_name = attribute_name;
  503. simple_selector.attribute_value = attribute_value;
  504. if (expected_end_of_attribute_selector != ']')
  505. consume_specific(expected_end_of_attribute_selector);
  506. consume_whitespace_or_comments();
  507. consume_specific(']');
  508. }
  509. if (peek() == ':') {
  510. // FIXME: Implement pseudo elements.
  511. [[maybe_unused]] bool is_pseudo_element = false;
  512. consume_one();
  513. if (peek() == ':') {
  514. is_pseudo_element = true;
  515. consume_one();
  516. }
  517. if (next_is("not")) {
  518. buffer.append(consume_one());
  519. buffer.append(consume_one());
  520. buffer.append(consume_one());
  521. buffer.append(consume_specific('('));
  522. while (peek() != ')')
  523. buffer.append(consume_one());
  524. buffer.append(consume_specific(')'));
  525. } else {
  526. while (is_valid_selector_char(peek()))
  527. buffer.append(consume_one());
  528. }
  529. auto pseudo_name = String::copy(buffer);
  530. buffer.clear();
  531. // Ignore for now, otherwise we produce a "false positive" selector
  532. // and apply styles to the element itself, not its pseudo element
  533. if (is_pseudo_element)
  534. return {};
  535. if (pseudo_name.equals_ignoring_case("link"))
  536. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Link;
  537. else if (pseudo_name.equals_ignoring_case("visited"))
  538. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Visited;
  539. else if (pseudo_name.equals_ignoring_case("hover"))
  540. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Hover;
  541. else if (pseudo_name.equals_ignoring_case("focus"))
  542. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Focus;
  543. else if (pseudo_name.equals_ignoring_case("first-child"))
  544. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::FirstChild;
  545. else if (pseudo_name.equals_ignoring_case("last-child"))
  546. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::LastChild;
  547. else if (pseudo_name.equals_ignoring_case("only-child"))
  548. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::OnlyChild;
  549. else if (pseudo_name.equals_ignoring_case("empty"))
  550. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Empty;
  551. else if (pseudo_name.equals_ignoring_case("root"))
  552. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Root;
  553. }
  554. if (index == index_at_start) {
  555. // We consumed nothing.
  556. return {};
  557. }
  558. return simple_selector;
  559. }
  560. Optional<CSS::Selector::ComplexSelector> parse_complex_selector()
  561. {
  562. auto relation = CSS::Selector::ComplexSelector::Relation::Descendant;
  563. if (peek() == '{' || peek() == ',')
  564. return {};
  565. if (is_combinator(peek())) {
  566. switch (peek()) {
  567. case '>':
  568. relation = CSS::Selector::ComplexSelector::Relation::ImmediateChild;
  569. break;
  570. case '+':
  571. relation = CSS::Selector::ComplexSelector::Relation::AdjacentSibling;
  572. break;
  573. case '~':
  574. relation = CSS::Selector::ComplexSelector::Relation::GeneralSibling;
  575. break;
  576. }
  577. consume_one();
  578. consume_whitespace_or_comments();
  579. }
  580. consume_whitespace_or_comments();
  581. Vector<CSS::Selector::SimpleSelector> simple_selectors;
  582. for (;;) {
  583. auto component = parse_simple_selector();
  584. if (!component.has_value())
  585. break;
  586. simple_selectors.append(component.value());
  587. // If this assert triggers, we're most likely up to no good.
  588. PARSE_ASSERT(simple_selectors.size() < 100);
  589. }
  590. if (simple_selectors.is_empty())
  591. return {};
  592. return CSS::Selector::ComplexSelector { relation, move(simple_selectors) };
  593. }
  594. void parse_selector()
  595. {
  596. Vector<CSS::Selector::ComplexSelector> complex_selectors;
  597. for (;;) {
  598. auto index_before = index;
  599. auto complex_selector = parse_complex_selector();
  600. if (complex_selector.has_value())
  601. complex_selectors.append(complex_selector.value());
  602. consume_whitespace_or_comments();
  603. if (!peek() || peek() == ',' || peek() == '{')
  604. break;
  605. // HACK: If we didn't move forward, just let go.
  606. if (index == index_before)
  607. break;
  608. }
  609. if (complex_selectors.is_empty())
  610. return;
  611. complex_selectors.first().relation = CSS::Selector::ComplexSelector::Relation::None;
  612. current_rule.selectors.append(CSS::Selector(move(complex_selectors)));
  613. }
  614. Optional<CSS::Selector> parse_individual_selector()
  615. {
  616. parse_selector();
  617. if (current_rule.selectors.is_empty())
  618. return {};
  619. return current_rule.selectors.last();
  620. }
  621. void parse_selector_list()
  622. {
  623. for (;;) {
  624. auto index_before = index;
  625. parse_selector();
  626. consume_whitespace_or_comments();
  627. if (peek() == ',') {
  628. consume_one();
  629. continue;
  630. }
  631. if (peek() == '{')
  632. break;
  633. // HACK: If we didn't move forward, just let go.
  634. if (index_before == index)
  635. break;
  636. }
  637. }
  638. bool is_valid_property_name_char(char ch) const
  639. {
  640. return ch && !isspace(ch) && ch != ':';
  641. }
  642. bool is_valid_property_value_char(char ch) const
  643. {
  644. return ch && ch != '!' && ch != ';' && ch != '}';
  645. }
  646. struct ValueAndImportant {
  647. String value;
  648. bool important { false };
  649. };
  650. ValueAndImportant consume_css_value()
  651. {
  652. buffer.clear();
  653. int paren_nesting_level = 0;
  654. bool important = false;
  655. for (;;) {
  656. char ch = peek();
  657. if (ch == '(') {
  658. ++paren_nesting_level;
  659. buffer.append(consume_one());
  660. continue;
  661. }
  662. if (ch == ')') {
  663. PARSE_ASSERT(paren_nesting_level > 0);
  664. --paren_nesting_level;
  665. buffer.append(consume_one());
  666. continue;
  667. }
  668. if (paren_nesting_level > 0) {
  669. buffer.append(consume_one());
  670. continue;
  671. }
  672. if (next_is("!important")) {
  673. consume_specific('!');
  674. consume_specific('i');
  675. consume_specific('m');
  676. consume_specific('p');
  677. consume_specific('o');
  678. consume_specific('r');
  679. consume_specific('t');
  680. consume_specific('a');
  681. consume_specific('n');
  682. consume_specific('t');
  683. important = true;
  684. continue;
  685. }
  686. if (next_is("/*")) {
  687. consume_whitespace_or_comments();
  688. continue;
  689. }
  690. if (!ch)
  691. break;
  692. if (ch == '\\') {
  693. consume_one();
  694. buffer.append(consume_one());
  695. continue;
  696. }
  697. if (ch == '}')
  698. break;
  699. if (ch == ';')
  700. break;
  701. buffer.append(consume_one());
  702. }
  703. // Remove trailing whitespace.
  704. while (!buffer.is_empty() && isspace(buffer.last()))
  705. buffer.take_last();
  706. auto string = String::copy(buffer);
  707. buffer.clear();
  708. return { string, important };
  709. }
  710. Optional<CSS::StyleProperty> parse_property()
  711. {
  712. consume_whitespace_or_comments();
  713. if (peek() == ';') {
  714. consume_one();
  715. return {};
  716. }
  717. if (peek() == '}')
  718. return {};
  719. buffer.clear();
  720. while (is_valid_property_name_char(peek()))
  721. buffer.append(consume_one());
  722. auto property_name = String::copy(buffer);
  723. buffer.clear();
  724. consume_whitespace_or_comments();
  725. consume_specific(':');
  726. consume_whitespace_or_comments();
  727. auto [property_value, important] = consume_css_value();
  728. consume_whitespace_or_comments();
  729. if (peek() && peek() != '}')
  730. consume_specific(';');
  731. auto property_id = CSS::property_id_from_string(property_name);
  732. if (property_id == CSS::PropertyID::Invalid) {
  733. dbg() << "CSSParser: Unrecognized property '" << property_name << "'";
  734. }
  735. auto value = parse_css_value(m_context, property_value);
  736. if (!value)
  737. return {};
  738. return CSS::StyleProperty { property_id, value.release_nonnull(), important };
  739. }
  740. void parse_declaration()
  741. {
  742. for (;;) {
  743. auto property = parse_property();
  744. if (property.has_value())
  745. current_rule.properties.append(property.value());
  746. consume_whitespace_or_comments();
  747. if (peek() == '}')
  748. break;
  749. }
  750. }
  751. void parse_rule()
  752. {
  753. consume_whitespace_or_comments();
  754. if (index >= css.length())
  755. return;
  756. // FIXME: We ignore @-rules for now.
  757. if (peek() == '@') {
  758. while (peek() != '{')
  759. consume_one();
  760. int level = 0;
  761. for (;;) {
  762. auto ch = consume_one();
  763. if (ch == '{') {
  764. ++level;
  765. } else if (ch == '}') {
  766. --level;
  767. if (level == 0)
  768. break;
  769. }
  770. }
  771. consume_whitespace_or_comments();
  772. return;
  773. }
  774. parse_selector_list();
  775. consume_specific('{');
  776. parse_declaration();
  777. consume_specific('}');
  778. rules.append(CSS::StyleRule::create(move(current_rule.selectors), CSS::StyleDeclaration::create(move(current_rule.properties))));
  779. consume_whitespace_or_comments();
  780. }
  781. RefPtr<CSS::StyleSheet> parse_sheet()
  782. {
  783. while (index < css.length()) {
  784. parse_rule();
  785. }
  786. return CSS::StyleSheet::create(move(rules));
  787. }
  788. RefPtr<CSS::StyleDeclaration> parse_standalone_declaration()
  789. {
  790. consume_whitespace_or_comments();
  791. for (;;) {
  792. auto property = parse_property();
  793. if (property.has_value())
  794. current_rule.properties.append(property.value());
  795. consume_whitespace_or_comments();
  796. if (!peek())
  797. break;
  798. }
  799. return CSS::StyleDeclaration::create(move(current_rule.properties));
  800. }
  801. private:
  802. CSS::ParsingContext m_context;
  803. NonnullRefPtrVector<CSS::StyleRule> rules;
  804. struct CurrentRule {
  805. Vector<CSS::Selector> selectors;
  806. Vector<CSS::StyleProperty> properties;
  807. };
  808. CurrentRule current_rule;
  809. Vector<char> buffer;
  810. size_t index = 0;
  811. StringView css;
  812. };
  813. Optional<CSS::Selector> parse_selector(const CSS::ParsingContext& context, const StringView& selector_text)
  814. {
  815. CSSParser parser(context, selector_text);
  816. return parser.parse_individual_selector();
  817. }
  818. RefPtr<CSS::StyleSheet> parse_css(const CSS::ParsingContext& context, const StringView& css)
  819. {
  820. if (css.is_empty())
  821. return CSS::StyleSheet::create({});
  822. CSSParser parser(context, css);
  823. return parser.parse_sheet();
  824. }
  825. RefPtr<CSS::StyleDeclaration> parse_css_declaration(const CSS::ParsingContext& context, const StringView& css)
  826. {
  827. if (css.is_empty())
  828. return CSS::StyleDeclaration::create({});
  829. CSSParser parser(context, css);
  830. return parser.parse_standalone_declaration();
  831. }
  832. RefPtr<CSS::StyleValue> parse_html_length(const DOM::Document& document, const StringView& string)
  833. {
  834. auto integer = string.to_int();
  835. if (integer.has_value())
  836. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  837. return parse_css_value(CSS::ParsingContext(document), string);
  838. }
  839. }