CSSParser.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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. 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.ends_with("px", CaseSensitivity::CaseInsensitive)) {
  249. type = CSS::Length::Type::Px;
  250. value = try_parse_float(view.substring_view(0, view.length() - 2));
  251. } else if (view.ends_with("pt", CaseSensitivity::CaseInsensitive)) {
  252. type = CSS::Length::Type::Pt;
  253. value = try_parse_float(view.substring_view(0, view.length() - 2));
  254. } else if (view.ends_with("rem", CaseSensitivity::CaseInsensitive)) {
  255. type = CSS::Length::Type::Rem;
  256. value = try_parse_float(view.substring_view(0, view.length() - 3));
  257. } else if (view.ends_with("em", CaseSensitivity::CaseInsensitive)) {
  258. type = CSS::Length::Type::Em;
  259. value = try_parse_float(view.substring_view(0, view.length() - 2));
  260. } else if (view.ends_with("ex", CaseSensitivity::CaseInsensitive)) {
  261. type = CSS::Length::Type::Ex;
  262. value = try_parse_float(view.substring_view(0, view.length() - 2));
  263. } else if (view == "0") {
  264. type = CSS::Length::Type::Px;
  265. value = 0;
  266. } else if (context.in_quirks_mode()) {
  267. type = CSS::Length::Type::Px;
  268. value = try_parse_float(view);
  269. } else {
  270. value = try_parse_float(view);
  271. if (value.has_value())
  272. is_bad_length = true;
  273. }
  274. if (!value.has_value())
  275. return {};
  276. return CSS::Length(value.value(), type);
  277. }
  278. RefPtr<CSS::StyleValue> parse_css_value(const CSS::ParsingContext& context, const StringView& string)
  279. {
  280. bool is_bad_length = false;
  281. auto length = parse_length(context, string, is_bad_length);
  282. if (is_bad_length)
  283. return nullptr;
  284. if (!length.is_undefined())
  285. return CSS::LengthStyleValue::create(length);
  286. if (string.equals_ignoring_case("inherit"))
  287. return CSS::InheritStyleValue::create();
  288. if (string.equals_ignoring_case("initial"))
  289. return CSS::InitialStyleValue::create();
  290. if (string.equals_ignoring_case("auto"))
  291. return CSS::LengthStyleValue::create(CSS::Length::make_auto());
  292. auto color = parse_css_color(context, string);
  293. if (color.has_value())
  294. return CSS::ColorStyleValue::create(color.value());
  295. if (string == "-libweb-link")
  296. return CSS::IdentifierStyleValue::create(CSS::ValueID::VendorSpecificLink);
  297. else if (string.starts_with("-libweb-palette-")) {
  298. auto value_id = value_id_for_palette_string(string.substring_view(16, string.length() - 16));
  299. return CSS::IdentifierStyleValue::create(value_id);
  300. }
  301. return CSS::StringStyleValue::create(string);
  302. }
  303. RefPtr<CSS::LengthStyleValue> parse_line_width(const CSS::ParsingContext& context, const StringView& part)
  304. {
  305. auto value = parse_css_value(context, part);
  306. if (value && value->is_length())
  307. return static_ptr_cast<CSS::LengthStyleValue>(value);
  308. return nullptr;
  309. }
  310. RefPtr<CSS::ColorStyleValue> parse_color(const CSS::ParsingContext& context, const StringView& part)
  311. {
  312. auto value = parse_css_value(context, part);
  313. if (value && value->is_color())
  314. return static_ptr_cast<CSS::ColorStyleValue>(value);
  315. return nullptr;
  316. }
  317. RefPtr<CSS::StringStyleValue> parse_line_style(const CSS::ParsingContext& context, const StringView& part)
  318. {
  319. auto parsed_value = parse_css_value(context, part);
  320. if (!parsed_value || !parsed_value->is_string())
  321. return nullptr;
  322. auto value = static_ptr_cast<CSS::StringStyleValue>(parsed_value);
  323. if (value->to_string() == "dotted")
  324. return value;
  325. if (value->to_string() == "dashed")
  326. return value;
  327. if (value->to_string() == "solid")
  328. return value;
  329. if (value->to_string() == "double")
  330. return value;
  331. if (value->to_string() == "groove")
  332. return value;
  333. if (value->to_string() == "ridge")
  334. return value;
  335. return nullptr;
  336. }
  337. class CSSParser {
  338. public:
  339. CSSParser(const CSS::ParsingContext& context, const StringView& input)
  340. : m_context(context)
  341. , css(input)
  342. {
  343. }
  344. bool next_is(const char* str) const
  345. {
  346. size_t len = strlen(str);
  347. for (size_t i = 0; i < len; ++i) {
  348. if (peek(i) != str[i])
  349. return false;
  350. }
  351. return true;
  352. }
  353. char peek(size_t offset = 0) const
  354. {
  355. if ((index + offset) < css.length())
  356. return css[index + offset];
  357. return 0;
  358. }
  359. char consume_specific(char ch)
  360. {
  361. if (peek() != ch) {
  362. dbg() << "peek() != '" << ch << "'";
  363. }
  364. if (peek() != ch) {
  365. PARSE_ERROR();
  366. }
  367. PARSE_ASSERT(index < css.length());
  368. ++index;
  369. return ch;
  370. }
  371. char consume_one()
  372. {
  373. PARSE_ASSERT(index < css.length());
  374. return css[index++];
  375. };
  376. bool consume_whitespace_or_comments()
  377. {
  378. size_t original_index = index;
  379. bool in_comment = false;
  380. for (; index < css.length(); ++index) {
  381. char ch = peek();
  382. if (isspace(ch))
  383. continue;
  384. if (!in_comment && ch == '/' && peek(1) == '*') {
  385. in_comment = true;
  386. ++index;
  387. continue;
  388. }
  389. if (in_comment && ch == '*' && peek(1) == '/') {
  390. in_comment = false;
  391. ++index;
  392. continue;
  393. }
  394. if (in_comment)
  395. continue;
  396. break;
  397. }
  398. return original_index != index;
  399. }
  400. bool is_valid_selector_char(char ch) const
  401. {
  402. return isalnum(ch) || ch == '-' || ch == '_' || ch == '(' || ch == ')' || ch == '@';
  403. }
  404. bool is_combinator(char ch) const
  405. {
  406. return ch == '~' || ch == '>' || ch == '+';
  407. }
  408. Optional<CSS::Selector::SimpleSelector> parse_simple_selector()
  409. {
  410. auto index_at_start = index;
  411. if (consume_whitespace_or_comments())
  412. return {};
  413. if (!peek() || peek() == '{' || peek() == ',' || is_combinator(peek()))
  414. return {};
  415. CSS::Selector::SimpleSelector::Type type;
  416. if (peek() == '*') {
  417. type = CSS::Selector::SimpleSelector::Type::Universal;
  418. consume_one();
  419. return CSS::Selector::SimpleSelector {
  420. type,
  421. CSS::Selector::SimpleSelector::PseudoClass::None,
  422. String(),
  423. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  424. String(),
  425. String()
  426. };
  427. }
  428. if (peek() == '.') {
  429. type = CSS::Selector::SimpleSelector::Type::Class;
  430. consume_one();
  431. } else if (peek() == '#') {
  432. type = CSS::Selector::SimpleSelector::Type::Id;
  433. consume_one();
  434. } else if (isalpha(peek())) {
  435. type = CSS::Selector::SimpleSelector::Type::TagName;
  436. } else {
  437. type = CSS::Selector::SimpleSelector::Type::Universal;
  438. }
  439. if (type != CSS::Selector::SimpleSelector::Type::Universal) {
  440. while (is_valid_selector_char(peek()))
  441. buffer.append(consume_one());
  442. PARSE_ASSERT(!buffer.is_null());
  443. }
  444. auto value = String::copy(buffer);
  445. if (type == CSS::Selector::SimpleSelector::Type::TagName) {
  446. // Some stylesheets use uppercase tag names, so here's a hack to just lowercase them internally.
  447. value = value.to_lowercase();
  448. }
  449. CSS::Selector::SimpleSelector simple_selector {
  450. type,
  451. CSS::Selector::SimpleSelector::PseudoClass::None,
  452. value,
  453. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  454. String(),
  455. String()
  456. };
  457. buffer.clear();
  458. if (peek() == '[') {
  459. CSS::Selector::SimpleSelector::AttributeMatchType attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::HasAttribute;
  460. String attribute_name;
  461. String attribute_value;
  462. bool in_value = false;
  463. consume_specific('[');
  464. char expected_end_of_attribute_selector = ']';
  465. while (peek() != expected_end_of_attribute_selector) {
  466. char ch = consume_one();
  467. if (ch == '=' || (ch == '~' && peek() == '=')) {
  468. if (ch == '=') {
  469. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::ExactValueMatch;
  470. } else if (ch == '~') {
  471. consume_one();
  472. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::Contains;
  473. }
  474. attribute_name = String::copy(buffer);
  475. buffer.clear();
  476. in_value = true;
  477. consume_whitespace_or_comments();
  478. if (peek() == '\'') {
  479. expected_end_of_attribute_selector = '\'';
  480. consume_one();
  481. } else if (peek() == '"') {
  482. expected_end_of_attribute_selector = '"';
  483. consume_one();
  484. }
  485. continue;
  486. }
  487. // FIXME: This is a hack that will go away when we replace this with a big boy CSS parser.
  488. if (ch == '\\')
  489. ch = consume_one();
  490. buffer.append(ch);
  491. }
  492. if (in_value)
  493. attribute_value = String::copy(buffer);
  494. else
  495. attribute_name = String::copy(buffer);
  496. buffer.clear();
  497. simple_selector.attribute_match_type = attribute_match_type;
  498. simple_selector.attribute_name = attribute_name;
  499. simple_selector.attribute_value = attribute_value;
  500. if (expected_end_of_attribute_selector != ']')
  501. consume_specific(expected_end_of_attribute_selector);
  502. consume_whitespace_or_comments();
  503. consume_specific(']');
  504. }
  505. if (peek() == ':') {
  506. // FIXME: Implement pseudo elements.
  507. [[maybe_unused]] bool is_pseudo_element = false;
  508. consume_one();
  509. if (peek() == ':') {
  510. is_pseudo_element = true;
  511. consume_one();
  512. }
  513. if (next_is("not")) {
  514. buffer.append(consume_one());
  515. buffer.append(consume_one());
  516. buffer.append(consume_one());
  517. buffer.append(consume_specific('('));
  518. while (peek() != ')')
  519. buffer.append(consume_one());
  520. buffer.append(consume_specific(')'));
  521. } else {
  522. while (is_valid_selector_char(peek()))
  523. buffer.append(consume_one());
  524. }
  525. auto pseudo_name = String::copy(buffer);
  526. buffer.clear();
  527. // Ignore for now, otherwise we produce a "false positive" selector
  528. // and apply styles to the element itself, not its pseudo element
  529. if (is_pseudo_element)
  530. return {};
  531. if (pseudo_name.equals_ignoring_case("link"))
  532. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Link;
  533. else if (pseudo_name.equals_ignoring_case("visited"))
  534. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Visited;
  535. else if (pseudo_name.equals_ignoring_case("hover"))
  536. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Hover;
  537. else if (pseudo_name.equals_ignoring_case("focus"))
  538. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Focus;
  539. else if (pseudo_name.equals_ignoring_case("first-child"))
  540. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::FirstChild;
  541. else if (pseudo_name.equals_ignoring_case("last-child"))
  542. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::LastChild;
  543. else if (pseudo_name.equals_ignoring_case("only-child"))
  544. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::OnlyChild;
  545. else if (pseudo_name.equals_ignoring_case("empty"))
  546. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Empty;
  547. else if (pseudo_name.equals_ignoring_case("root"))
  548. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Root;
  549. }
  550. if (index == index_at_start) {
  551. // We consumed nothing.
  552. return {};
  553. }
  554. return simple_selector;
  555. }
  556. Optional<CSS::Selector::ComplexSelector> parse_complex_selector()
  557. {
  558. auto relation = CSS::Selector::ComplexSelector::Relation::Descendant;
  559. if (peek() == '{' || peek() == ',')
  560. return {};
  561. if (is_combinator(peek())) {
  562. switch (peek()) {
  563. case '>':
  564. relation = CSS::Selector::ComplexSelector::Relation::ImmediateChild;
  565. break;
  566. case '+':
  567. relation = CSS::Selector::ComplexSelector::Relation::AdjacentSibling;
  568. break;
  569. case '~':
  570. relation = CSS::Selector::ComplexSelector::Relation::GeneralSibling;
  571. break;
  572. }
  573. consume_one();
  574. consume_whitespace_or_comments();
  575. }
  576. consume_whitespace_or_comments();
  577. Vector<CSS::Selector::SimpleSelector> simple_selectors;
  578. for (;;) {
  579. auto component = parse_simple_selector();
  580. if (!component.has_value())
  581. break;
  582. simple_selectors.append(component.value());
  583. // If this assert triggers, we're most likely up to no good.
  584. PARSE_ASSERT(simple_selectors.size() < 100);
  585. }
  586. if (simple_selectors.is_empty())
  587. return {};
  588. return CSS::Selector::ComplexSelector { relation, move(simple_selectors) };
  589. }
  590. void parse_selector()
  591. {
  592. Vector<CSS::Selector::ComplexSelector> complex_selectors;
  593. for (;;) {
  594. auto index_before = index;
  595. auto complex_selector = parse_complex_selector();
  596. if (complex_selector.has_value())
  597. complex_selectors.append(complex_selector.value());
  598. consume_whitespace_or_comments();
  599. if (!peek() || peek() == ',' || peek() == '{')
  600. break;
  601. // HACK: If we didn't move forward, just let go.
  602. if (index == index_before)
  603. break;
  604. }
  605. if (complex_selectors.is_empty())
  606. return;
  607. complex_selectors.first().relation = CSS::Selector::ComplexSelector::Relation::None;
  608. current_rule.selectors.append(CSS::Selector(move(complex_selectors)));
  609. }
  610. Optional<CSS::Selector> parse_individual_selector()
  611. {
  612. parse_selector();
  613. if (current_rule.selectors.is_empty())
  614. return {};
  615. return current_rule.selectors.last();
  616. }
  617. void parse_selector_list()
  618. {
  619. for (;;) {
  620. auto index_before = index;
  621. parse_selector();
  622. consume_whitespace_or_comments();
  623. if (peek() == ',') {
  624. consume_one();
  625. continue;
  626. }
  627. if (peek() == '{')
  628. break;
  629. // HACK: If we didn't move forward, just let go.
  630. if (index_before == index)
  631. break;
  632. }
  633. }
  634. bool is_valid_property_name_char(char ch) const
  635. {
  636. return ch && !isspace(ch) && ch != ':';
  637. }
  638. bool is_valid_property_value_char(char ch) const
  639. {
  640. return ch && ch != '!' && ch != ';' && ch != '}';
  641. }
  642. struct ValueAndImportant {
  643. String value;
  644. bool important { false };
  645. };
  646. ValueAndImportant consume_css_value()
  647. {
  648. buffer.clear();
  649. int paren_nesting_level = 0;
  650. bool important = false;
  651. for (;;) {
  652. char ch = peek();
  653. if (ch == '(') {
  654. ++paren_nesting_level;
  655. buffer.append(consume_one());
  656. continue;
  657. }
  658. if (ch == ')') {
  659. PARSE_ASSERT(paren_nesting_level > 0);
  660. --paren_nesting_level;
  661. buffer.append(consume_one());
  662. continue;
  663. }
  664. if (paren_nesting_level > 0) {
  665. buffer.append(consume_one());
  666. continue;
  667. }
  668. if (next_is("!important")) {
  669. consume_specific('!');
  670. consume_specific('i');
  671. consume_specific('m');
  672. consume_specific('p');
  673. consume_specific('o');
  674. consume_specific('r');
  675. consume_specific('t');
  676. consume_specific('a');
  677. consume_specific('n');
  678. consume_specific('t');
  679. important = true;
  680. continue;
  681. }
  682. if (next_is("/*")) {
  683. consume_whitespace_or_comments();
  684. continue;
  685. }
  686. if (!ch)
  687. break;
  688. if (ch == '\\') {
  689. consume_one();
  690. buffer.append(consume_one());
  691. continue;
  692. }
  693. if (ch == '}')
  694. break;
  695. if (ch == ';')
  696. break;
  697. buffer.append(consume_one());
  698. }
  699. // Remove trailing whitespace.
  700. while (!buffer.is_empty() && isspace(buffer.last()))
  701. buffer.take_last();
  702. auto string = String::copy(buffer);
  703. buffer.clear();
  704. return { string, important };
  705. }
  706. Optional<CSS::StyleProperty> parse_property()
  707. {
  708. consume_whitespace_or_comments();
  709. if (peek() == ';') {
  710. consume_one();
  711. return {};
  712. }
  713. if (peek() == '}')
  714. return {};
  715. buffer.clear();
  716. while (is_valid_property_name_char(peek()))
  717. buffer.append(consume_one());
  718. auto property_name = String::copy(buffer);
  719. buffer.clear();
  720. consume_whitespace_or_comments();
  721. consume_specific(':');
  722. consume_whitespace_or_comments();
  723. auto [property_value, important] = consume_css_value();
  724. consume_whitespace_or_comments();
  725. if (peek() && peek() != '}')
  726. consume_specific(';');
  727. auto property_id = CSS::property_id_from_string(property_name);
  728. if (property_id == CSS::PropertyID::Invalid) {
  729. dbg() << "CSSParser: Unrecognized property '" << property_name << "'";
  730. }
  731. auto value = parse_css_value(m_context, property_value);
  732. if (!value)
  733. return {};
  734. return CSS::StyleProperty { property_id, value.release_nonnull(), important };
  735. }
  736. void parse_declaration()
  737. {
  738. for (;;) {
  739. auto property = parse_property();
  740. if (property.has_value())
  741. current_rule.properties.append(property.value());
  742. consume_whitespace_or_comments();
  743. if (peek() == '}')
  744. break;
  745. }
  746. }
  747. void parse_rule()
  748. {
  749. consume_whitespace_or_comments();
  750. if (index >= css.length())
  751. return;
  752. // FIXME: We ignore @-rules for now.
  753. if (peek() == '@') {
  754. while (peek() != '{')
  755. consume_one();
  756. int level = 0;
  757. for (;;) {
  758. auto ch = consume_one();
  759. if (ch == '{') {
  760. ++level;
  761. } else if (ch == '}') {
  762. --level;
  763. if (level == 0)
  764. break;
  765. }
  766. }
  767. consume_whitespace_or_comments();
  768. return;
  769. }
  770. parse_selector_list();
  771. consume_specific('{');
  772. parse_declaration();
  773. consume_specific('}');
  774. rules.append(CSS::StyleRule::create(move(current_rule.selectors), CSS::StyleDeclaration::create(move(current_rule.properties))));
  775. consume_whitespace_or_comments();
  776. }
  777. RefPtr<CSS::StyleSheet> parse_sheet()
  778. {
  779. while (index < css.length()) {
  780. parse_rule();
  781. }
  782. return CSS::StyleSheet::create(move(rules));
  783. }
  784. RefPtr<CSS::StyleDeclaration> parse_standalone_declaration()
  785. {
  786. consume_whitespace_or_comments();
  787. for (;;) {
  788. auto property = parse_property();
  789. if (property.has_value())
  790. current_rule.properties.append(property.value());
  791. consume_whitespace_or_comments();
  792. if (!peek())
  793. break;
  794. }
  795. return CSS::StyleDeclaration::create(move(current_rule.properties));
  796. }
  797. private:
  798. CSS::ParsingContext m_context;
  799. NonnullRefPtrVector<CSS::StyleRule> rules;
  800. struct CurrentRule {
  801. Vector<CSS::Selector> selectors;
  802. Vector<CSS::StyleProperty> properties;
  803. };
  804. CurrentRule current_rule;
  805. Vector<char> buffer;
  806. size_t index = 0;
  807. StringView css;
  808. };
  809. Optional<CSS::Selector> parse_selector(const CSS::ParsingContext& context, const StringView& selector_text)
  810. {
  811. CSSParser parser(context, selector_text);
  812. return parser.parse_individual_selector();
  813. }
  814. RefPtr<CSS::StyleSheet> parse_css(const CSS::ParsingContext& context, const StringView& css)
  815. {
  816. if (css.is_empty())
  817. return CSS::StyleSheet::create({});
  818. CSSParser parser(context, css);
  819. return parser.parse_sheet();
  820. }
  821. RefPtr<CSS::StyleDeclaration> parse_css_declaration(const CSS::ParsingContext& context, const StringView& css)
  822. {
  823. if (css.is_empty())
  824. return CSS::StyleDeclaration::create({});
  825. CSSParser parser(context, css);
  826. return parser.parse_standalone_declaration();
  827. }
  828. RefPtr<CSS::StyleValue> parse_html_length(const DOM::Document& document, const StringView& string)
  829. {
  830. auto integer = string.to_int();
  831. if (integer.has_value())
  832. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  833. return parse_css_value(CSS::ParsingContext(document), string);
  834. }
  835. }