CSSParser.cpp 35 KB

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