CSSParser.cpp 35 KB

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