CSSParser.cpp 32 KB

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