CSSParser.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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.equals_ignoring_case("none"))
  368. return CSS::ValueID::None;
  369. if (string.equals_ignoring_case("both"))
  370. return CSS::ValueID::Both;
  371. if (string.equals_ignoring_case("hidden"))
  372. return CSS::ValueID::Hidden;
  373. if (string.equals_ignoring_case("dotted"))
  374. return CSS::ValueID::Dotted;
  375. if (string.equals_ignoring_case("dashed"))
  376. return CSS::ValueID::Dashed;
  377. if (string.equals_ignoring_case("solid"))
  378. return CSS::ValueID::Solid;
  379. if (string.equals_ignoring_case("double"))
  380. return CSS::ValueID::Double;
  381. if (string.equals_ignoring_case("groove"))
  382. return CSS::ValueID::Groove;
  383. if (string.equals_ignoring_case("ridge"))
  384. return CSS::ValueID::Ridge;
  385. if (string.equals_ignoring_case("inset"))
  386. return CSS::ValueID::Inset;
  387. if (string.equals_ignoring_case("outset"))
  388. return CSS::ValueID::Outset;
  389. if (string.equals_ignoring_case("nowrap"))
  390. return CSS::ValueID::Nowrap;
  391. if (string.equals_ignoring_case("pre"))
  392. return CSS::ValueID::Pre;
  393. if (string.equals_ignoring_case("pre-line"))
  394. return CSS::ValueID::PreLine;
  395. if (string.equals_ignoring_case("pre-wrap"))
  396. return CSS::ValueID::PreWrap;
  397. if (string.equals_ignoring_case("block"))
  398. return CSS::ValueID::Block;
  399. if (string.equals_ignoring_case("inline"))
  400. return CSS::ValueID::Inline;
  401. if (string.equals_ignoring_case("inline-block"))
  402. return CSS::ValueID::InlineBlock;
  403. if (string.equals_ignoring_case("list-item"))
  404. return CSS::ValueID::ListItem;
  405. if (string.equals_ignoring_case("table"))
  406. return CSS::ValueID::Table;
  407. if (string.equals_ignoring_case("table-row"))
  408. return CSS::ValueID::TableRow;
  409. if (string.equals_ignoring_case("table-cell"))
  410. return CSS::ValueID::TableCell;
  411. if (string.equals_ignoring_case("table-row-group"))
  412. return CSS::ValueID::TableRowGroup;
  413. if (string.equals_ignoring_case("table-header-group"))
  414. return CSS::ValueID::TableHeaderGroup;
  415. if (string.equals_ignoring_case("table-footer-group"))
  416. return CSS::ValueID::TableFooterGroup;
  417. if (string.equals_ignoring_case("underline"))
  418. return CSS::ValueID::Underline;
  419. if (string.equals_ignoring_case("overline"))
  420. return CSS::ValueID::Overline;
  421. if (string.equals_ignoring_case("line-through"))
  422. return CSS::ValueID::LineThrough;
  423. if (string.equals_ignoring_case("blink"))
  424. return CSS::ValueID::Blink;
  425. if (string.starts_with("-libweb-palette-", CaseSensitivity::CaseInsensitive))
  426. return value_id_for_palette_string(string.substring_view(16, string.length() - 16));
  427. return {};
  428. }
  429. RefPtr<CSS::StyleValue> parse_css_value(const CSS::ParsingContext& context, const StringView& string, CSS::PropertyID property_id)
  430. {
  431. bool is_bad_length = false;
  432. if (takes_integer_value(property_id)) {
  433. auto integer = string.to_int();
  434. if (integer.has_value())
  435. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  436. }
  437. auto length = parse_length(context, string, is_bad_length);
  438. if (is_bad_length)
  439. return nullptr;
  440. if (!length.is_undefined())
  441. return CSS::LengthStyleValue::create(length);
  442. if (string.equals_ignoring_case("inherit"))
  443. return CSS::InheritStyleValue::create();
  444. if (string.equals_ignoring_case("initial"))
  445. return CSS::InitialStyleValue::create();
  446. if (string.equals_ignoring_case("auto"))
  447. return CSS::LengthStyleValue::create(CSS::Length::make_auto());
  448. auto value_id = value_id_from_string(string);
  449. if (value_id.has_value())
  450. return CSS::IdentifierStyleValue::create(value_id.value());
  451. auto color = parse_css_color(context, string);
  452. if (color.has_value())
  453. return CSS::ColorStyleValue::create(color.value());
  454. return CSS::StringStyleValue::create(string);
  455. }
  456. RefPtr<CSS::LengthStyleValue> parse_line_width(const CSS::ParsingContext& context, const StringView& part)
  457. {
  458. auto value = parse_css_value(context, part);
  459. if (value && value->is_length())
  460. return static_ptr_cast<CSS::LengthStyleValue>(value);
  461. return nullptr;
  462. }
  463. RefPtr<CSS::ColorStyleValue> parse_color(const CSS::ParsingContext& context, const StringView& part)
  464. {
  465. auto value = parse_css_value(context, part);
  466. if (value && value->is_color())
  467. return static_ptr_cast<CSS::ColorStyleValue>(value);
  468. return nullptr;
  469. }
  470. RefPtr<CSS::StringStyleValue> parse_line_style(const CSS::ParsingContext& context, const StringView& part)
  471. {
  472. auto parsed_value = parse_css_value(context, part);
  473. if (!parsed_value || !parsed_value->is_string())
  474. return nullptr;
  475. auto value = static_ptr_cast<CSS::StringStyleValue>(parsed_value);
  476. if (value->to_string() == "dotted")
  477. return value;
  478. if (value->to_string() == "dashed")
  479. return value;
  480. if (value->to_string() == "solid")
  481. return value;
  482. if (value->to_string() == "double")
  483. return value;
  484. if (value->to_string() == "groove")
  485. return value;
  486. if (value->to_string() == "ridge")
  487. return value;
  488. return nullptr;
  489. }
  490. class CSSParser {
  491. public:
  492. CSSParser(const CSS::ParsingContext& context, const StringView& input)
  493. : m_context(context)
  494. , css(input)
  495. {
  496. }
  497. bool next_is(const char* str) const
  498. {
  499. size_t len = strlen(str);
  500. for (size_t i = 0; i < len; ++i) {
  501. if (peek(i) != str[i])
  502. return false;
  503. }
  504. return true;
  505. }
  506. char peek(size_t offset = 0) const
  507. {
  508. if ((index + offset) < css.length())
  509. return css[index + offset];
  510. return 0;
  511. }
  512. bool consume_specific(char ch)
  513. {
  514. if (peek() != ch) {
  515. dbgln("CSSParser: Peeked '{:c}' wanted specific '{:c}'", peek(), ch);
  516. }
  517. if (!peek()) {
  518. PARSE_ERROR();
  519. return false;
  520. }
  521. if (peek() != ch) {
  522. PARSE_ERROR();
  523. ++index;
  524. return false;
  525. }
  526. ++index;
  527. return true;
  528. }
  529. char consume_one()
  530. {
  531. PARSE_ASSERT(index < css.length());
  532. return css[index++];
  533. };
  534. bool consume_whitespace_or_comments()
  535. {
  536. size_t original_index = index;
  537. bool in_comment = false;
  538. for (; index < css.length(); ++index) {
  539. char ch = peek();
  540. if (isspace(ch))
  541. continue;
  542. if (!in_comment && ch == '/' && peek(1) == '*') {
  543. in_comment = true;
  544. ++index;
  545. continue;
  546. }
  547. if (in_comment && ch == '*' && peek(1) == '/') {
  548. in_comment = false;
  549. ++index;
  550. continue;
  551. }
  552. if (in_comment)
  553. continue;
  554. break;
  555. }
  556. return original_index != index;
  557. }
  558. bool is_valid_selector_char(char ch) const
  559. {
  560. return isalnum(ch) || ch == '-' || ch == '_' || ch == '(' || ch == ')' || ch == '@';
  561. }
  562. bool is_combinator(char ch) const
  563. {
  564. return ch == '~' || ch == '>' || ch == '+';
  565. }
  566. Optional<CSS::Selector::SimpleSelector> parse_simple_selector()
  567. {
  568. auto index_at_start = index;
  569. if (consume_whitespace_or_comments())
  570. return {};
  571. if (!peek() || peek() == '{' || peek() == ',' || is_combinator(peek()))
  572. return {};
  573. CSS::Selector::SimpleSelector::Type type;
  574. if (peek() == '*') {
  575. type = CSS::Selector::SimpleSelector::Type::Universal;
  576. consume_one();
  577. return CSS::Selector::SimpleSelector {
  578. type,
  579. CSS::Selector::SimpleSelector::PseudoClass::None,
  580. CSS::Selector::SimpleSelector::PseudoElement::None,
  581. String(),
  582. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  583. String(),
  584. String()
  585. };
  586. }
  587. if (peek() == '.') {
  588. type = CSS::Selector::SimpleSelector::Type::Class;
  589. consume_one();
  590. } else if (peek() == '#') {
  591. type = CSS::Selector::SimpleSelector::Type::Id;
  592. consume_one();
  593. } else if (isalpha(peek())) {
  594. type = CSS::Selector::SimpleSelector::Type::TagName;
  595. } else {
  596. type = CSS::Selector::SimpleSelector::Type::Universal;
  597. }
  598. if (type != CSS::Selector::SimpleSelector::Type::Universal) {
  599. while (is_valid_selector_char(peek()))
  600. buffer.append(consume_one());
  601. PARSE_ASSERT(!buffer.is_null());
  602. }
  603. auto value = String::copy(buffer);
  604. if (type == CSS::Selector::SimpleSelector::Type::TagName) {
  605. // Some stylesheets use uppercase tag names, so here's a hack to just lowercase them internally.
  606. value = value.to_lowercase();
  607. }
  608. CSS::Selector::SimpleSelector simple_selector {
  609. type,
  610. CSS::Selector::SimpleSelector::PseudoClass::None,
  611. CSS::Selector::SimpleSelector::PseudoElement::None,
  612. value,
  613. CSS::Selector::SimpleSelector::AttributeMatchType::None,
  614. String(),
  615. String()
  616. };
  617. buffer.clear();
  618. if (peek() == '[') {
  619. CSS::Selector::SimpleSelector::AttributeMatchType attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::HasAttribute;
  620. String attribute_name;
  621. String attribute_value;
  622. bool in_value = false;
  623. consume_specific('[');
  624. char expected_end_of_attribute_selector = ']';
  625. while (peek() != expected_end_of_attribute_selector) {
  626. char ch = consume_one();
  627. if (ch == '=' || (ch == '~' && peek() == '=')) {
  628. if (ch == '=') {
  629. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::ExactValueMatch;
  630. } else if (ch == '~') {
  631. consume_one();
  632. attribute_match_type = CSS::Selector::SimpleSelector::AttributeMatchType::Contains;
  633. }
  634. attribute_name = String::copy(buffer);
  635. buffer.clear();
  636. in_value = true;
  637. consume_whitespace_or_comments();
  638. if (peek() == '\'') {
  639. expected_end_of_attribute_selector = '\'';
  640. consume_one();
  641. } else if (peek() == '"') {
  642. expected_end_of_attribute_selector = '"';
  643. consume_one();
  644. }
  645. continue;
  646. }
  647. // FIXME: This is a hack that will go away when we replace this with a big boy CSS parser.
  648. if (ch == '\\')
  649. ch = consume_one();
  650. buffer.append(ch);
  651. }
  652. if (in_value)
  653. attribute_value = String::copy(buffer);
  654. else
  655. attribute_name = String::copy(buffer);
  656. buffer.clear();
  657. simple_selector.attribute_match_type = attribute_match_type;
  658. simple_selector.attribute_name = attribute_name;
  659. simple_selector.attribute_value = attribute_value;
  660. if (expected_end_of_attribute_selector != ']') {
  661. if (!consume_specific(expected_end_of_attribute_selector))
  662. return {};
  663. }
  664. consume_whitespace_or_comments();
  665. if (!consume_specific(']'))
  666. return {};
  667. }
  668. if (peek() == ':') {
  669. // FIXME: Implement pseudo elements.
  670. [[maybe_unused]] bool is_pseudo_element = false;
  671. consume_one();
  672. if (peek() == ':') {
  673. is_pseudo_element = true;
  674. consume_one();
  675. }
  676. if (next_is("not")) {
  677. buffer.append(consume_one());
  678. buffer.append(consume_one());
  679. buffer.append(consume_one());
  680. if (!consume_specific('('))
  681. return {};
  682. buffer.append('(');
  683. while (peek() != ')')
  684. buffer.append(consume_one());
  685. if (!consume_specific(')'))
  686. return {};
  687. buffer.append(')');
  688. } else {
  689. while (is_valid_selector_char(peek()))
  690. buffer.append(consume_one());
  691. }
  692. auto pseudo_name = String::copy(buffer);
  693. buffer.clear();
  694. // Ignore for now, otherwise we produce a "false positive" selector
  695. // and apply styles to the element itself, not its pseudo element
  696. if (is_pseudo_element)
  697. return {};
  698. if (pseudo_name.equals_ignoring_case("link"))
  699. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Link;
  700. else if (pseudo_name.equals_ignoring_case("visited"))
  701. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Visited;
  702. else if (pseudo_name.equals_ignoring_case("hover"))
  703. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Hover;
  704. else if (pseudo_name.equals_ignoring_case("focus"))
  705. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Focus;
  706. else if (pseudo_name.equals_ignoring_case("first-child"))
  707. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::FirstChild;
  708. else if (pseudo_name.equals_ignoring_case("last-child"))
  709. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::LastChild;
  710. else if (pseudo_name.equals_ignoring_case("only-child"))
  711. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::OnlyChild;
  712. else if (pseudo_name.equals_ignoring_case("empty"))
  713. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Empty;
  714. else if (pseudo_name.equals_ignoring_case("root"))
  715. simple_selector.pseudo_class = CSS::Selector::SimpleSelector::PseudoClass::Root;
  716. else if (pseudo_name.equals_ignoring_case("before"))
  717. simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::Before;
  718. else if (pseudo_name.equals_ignoring_case("after"))
  719. simple_selector.pseudo_element = CSS::Selector::SimpleSelector::PseudoElement::After;
  720. }
  721. if (index == index_at_start) {
  722. // We consumed nothing.
  723. return {};
  724. }
  725. return simple_selector;
  726. }
  727. Optional<CSS::Selector::ComplexSelector> parse_complex_selector()
  728. {
  729. auto relation = CSS::Selector::ComplexSelector::Relation::Descendant;
  730. if (peek() == '{' || peek() == ',')
  731. return {};
  732. if (is_combinator(peek())) {
  733. switch (peek()) {
  734. case '>':
  735. relation = CSS::Selector::ComplexSelector::Relation::ImmediateChild;
  736. break;
  737. case '+':
  738. relation = CSS::Selector::ComplexSelector::Relation::AdjacentSibling;
  739. break;
  740. case '~':
  741. relation = CSS::Selector::ComplexSelector::Relation::GeneralSibling;
  742. break;
  743. }
  744. consume_one();
  745. consume_whitespace_or_comments();
  746. }
  747. consume_whitespace_or_comments();
  748. Vector<CSS::Selector::SimpleSelector> simple_selectors;
  749. for (;;) {
  750. auto component = parse_simple_selector();
  751. if (!component.has_value())
  752. break;
  753. simple_selectors.append(component.value());
  754. // If this assert triggers, we're most likely up to no good.
  755. PARSE_ASSERT(simple_selectors.size() < 100);
  756. }
  757. if (simple_selectors.is_empty())
  758. return {};
  759. return CSS::Selector::ComplexSelector { relation, move(simple_selectors) };
  760. }
  761. void parse_selector()
  762. {
  763. Vector<CSS::Selector::ComplexSelector> complex_selectors;
  764. for (;;) {
  765. auto index_before = index;
  766. auto complex_selector = parse_complex_selector();
  767. if (complex_selector.has_value())
  768. complex_selectors.append(complex_selector.value());
  769. consume_whitespace_or_comments();
  770. if (!peek() || peek() == ',' || peek() == '{')
  771. break;
  772. // HACK: If we didn't move forward, just let go.
  773. if (index == index_before)
  774. break;
  775. }
  776. if (complex_selectors.is_empty())
  777. return;
  778. complex_selectors.first().relation = CSS::Selector::ComplexSelector::Relation::None;
  779. current_rule.selectors.append(CSS::Selector(move(complex_selectors)));
  780. }
  781. Optional<CSS::Selector> parse_individual_selector()
  782. {
  783. parse_selector();
  784. if (current_rule.selectors.is_empty())
  785. return {};
  786. return current_rule.selectors.last();
  787. }
  788. void parse_selector_list()
  789. {
  790. for (;;) {
  791. auto index_before = index;
  792. parse_selector();
  793. consume_whitespace_or_comments();
  794. if (peek() == ',') {
  795. consume_one();
  796. continue;
  797. }
  798. if (peek() == '{')
  799. break;
  800. // HACK: If we didn't move forward, just let go.
  801. if (index_before == index)
  802. break;
  803. }
  804. }
  805. bool is_valid_property_name_char(char ch) const
  806. {
  807. return ch && !isspace(ch) && ch != ':';
  808. }
  809. bool is_valid_property_value_char(char ch) const
  810. {
  811. return ch && ch != '!' && ch != ';' && ch != '}';
  812. }
  813. struct ValueAndImportant {
  814. String value;
  815. bool important { false };
  816. };
  817. ValueAndImportant consume_css_value()
  818. {
  819. buffer.clear();
  820. int paren_nesting_level = 0;
  821. bool important = false;
  822. for (;;) {
  823. char ch = peek();
  824. if (ch == '(') {
  825. ++paren_nesting_level;
  826. buffer.append(consume_one());
  827. continue;
  828. }
  829. if (ch == ')') {
  830. PARSE_ASSERT(paren_nesting_level > 0);
  831. --paren_nesting_level;
  832. buffer.append(consume_one());
  833. continue;
  834. }
  835. if (paren_nesting_level > 0) {
  836. buffer.append(consume_one());
  837. continue;
  838. }
  839. if (next_is("!important")) {
  840. consume_specific('!');
  841. consume_specific('i');
  842. consume_specific('m');
  843. consume_specific('p');
  844. consume_specific('o');
  845. consume_specific('r');
  846. consume_specific('t');
  847. consume_specific('a');
  848. consume_specific('n');
  849. consume_specific('t');
  850. important = true;
  851. continue;
  852. }
  853. if (next_is("/*")) {
  854. consume_whitespace_or_comments();
  855. continue;
  856. }
  857. if (!ch)
  858. break;
  859. if (ch == '\\') {
  860. consume_one();
  861. buffer.append(consume_one());
  862. continue;
  863. }
  864. if (ch == '}')
  865. break;
  866. if (ch == ';')
  867. break;
  868. buffer.append(consume_one());
  869. }
  870. // Remove trailing whitespace.
  871. while (!buffer.is_empty() && isspace(buffer.last()))
  872. buffer.take_last();
  873. auto string = String::copy(buffer);
  874. buffer.clear();
  875. return { string, important };
  876. }
  877. Optional<CSS::StyleProperty> parse_property()
  878. {
  879. consume_whitespace_or_comments();
  880. if (peek() == ';') {
  881. consume_one();
  882. return {};
  883. }
  884. if (peek() == '}')
  885. return {};
  886. buffer.clear();
  887. while (is_valid_property_name_char(peek()))
  888. buffer.append(consume_one());
  889. auto property_name = String::copy(buffer);
  890. buffer.clear();
  891. consume_whitespace_or_comments();
  892. if (!consume_specific(':'))
  893. return {};
  894. consume_whitespace_or_comments();
  895. auto [property_value, important] = consume_css_value();
  896. consume_whitespace_or_comments();
  897. if (peek() && peek() != '}') {
  898. if (!consume_specific(';'))
  899. return {};
  900. }
  901. auto property_id = CSS::property_id_from_string(property_name);
  902. if (property_id == CSS::PropertyID::Invalid) {
  903. dbg() << "CSSParser: Unrecognized property '" << property_name << "'";
  904. }
  905. auto value = parse_css_value(m_context, property_value, property_id);
  906. if (!value)
  907. return {};
  908. return CSS::StyleProperty { property_id, value.release_nonnull(), important };
  909. }
  910. void parse_declaration()
  911. {
  912. for (;;) {
  913. auto property = parse_property();
  914. if (property.has_value())
  915. current_rule.properties.append(property.value());
  916. consume_whitespace_or_comments();
  917. if (!peek() || peek() == '}')
  918. break;
  919. }
  920. }
  921. void parse_rule()
  922. {
  923. consume_whitespace_or_comments();
  924. if (!peek())
  925. return;
  926. // FIXME: We ignore @-rules for now.
  927. if (peek() == '@') {
  928. while (peek() != '{')
  929. consume_one();
  930. int level = 0;
  931. for (;;) {
  932. auto ch = consume_one();
  933. if (ch == '{') {
  934. ++level;
  935. } else if (ch == '}') {
  936. --level;
  937. if (level == 0)
  938. break;
  939. }
  940. }
  941. consume_whitespace_or_comments();
  942. return;
  943. }
  944. parse_selector_list();
  945. if (!consume_specific('{')) {
  946. PARSE_ERROR();
  947. return;
  948. }
  949. parse_declaration();
  950. if (!consume_specific('}')) {
  951. PARSE_ERROR();
  952. return;
  953. }
  954. rules.append(CSS::StyleRule::create(move(current_rule.selectors), CSS::StyleDeclaration::create(move(current_rule.properties))));
  955. consume_whitespace_or_comments();
  956. }
  957. RefPtr<CSS::StyleSheet> parse_sheet()
  958. {
  959. if (peek(0) == (char)0xef && peek(1) == (char)0xbb && peek(2) == (char)0xbf) {
  960. // HACK: Skip UTF-8 BOM.
  961. index += 3;
  962. }
  963. while (peek()) {
  964. parse_rule();
  965. }
  966. return CSS::StyleSheet::create(move(rules));
  967. }
  968. RefPtr<CSS::StyleDeclaration> parse_standalone_declaration()
  969. {
  970. consume_whitespace_or_comments();
  971. for (;;) {
  972. auto property = parse_property();
  973. if (property.has_value())
  974. current_rule.properties.append(property.value());
  975. consume_whitespace_or_comments();
  976. if (!peek())
  977. break;
  978. }
  979. return CSS::StyleDeclaration::create(move(current_rule.properties));
  980. }
  981. private:
  982. CSS::ParsingContext m_context;
  983. NonnullRefPtrVector<CSS::StyleRule> rules;
  984. struct CurrentRule {
  985. Vector<CSS::Selector> selectors;
  986. Vector<CSS::StyleProperty> properties;
  987. };
  988. CurrentRule current_rule;
  989. Vector<char> buffer;
  990. size_t index = 0;
  991. StringView css;
  992. };
  993. Optional<CSS::Selector> parse_selector(const CSS::ParsingContext& context, const StringView& selector_text)
  994. {
  995. CSSParser parser(context, selector_text);
  996. return parser.parse_individual_selector();
  997. }
  998. RefPtr<CSS::StyleSheet> parse_css(const CSS::ParsingContext& context, const StringView& css)
  999. {
  1000. if (css.is_empty())
  1001. return CSS::StyleSheet::create({});
  1002. CSSParser parser(context, css);
  1003. return parser.parse_sheet();
  1004. }
  1005. RefPtr<CSS::StyleDeclaration> parse_css_declaration(const CSS::ParsingContext& context, const StringView& css)
  1006. {
  1007. if (css.is_empty())
  1008. return CSS::StyleDeclaration::create({});
  1009. CSSParser parser(context, css);
  1010. return parser.parse_standalone_declaration();
  1011. }
  1012. RefPtr<CSS::StyleValue> parse_html_length(const DOM::Document& document, const StringView& string)
  1013. {
  1014. auto integer = string.to_int();
  1015. if (integer.has_value())
  1016. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  1017. return parse_css_value(CSS::ParsingContext(document), string);
  1018. }
  1019. }