CSSParser.cpp 33 KB

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