CSSParser.cpp 33 KB

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