Skip to main content

fleuron/style/sheet/
mod.rs

1//! Parsing: CSS text in, rules and diagnostics out.
2//!
3//! Nothing here matches or cascades. What it does decide is what the
4//! engine claims to understand: a declaration outside the novel
5//! subset does not become a rule, it becomes a warning naming the
6//! position it was written at, and the rest of the sheet parses on.
7//!
8//! The parsers have a file each: `declaration` holds the property
9//! table, `value` reads one value, `color` reads a colour, `page`
10//! reads `@page`, `face` reads `@font-face`, and `vocabulary` is what
11//! the subset document is written from.
12
13use std::fmt;
14use std::ops::Range;
15
16use cssparser::{
17    AtRuleParser, BasicParseErrorKind, CowRcStr, ParseError, ParseErrorKind, Parser, ParserInput,
18    ParserState, QualifiedRuleParser, RuleBodyParser, SourceLocation, StyleSheetParser,
19    match_ignore_ascii_case,
20};
21use selectors::SelectorList;
22use selectors::parser::{ParseRelative, SelectorParseErrorKind};
23
24use crate::Warning;
25use crate::pages::Side;
26use crate::style::element::{Fleuron, PseudoElement};
27use crate::style::properties::{
28    AlignContent, BackgroundRepeat, BorderStyle, Color, Content, Declaration, Edge, Length,
29    MarginBox, Marks, Pending, SizeSource, Url,
30};
31
32mod color;
33mod custom;
34mod declaration;
35mod face;
36mod page;
37mod value;
38mod vocabulary;
39
40pub use face::{FontFace, Src};
41
42pub(crate) use color::NAMED;
43pub(crate) use custom::{
44    Unresolved, longhands, margin_longhands, page_longhands, read_pending, read_pending_margin,
45    read_pending_page, substitute,
46};
47pub(crate) use declaration::{PROPERTIES, Spec};
48pub(crate) use face::FONT_FACE_DESCRIPTORS;
49#[cfg(test)]
50pub(crate) use face::FaceDeclaration;
51pub(crate) use page::{MARGIN_BOX_PROPERTIES, PAGE_PROPERTIES, PAGE_SELECTORS, PAGE_SIZES};
52pub(crate) use value::UNITS;
53pub(crate) use vocabulary::{
54    COMBINATORS, COMPOUNDS, CUSTOM_PROPERTY, DECLARATION, FIRST_LINE_PROPERTIES, PSEUDO_CLASSES,
55    PSEUDO_ELEMENTS, SELECTOR_LIST, VAR,
56};
57
58use declaration::declarations;
59use face::font_face;
60use page::{PageBody, PageItem, page_selector};
61
62/// Where a stylesheet came from. The cascade sorts by this before it
63/// sorts by anything else: author CSS overrides the built-in sheet
64/// however specific the built-in rule was.
65#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
66pub enum Origin {
67    /// The built-in sheet.
68    UserAgent,
69    /// A sheet the host handed in.
70    #[default]
71    Author,
72}
73
74/// One stylesheet handed to the compiler: its text, a name for
75/// diagnostics, and the origin it cascades at.
76#[derive(Debug, Clone)]
77pub struct Source<'a> {
78    /// What diagnostics call this sheet.
79    pub name: &'a str,
80    /// The sheet's text.
81    pub css: &'a str,
82    /// Which origin it cascades at.
83    pub origin: Origin,
84}
85
86impl<'a> Source<'a> {
87    /// A sheet the author supplied.
88    pub fn author(name: &'a str, css: &'a str) -> Source<'a> {
89        Source {
90            name,
91            css,
92            origin: Origin::Author,
93        }
94    }
95
96    /// A sheet that cascades with the built-in defaults.
97    pub fn user_agent(name: &'a str, css: &'a str) -> Source<'a> {
98        Source {
99            name,
100            css,
101            origin: Origin::UserAgent,
102        }
103    }
104}
105
106/// `!important` beats a normal declaration of the same property in
107/// the same origin.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
109pub enum Importance {
110    Normal,
111    Important,
112}
113
114/// Where something was written in a stylesheet: the sheet's name, and
115/// the line and column of its first character, counted the way a
116/// warning counts them.
117#[derive(Debug, Clone, Default, PartialEq, Eq)]
118pub struct SheetPosition {
119    /// The name the sheet was handed in under.
120    pub sheet: String,
121    /// The line, counting from 1.
122    pub line: u32,
123    /// The column, counting from 1.
124    pub column: u32,
125}
126
127impl SheetPosition {
128    pub(super) fn at(sheet: &str, location: SourceLocation) -> SheetPosition {
129        SheetPosition {
130            sheet: sheet.to_string(),
131            line: location.line + 1,
132            column: location.column,
133        }
134    }
135}
136
137impl fmt::Display for SheetPosition {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        write!(f, "{}:{}:{}", self.sheet, self.line, self.column)
140    }
141}
142
143/// One declaration as the author wrote it, and the longhands it
144/// became.
145#[derive(Debug, Clone, PartialEq)]
146pub struct Written {
147    /// The property name, in lowercase.
148    pub property: String,
149    /// The value, as written, without `!important`.
150    pub value: String,
151    /// Whether it was written `!important`.
152    pub important: bool,
153    /// Which of the rule's declarations it expanded to: several for a
154    /// shorthand, one for a longhand.
155    pub longhands: Range<usize>,
156    /// Where the declaration begins.
157    pub position: SheetPosition,
158}
159
160/// One style rule: what it matches, and what it says.
161#[derive(Debug)]
162pub struct StyleRule {
163    pub selectors: SelectorList<Fleuron>,
164    pub declarations: Vec<(Declaration, Importance)>,
165    /// The declarations as they were written, in order.
166    pub written: Vec<Written>,
167    /// Where the rule begins.
168    pub position: SheetPosition,
169}
170
171/// A `@page` rule: which pages it selects, the page box it sets, and
172/// the margin boxes it fills.
173#[derive(Debug, Default, Clone)]
174pub struct PageRule {
175    /// The named page this rule is for, from `page: <name>`.
176    pub name: Option<String>,
177    /// `:first` — the page a page group opens on.
178    pub first: bool,
179    /// `:blank` — a page inserted to square the sheet.
180    pub blank: bool,
181    /// `:left` / `:right`, as the side of the spread.
182    pub side: Option<Side>,
183    pub declarations: Vec<PageDeclaration>,
184    pub boxes: Vec<MarginRule>,
185    /// The prelude as written, `@page` included.
186    pub selector: String,
187    /// Where the rule begins.
188    pub position: SheetPosition,
189}
190
191/// One margin box inside a `@page` rule.
192#[derive(Debug, Clone)]
193pub struct MarginRule {
194    pub which: MarginBox,
195    pub declarations: Vec<MarginDeclaration>,
196    /// The declarations as they were written, in order.
197    pub written: Vec<Written>,
198}
199
200impl PageRule {
201    /// CSS 2.1 page-selector specificity: the name outweighs `:first`
202    /// and `:blank`, which outweigh `:left` and `:right`.
203    pub fn specificity(&self) -> (u8, u8, u8) {
204        (
205            self.name.is_some() as u8,
206            (self.first || self.blank) as u8,
207            self.side.is_some() as u8,
208        )
209    }
210}
211
212/// A declaration inside `@page`.
213#[derive(Debug, Clone, PartialEq)]
214pub enum PageDeclaration {
215    /// Trim size in points.
216    Size(f32, f32),
217    Margin(Edge, Length),
218    BackgroundColor(Option<Color>),
219    BackgroundImage(Option<Url>),
220    BackgroundRepeat(BackgroundRepeat),
221    BackgroundSize(SizeSource),
222    /// Across the page, then down it.
223    BackgroundPosition(Length, Length),
224    /// `column-count`, or `None` for `auto`.
225    ColumnCount(Option<u32>),
226    /// `column-width`, or `None` for `auto`.
227    ColumnWidth(Option<Length>),
228    /// `column-gap`, or `None` for `normal`.
229    ColumnGap(Option<Length>),
230    ColumnRuleWidth(Length),
231    ColumnRuleStyle(BorderStyle),
232    AlignContent(AlignContent),
233    /// `bleed`, or `None` for `auto`.
234    Bleed(Option<Length>),
235    Marks(Marks),
236    /// A value that reads a custom property of the book's root.
237    Pending(Pending),
238}
239
240/// A declaration inside a page margin box.
241#[derive(Debug, Clone, PartialEq)]
242pub enum MarginDeclaration {
243    Content(Content),
244    /// A text property; margin boxes set a line like any other.
245    Style(Declaration),
246    /// A value that reads a custom property of the book's root.
247    Pending(Pending),
248}
249
250/// One parsed sheet.
251#[derive(Debug, Default)]
252pub struct Sheet {
253    pub origin: Origin,
254    pub rules: Vec<StyleRule>,
255    pub pages: Vec<PageRule>,
256    pub faces: Vec<FontFace>,
257}
258
259/// Why some fragment of CSS did not become a rule.
260#[derive(Debug, Clone)]
261pub enum StyleError<'i> {
262    UnsupportedProperty(CowRcStr<'i>),
263    NotOnFirstLine(CowRcStr<'i>),
264    UnsupportedValue(CowRcStr<'i>),
265    UnsupportedAtRule(CowRcStr<'i>),
266    UnsupportedPageSelector,
267    Selector(SelectorParseErrorKind<'i>),
268}
269
270impl<'i> From<SelectorParseErrorKind<'i>> for StyleError<'i> {
271    fn from(kind: SelectorParseErrorKind<'i>) -> Self {
272        StyleError::Selector(kind)
273    }
274}
275
276/// Parses one sheet, returning what the engine understood and a
277/// warning for everything else.
278pub fn parse(source: &Source<'_>) -> (Sheet, Vec<Warning>) {
279    let mut input = ParserInput::new(source.css);
280    let mut parser = Parser::new(&mut input);
281    let mut top = TopLevel {
282        sheet: Sheet {
283            origin: source.origin,
284            ..Sheet::default()
285        },
286        warnings: Vec::new(),
287        name: source.name.to_string(),
288    };
289    let rules = StyleSheetParser::new(&mut parser, &mut top);
290    let collected: Vec<_> = rules
291        .map(|result| result.map_err(|(error, _)| error))
292        .collect();
293    for result in collected {
294        match result {
295            Ok(rule) => top.keep(rule),
296            Err(error) => top.warn(&error),
297        }
298    }
299    (top.sheet, top.warnings)
300}
301
302/// A parsed top-level rule, before it is filed into the sheet.
303pub enum Rule {
304    Style(StyleRule),
305    Page(PageRule),
306    FontFace(FontFace),
307}
308
309struct TopLevel {
310    sheet: Sheet,
311    warnings: Vec<Warning>,
312    name: String,
313}
314
315impl TopLevel {
316    fn keep(&mut self, rule: Rule) {
317        match rule {
318            Rule::Style(rule) => self.sheet.rules.push(rule),
319            Rule::Page(rule) => self.sheet.pages.push(rule),
320            Rule::FontFace(face) => self.sheet.faces.push(face),
321        }
322    }
323
324    fn warn(&mut self, error: &ParseError<'_, StyleError<'_>>) {
325        self.warnings.push(warning(&self.name, error));
326    }
327}
328
329/// What happens to a declaration the parser refuses.
330const IGNORED_DECLARATION: &str = "The declaration is ignored.";
331
332/// What happens to a rule the parser refuses.
333const IGNORED_RULE: &str = "The rule is ignored.";
334
335/// One parse error as the diagnostic a reader can act on: what the
336/// engine did not understand, and where it was written.
337pub fn warning(sheet: &str, error: &ParseError<'_, StyleError<'_>>) -> Warning {
338    let message = match &error.kind {
339        ParseErrorKind::Custom(StyleError::UnsupportedProperty(name)) => {
340            format!("Unsupported property `{name}`. {IGNORED_DECLARATION}")
341        }
342        ParseErrorKind::Custom(StyleError::NotOnFirstLine(name)) => {
343            format!("Unsupported property `{name}` on `::first-line`. {IGNORED_DECLARATION}")
344        }
345        ParseErrorKind::Custom(StyleError::UnsupportedValue(name)) => {
346            format!("Unsupported value for `{name}`. {IGNORED_DECLARATION}")
347        }
348        ParseErrorKind::Custom(StyleError::UnsupportedAtRule(name)) => {
349            format!("Unsupported at-rule `@{name}`. {IGNORED_RULE}")
350        }
351        ParseErrorKind::Custom(StyleError::UnsupportedPageSelector) => {
352            format!("Unsupported `@page` selector. {IGNORED_RULE}")
353        }
354        ParseErrorKind::Custom(StyleError::Selector(
355            SelectorParseErrorKind::UnsupportedPseudoClassOrElement(name),
356        )) => format!("Unsupported selector `:{name}`. {IGNORED_RULE}"),
357        ParseErrorKind::Custom(StyleError::Selector(_)) => {
358            format!("Unsupported selector. {IGNORED_RULE}")
359        }
360        ParseErrorKind::Basic(BasicParseErrorKind::AtRuleInvalid(name)) => {
361            format!("Unsupported at-rule `@{name}`. {IGNORED_RULE}")
362        }
363        ParseErrorKind::Basic(_) => format!("Malformed CSS. {IGNORED_DECLARATION}"),
364    };
365    Warning {
366        message,
367        origin: Some(position(sheet, error.location)),
368    }
369}
370
371/// A CSS position as diagnostics spell it: `author.css:12:3`.
372pub(super) fn position(sheet: &str, location: SourceLocation) -> String {
373    SheetPosition::at(sheet, location).to_string()
374}
375
376impl<'i> QualifiedRuleParser<'i> for TopLevel {
377    type Prelude = SelectorList<Fleuron>;
378    type QualifiedRule = Rule;
379    type Error = StyleError<'i>;
380
381    fn parse_prelude<'t>(
382        &mut self,
383        input: &mut Parser<'i, 't>,
384    ) -> Result<Self::Prelude, ParseError<'i, Self::Error>> {
385        SelectorList::parse(&Selectors, input, ParseRelative::No)
386    }
387
388    fn parse_block<'t>(
389        &mut self,
390        selectors: Self::Prelude,
391        start: &ParserState,
392        input: &mut Parser<'i, 't>,
393    ) -> Result<Self::QualifiedRule, ParseError<'i, Self::Error>> {
394        let first_line = selectors
395            .slice()
396            .iter()
397            .all(|selector| selector.pseudo_element() == Some(&PseudoElement::FirstLine));
398        let (declarations, written, warnings) = declarations(input, &self.name, first_line);
399        self.warnings.extend(warnings);
400        Ok(Rule::Style(StyleRule {
401            selectors,
402            declarations,
403            written,
404            position: SheetPosition::at(&self.name, start.source_location()),
405        }))
406    }
407}
408
409impl<'i> AtRuleParser<'i> for TopLevel {
410    type Prelude = AtRule;
411    type AtRule = Rule;
412    type Error = StyleError<'i>;
413
414    fn parse_prelude<'t>(
415        &mut self,
416        name: CowRcStr<'i>,
417        input: &mut Parser<'i, 't>,
418    ) -> Result<Self::Prelude, ParseError<'i, Self::Error>> {
419        match_ignore_ascii_case! { &name,
420            "page" => {
421                let from = input.position();
422                let mut rule = page_selector(input)?;
423                rule.selector = format!("@page {}", input.slice_from(from).trim())
424                    .trim_end()
425                    .to_string();
426                Ok(AtRule::Page(rule))
427            },
428            "font-face" => Ok(AtRule::FontFace),
429            _ => Err(input.new_custom_error(StyleError::UnsupportedAtRule(name.clone()))),
430        }
431    }
432
433    fn parse_block<'t>(
434        &mut self,
435        prelude: Self::Prelude,
436        start: &ParserState,
437        input: &mut Parser<'i, 't>,
438    ) -> Result<Self::AtRule, ParseError<'i, Self::Error>> {
439        match prelude {
440            AtRule::Page(mut rule) => {
441                rule.position = SheetPosition::at(&self.name, start.source_location());
442                let mut body = PageBody {
443                    name: self.name.clone(),
444                    warnings: Vec::new(),
445                };
446                let items: Vec<_> = RuleBodyParser::new(input, &mut body)
447                    .map(|result| result.map_err(|(error, _)| error))
448                    .collect();
449                self.warnings.append(&mut body.warnings);
450                for item in items {
451                    match item {
452                        Ok(parsed) => {
453                            for item in parsed {
454                                match item {
455                                    PageItem::Declaration(declaration) => {
456                                        rule.declarations.push(declaration)
457                                    }
458                                    PageItem::Box(margin) => rule.boxes.push(margin),
459                                }
460                            }
461                        }
462                        Err(error) => self.warnings.push(warning(&self.name, &error)),
463                    }
464                }
465                Ok(Rule::Page(rule))
466            }
467            AtRule::FontFace => {
468                let (face, warnings) = font_face(input, &self.name);
469                self.warnings.extend(warnings);
470                Ok(Rule::FontFace(face))
471            }
472        }
473    }
474}
475
476/// The at-rules the engine parses, once their prelude is read.
477pub enum AtRule {
478    Page(PageRule),
479    FontFace,
480}
481
482/// The selector parser: the engine takes plain selectors and nothing
483/// that assumes a live document.
484struct Selectors;
485
486impl<'i> selectors::Parser<'i> for Selectors {
487    type Impl = Fleuron;
488    type Error = StyleError<'i>;
489
490    fn parse_is_and_where(&self) -> bool {
491        true
492    }
493
494    fn parse_nth_child_of(&self) -> bool {
495        true
496    }
497
498    fn parse_has(&self) -> bool {
499        true
500    }
501
502    fn parse_pseudo_element(
503        &self,
504        location: SourceLocation,
505        name: CowRcStr<'i>,
506    ) -> Result<PseudoElement, ParseError<'i, StyleError<'i>>> {
507        match_ignore_ascii_case! { &name,
508            "first-letter" => Ok(PseudoElement::FirstLetter),
509            "first-line" => Ok(PseudoElement::FirstLine),
510            "before" => Ok(PseudoElement::Before),
511            "after" => Ok(PseudoElement::After),
512            _ => Err(location.new_custom_error(
513                SelectorParseErrorKind::UnsupportedPseudoClassOrElement(name.clone()),
514            )),
515        }
516    }
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522
523    /// A rule records the sheet, line and column it begins at, and a
524    /// warning about a rule written at the same place names the same
525    /// position.
526    #[test]
527    fn a_rule_records_the_position_a_warning_names() {
528        let kept = "p { color: red }\n\n  h1 { color: red }";
529        let refused = "p { color: red }\n\n  !h1 { color: red }";
530        let (sheet, _) = parse(&Source::author("author.css", kept));
531        let (_, warnings) = parse(&Source::author("author.css", refused));
532
533        let rule = &sheet.rules[1];
534        assert_eq!(
535            rule.position,
536            SheetPosition {
537                sheet: "author.css".into(),
538                line: 3,
539                column: 3,
540            }
541        );
542        assert_eq!(warnings.len(), 1, "{warnings:?}");
543        assert_eq!(
544            warnings[0].origin.as_deref(),
545            Some(rule.position.to_string().as_str())
546        );
547
548        let page = "\n@page :left {\n  @top-left { content: \"Left\" }\n}";
549        let (sheet, _) = parse(&Source::author("pages.css", page));
550        assert_eq!(sheet.pages[0].position.to_string(), "pages.css:2:1");
551        assert_eq!(sheet.pages[0].selector, "@page :left");
552    }
553
554    /// A declaration keeps the name and value it was written with,
555    /// and a shorthand names every longhand it became.
556    #[test]
557    fn a_declaration_keeps_what_was_written() {
558        let css = "p { MARGIN: 1em 2em; color: red !important }";
559        let (sheet, _) = parse(&Source::author("author.css", css));
560        let rule = &sheet.rules[0];
561        assert_eq!(
562            rule.written,
563            vec![
564                Written {
565                    property: "margin".into(),
566                    value: "1em 2em".into(),
567                    important: false,
568                    longhands: 0..4,
569                    position: SheetPosition {
570                        sheet: "author.css".into(),
571                        line: 1,
572                        column: 5,
573                    },
574                },
575                Written {
576                    property: "color".into(),
577                    value: "red".into(),
578                    important: true,
579                    longhands: 4..5,
580                    position: SheetPosition {
581                        sheet: "author.css".into(),
582                        line: 1,
583                        column: 22,
584                    },
585                },
586            ]
587        );
588        assert_eq!(rule.declarations.len(), 5);
589    }
590
591    /// Part: a declaration whose name starts with `--` is kept as the
592    /// text it was written as rather than rejected, and a value that
593    /// reads one is kept as text for the cascade.
594    #[test]
595    fn a_custom_property_is_kept_as_written() {
596        let css = "p {\n  --Accent: rgb(214, 7, 94) !important;\n  color: var(--Accent, black);\n}";
597        let (sheet, warnings) = parse(&Source::author("author.css", css));
598        assert!(warnings.is_empty(), "{warnings:?}");
599        let rule = &sheet.rules[0];
600        assert_eq!(
601            rule.declarations,
602            vec![
603                (
604                    Declaration::Custom(crate::style::properties::Custom {
605                        name: "--Accent".into(),
606                        value: "rgb(214, 7, 94)".into(),
607                        origin: "author.css:2:3".into(),
608                    }),
609                    Importance::Important,
610                ),
611                (
612                    Declaration::Pending(Pending {
613                        property: "color".into(),
614                        value: "var(--Accent, black)".into(),
615                        origin: "author.css:3:3".into(),
616                    }),
617                    Importance::Normal,
618                ),
619            ]
620        );
621        assert_eq!(rule.written[0].property, "--Accent");
622        assert_eq!(rule.written[1].value, "var(--Accent, black)");
623    }
624}