CSSParser.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. if (peek() != ch) {
  115. dbg() << "peek() != '" << ch << "'";
  116. }
  117. PARSE_ASSERT(peek() == ch);
  118. PARSE_ASSERT(index < css.length());
  119. ++index;
  120. return ch;
  121. }
  122. char consume_one()
  123. {
  124. PARSE_ASSERT(index < css.length());
  125. return css[index++];
  126. };
  127. void consume_whitespace_or_comments()
  128. {
  129. bool in_comment = false;
  130. for (; index < css.length(); ++index) {
  131. char ch = peek();
  132. if (isspace(ch))
  133. continue;
  134. if (!in_comment && ch == '/' && peek(1) == '*') {
  135. in_comment = true;
  136. ++index;
  137. continue;
  138. }
  139. if (in_comment && ch == '*' && peek(1) == '/') {
  140. in_comment = false;
  141. ++index;
  142. continue;
  143. }
  144. if (in_comment)
  145. continue;
  146. break;
  147. }
  148. }
  149. bool is_valid_selector_char(char ch) const
  150. {
  151. return isalnum(ch) || ch == '-' || ch == '_' || ch == '(' || ch == ')' || ch == '@';
  152. }
  153. bool is_combinator(char ch) const
  154. {
  155. return ch == '~' || ch == '>' || ch == '+';
  156. }
  157. Optional<Selector::Component> parse_selector_component()
  158. {
  159. consume_whitespace_or_comments();
  160. Selector::Component::Type type;
  161. Selector::Component::Relation relation = Selector::Component::Relation::Descendant;
  162. if (peek() == '{')
  163. return {};
  164. if (is_combinator(peek())) {
  165. switch (peek()) {
  166. case '>':
  167. relation = Selector::Component::Relation::ImmediateChild;
  168. break;
  169. case '+':
  170. relation = Selector::Component::Relation::AdjacentSibling;
  171. break;
  172. case '~':
  173. relation = Selector::Component::Relation::GeneralSibling;
  174. break;
  175. }
  176. consume_one();
  177. consume_whitespace_or_comments();
  178. }
  179. if (peek() == '.') {
  180. type = Selector::Component::Type::Class;
  181. consume_one();
  182. } else if (peek() == '#') {
  183. type = Selector::Component::Type::Id;
  184. consume_one();
  185. } else {
  186. type = Selector::Component::Type::TagName;
  187. }
  188. while (is_valid_selector_char(peek()))
  189. buffer.append(consume_one());
  190. PARSE_ASSERT(!buffer.is_null());
  191. Selector::Component component { type, Selector::Component::PseudoClass::None, relation, String::copy(buffer) };
  192. buffer.clear();
  193. if (peek() == '[') {
  194. // FIXME: Implement attribute selectors.
  195. while (peek() != ']') {
  196. consume_one();
  197. }
  198. consume_one();
  199. }
  200. if (peek() == ':') {
  201. // FIXME: Implement pseudo elements.
  202. [[maybe_unused]] bool is_pseudo_element = false;
  203. consume_one();
  204. if (peek() == ':') {
  205. is_pseudo_element = true;
  206. consume_one();
  207. }
  208. while (is_valid_selector_char(peek()))
  209. buffer.append(consume_one());
  210. auto pseudo_name = String::copy(buffer);
  211. buffer.clear();
  212. if (pseudo_name == "link")
  213. component.pseudo_class = Selector::Component::PseudoClass::Link;
  214. else if (pseudo_name == "hover")
  215. component.pseudo_class = Selector::Component::PseudoClass::Hover;
  216. }
  217. return component;
  218. }
  219. void parse_selector()
  220. {
  221. Vector<Selector::Component> components;
  222. for (;;) {
  223. auto component = parse_selector_component();
  224. if (component.has_value())
  225. components.append(component.value());
  226. consume_whitespace_or_comments();
  227. if (peek() == ',' || peek() == '{')
  228. break;
  229. }
  230. if (components.is_empty())
  231. return;
  232. components.first().relation = Selector::Component::Relation::None;
  233. current_rule.selectors.append(Selector(move(components)));
  234. };
  235. void parse_selector_list()
  236. {
  237. for (;;) {
  238. parse_selector();
  239. consume_whitespace_or_comments();
  240. if (peek() == ',') {
  241. consume_one();
  242. continue;
  243. }
  244. if (peek() == '{')
  245. break;
  246. }
  247. }
  248. bool is_valid_property_name_char(char ch) const
  249. {
  250. return ch && !isspace(ch) && ch != ':';
  251. }
  252. bool is_valid_property_value_char(char ch) const
  253. {
  254. return ch && ch != '!' && ch != ';' && ch != '}';
  255. }
  256. Optional<StyleProperty> parse_property()
  257. {
  258. consume_whitespace_or_comments();
  259. if (peek() == ';') {
  260. consume_one();
  261. return {};
  262. }
  263. buffer.clear();
  264. while (is_valid_property_name_char(peek()))
  265. buffer.append(consume_one());
  266. auto property_name = String::copy(buffer);
  267. buffer.clear();
  268. consume_whitespace_or_comments();
  269. consume_specific(':');
  270. consume_whitespace_or_comments();
  271. while (is_valid_property_value_char(peek()))
  272. buffer.append(consume_one());
  273. // Remove trailing whitespace.
  274. while (!buffer.is_empty() && isspace(buffer.last()))
  275. buffer.take_last();
  276. auto property_value = String::copy(buffer);
  277. buffer.clear();
  278. consume_whitespace_or_comments();
  279. bool is_important = false;
  280. if (peek() == '!') {
  281. consume_specific('!');
  282. consume_specific('i');
  283. consume_specific('m');
  284. consume_specific('p');
  285. consume_specific('o');
  286. consume_specific('r');
  287. consume_specific('t');
  288. consume_specific('a');
  289. consume_specific('n');
  290. consume_specific('t');
  291. consume_whitespace_or_comments();
  292. is_important = true;
  293. }
  294. if (peek() && peek() != '}')
  295. consume_specific(';');
  296. return StyleProperty { parse_css_property_id(property_name), parse_css_value(property_value), is_important };
  297. }
  298. void parse_declaration()
  299. {
  300. for (;;) {
  301. auto property = parse_property();
  302. if (property.has_value())
  303. current_rule.properties.append(property.value());
  304. consume_whitespace_or_comments();
  305. if (peek() == '}')
  306. break;
  307. }
  308. }
  309. void parse_rule()
  310. {
  311. consume_whitespace_or_comments();
  312. if (index >= css.length())
  313. return;
  314. // FIXME: We ignore @media rules for now.
  315. if (next_is("@media")) {
  316. while (peek() != '{')
  317. consume_one();
  318. int level = 0;
  319. for (;;) {
  320. auto ch = consume_one();
  321. if (ch == '{') {
  322. ++level;
  323. } else if (ch == '}') {
  324. --level;
  325. if (level == 0)
  326. break;
  327. }
  328. }
  329. consume_whitespace_or_comments();
  330. return;
  331. }
  332. parse_selector_list();
  333. consume_specific('{');
  334. parse_declaration();
  335. consume_specific('}');
  336. rules.append(StyleRule::create(move(current_rule.selectors), StyleDeclaration::create(move(current_rule.properties))));
  337. consume_whitespace_or_comments();
  338. }
  339. RefPtr<StyleSheet> parse_sheet()
  340. {
  341. while (index < css.length()) {
  342. parse_rule();
  343. }
  344. return StyleSheet::create(move(rules));
  345. }
  346. RefPtr<StyleDeclaration> parse_standalone_declaration()
  347. {
  348. consume_whitespace_or_comments();
  349. for (;;) {
  350. auto property = parse_property();
  351. if (property.has_value())
  352. current_rule.properties.append(property.value());
  353. consume_whitespace_or_comments();
  354. if (!peek())
  355. break;
  356. }
  357. return StyleDeclaration::create(move(current_rule.properties));
  358. }
  359. private:
  360. NonnullRefPtrVector<StyleRule> rules;
  361. struct CurrentRule {
  362. Vector<Selector> selectors;
  363. Vector<StyleProperty> properties;
  364. };
  365. CurrentRule current_rule;
  366. Vector<char> buffer;
  367. int index = 0;
  368. StringView css;
  369. };
  370. RefPtr<StyleSheet> parse_css(const StringView& css)
  371. {
  372. CSSParser parser(css);
  373. return parser.parse_sheet();
  374. }
  375. RefPtr<StyleDeclaration> parse_css_declaration(const StringView& css)
  376. {
  377. CSSParser parser(css);
  378. return parser.parse_standalone_declaration();
  379. }