CSSParser.cpp 41 KB

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