CSSParser.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. #include <AK/HashMap.h>
  2. #include <LibHTML/CSS/StyleSheet.h>
  3. #include <LibHTML/Parser/CSSParser.h>
  4. #include <ctype.h>
  5. #include <stdio.h>
  6. #define PARSE_ASSERT(x) \
  7. if (!(x)) { \
  8. dbg() << "CSS PARSER ASSERTION FAILED: " << #x; \
  9. dbg() << "At character# " << index << " in CSS: _" << css << "_"; \
  10. ASSERT_NOT_REACHED(); \
  11. }
  12. static Optional<Color> parse_css_color(const StringView& view)
  13. {
  14. auto color = Color::from_string(view);
  15. if (color.has_value())
  16. return color;
  17. // FIXME: Parse all valid color strings :^)
  18. return {};
  19. }
  20. NonnullRefPtr<StyleValue> parse_css_value(const StringView& view)
  21. {
  22. String string(view);
  23. bool ok;
  24. int as_int = string.to_int(ok);
  25. if (ok)
  26. return LengthStyleValue::create(Length(as_int, Length::Type::Absolute));
  27. unsigned as_uint = string.to_uint(ok);
  28. if (ok)
  29. return LengthStyleValue::create(Length(as_uint, Length::Type::Absolute));
  30. if (string == "inherit")
  31. return InheritStyleValue::create();
  32. if (string == "initial")
  33. return InitialStyleValue::create();
  34. if (string == "auto")
  35. return LengthStyleValue::create(Length());
  36. auto color = parse_css_color(view);
  37. if (color.has_value())
  38. return ColorStyleValue::create(color.value());
  39. if (string == "-libhtml-link")
  40. return IdentifierStyleValue::create(CSS::ValueID::VendorSpecificLink);
  41. return StringStyleValue::create(string);
  42. }
  43. static CSS::PropertyID parse_css_property_id(const StringView& string)
  44. {
  45. static HashMap<String, CSS::PropertyID> map;
  46. if (map.is_empty()) {
  47. map.set("background-color", CSS::PropertyID::BackgroundColor);
  48. map.set("border-bottom-style", CSS::PropertyID::BorderBottomStyle);
  49. map.set("border-bottom-width", CSS::PropertyID::BorderBottomWidth);
  50. map.set("border-collapse", CSS::PropertyID::BorderCollapse);
  51. map.set("border-left-style", CSS::PropertyID::BorderLeftStyle);
  52. map.set("border-left-width", CSS::PropertyID::BorderLeftWidth);
  53. map.set("border-right-style", CSS::PropertyID::BorderRightStyle);
  54. map.set("border-right-width", CSS::PropertyID::BorderRightWidth);
  55. map.set("border-spacing", CSS::PropertyID::BorderSpacing);
  56. map.set("border-top-style", CSS::PropertyID::BorderTopStyle);
  57. map.set("border-top-width", CSS::PropertyID::BorderTopWidth);
  58. map.set("color", CSS::PropertyID::Color);
  59. map.set("display", CSS::PropertyID::Display);
  60. map.set("font-family", CSS::PropertyID::FontFamily);
  61. map.set("font-size", CSS::PropertyID::FontSize);
  62. map.set("font-style", CSS::PropertyID::FontStyle);
  63. map.set("font-variant", CSS::PropertyID::FontVariant);
  64. map.set("font-weight", CSS::PropertyID::FontWeight);
  65. map.set("height", CSS::PropertyID::Height);
  66. map.set("letter-spacing", CSS::PropertyID::LetterSpacing);
  67. map.set("line-height", CSS::PropertyID::LineHeight);
  68. map.set("list-style", CSS::PropertyID::ListStyle);
  69. map.set("list-style-image", CSS::PropertyID::ListStyleImage);
  70. map.set("list-style-position", CSS::PropertyID::ListStylePosition);
  71. map.set("list-style-type", CSS::PropertyID::ListStyleType);
  72. map.set("margin-bottom", CSS::PropertyID::MarginBottom);
  73. map.set("margin-left", CSS::PropertyID::MarginLeft);
  74. map.set("margin-right", CSS::PropertyID::MarginRight);
  75. map.set("margin-top", CSS::PropertyID::MarginTop);
  76. map.set("padding-bottom", CSS::PropertyID::PaddingBottom);
  77. map.set("padding-left", CSS::PropertyID::PaddingLeft);
  78. map.set("padding-right", CSS::PropertyID::PaddingRight);
  79. map.set("padding-top", CSS::PropertyID::PaddingTop);
  80. map.set("text-align", CSS::PropertyID::TextAlign);
  81. map.set("text-decoration", CSS::PropertyID::TextDecoration);
  82. map.set("text-indent", CSS::PropertyID::TextIndent);
  83. map.set("text-transform", CSS::PropertyID::TextTransform);
  84. map.set("visibility", CSS::PropertyID::Visibility);
  85. map.set("white-space", CSS::PropertyID::WhiteSpace);
  86. map.set("width", CSS::PropertyID::Width);
  87. map.set("word-spacing", CSS::PropertyID::WordSpacing);
  88. }
  89. return map.get(string).value_or(CSS::PropertyID::Invalid);
  90. }
  91. class CSSParser {
  92. public:
  93. CSSParser(const StringView& input)
  94. : css(input)
  95. {
  96. }
  97. bool next_is(const char* str) const
  98. {
  99. int len = strlen(str);
  100. for (int i = 0; i < len; ++i) {
  101. if (peek(i) != str[i])
  102. return false;
  103. }
  104. return true;
  105. }
  106. char peek(int offset = 0) const
  107. {
  108. if ((index + offset) < css.length())
  109. return css[index + offset];
  110. return 0;
  111. }
  112. char consume_specific(char ch)
  113. {
  114. PARSE_ASSERT(peek() == ch);
  115. PARSE_ASSERT(index < css.length());
  116. ++index;
  117. return ch;
  118. }
  119. char consume_one()
  120. {
  121. PARSE_ASSERT(index < css.length());
  122. return css[index++];
  123. };
  124. void consume_whitespace_or_comments()
  125. {
  126. bool in_comment = false;
  127. for (; index < css.length(); ++index) {
  128. char ch = peek();
  129. if (isspace(ch))
  130. continue;
  131. if (!in_comment && ch == '/' && peek(1) == '*') {
  132. in_comment = true;
  133. ++index;
  134. continue;
  135. }
  136. if (in_comment && ch == '*' && peek(1) == '/') {
  137. in_comment = false;
  138. ++index;
  139. continue;
  140. }
  141. if (in_comment)
  142. continue;
  143. break;
  144. }
  145. }
  146. bool is_valid_selector_char(char ch) const
  147. {
  148. return isalnum(ch) || ch == '-' || ch == '_' || ch == '(' || ch == ')' || ch == '@';
  149. }
  150. bool is_combinator(char ch) const
  151. {
  152. return ch == '~' || ch == '>' || ch == '+';
  153. }
  154. Optional<Selector::Component> parse_selector_component()
  155. {
  156. consume_whitespace_or_comments();
  157. Selector::Component::Type type;
  158. Selector::Component::Relation relation = Selector::Component::Relation::Descendant;
  159. if (peek() == '{')
  160. return {};
  161. if (is_combinator(peek())) {
  162. switch (peek()) {
  163. case '>':
  164. relation = Selector::Component::Relation::ImmediateChild;
  165. break;
  166. case '+':
  167. relation = Selector::Component::Relation::AdjacentSibling;
  168. break;
  169. case '~':
  170. relation = Selector::Component::Relation::GeneralSibling;
  171. break;
  172. }
  173. consume_one();
  174. consume_whitespace_or_comments();
  175. }
  176. if (peek() == '.') {
  177. type = Selector::Component::Type::Class;
  178. consume_one();
  179. } else if (peek() == '#') {
  180. type = Selector::Component::Type::Id;
  181. consume_one();
  182. } else {
  183. type = Selector::Component::Type::TagName;
  184. }
  185. while (is_valid_selector_char(peek()))
  186. buffer.append(consume_one());
  187. PARSE_ASSERT(!buffer.is_null());
  188. Selector::Component component { type, Selector::Component::PseudoClass::None, relation, String::copy(buffer) };
  189. buffer.clear();
  190. if (peek() == '[') {
  191. // FIXME: Implement attribute selectors.
  192. while (peek() != ']') {
  193. consume_one();
  194. }
  195. consume_one();
  196. }
  197. if (peek() == ':') {
  198. // FIXME: Implement pseudo elements.
  199. [[maybe_unused]] bool is_pseudo_element = false;
  200. consume_one();
  201. if (peek() == ':') {
  202. is_pseudo_element = true;
  203. consume_one();
  204. }
  205. while (is_valid_selector_char(peek()))
  206. buffer.append(consume_one());
  207. auto pseudo_name = String::copy(buffer);
  208. buffer.clear();
  209. if (pseudo_name == "link")
  210. component.pseudo_class = Selector::Component::PseudoClass::Link;
  211. else if (pseudo_name == "hover")
  212. component.pseudo_class = Selector::Component::PseudoClass::Hover;
  213. }
  214. return component;
  215. }
  216. void parse_selector()
  217. {
  218. Vector<Selector::Component> components;
  219. for (;;) {
  220. auto component = parse_selector_component();
  221. if (component.has_value())
  222. components.append(component.value());
  223. consume_whitespace_or_comments();
  224. if (peek() == ',' || peek() == '{')
  225. break;
  226. }
  227. if (components.is_empty())
  228. return;
  229. components.first().relation = Selector::Component::Relation::None;
  230. current_rule.selectors.append(Selector(move(components)));
  231. };
  232. void parse_selector_list()
  233. {
  234. for (;;) {
  235. parse_selector();
  236. consume_whitespace_or_comments();
  237. if (peek() == ',') {
  238. consume_one();
  239. continue;
  240. }
  241. if (peek() == '{')
  242. break;
  243. }
  244. }
  245. bool is_valid_property_name_char(char ch) const
  246. {
  247. return ch && !isspace(ch) && ch != ':';
  248. }
  249. bool is_valid_property_value_char(char ch) const
  250. {
  251. return ch && ch != '!' && ch != ';';
  252. }
  253. Optional<StyleProperty> parse_property()
  254. {
  255. consume_whitespace_or_comments();
  256. if (peek() == ';') {
  257. consume_one();
  258. return {};
  259. }
  260. buffer.clear();
  261. while (is_valid_property_name_char(peek()))
  262. buffer.append(consume_one());
  263. auto property_name = String::copy(buffer);
  264. buffer.clear();
  265. consume_whitespace_or_comments();
  266. consume_specific(':');
  267. consume_whitespace_or_comments();
  268. while (is_valid_property_value_char(peek()))
  269. buffer.append(consume_one());
  270. // Remove trailing whitespace.
  271. while (!buffer.is_empty() && isspace(buffer.last()))
  272. buffer.take_last();
  273. auto property_value = String::copy(buffer);
  274. buffer.clear();
  275. consume_whitespace_or_comments();
  276. bool is_important = false;
  277. if (peek() == '!') {
  278. consume_specific('!');
  279. consume_specific('i');
  280. consume_specific('m');
  281. consume_specific('p');
  282. consume_specific('o');
  283. consume_specific('r');
  284. consume_specific('t');
  285. consume_specific('a');
  286. consume_specific('n');
  287. consume_specific('t');
  288. consume_whitespace_or_comments();
  289. is_important = true;
  290. }
  291. if (peek() && peek() != '}')
  292. consume_specific(';');
  293. return StyleProperty { parse_css_property_id(property_name), parse_css_value(property_value), is_important };
  294. }
  295. void parse_declaration()
  296. {
  297. for (;;) {
  298. auto property = parse_property();
  299. if (property.has_value())
  300. current_rule.properties.append(property.value());
  301. consume_whitespace_or_comments();
  302. if (peek() == '}')
  303. break;
  304. }
  305. }
  306. void parse_rule()
  307. {
  308. // FIXME: We ignore @media rules for now.
  309. if (next_is("@media")) {
  310. while (peek() != '{')
  311. consume_one();
  312. int level = 0;
  313. for (;;) {
  314. auto ch = consume_one();
  315. if (ch == '{') {
  316. ++level;
  317. } else if (ch == '}') {
  318. --level;
  319. if (level == 0)
  320. break;
  321. }
  322. }
  323. consume_whitespace_or_comments();
  324. return;
  325. }
  326. parse_selector_list();
  327. consume_specific('{');
  328. parse_declaration();
  329. consume_specific('}');
  330. rules.append(StyleRule::create(move(current_rule.selectors), StyleDeclaration::create(move(current_rule.properties))));
  331. consume_whitespace_or_comments();
  332. }
  333. NonnullRefPtr<StyleSheet> parse_sheet()
  334. {
  335. while (index < css.length()) {
  336. parse_rule();
  337. }
  338. return StyleSheet::create(move(rules));
  339. }
  340. NonnullRefPtr<StyleDeclaration> parse_standalone_declaration()
  341. {
  342. consume_whitespace_or_comments();
  343. for (;;) {
  344. auto property = parse_property();
  345. if (property.has_value())
  346. current_rule.properties.append(property.value());
  347. consume_whitespace_or_comments();
  348. if (!peek())
  349. break;
  350. }
  351. return StyleDeclaration::create(move(current_rule.properties));
  352. }
  353. private:
  354. NonnullRefPtrVector<StyleRule> rules;
  355. struct CurrentRule {
  356. Vector<Selector> selectors;
  357. Vector<StyleProperty> properties;
  358. };
  359. CurrentRule current_rule;
  360. Vector<char> buffer;
  361. int index = 0;
  362. StringView css;
  363. };
  364. NonnullRefPtr<StyleSheet> parse_css(const StringView& css)
  365. {
  366. CSSParser parser(css);
  367. return parser.parse_sheet();
  368. }
  369. NonnullRefPtr<StyleDeclaration> parse_css_declaration(const StringView& css)
  370. {
  371. CSSParser parser(css);
  372. return parser.parse_standalone_declaration();
  373. }