CSSParser.cpp 11 KB

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