CSSParser.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. String(),
  455. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  456. String(),
  457. String()
  458. };
  459. }
  460. if (peek() == '.') {
  461. type = CSS::Selector::SimpleSelector::Type::Class;
  462. consume_one();
  463. } else if (peek() == '#') {
  464. type = CSS::Selector::SimpleSelector::Type::Id;
  465. consume_one();
  466. } else if (isalpha(peek())) {
  467. type = CSS::Selector::SimpleSelector::Type::TagName;
  468. } else {
  469. type = CSS::Selector::SimpleSelector::Type::Universal;
  470. }
  471. if (type != CSS::Selector::SimpleSelector::Type::Universal) {
  472. while (is_valid_selector_char(peek()))
  473. buffer.append(consume_one());
  474. PARSE_ASSERT(!buffer.is_null());
  475. }
  476. auto value = String::copy(buffer);
  477. if (type == CSS::Selector::SimpleSelector::Type::TagName) {
  478. // Some stylesheets use uppercase tag names, so here's a hack to just lowercase them internally.
  479. value = value.to_lowercase();
  480. }
  481. CSS::Selector::SimpleSelector simple_selector {
  482. type,
  483. CSS::Selector::SimpleSelector::PseudoClass::None,
  484. value,
  485. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  486. String(),
  487. String()
  488. };
  489. buffer.clear();
  490. if (peek() == '[') {
  491. CSS::Selector::SimpleSelector::AttributeMatchType attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::HasAttribute;
  492. String attribute_name;
  493. String attribute_value;
  494. bool in_value = false;
  495. consume_specific('[');
  496. char expected_end_of_attribute_selector = ']';
  497. while (peek() != expected_end_of_attribute_selector) {
  498. char ch = consume_one();
  499. if (ch == '=' || (ch == '~' && peek() == '=')) {
  500. if (ch == '=') {
  501. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::ExactValueMatch;
  502. } else if (ch == '~') {
  503. consume_one();
  504. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::Contains;
  505. }
  506. attribute_name = String::copy(buffer);
  507. buffer.clear();
  508. in_value = true;
  509. consume_whitespace_or_comments();
  510. if (peek() == '\'') {
  511. expected_end_of_attribute_selector = '\'';
  512. consume_one();
  513. } else if (peek() == '"') {
  514. expected_end_of_attribute_selector = '"';
  515. consume_one();
  516. }
  517. continue;
  518. }
  519. // FIXME: This is a hack that will go away when we replace this with a big boy CSS parser.
  520. if (ch == '\\')
  521. ch = consume_one();
  522. buffer.append(ch);
  523. }
  524. if (in_value)
  525. attribute_value = String::copy(buffer);
  526. else
  527. attribute_name = String::copy(buffer);
  528. buffer.clear();
  529. simple_selector.attribute_match_type = attribute_match_type;
  530. simple_selector.attribute_name = attribute_name;
  531. simple_selector.attribute_value = attribute_value;
  532. if (expected_end_of_attribute_selector != ']')
  533. consume_specific(expected_end_of_attribute_selector);
  534. consume_whitespace_or_comments();
  535. consume_specific(']');
  536. }
  537. if (peek() == ':') {
  538. // FIXME: Implement pseudo elements.
  539. [[maybe_unused]] bool is_pseudo_element = false;
  540. consume_one();
  541. if (peek() == ':') {
  542. is_pseudo_element = true;
  543. consume_one();
  544. }
  545. if (next_is("not")) {
  546. buffer.append(consume_one());
  547. buffer.append(consume_one());
  548. buffer.append(consume_one());
  549. buffer.append(consume_specific('('));
  550. while (peek() != ')')
  551. buffer.append(consume_one());
  552. buffer.append(consume_specific(')'));
  553. } else {
  554. while (is_valid_selector_char(peek()))
  555. buffer.append(consume_one());
  556. }
  557. auto pseudo_name = String::copy(buffer);
  558. buffer.clear();
  559. // Ignore for now, otherwise we produce a "false positive" selector
  560. // and apply styles to the element itself, not its pseudo element
  561. if (is_pseudo_element)
  562. return {};
  563. if (pseudo_name.equals_ignoring_case("link"))
  564. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Link;
  565. else if (pseudo_name.equals_ignoring_case("visited"))
  566. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Visited;
  567. else if (pseudo_name.equals_ignoring_case("hover"))
  568. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Hover;
  569. else if (pseudo_name.equals_ignoring_case("focus"))
  570. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Focus;
  571. else if (pseudo_name.equals_ignoring_case("first-child"))
  572. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::FirstChild;
  573. else if (pseudo_name.equals_ignoring_case("last-child"))
  574. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::LastChild;
  575. else if (pseudo_name.equals_ignoring_case("only-child"))
  576. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::OnlyChild;
  577. else if (pseudo_name.equals_ignoring_case("empty"))
  578. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Empty;
  579. else if (pseudo_name.equals_ignoring_case("root"))
  580. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Root;
  581. }
  582. if (index == index_at_start) {
  583. // We consumed nothing.
  584. return {};
  585. }
  586. return simple_selector;
  587. }
  588. Optional<CSS::Selector::ComplexSelector> parse_complex_selector()
  589. {
  590. auto relation = CSS::Selector::ComplexSelector::Relation::Descendant;
  591. if (peek() == '{' || peek() == ',')
  592. return {};
  593. if (is_combinator(peek())) {
  594. switch (peek()) {
  595. case '>':
  596. relation = CSS::Selector::ComplexSelector::Relation::ImmediateChild;
  597. break;
  598. case '+':
  599. relation = CSS::Selector::ComplexSelector::Relation::AdjacentSibling;
  600. break;
  601. case '~':
  602. relation = CSS::Selector::ComplexSelector::Relation::GeneralSibling;
  603. break;
  604. }
  605. consume_one();
  606. consume_whitespace_or_comments();
  607. }
  608. consume_whitespace_or_comments();
  609. Vector<CSS::Selector::SimpleSelector> simple_selectors;
  610. for (;;) {
  611. auto component = parse_simple_selector();
  612. if (!component.has_value())
  613. break;
  614. simple_selectors.append(component.value());
  615. // If this assert triggers, we're most likely up to no good.
  616. PARSE_ASSERT(simple_selectors.size() < 100);
  617. }
  618. if (simple_selectors.is_empty())
  619. return {};
  620. return CSS::Selector::ComplexSelector { relation, move(simple_selectors) };
  621. }
  622. void parse_selector()
  623. {
  624. Vector<CSS::Selector::ComplexSelector> complex_selectors;
  625. for (;;) {
  626. auto index_before = index;
  627. auto complex_selector = parse_complex_selector();
  628. if (complex_selector.has_value())
  629. complex_selectors.append(complex_selector.value());
  630. consume_whitespace_or_comments();
  631. if (!peek() || peek() == ',' || peek() == '{')
  632. break;
  633. // HACK: If we didn't move forward, just let go.
  634. if (index == index_before)
  635. break;
  636. }
  637. if (complex_selectors.is_empty())
  638. return;
  639. complex_selectors.first().relation = CSS::Selector::ComplexSelector::Relation::None;
  640. current_rule.selectors.append(CSS::Selector(move(complex_selectors)));
  641. }
  642. Optional<CSS::Selector> parse_individual_selector()
  643. {
  644. parse_selector();
  645. if (current_rule.selectors.is_empty())
  646. return {};
  647. return current_rule.selectors.last();
  648. }
  649. void parse_selector_list()
  650. {
  651. for (;;) {
  652. auto index_before = index;
  653. parse_selector();
  654. consume_whitespace_or_comments();
  655. if (peek() == ',') {
  656. consume_one();
  657. continue;
  658. }
  659. if (peek() == '{')
  660. break;
  661. // HACK: If we didn't move forward, just let go.
  662. if (index_before == index)
  663. break;
  664. }
  665. }
  666. bool is_valid_property_name_char(char ch) const
  667. {
  668. return ch && !isspace(ch) && ch != ':';
  669. }
  670. bool is_valid_property_value_char(char ch) const
  671. {
  672. return ch && ch != '!' && ch != ';' && ch != '}';
  673. }
  674. struct ValueAndImportant {
  675. String value;
  676. bool important { false };
  677. };
  678. ValueAndImportant consume_css_value()
  679. {
  680. buffer.clear();
  681. int paren_nesting_level = 0;
  682. bool important = false;
  683. for (;;) {
  684. char ch = peek();
  685. if (ch == '(') {
  686. ++paren_nesting_level;
  687. buffer.append(consume_one());
  688. continue;
  689. }
  690. if (ch == ')') {
  691. PARSE_ASSERT(paren_nesting_level > 0);
  692. --paren_nesting_level;
  693. buffer.append(consume_one());
  694. continue;
  695. }
  696. if (paren_nesting_level > 0) {
  697. buffer.append(consume_one());
  698. continue;
  699. }
  700. if (next_is("!important")) {
  701. consume_specific('!');
  702. consume_specific('i');
  703. consume_specific('m');
  704. consume_specific('p');
  705. consume_specific('o');
  706. consume_specific('r');
  707. consume_specific('t');
  708. consume_specific('a');
  709. consume_specific('n');
  710. consume_specific('t');
  711. important = true;
  712. continue;
  713. }
  714. if (next_is("/*")) {
  715. consume_whitespace_or_comments();
  716. continue;
  717. }
  718. if (!ch)
  719. break;
  720. if (ch == '\\') {
  721. consume_one();
  722. buffer.append(consume_one());
  723. continue;
  724. }
  725. if (ch == '}')
  726. break;
  727. if (ch == ';')
  728. break;
  729. buffer.append(consume_one());
  730. }
  731. // Remove trailing whitespace.
  732. while (!buffer.is_empty() && isspace(buffer.last()))
  733. buffer.take_last();
  734. auto string = String::copy(buffer);
  735. buffer.clear();
  736. return { string, important };
  737. }
  738. Optional<CSS::StyleProperty> parse_property()
  739. {
  740. consume_whitespace_or_comments();
  741. if (peek() == ';') {
  742. consume_one();
  743. return {};
  744. }
  745. if (peek() == '}')
  746. return {};
  747. buffer.clear();
  748. while (is_valid_property_name_char(peek()))
  749. buffer.append(consume_one());
  750. auto property_name = String::copy(buffer);
  751. buffer.clear();
  752. consume_whitespace_or_comments();
  753. consume_specific(':');
  754. consume_whitespace_or_comments();
  755. auto [property_value, important] = consume_css_value();
  756. consume_whitespace_or_comments();
  757. if (peek() && peek() != '}')
  758. consume_specific(';');
  759. auto property_id = CSS::property_id_from_string(property_name);
  760. if (property_id == CSS::PropertyID::Invalid) {
  761. dbg() << "CSSParser: Unrecognized property '" << property_name << "'";
  762. }
  763. auto value = parse_css_value(m_context, property_value);
  764. if (!value)
  765. return {};
  766. return CSS::StyleProperty { property_id, value.release_nonnull(), important };
  767. }
  768. void parse_declaration()
  769. {
  770. for (;;) {
  771. auto property = parse_property();
  772. if (property.has_value())
  773. current_rule.properties.append(property.value());
  774. consume_whitespace_or_comments();
  775. if (peek() == '}')
  776. break;
  777. }
  778. }
  779. void parse_rule()
  780. {
  781. consume_whitespace_or_comments();
  782. if (index >= css.length())
  783. return;
  784. // FIXME: We ignore @-rules for now.
  785. if (peek() == '@') {
  786. while (peek() != '{')
  787. consume_one();
  788. int level = 0;
  789. for (;;) {
  790. auto ch = consume_one();
  791. if (ch == '{') {
  792. ++level;
  793. } else if (ch == '}') {
  794. --level;
  795. if (level == 0)
  796. break;
  797. }
  798. }
  799. consume_whitespace_or_comments();
  800. return;
  801. }
  802. parse_selector_list();
  803. consume_specific('{');
  804. parse_declaration();
  805. consume_specific('}');
  806. rules.append(CSS::StyleRule::create(move(current_rule.selectors), CSS::StyleDeclaration::create(move(current_rule.properties))));
  807. consume_whitespace_or_comments();
  808. }
  809. RefPtr<CSS::StyleSheet> parse_sheet()
  810. {
  811. while (index < css.length()) {
  812. parse_rule();
  813. }
  814. return CSS::StyleSheet::create(move(rules));
  815. }
  816. RefPtr<CSS::StyleDeclaration> parse_standalone_declaration()
  817. {
  818. consume_whitespace_or_comments();
  819. for (;;) {
  820. auto property = parse_property();
  821. if (property.has_value())
  822. current_rule.properties.append(property.value());
  823. consume_whitespace_or_comments();
  824. if (!peek())
  825. break;
  826. }
  827. return CSS::StyleDeclaration::create(move(current_rule.properties));
  828. }
  829. private:
  830. CSS::ParsingContext m_context;
  831. NonnullRefPtrVector<CSS::StyleRule> rules;
  832. struct CurrentRule {
  833. Vector<CSS::Selector> selectors;
  834. Vector<CSS::StyleProperty> properties;
  835. };
  836. CurrentRule current_rule;
  837. Vector<char> buffer;
  838. size_t index = 0;
  839. StringView css;
  840. };
  841. Optional<CSS::Selector> parse_selector(const CSS::ParsingContext& context, const StringView& selector_text)
  842. {
  843. CSSParser parser(context, selector_text);
  844. return parser.parse_individual_selector();
  845. }
  846. RefPtr<CSS::StyleSheet> parse_css(const CSS::ParsingContext& context, const StringView& css)
  847. {
  848. if (css.is_empty())
  849. return CSS::StyleSheet::create({});
  850. CSSParser parser(context, css);
  851. return parser.parse_sheet();
  852. }
  853. RefPtr<CSS::StyleDeclaration> parse_css_declaration(const CSS::ParsingContext& context, const StringView& css)
  854. {
  855. if (css.is_empty())
  856. return CSS::StyleDeclaration::create({});
  857. CSSParser parser(context, css);
  858. return parser.parse_standalone_declaration();
  859. }
  860. RefPtr<CSS::StyleValue> parse_html_length(const DOM::Document& document, const StringView& string)
  861. {
  862. auto integer = string.to_int();
  863. if (integer.has_value())
  864. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  865. return parse_css_value(CSS::ParsingContext(document), string);
  866. }
  867. }