Skip to main content

eternal_styler/
stylesheet.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Stylesheets, rules and declaration blocks.
6
7use cssparser::{
8    AtRuleParser, CowRcStr, DeclarationParser, Delimiter, ParseError, Parser, ParserInput,
9    ParserState, QualifiedRuleParser, RuleBodyItemParser, RuleBodyParser, StyleSheetParser,
10    parse_important,
11};
12
13use crate::error::{Error, StyleParseErrorKind, value_error};
14use crate::properties::{PropertyDeclaration, PropertyId, parse_property_value};
15use crate::selector::{RawSelectorList, SelectorList, parse_selector_list};
16
17/// One longhand declaration and whether it was marked `!important`.
18#[derive(Clone, Debug, PartialEq)]
19pub struct Declaration {
20    pub value: PropertyDeclaration,
21    pub important: bool,
22}
23
24/// The `{ ... }` part of a rule, or an inline style.
25///
26/// Shorthands are expanded when parsed, so this only ever holds longhands.
27/// Later declarations of the same longhand win over earlier ones.
28#[derive(Clone, Debug, Default, PartialEq)]
29pub struct DeclarationBlock {
30    declarations: Vec<Declaration>,
31}
32
33impl DeclarationBlock {
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    /// Parses declarations without the surrounding braces, such as
39    /// `color: red; padding: 4px !important`. The first problem is an error.
40    pub fn parse(css: &str) -> Result<Self, Error> {
41        let (block, errors) = Self::parse_lenient(css);
42        match errors.into_iter().next() {
43            Some(error) => Err(error),
44            None => Ok(block),
45        }
46    }
47
48    /// Like [`parse`](Self::parse), but skips declarations it cannot parse
49    /// the way a browser would, and returns the problems alongside.
50    pub fn parse_lenient(css: &str) -> (Self, Vec<Error>) {
51        let mut input = ParserInput::new(css);
52        let mut parser = Parser::new(&mut input);
53        let mut errors = Vec::new();
54        let block = parse_declaration_block(&mut parser, &mut errors);
55        (block, errors)
56    }
57
58    pub fn push(&mut self, value: PropertyDeclaration, important: bool) {
59        self.declarations.push(Declaration { value, important });
60    }
61
62    pub fn declarations(&self) -> &[Declaration] {
63        &self.declarations
64    }
65
66    pub fn len(&self) -> usize {
67        self.declarations.len()
68    }
69
70    pub fn is_empty(&self) -> bool {
71        self.declarations.is_empty()
72    }
73}
74
75/// A selector list and the declarations that apply to what it matches.
76#[derive(Clone, Debug)]
77pub struct StyleRule {
78    pub selectors: SelectorList,
79    pub declarations: DeclarationBlock,
80}
81
82/// A list of style rules in source order.
83#[derive(Clone, Debug, Default)]
84pub struct Stylesheet {
85    rules: Vec<StyleRule>,
86}
87
88impl Stylesheet {
89    pub fn new() -> Self {
90        Self::default()
91    }
92
93    /// Parses a stylesheet. The first problem is an error: an unknown
94    /// property, a bad value, a selector this crate does not support, or an
95    /// at-rule.
96    pub fn parse(css: &str) -> Result<Self, Error> {
97        let (sheet, errors) = Self::parse_lenient(css);
98        match errors.into_iter().next() {
99            Some(error) => Err(error),
100            None => Ok(sheet),
101        }
102    }
103
104    /// Like [`parse`](Self::parse), but skips what it cannot parse the way a
105    /// browser would, and returns the problems alongside. A bad declaration
106    /// loses only itself; a bad selector loses its whole rule.
107    pub fn parse_lenient(css: &str) -> (Self, Vec<Error>) {
108        let mut input = ParserInput::new(css);
109        let mut parser = Parser::new(&mut input);
110        let mut rule_parser = RuleParser { errors: Vec::new() };
111        let mut rules = Vec::new();
112        let mut errors = Vec::new();
113        for result in StyleSheetParser::new(&mut parser, &mut rule_parser) {
114            match result {
115                Ok(rule) => rules.push(rule),
116                Err((error, _)) => errors.push(Error::from_parse_error(error)),
117            }
118        }
119        // Declaration errors were collected separately from rule errors;
120        // put them back in source order.
121        errors.append(&mut rule_parser.errors);
122        errors.sort_by_key(|error| (error.line(), error.column()));
123        (Self { rules }, errors)
124    }
125
126    pub fn push(&mut self, rule: StyleRule) {
127        self.rules.push(rule);
128    }
129
130    pub fn rules(&self) -> &[StyleRule] {
131        &self.rules
132    }
133
134    pub fn len(&self) -> usize {
135        self.rules.len()
136    }
137
138    pub fn is_empty(&self) -> bool {
139        self.rules.is_empty()
140    }
141}
142
143/// Parses the inside of a `{ ... }` block, collecting problems into `errors`.
144fn parse_declaration_block(
145    input: &mut Parser<'_, '_>,
146    errors: &mut Vec<Error>,
147) -> DeclarationBlock {
148    let mut block = DeclarationBlock::new();
149    let mut parser = DeclarationBlockParser;
150    for item in RuleBodyParser::new(input, &mut parser) {
151        match item {
152            Ok(declarations) => block.declarations.extend(declarations),
153            Err((error, _)) => errors.push(Error::from_parse_error(error)),
154        }
155    }
156    block
157}
158
159struct DeclarationBlockParser;
160
161impl<'i> DeclarationParser<'i> for DeclarationBlockParser {
162    type Declaration = Vec<Declaration>;
163    type Error = StyleParseErrorKind<'i>;
164
165    fn parse_value<'t>(
166        &mut self,
167        name: CowRcStr<'i>,
168        input: &mut Parser<'i, 't>,
169        declaration_start: &ParserState,
170    ) -> Result<Self::Declaration, ParseError<'i, Self::Error>> {
171        let Some(id) = PropertyId::from_name(&name) else {
172            return Err(declaration_start
173                .source_location()
174                .new_custom_error(StyleParseErrorKind::UnknownProperty(name)));
175        };
176        let mut values = Vec::new();
177        input
178            .parse_until_before(Delimiter::Bang, |input| {
179                parse_property_value(id, input, &mut values)?;
180                input.expect_exhausted()?;
181                Ok(())
182            })
183            .map_err(|error| value_error(name.clone(), error))?;
184        let important = input.try_parse(parse_important).is_ok();
185        input
186            .expect_exhausted()
187            .map_err(|error| value_error(name, error.into()))?;
188        Ok(values
189            .into_iter()
190            .map(|value| Declaration { value, important })
191            .collect())
192    }
193}
194
195// Declaration blocks hold neither at-rules nor nested rules. The default
196// implementations reject both.
197impl<'i> AtRuleParser<'i> for DeclarationBlockParser {
198    type Prelude = ();
199    type AtRule = Vec<Declaration>;
200    type Error = StyleParseErrorKind<'i>;
201}
202
203impl<'i> QualifiedRuleParser<'i> for DeclarationBlockParser {
204    type Prelude = ();
205    type QualifiedRule = Vec<Declaration>;
206    type Error = StyleParseErrorKind<'i>;
207}
208
209impl<'i> RuleBodyItemParser<'i, Vec<Declaration>, StyleParseErrorKind<'i>>
210    for DeclarationBlockParser
211{
212    fn parse_declarations(&self) -> bool {
213        true
214    }
215
216    fn parse_qualified(&self) -> bool {
217        false
218    }
219}
220
221struct RuleParser {
222    errors: Vec<Error>,
223}
224
225impl<'i> QualifiedRuleParser<'i> for RuleParser {
226    type Prelude = RawSelectorList;
227    type QualifiedRule = StyleRule;
228    type Error = StyleParseErrorKind<'i>;
229
230    fn parse_prelude<'t>(
231        &mut self,
232        input: &mut Parser<'i, 't>,
233    ) -> Result<Self::Prelude, ParseError<'i, Self::Error>> {
234        parse_selector_list(input)
235    }
236
237    fn parse_block<'t>(
238        &mut self,
239        prelude: Self::Prelude,
240        _start: &ParserState,
241        input: &mut Parser<'i, 't>,
242    ) -> Result<Self::QualifiedRule, ParseError<'i, Self::Error>> {
243        let declarations = parse_declaration_block(input, &mut self.errors);
244        Ok(StyleRule {
245            selectors: SelectorList::from_raw(prelude),
246            declarations,
247        })
248    }
249}
250
251// No at-rules. The default implementation reports them as invalid, which
252// becomes `ErrorKind::UnsupportedAtRule`.
253impl<'i> AtRuleParser<'i> for RuleParser {
254    type Prelude = ();
255    type AtRule = StyleRule;
256    type Error = StyleParseErrorKind<'i>;
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262    use crate::ErrorKind;
263    use crate::properties::LonghandId;
264
265    #[test]
266    fn parses_rules_and_declarations() {
267        let sheet = Stylesheet::parse(
268            "button, .link { color: red; padding: 4px 8px !important }\n\
269             /* a comment */\n\
270             #save:hover { opacity: .5 }",
271        )
272        .unwrap();
273        assert_eq!(sheet.len(), 2);
274        let first = &sheet.rules()[0];
275        assert_eq!(first.selectors.len(), 2);
276        assert_eq!(first.declarations.len(), 5);
277        assert!(!first.declarations.declarations()[0].important);
278        assert!(first.declarations.declarations()[1].important);
279        assert_eq!(
280            first.declarations.declarations()[4].value.id(),
281            LonghandId::PaddingLeft
282        );
283        assert_eq!(sheet.rules()[1].selectors.to_string(), "#save:hover");
284    }
285
286    #[test]
287    fn empty_input_is_fine() {
288        assert!(Stylesheet::parse("").unwrap().is_empty());
289        assert!(Stylesheet::parse("  \n ").unwrap().is_empty());
290        assert!(DeclarationBlock::parse("").unwrap().is_empty());
291        assert!(DeclarationBlock::parse(";;").unwrap().is_empty());
292    }
293
294    #[test]
295    fn reports_where_things_went_wrong() {
296        let error = Stylesheet::parse("button {\n  colour: red;\n}").unwrap_err();
297        assert_eq!(error.kind(), &ErrorKind::UnknownProperty("colour".into()));
298        assert_eq!((error.line(), error.column()), (2, 3));
299
300        let error = Stylesheet::parse("button { width: red }").unwrap_err();
301        assert_eq!(
302            error.to_string(),
303            "line 1, column 17: invalid value for 'width': unexpected 'red'"
304        );
305
306        let error = Stylesheet::parse("button { width: 1px 2px }").unwrap_err();
307        assert!(
308            matches!(error.kind(), ErrorKind::InvalidValue { .. }),
309            "{error}"
310        );
311
312        let error = Stylesheet::parse("button { color: red !importantly }").unwrap_err();
313        assert!(
314            matches!(error.kind(), ErrorKind::InvalidValue { .. }),
315            "{error}"
316        );
317
318        let error = Stylesheet::parse("@media (width > 0) { }").unwrap_err();
319        assert_eq!(error.kind(), &ErrorKind::UnsupportedAtRule("media".into()));
320
321        let error = Stylesheet::parse("a::before { }").unwrap_err();
322        assert!(
323            matches!(error.kind(), ErrorKind::InvalidSelector(_)),
324            "{error}"
325        );
326
327        let error = DeclarationBlock::parse("color red").unwrap_err();
328        assert!(matches!(error.kind(), ErrorKind::Syntax(_)), "{error}");
329    }
330
331    #[test]
332    fn lenient_parsing_keeps_what_it_can() {
333        let (sheet, errors) = Stylesheet::parse_lenient(
334            "a { color: red; colour: blue; width: 1px }\n\
335             b::after { color: red }\n\
336             @import 'x.css';\n\
337             c { color: green }",
338        );
339        assert_eq!(sheet.len(), 2);
340        assert_eq!(sheet.rules()[0].declarations.len(), 2);
341        assert_eq!(sheet.rules()[1].selectors.to_string(), "c");
342        let lines: Vec<u32> = errors.iter().map(Error::line).collect();
343        assert_eq!(lines, [1, 2, 3]);
344
345        let (block, errors) = DeclarationBlock::parse_lenient("color: red; nope: 1; opacity: 0");
346        assert_eq!(block.len(), 2);
347        assert_eq!(errors.len(), 1);
348    }
349}