CSSParser.cpp 32 KB

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