CSSParser.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. char peek(int offset = 0) const
  98. {
  99. if ((index + offset) < css.length())
  100. return css[index + offset];
  101. return 0;
  102. }
  103. char consume_specific(char ch)
  104. {
  105. PARSE_ASSERT(peek() == ch);
  106. PARSE_ASSERT(index < css.length());
  107. ++index;
  108. return ch;
  109. }
  110. char consume_one()
  111. {
  112. PARSE_ASSERT(index < css.length());
  113. return css[index++];
  114. };
  115. void consume_whitespace_or_comments()
  116. {
  117. bool in_comment = false;
  118. for (; index < css.length(); ++index) {
  119. char ch = peek();
  120. if (isspace(ch))
  121. continue;
  122. if (!in_comment && ch == '/' && peek(1) == '*') {
  123. in_comment = true;
  124. ++index;
  125. continue;
  126. }
  127. if (in_comment && ch == '*' && peek(1) == '/') {
  128. in_comment = false;
  129. ++index;
  130. continue;
  131. }
  132. if (in_comment)
  133. continue;
  134. break;
  135. }
  136. }
  137. bool is_valid_selector_char(char ch) const
  138. {
  139. return isalnum(ch) || ch == '-' || ch == '_' || ch == '(' || ch == ')' || ch == '@';
  140. }
  141. bool is_combinator(char ch) const
  142. {
  143. return ch == '~' || ch == '>' || ch == '+';
  144. }
  145. Optional<Selector::Component> parse_selector_component()
  146. {
  147. consume_whitespace_or_comments();
  148. Selector::Component::Type type;
  149. Selector::Component::Relation relation = Selector::Component::Relation::Descendant;
  150. if (peek() == '{')
  151. return {};
  152. if (is_combinator(peek())) {
  153. switch (peek()) {
  154. case '>':
  155. relation = Selector::Component::Relation::ImmediateChild;
  156. break;
  157. case '+':
  158. relation = Selector::Component::Relation::AdjacentSibling;
  159. break;
  160. case '~':
  161. relation = Selector::Component::Relation::GeneralSibling;
  162. break;
  163. }
  164. consume_one();
  165. consume_whitespace_or_comments();
  166. }
  167. if (peek() == '.') {
  168. type = Selector::Component::Type::Class;
  169. consume_one();
  170. } else if (peek() == '#') {
  171. type = Selector::Component::Type::Id;
  172. consume_one();
  173. } else {
  174. type = Selector::Component::Type::TagName;
  175. }
  176. while (is_valid_selector_char(peek()))
  177. buffer.append(consume_one());
  178. PARSE_ASSERT(!buffer.is_null());
  179. Selector::Component component { type, relation, String::copy(buffer) };
  180. buffer.clear();
  181. if (peek() == '[') {
  182. // FIXME: Implement attribute selectors.
  183. while (peek() != ']') {
  184. consume_one();
  185. }
  186. consume_one();
  187. }
  188. if (peek() == ':') {
  189. // FIXME: Implement pseudo stuff.
  190. consume_one();
  191. if (peek() == ':')
  192. consume_one();
  193. while (is_valid_selector_char(peek()))
  194. consume_one();
  195. }
  196. return component;
  197. }
  198. void parse_selector()
  199. {
  200. Vector<Selector::Component> components;
  201. for (;;) {
  202. auto component = parse_selector_component();
  203. if (component.has_value())
  204. components.append(component.value());
  205. consume_whitespace_or_comments();
  206. if (peek() == ',' || peek() == '{')
  207. break;
  208. }
  209. if (components.is_empty())
  210. return;
  211. components.first().relation = Selector::Component::Relation::None;
  212. current_rule.selectors.append(Selector(move(components)));
  213. };
  214. void parse_selector_list()
  215. {
  216. for (;;) {
  217. parse_selector();
  218. consume_whitespace_or_comments();
  219. if (peek() == ',') {
  220. consume_one();
  221. continue;
  222. }
  223. if (peek() == '{')
  224. break;
  225. }
  226. }
  227. bool is_valid_property_name_char(char ch) const
  228. {
  229. return ch && !isspace(ch) && ch != ':';
  230. }
  231. bool is_valid_property_value_char(char ch) const
  232. {
  233. return ch && ch != '!' && ch != ';';
  234. }
  235. Optional<StyleProperty> parse_property()
  236. {
  237. consume_whitespace_or_comments();
  238. if (peek() == ';') {
  239. consume_one();
  240. return {};
  241. }
  242. buffer.clear();
  243. while (is_valid_property_name_char(peek()))
  244. buffer.append(consume_one());
  245. auto property_name = String::copy(buffer);
  246. buffer.clear();
  247. consume_whitespace_or_comments();
  248. consume_specific(':');
  249. consume_whitespace_or_comments();
  250. while (is_valid_property_value_char(peek()))
  251. buffer.append(consume_one());
  252. auto property_value = String::copy(buffer);
  253. buffer.clear();
  254. consume_whitespace_or_comments();
  255. bool is_important = false;
  256. if (peek() == '!') {
  257. consume_specific('!');
  258. consume_specific('i');
  259. consume_specific('m');
  260. consume_specific('p');
  261. consume_specific('o');
  262. consume_specific('r');
  263. consume_specific('t');
  264. consume_specific('a');
  265. consume_specific('n');
  266. consume_specific('t');
  267. consume_whitespace_or_comments();
  268. is_important = true;
  269. }
  270. if (peek() && peek() != '}')
  271. consume_specific(';');
  272. return StyleProperty { parse_css_property_id(property_name), parse_css_value(property_value), is_important };
  273. }
  274. void parse_declaration()
  275. {
  276. for (;;) {
  277. auto property = parse_property();
  278. if (property.has_value())
  279. current_rule.properties.append(property.value());
  280. consume_whitespace_or_comments();
  281. if (peek() == '}')
  282. break;
  283. }
  284. }
  285. void parse_rule()
  286. {
  287. parse_selector_list();
  288. consume_specific('{');
  289. parse_declaration();
  290. consume_specific('}');
  291. rules.append(StyleRule::create(move(current_rule.selectors), StyleDeclaration::create(move(current_rule.properties))));
  292. consume_whitespace_or_comments();
  293. }
  294. NonnullRefPtr<StyleSheet> parse_sheet()
  295. {
  296. while (index < css.length()) {
  297. parse_rule();
  298. }
  299. return StyleSheet::create(move(rules));
  300. }
  301. NonnullRefPtr<StyleDeclaration> parse_standalone_declaration()
  302. {
  303. consume_whitespace_or_comments();
  304. for (;;) {
  305. auto property = parse_property();
  306. if (property.has_value())
  307. current_rule.properties.append(property.value());
  308. consume_whitespace_or_comments();
  309. if (!peek())
  310. break;
  311. }
  312. return StyleDeclaration::create(move(current_rule.properties));
  313. }
  314. private:
  315. NonnullRefPtrVector<StyleRule> rules;
  316. struct CurrentRule {
  317. Vector<Selector> selectors;
  318. Vector<StyleProperty> properties;
  319. };
  320. CurrentRule current_rule;
  321. Vector<char> buffer;
  322. int index = 0;
  323. StringView css;
  324. };
  325. NonnullRefPtr<StyleSheet> parse_css(const StringView& css)
  326. {
  327. CSSParser parser(css);
  328. return parser.parse_sheet();
  329. }
  330. NonnullRefPtr<StyleDeclaration> parse_css_declaration(const StringView& css)
  331. {
  332. CSSParser parser(css);
  333. return parser.parse_standalone_declaration();
  334. }