CSSParser.cpp 11 KB

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