CSSParser.cpp 11 KB

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