CSSParser.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  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 Optional<CSS::ValueID> value_id_for_palette_string(const StringView& string)
  64. {
  65. if (string.equals_ignoring_case("desktop-background"))
  66. return CSS::ValueID::VendorSpecificPaletteDesktopBackground;
  67. if (string.equals_ignoring_case("active-window-border1"))
  68. return CSS::ValueID::VendorSpecificPaletteActiveWindowBorder1;
  69. if (string.equals_ignoring_case("active-window-border2"))
  70. return CSS::ValueID::VendorSpecificPaletteActiveWindowBorder2;
  71. if (string.equals_ignoring_case("active-window-title"))
  72. return CSS::ValueID::VendorSpecificPaletteActiveWindowTitle;
  73. if (string.equals_ignoring_case("inactive-window-border1"))
  74. return CSS::ValueID::VendorSpecificPaletteInactiveWindowBorder1;
  75. if (string.equals_ignoring_case("inactive-window-border2"))
  76. return CSS::ValueID::VendorSpecificPaletteInactiveWindowBorder2;
  77. if (string.equals_ignoring_case("inactive-window-title"))
  78. return CSS::ValueID::VendorSpecificPaletteInactiveWindowTitle;
  79. if (string.equals_ignoring_case("moving-window-border1"))
  80. return CSS::ValueID::VendorSpecificPaletteMovingWindowBorder1;
  81. if (string.equals_ignoring_case("moving-window-border2"))
  82. return CSS::ValueID::VendorSpecificPaletteMovingWindowBorder2;
  83. if (string.equals_ignoring_case("moving-window-title"))
  84. return CSS::ValueID::VendorSpecificPaletteMovingWindowTitle;
  85. if (string.equals_ignoring_case("highlight-window-border1"))
  86. return CSS::ValueID::VendorSpecificPaletteHighlightWindowBorder1;
  87. if (string.equals_ignoring_case("highlight-window-border2"))
  88. return CSS::ValueID::VendorSpecificPaletteHighlightWindowBorder2;
  89. if (string.equals_ignoring_case("highlight-window-title"))
  90. return CSS::ValueID::VendorSpecificPaletteHighlightWindowTitle;
  91. if (string.equals_ignoring_case("menu-stripe"))
  92. return CSS::ValueID::VendorSpecificPaletteMenuStripe;
  93. if (string.equals_ignoring_case("menu-base"))
  94. return CSS::ValueID::VendorSpecificPaletteMenuBase;
  95. if (string.equals_ignoring_case("menu-base-text"))
  96. return CSS::ValueID::VendorSpecificPaletteMenuBaseText;
  97. if (string.equals_ignoring_case("menu-selection"))
  98. return CSS::ValueID::VendorSpecificPaletteMenuSelection;
  99. if (string.equals_ignoring_case("menu-selection-text"))
  100. return CSS::ValueID::VendorSpecificPaletteMenuSelectionText;
  101. if (string.equals_ignoring_case("window"))
  102. return CSS::ValueID::VendorSpecificPaletteWindow;
  103. if (string.equals_ignoring_case("window-text"))
  104. return CSS::ValueID::VendorSpecificPaletteWindowText;
  105. if (string.equals_ignoring_case("button"))
  106. return CSS::ValueID::VendorSpecificPaletteButton;
  107. if (string.equals_ignoring_case("button-text"))
  108. return CSS::ValueID::VendorSpecificPaletteButtonText;
  109. if (string.equals_ignoring_case("base"))
  110. return CSS::ValueID::VendorSpecificPaletteBase;
  111. if (string.equals_ignoring_case("base-text"))
  112. return CSS::ValueID::VendorSpecificPaletteBaseText;
  113. if (string.equals_ignoring_case("threed-highlight"))
  114. return CSS::ValueID::VendorSpecificPaletteThreedHighlight;
  115. if (string.equals_ignoring_case("threed-shadow1"))
  116. return CSS::ValueID::VendorSpecificPaletteThreedShadow1;
  117. if (string.equals_ignoring_case("threed-shadow2"))
  118. return CSS::ValueID::VendorSpecificPaletteThreedShadow2;
  119. if (string.equals_ignoring_case("hover-highlight"))
  120. return CSS::ValueID::VendorSpecificPaletteHoverHighlight;
  121. if (string.equals_ignoring_case("selection"))
  122. return CSS::ValueID::VendorSpecificPaletteSelection;
  123. if (string.equals_ignoring_case("selection-text"))
  124. return CSS::ValueID::VendorSpecificPaletteSelectionText;
  125. if (string.equals_ignoring_case("inactive-selection"))
  126. return CSS::ValueID::VendorSpecificPaletteInactiveSelection;
  127. if (string.equals_ignoring_case("inactive-selection-text"))
  128. return CSS::ValueID::VendorSpecificPaletteInactiveSelectionText;
  129. if (string.equals_ignoring_case("rubber-band-fill"))
  130. return CSS::ValueID::VendorSpecificPaletteRubberBandFill;
  131. if (string.equals_ignoring_case("rubber-band-border"))
  132. return CSS::ValueID::VendorSpecificPaletteRubberBandBorder;
  133. if (string.equals_ignoring_case("link"))
  134. return CSS::ValueID::VendorSpecificPaletteLink;
  135. if (string.equals_ignoring_case("active-link"))
  136. return CSS::ValueID::VendorSpecificPaletteActiveLink;
  137. if (string.equals_ignoring_case("visited-link"))
  138. return CSS::ValueID::VendorSpecificPaletteVisitedLink;
  139. if (string.equals_ignoring_case("ruler"))
  140. return CSS::ValueID::VendorSpecificPaletteRuler;
  141. if (string.equals_ignoring_case("ruler-border"))
  142. return CSS::ValueID::VendorSpecificPaletteRulerBorder;
  143. if (string.equals_ignoring_case("ruler-active-text"))
  144. return CSS::ValueID::VendorSpecificPaletteRulerActiveText;
  145. if (string.equals_ignoring_case("ruler-inactive-text"))
  146. return CSS::ValueID::VendorSpecificPaletteRulerInactiveText;
  147. if (string.equals_ignoring_case("text-cursor"))
  148. return CSS::ValueID::VendorSpecificPaletteTextCursor;
  149. if (string.equals_ignoring_case("focus-outline"))
  150. return CSS::ValueID::VendorSpecificPaletteFocusOutline;
  151. if (string.equals_ignoring_case("syntax-comment"))
  152. return CSS::ValueID::VendorSpecificPaletteSyntaxComment;
  153. if (string.equals_ignoring_case("syntax-number"))
  154. return CSS::ValueID::VendorSpecificPaletteSyntaxNumber;
  155. if (string.equals_ignoring_case("syntax-string"))
  156. return CSS::ValueID::VendorSpecificPaletteSyntaxString;
  157. if (string.equals_ignoring_case("syntax-type"))
  158. return CSS::ValueID::VendorSpecificPaletteSyntaxType;
  159. if (string.equals_ignoring_case("syntax-punctuation"))
  160. return CSS::ValueID::VendorSpecificPaletteSyntaxPunctuation;
  161. if (string.equals_ignoring_case("syntax-operator"))
  162. return CSS::ValueID::VendorSpecificPaletteSyntaxOperator;
  163. if (string.equals_ignoring_case("syntax-keyword"))
  164. return CSS::ValueID::VendorSpecificPaletteSyntaxKeyword;
  165. if (string.equals_ignoring_case("syntax-control-keyword"))
  166. return CSS::ValueID::VendorSpecificPaletteSyntaxControlKeyword;
  167. if (string.equals_ignoring_case("syntax-identifier"))
  168. return CSS::ValueID::VendorSpecificPaletteSyntaxIdentifier;
  169. if (string.equals_ignoring_case("syntax-preprocessor-statement"))
  170. return CSS::ValueID::VendorSpecificPaletteSyntaxPreprocessorStatement;
  171. if (string.equals_ignoring_case("syntax-preprocessor-value"))
  172. return CSS::ValueID::VendorSpecificPaletteSyntaxPreprocessorValue;
  173. return {};
  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("pc", CaseSensitivity::CaseInsensitive)) {
  259. type = CSS::Length::Type::Pc;
  260. value = try_parse_float(view.substring_view(0, view.length() - 2));
  261. } else if (view.ends_with("mm", CaseSensitivity::CaseInsensitive)) {
  262. type = CSS::Length::Type::Mm;
  263. value = try_parse_float(view.substring_view(0, view.length() - 2));
  264. } else if (view.ends_with("rem", CaseSensitivity::CaseInsensitive)) {
  265. type = CSS::Length::Type::Rem;
  266. value = try_parse_float(view.substring_view(0, view.length() - 3));
  267. } else if (view.ends_with("em", CaseSensitivity::CaseInsensitive)) {
  268. type = CSS::Length::Type::Em;
  269. value = try_parse_float(view.substring_view(0, view.length() - 2));
  270. } else if (view.ends_with("ex", CaseSensitivity::CaseInsensitive)) {
  271. type = CSS::Length::Type::Ex;
  272. value = try_parse_float(view.substring_view(0, view.length() - 2));
  273. } else if (view.ends_with("vw", CaseSensitivity::CaseInsensitive)) {
  274. type = CSS::Length::Type::Vw;
  275. value = try_parse_float(view.substring_view(0, view.length() - 2));
  276. } else if (view.ends_with("vh", CaseSensitivity::CaseInsensitive)) {
  277. type = CSS::Length::Type::Vh;
  278. value = try_parse_float(view.substring_view(0, view.length() - 2));
  279. } else if (view.ends_with("vmax", CaseSensitivity::CaseInsensitive)) {
  280. type = CSS::Length::Type::Vmax;
  281. value = try_parse_float(view.substring_view(0, view.length() - 4));
  282. } else if (view.ends_with("vmin", CaseSensitivity::CaseInsensitive)) {
  283. type = CSS::Length::Type::Vmin;
  284. value = try_parse_float(view.substring_view(0, view.length() - 4));
  285. } else if (view.ends_with("cm", CaseSensitivity::CaseInsensitive)) {
  286. type = CSS::Length::Type::Cm;
  287. value = try_parse_float(view.substring_view(0, view.length() - 2));
  288. } else if (view.ends_with("in", CaseSensitivity::CaseInsensitive)) {
  289. type = CSS::Length::Type::In;
  290. value = try_parse_float(view.substring_view(0, view.length() - 2));
  291. } else if (view.ends_with("Q", CaseSensitivity::CaseInsensitive)) {
  292. type = CSS::Length::Type::Q;
  293. value = try_parse_float(view.substring_view(0, view.length() - 1));
  294. } else if (view == "0") {
  295. type = CSS::Length::Type::Px;
  296. value = 0;
  297. } else if (context.in_quirks_mode()) {
  298. type = CSS::Length::Type::Px;
  299. value = try_parse_float(view);
  300. } else {
  301. value = try_parse_float(view);
  302. if (value.has_value())
  303. is_bad_length = true;
  304. }
  305. if (!value.has_value())
  306. return {};
  307. return CSS::Length(value.value(), type);
  308. }
  309. static bool takes_integer_value(CSS::PropertyID property_id)
  310. {
  311. return property_id == CSS::PropertyID::ZIndex || property_id == CSS::PropertyID::FontWeight;
  312. }
  313. static Optional<CSS::ValueID> value_id_from_string(const String& string)
  314. {
  315. // FIXME: Handle all identifiers
  316. // FIXME: Generate this code
  317. if (string.equals_ignoring_case("bold"))
  318. return CSS::ValueID::Bold;
  319. if (string.equals_ignoring_case("bolder"))
  320. return CSS::ValueID::Bolder;
  321. if (string.equals_ignoring_case("center"))
  322. return CSS::ValueID::Center;
  323. if (string.equals_ignoring_case("justify"))
  324. return CSS::ValueID::Justify;
  325. if (string.equals_ignoring_case("large"))
  326. return CSS::ValueID::Large;
  327. if (string.equals_ignoring_case("larger"))
  328. return CSS::ValueID::Larger;
  329. if (string.equals_ignoring_case("left"))
  330. return CSS::ValueID::Left;
  331. if (string.equals_ignoring_case("lighter"))
  332. return CSS::ValueID::Lighter;
  333. if (string.equals_ignoring_case("medium"))
  334. return CSS::ValueID::Medium;
  335. if (string.equals_ignoring_case("normal"))
  336. return CSS::ValueID::Normal;
  337. if (string.equals_ignoring_case("small"))
  338. return CSS::ValueID::Small;
  339. if (string.equals_ignoring_case("right"))
  340. return CSS::ValueID::Right;
  341. if (string.equals_ignoring_case("smaller"))
  342. return CSS::ValueID::Smaller;
  343. if (string.equals_ignoring_case("x-large"))
  344. return CSS::ValueID::XLarge;
  345. if (string.equals_ignoring_case("x-small"))
  346. return CSS::ValueID::XSmall;
  347. if (string.equals_ignoring_case("xx-large"))
  348. return CSS::ValueID::XxLarge;
  349. if (string.equals_ignoring_case("xx-small"))
  350. return CSS::ValueID::XxSmall;
  351. if (string.equals_ignoring_case("xxx-large"))
  352. return CSS::ValueID::XxxLarge;
  353. if (string.equals_ignoring_case("-libweb-center"))
  354. return CSS::ValueID::VendorSpecificCenter;
  355. if (string.equals_ignoring_case("-libweb-link"))
  356. return CSS::ValueID::VendorSpecificLink;
  357. if (string.equals_ignoring_case("static"))
  358. return CSS::ValueID::Static;
  359. if (string.equals_ignoring_case("relative"))
  360. return CSS::ValueID::Relative;
  361. if (string.equals_ignoring_case("absolute"))
  362. return CSS::ValueID::Absolute;
  363. if (string.equals_ignoring_case("fixed"))
  364. return CSS::ValueID::Fixed;
  365. if (string.equals_ignoring_case("sticky"))
  366. return CSS::ValueID::Sticky;
  367. if (string.starts_with("-libweb-palette-", CaseSensitivity::CaseInsensitive))
  368. return value_id_for_palette_string(string.substring_view(16, string.length() - 16));
  369. return {};
  370. }
  371. RefPtr<CSS::StyleValue> parse_css_value(const CSS::ParsingContext& context, const StringView& string, CSS::PropertyID property_id)
  372. {
  373. bool is_bad_length = false;
  374. if (takes_integer_value(property_id)) {
  375. auto integer = string.to_int();
  376. if (integer.has_value())
  377. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  378. }
  379. auto length = parse_length(context, string, is_bad_length);
  380. if (is_bad_length)
  381. return nullptr;
  382. if (!length.is_undefined())
  383. return CSS::LengthStyleValue::create(length);
  384. if (string.equals_ignoring_case("inherit"))
  385. return CSS::InheritStyleValue::create();
  386. if (string.equals_ignoring_case("initial"))
  387. return CSS::InitialStyleValue::create();
  388. if (string.equals_ignoring_case("auto"))
  389. return CSS::LengthStyleValue::create(CSS::Length::make_auto());
  390. auto value_id = value_id_from_string(string);
  391. if (value_id.has_value())
  392. return CSS::IdentifierStyleValue::create(value_id.value());
  393. auto color = parse_css_color(context, string);
  394. if (color.has_value())
  395. return CSS::ColorStyleValue::create(color.value());
  396. return CSS::StringStyleValue::create(string);
  397. }
  398. RefPtr<CSS::LengthStyleValue> parse_line_width(const CSS::ParsingContext& context, const StringView& part)
  399. {
  400. auto value = parse_css_value(context, part);
  401. if (value && value->is_length())
  402. return static_ptr_cast<CSS::LengthStyleValue>(value);
  403. return nullptr;
  404. }
  405. RefPtr<CSS::ColorStyleValue> parse_color(const CSS::ParsingContext& context, const StringView& part)
  406. {
  407. auto value = parse_css_value(context, part);
  408. if (value && value->is_color())
  409. return static_ptr_cast<CSS::ColorStyleValue>(value);
  410. return nullptr;
  411. }
  412. RefPtr<CSS::StringStyleValue> parse_line_style(const CSS::ParsingContext& context, const StringView& part)
  413. {
  414. auto parsed_value = parse_css_value(context, part);
  415. if (!parsed_value || !parsed_value->is_string())
  416. return nullptr;
  417. auto value = static_ptr_cast<CSS::StringStyleValue>(parsed_value);
  418. if (value->to_string() == "dotted")
  419. return value;
  420. if (value->to_string() == "dashed")
  421. return value;
  422. if (value->to_string() == "solid")
  423. return value;
  424. if (value->to_string() == "double")
  425. return value;
  426. if (value->to_string() == "groove")
  427. return value;
  428. if (value->to_string() == "ridge")
  429. return value;
  430. return nullptr;
  431. }
  432. class CSSParser {
  433. public:
  434. CSSParser(const CSS::ParsingContext& context, const StringView& input)
  435. : m_context(context)
  436. , css(input)
  437. {
  438. }
  439. bool next_is(const char* str) const
  440. {
  441. size_t len = strlen(str);
  442. for (size_t i = 0; i < len; ++i) {
  443. if (peek(i) != str[i])
  444. return false;
  445. }
  446. return true;
  447. }
  448. char peek(size_t offset = 0) const
  449. {
  450. if ((index + offset) < css.length())
  451. return css[index + offset];
  452. return 0;
  453. }
  454. bool consume_specific(char ch)
  455. {
  456. if (peek() != ch) {
  457. dbgln("CSSParser: Peeked '{:c}' wanted specific '{:c}'", peek(), ch);
  458. }
  459. if (!peek()) {
  460. PARSE_ERROR();
  461. return false;
  462. }
  463. if (peek() != ch) {
  464. PARSE_ERROR();
  465. ++index;
  466. return false;
  467. }
  468. ++index;
  469. return true;
  470. }
  471. char consume_one()
  472. {
  473. PARSE_ASSERT(index < css.length());
  474. return css[index++];
  475. };
  476. bool consume_whitespace_or_comments()
  477. {
  478. size_t original_index = index;
  479. bool in_comment = false;
  480. for (; index < css.length(); ++index) {
  481. char ch = peek();
  482. if (isspace(ch))
  483. continue;
  484. if (!in_comment && ch == '/' && peek(1) == '*') {
  485. in_comment = true;
  486. ++index;
  487. continue;
  488. }
  489. if (in_comment && ch == '*' && peek(1) == '/') {
  490. in_comment = false;
  491. ++index;
  492. continue;
  493. }
  494. if (in_comment)
  495. continue;
  496. break;
  497. }
  498. return original_index != index;
  499. }
  500. bool is_valid_selector_char(char ch) const
  501. {
  502. return isalnum(ch) || ch == '-' || ch == '_' || ch == '(' || ch == ')' || ch == '@';
  503. }
  504. bool is_combinator(char ch) const
  505. {
  506. return ch == '~' || ch == '>' || ch == '+';
  507. }
  508. Optional<CSS::Selector::SimpleSelector> parse_simple_selector()
  509. {
  510. auto index_at_start = index;
  511. if (consume_whitespace_or_comments())
  512. return {};
  513. if (!peek() || peek() == '{' || peek() == ',' || is_combinator(peek()))
  514. return {};
  515. CSS::Selector::SimpleSelector::Type type;
  516. if (peek() == '*') {
  517. type = CSS::Selector::SimpleSelector::Type::Universal;
  518. consume_one();
  519. return CSS::Selector::SimpleSelector {
  520. type,
  521. CSS::Selector::SimpleSelector::PseudoClass::None,
  522. CSS::Selector::SimpleSelector::PseudoElement::None,
  523. String(),
  524. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  525. String(),
  526. String()
  527. };
  528. }
  529. if (peek() == '.') {
  530. type = CSS::Selector::SimpleSelector::Type::Class;
  531. consume_one();
  532. } else if (peek() == '#') {
  533. type = CSS::Selector::SimpleSelector::Type::Id;
  534. consume_one();
  535. } else if (isalpha(peek())) {
  536. type = CSS::Selector::SimpleSelector::Type::TagName;
  537. } else {
  538. type = CSS::Selector::SimpleSelector::Type::Universal;
  539. }
  540. if (type != CSS::Selector::SimpleSelector::Type::Universal) {
  541. while (is_valid_selector_char(peek()))
  542. buffer.append(consume_one());
  543. PARSE_ASSERT(!buffer.is_null());
  544. }
  545. auto value = String::copy(buffer);
  546. if (type == CSS::Selector::SimpleSelector::Type::TagName) {
  547. // Some stylesheets use uppercase tag names, so here's a hack to just lowercase them internally.
  548. value = value.to_lowercase();
  549. }
  550. CSS::Selector::SimpleSelector simple_selector {
  551. type,
  552. CSS::Selector::SimpleSelector::PseudoClass::None,
  553. CSS::Selector::SimpleSelector::PseudoElement::None,
  554. value,
  555. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  556. String(),
  557. String()
  558. };
  559. buffer.clear();
  560. if (peek() == '[') {
  561. CSS::Selector::SimpleSelector::AttributeMatchType attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::HasAttribute;
  562. String attribute_name;
  563. String attribute_value;
  564. bool in_value = false;
  565. consume_specific('[');
  566. char expected_end_of_attribute_selector = ']';
  567. while (peek() != expected_end_of_attribute_selector) {
  568. char ch = consume_one();
  569. if (ch == '=' || (ch == '~' && peek() == '=')) {
  570. if (ch == '=') {
  571. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::ExactValueMatch;
  572. } else if (ch == '~') {
  573. consume_one();
  574. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::Contains;
  575. }
  576. attribute_name = String::copy(buffer);
  577. buffer.clear();
  578. in_value = true;
  579. consume_whitespace_or_comments();
  580. if (peek() == '\'') {
  581. expected_end_of_attribute_selector = '\'';
  582. consume_one();
  583. } else if (peek() == '"') {
  584. expected_end_of_attribute_selector = '"';
  585. consume_one();
  586. }
  587. continue;
  588. }
  589. // FIXME: This is a hack that will go away when we replace this with a big boy CSS parser.
  590. if (ch == '\\')
  591. ch = consume_one();
  592. buffer.append(ch);
  593. }
  594. if (in_value)
  595. attribute_value = String::copy(buffer);
  596. else
  597. attribute_name = String::copy(buffer);
  598. buffer.clear();
  599. simple_selector.attribute_match_type = attribute_match_type;
  600. simple_selector.attribute_name = attribute_name;
  601. simple_selector.attribute_value = attribute_value;
  602. if (expected_end_of_attribute_selector != ']') {
  603. if (!consume_specific(expected_end_of_attribute_selector))
  604. return {};
  605. }
  606. consume_whitespace_or_comments();
  607. if (!consume_specific(']'))
  608. return {};
  609. }
  610. if (peek() == ':') {
  611. // FIXME: Implement pseudo elements.
  612. [[maybe_unused]] bool is_pseudo_element = false;
  613. consume_one();
  614. if (peek() == ':') {
  615. is_pseudo_element = true;
  616. consume_one();
  617. }
  618. if (next_is("not")) {
  619. buffer.append(consume_one());
  620. buffer.append(consume_one());
  621. buffer.append(consume_one());
  622. if (!consume_specific('('))
  623. return {};
  624. buffer.append('(');
  625. while (peek() != ')')
  626. buffer.append(consume_one());
  627. if (!consume_specific(')'))
  628. return {};
  629. buffer.append(')');
  630. } else {
  631. while (is_valid_selector_char(peek()))
  632. buffer.append(consume_one());
  633. }
  634. auto pseudo_name = String::copy(buffer);
  635. buffer.clear();
  636. // Ignore for now, otherwise we produce a "false positive" selector
  637. // and apply styles to the element itself, not its pseudo element
  638. if (is_pseudo_element)
  639. return {};
  640. if (pseudo_name.equals_ignoring_case("link"))
  641. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Link;
  642. else if (pseudo_name.equals_ignoring_case("visited"))
  643. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Visited;
  644. else if (pseudo_name.equals_ignoring_case("hover"))
  645. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Hover;
  646. else if (pseudo_name.equals_ignoring_case("focus"))
  647. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Focus;
  648. else if (pseudo_name.equals_ignoring_case("first-child"))
  649. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::FirstChild;
  650. else if (pseudo_name.equals_ignoring_case("last-child"))
  651. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::LastChild;
  652. else if (pseudo_name.equals_ignoring_case("only-child"))
  653. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::OnlyChild;
  654. else if (pseudo_name.equals_ignoring_case("empty"))
  655. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Empty;
  656. else if (pseudo_name.equals_ignoring_case("root"))
  657. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Root;
  658. else if (pseudo_name.equals_ignoring_case("before"))
  659. simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::Before;
  660. else if (pseudo_name.equals_ignoring_case("after"))
  661. simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::After;
  662. }
  663. if (index == index_at_start) {
  664. // We consumed nothing.
  665. return {};
  666. }
  667. return simple_selector;
  668. }
  669. Optional<CSS::Selector::ComplexSelector> parse_complex_selector()
  670. {
  671. auto relation = CSS::Selector::ComplexSelector::Relation::Descendant;
  672. if (peek() == '{' || peek() == ',')
  673. return {};
  674. if (is_combinator(peek())) {
  675. switch (peek()) {
  676. case '>':
  677. relation = CSS::Selector::ComplexSelector::Relation::ImmediateChild;
  678. break;
  679. case '+':
  680. relation = CSS::Selector::ComplexSelector::Relation::AdjacentSibling;
  681. break;
  682. case '~':
  683. relation = CSS::Selector::ComplexSelector::Relation::GeneralSibling;
  684. break;
  685. }
  686. consume_one();
  687. consume_whitespace_or_comments();
  688. }
  689. consume_whitespace_or_comments();
  690. Vector<CSS::Selector::SimpleSelector> simple_selectors;
  691. for (;;) {
  692. auto component = parse_simple_selector();
  693. if (!component.has_value())
  694. break;
  695. simple_selectors.append(component.value());
  696. // If this assert triggers, we're most likely up to no good.
  697. PARSE_ASSERT(simple_selectors.size() < 100);
  698. }
  699. if (simple_selectors.is_empty())
  700. return {};
  701. return CSS::Selector::ComplexSelector { relation, move(simple_selectors) };
  702. }
  703. void parse_selector()
  704. {
  705. Vector<CSS::Selector::ComplexSelector> complex_selectors;
  706. for (;;) {
  707. auto index_before = index;
  708. auto complex_selector = parse_complex_selector();
  709. if (complex_selector.has_value())
  710. complex_selectors.append(complex_selector.value());
  711. consume_whitespace_or_comments();
  712. if (!peek() || peek() == ',' || peek() == '{')
  713. break;
  714. // HACK: If we didn't move forward, just let go.
  715. if (index == index_before)
  716. break;
  717. }
  718. if (complex_selectors.is_empty())
  719. return;
  720. complex_selectors.first().relation = CSS::Selector::ComplexSelector::Relation::None;
  721. current_rule.selectors.append(CSS::Selector(move(complex_selectors)));
  722. }
  723. Optional<CSS::Selector> parse_individual_selector()
  724. {
  725. parse_selector();
  726. if (current_rule.selectors.is_empty())
  727. return {};
  728. return current_rule.selectors.last();
  729. }
  730. void parse_selector_list()
  731. {
  732. for (;;) {
  733. auto index_before = index;
  734. parse_selector();
  735. consume_whitespace_or_comments();
  736. if (peek() == ',') {
  737. consume_one();
  738. continue;
  739. }
  740. if (peek() == '{')
  741. break;
  742. // HACK: If we didn't move forward, just let go.
  743. if (index_before == index)
  744. break;
  745. }
  746. }
  747. bool is_valid_property_name_char(char ch) const
  748. {
  749. return ch && !isspace(ch) && ch != ':';
  750. }
  751. bool is_valid_property_value_char(char ch) const
  752. {
  753. return ch && ch != '!' && ch != ';' && ch != '}';
  754. }
  755. struct ValueAndImportant {
  756. String value;
  757. bool important { false };
  758. };
  759. ValueAndImportant consume_css_value()
  760. {
  761. buffer.clear();
  762. int paren_nesting_level = 0;
  763. bool important = false;
  764. for (;;) {
  765. char ch = peek();
  766. if (ch == '(') {
  767. ++paren_nesting_level;
  768. buffer.append(consume_one());
  769. continue;
  770. }
  771. if (ch == ')') {
  772. PARSE_ASSERT(paren_nesting_level > 0);
  773. --paren_nesting_level;
  774. buffer.append(consume_one());
  775. continue;
  776. }
  777. if (paren_nesting_level > 0) {
  778. buffer.append(consume_one());
  779. continue;
  780. }
  781. if (next_is("!important")) {
  782. consume_specific('!');
  783. consume_specific('i');
  784. consume_specific('m');
  785. consume_specific('p');
  786. consume_specific('o');
  787. consume_specific('r');
  788. consume_specific('t');
  789. consume_specific('a');
  790. consume_specific('n');
  791. consume_specific('t');
  792. important = true;
  793. continue;
  794. }
  795. if (next_is("/*")) {
  796. consume_whitespace_or_comments();
  797. continue;
  798. }
  799. if (!ch)
  800. break;
  801. if (ch == '\\') {
  802. consume_one();
  803. buffer.append(consume_one());
  804. continue;
  805. }
  806. if (ch == '}')
  807. break;
  808. if (ch == ';')
  809. break;
  810. buffer.append(consume_one());
  811. }
  812. // Remove trailing whitespace.
  813. while (!buffer.is_empty() && isspace(buffer.last()))
  814. buffer.take_last();
  815. auto string = String::copy(buffer);
  816. buffer.clear();
  817. return { string, important };
  818. }
  819. Optional<CSS::StyleProperty> parse_property()
  820. {
  821. consume_whitespace_or_comments();
  822. if (peek() == ';') {
  823. consume_one();
  824. return {};
  825. }
  826. if (peek() == '}')
  827. return {};
  828. buffer.clear();
  829. while (is_valid_property_name_char(peek()))
  830. buffer.append(consume_one());
  831. auto property_name = String::copy(buffer);
  832. buffer.clear();
  833. consume_whitespace_or_comments();
  834. if (!consume_specific(':'))
  835. return {};
  836. consume_whitespace_or_comments();
  837. auto [property_value, important] = consume_css_value();
  838. consume_whitespace_or_comments();
  839. if (peek() && peek() != '}') {
  840. if (!consume_specific(';'))
  841. return {};
  842. }
  843. auto property_id = CSS::property_id_from_string(property_name);
  844. if (property_id == CSS::PropertyID::Invalid) {
  845. dbg() << "CSSParser: Unrecognized property '" << property_name << "'";
  846. }
  847. auto value = parse_css_value(m_context, property_value, property_id);
  848. if (!value)
  849. return {};
  850. return CSS::StyleProperty { property_id, value.release_nonnull(), important };
  851. }
  852. void parse_declaration()
  853. {
  854. for (;;) {
  855. auto property = parse_property();
  856. if (property.has_value())
  857. current_rule.properties.append(property.value());
  858. consume_whitespace_or_comments();
  859. if (!peek() || peek() == '}')
  860. break;
  861. }
  862. }
  863. void parse_rule()
  864. {
  865. consume_whitespace_or_comments();
  866. if (!peek())
  867. return;
  868. // FIXME: We ignore @-rules for now.
  869. if (peek() == '@') {
  870. while (peek() != '{')
  871. consume_one();
  872. int level = 0;
  873. for (;;) {
  874. auto ch = consume_one();
  875. if (ch == '{') {
  876. ++level;
  877. } else if (ch == '}') {
  878. --level;
  879. if (level == 0)
  880. break;
  881. }
  882. }
  883. consume_whitespace_or_comments();
  884. return;
  885. }
  886. parse_selector_list();
  887. if (!consume_specific('{')) {
  888. PARSE_ERROR();
  889. return;
  890. }
  891. parse_declaration();
  892. if (!consume_specific('}')) {
  893. PARSE_ERROR();
  894. return;
  895. }
  896. rules.append(CSS::StyleRule::create(move(current_rule.selectors), CSS::StyleDeclaration::create(move(current_rule.properties))));
  897. consume_whitespace_or_comments();
  898. }
  899. RefPtr<CSS::StyleSheet> parse_sheet()
  900. {
  901. if (peek(0) == (char)0xef && peek(1) == (char)0xbb && peek(2) == (char)0xbf) {
  902. // HACK: Skip UTF-8 BOM.
  903. index += 3;
  904. }
  905. while (peek()) {
  906. parse_rule();
  907. }
  908. return CSS::StyleSheet::create(move(rules));
  909. }
  910. RefPtr<CSS::StyleDeclaration> parse_standalone_declaration()
  911. {
  912. consume_whitespace_or_comments();
  913. for (;;) {
  914. auto property = parse_property();
  915. if (property.has_value())
  916. current_rule.properties.append(property.value());
  917. consume_whitespace_or_comments();
  918. if (!peek())
  919. break;
  920. }
  921. return CSS::StyleDeclaration::create(move(current_rule.properties));
  922. }
  923. private:
  924. CSS::ParsingContext m_context;
  925. NonnullRefPtrVector<CSS::StyleRule> rules;
  926. struct CurrentRule {
  927. Vector<CSS::Selector> selectors;
  928. Vector<CSS::StyleProperty> properties;
  929. };
  930. CurrentRule current_rule;
  931. Vector<char> buffer;
  932. size_t index = 0;
  933. StringView css;
  934. };
  935. Optional<CSS::Selector> parse_selector(const CSS::ParsingContext& context, const StringView& selector_text)
  936. {
  937. CSSParser parser(context, selector_text);
  938. return parser.parse_individual_selector();
  939. }
  940. RefPtr<CSS::StyleSheet> parse_css(const CSS::ParsingContext& context, const StringView& css)
  941. {
  942. if (css.is_empty())
  943. return CSS::StyleSheet::create({});
  944. CSSParser parser(context, css);
  945. return parser.parse_sheet();
  946. }
  947. RefPtr<CSS::StyleDeclaration> parse_css_declaration(const CSS::ParsingContext& context, const StringView& css)
  948. {
  949. if (css.is_empty())
  950. return CSS::StyleDeclaration::create({});
  951. CSSParser parser(context, css);
  952. return parser.parse_standalone_declaration();
  953. }
  954. RefPtr<CSS::StyleValue> parse_html_length(const DOM::Document& document, const StringView& string)
  955. {
  956. auto integer = string.to_int();
  957. if (integer.has_value())
  958. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  959. return parse_css_value(CSS::ParsingContext(document), string);
  960. }
  961. }