CSSParser.cpp 34 KB

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