Skip to main content

parsec_css/
serialize.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Back to CSS text. The spec asks only that parsing the output gives the
5//! same values again, runs of whitespace aside; this writes each token in
6//! its plainest form and puts `/**/` between two tokens wherever the
7//! spec's table says they'd otherwise run together.
8
9use std::fmt::{self, Write};
10
11use crate::parser::{
12    AtRule, Block, BlockContents, ComponentValue, Declaration, Item, QualifiedRule, Rule,
13    SimpleBlock, Stylesheet,
14};
15use crate::tokenizer::{Token, is_non_ascii_ident};
16
17/// What the last token written was, as far as the comment table cares.
18#[derive(Clone, Copy, PartialEq, Eq)]
19enum Last {
20    Other,
21    Ident,
22    /// The ident `--`, which before `>` would read back as `-->`.
23    Dashes,
24    AtKeyword,
25    Hash,
26    Dimension,
27    Number,
28    Delim(char),
29}
30
31/// What the next token is, as the table's columns see it.
32#[derive(Clone, Copy, PartialEq, Eq)]
33enum Next {
34    Other,
35    /// Ident, function, url or bad url: they start alike.
36    IdentLike,
37    Number,
38    Cdc,
39    OpenParen,
40    Delim(char),
41}
42
43fn needs_comment(last: Last, next: Next) -> bool {
44    use Next::{Cdc, IdentLike, Number as Num, OpenParen};
45    match last {
46        Last::Ident => matches!(next, IdentLike | Num | Cdc | OpenParen | Next::Delim('-')),
47        // Not in the table either.
48        Last::Dashes => needs_comment(Last::Ident, next) || next == Next::Delim('>'),
49        Last::AtKeyword | Last::Hash | Last::Dimension | Last::Delim('#' | '-') => {
50            matches!(next, IdentLike | Num | Cdc | Next::Delim('-'))
51        }
52        Last::Number => matches!(next, IdentLike | Num | Cdc | Next::Delim('%')),
53        Last::Delim('@') => matches!(next, IdentLike | Cdc | Next::Delim('-')),
54        Last::Delim('.' | '+') => next == Num,
55        Last::Delim('/') => next == Next::Delim('*'),
56        // Not in the table, but `<` `!` `--` would read back as `<!--`.
57        Last::Delim('<') => next == Next::Delim('!'),
58        _ => false,
59    }
60}
61
62/// Writes tokens, remembering the last one.
63struct Writer<'w, W> {
64    out: &'w mut W,
65    last: Last,
66}
67
68fn is_name_char(c: char) -> bool {
69    c.is_ascii_alphanumeric() || matches!(c, '-' | '_') || is_non_ascii_ident(c)
70}
71
72fn hex_escape(out: &mut impl Write, c: char) -> fmt::Result {
73    write!(out, "\\{:x} ", c as u32)
74}
75
76/// CSSOM's "serialize an identifier", except that a non-ASCII code point
77/// outside the ident set is escaped, as it must be since CSS Syntax
78/// narrowed that set in 2024.
79pub fn write_identifier(out: &mut impl Write, ident: &str) -> fmt::Result {
80    if ident == "-" {
81        return out.write_str("\\-");
82    }
83    for (i, c) in ident.chars().enumerate() {
84        let digit_first = c.is_ascii_digit() && (i == 0 || (i == 1 && ident.starts_with('-')));
85        match c {
86            '\0' => out.write_char('\u{fffd}')?,
87            '\x01'..='\x1f' | '\x7f' => hex_escape(out, c)?,
88            _ if digit_first => hex_escape(out, c)?,
89            _ if is_name_char(c) => out.write_char(c)?,
90            _ => {
91                out.write_char('\\')?;
92                out.write_char(c)?;
93            }
94        }
95    }
96    Ok(())
97}
98
99/// Like [`write_identifier`] but for what follows `#` in a hash that isn't
100/// an identifier, where a leading digit or `-` needs no escape.
101fn write_name(out: &mut impl Write, name: &str) -> fmt::Result {
102    for c in name.chars() {
103        match c {
104            '\0' => out.write_char('\u{fffd}')?,
105            '\x01'..='\x1f' | '\x7f' => hex_escape(out, c)?,
106            _ if is_name_char(c) => out.write_char(c)?,
107            _ => {
108                out.write_char('\\')?;
109                out.write_char(c)?;
110            }
111        }
112    }
113    Ok(())
114}
115
116/// CSSOM's "serialize a string", in double quotes.
117pub fn write_string(out: &mut impl Write, s: &str) -> fmt::Result {
118    out.write_char('"')?;
119    for c in s.chars() {
120        match c {
121            '\0' => out.write_char('\u{fffd}')?,
122            '\x01'..='\x1f' | '\x7f' => hex_escape(out, c)?,
123            '"' | '\\' => {
124                out.write_char('\\')?;
125                out.write_char(c)?;
126            }
127            _ => out.write_char(c)?,
128        }
129    }
130    out.write_char('"')
131}
132
133/// An unquoted `url(…)`'s contents, escaped where the tokenizer would
134/// otherwise stop or go bad.
135fn write_url(out: &mut impl Write, s: &str) -> fmt::Result {
136    for c in s.chars() {
137        match c {
138            '\0' => out.write_char('\u{fffd}')?,
139            '\x01'..=' ' | '\x7f' | '(' | ')' | '"' | '\'' => hex_escape(out, c)?,
140            '\\' => out.write_str("\\\\")?,
141            _ => out.write_char(c)?,
142        }
143    }
144    Ok(())
145}
146
147/// A dimension's unit, escaping an `e` that would read as an exponent.
148fn write_unit(out: &mut impl Write, unit: &str) -> fmt::Result {
149    let mut chars = unit.chars();
150    let exponent = matches!(chars.next(), Some('e' | 'E'))
151        && match chars.next() {
152            Some('0'..='9') => true,
153            Some('+' | '-') => chars.next().is_some_and(|c| c.is_ascii_digit()),
154            _ => false,
155        };
156    if exponent {
157        hex_escape(out, unit.chars().next().unwrap())?;
158        return write_name(out, &unit[1..]);
159    }
160    write_identifier(out, unit)
161}
162
163impl<W: Write> Writer<'_, W> {
164    fn start(&mut self, next: Next) -> fmt::Result {
165        if needs_comment(self.last, next) {
166            self.out.write_str("/**/")?;
167        }
168        Ok(())
169    }
170
171    fn token(&mut self, token: &Token<'_>) -> fmt::Result {
172        let next = match token {
173            Token::Ident(_) | Token::Function(_) | Token::Url(_) | Token::BadUrl => Next::IdentLike,
174            Token::Number(_) | Token::Percentage(_) | Token::Dimension { .. } => Next::Number,
175            Token::Cdc => Next::Cdc,
176            Token::LeftParen => Next::OpenParen,
177            Token::Delim(c) => Next::Delim(*c),
178            _ => Next::Other,
179        };
180        self.start(next)?;
181        let out = &mut *self.out;
182        self.last = Last::Other;
183        match token {
184            Token::Ident(v) => {
185                write_identifier(out, v)?;
186                self.last = if v == "--" { Last::Dashes } else { Last::Ident };
187            }
188            Token::Function(v) => {
189                write_identifier(out, v)?;
190                out.write_char('(')?;
191            }
192            Token::AtKeyword(v) => {
193                out.write_char('@')?;
194                write_identifier(out, v)?;
195                self.last = Last::AtKeyword;
196            }
197            Token::Hash { value, id } => {
198                out.write_char('#')?;
199                if *id {
200                    write_identifier(out, value)?;
201                } else {
202                    write_name(out, value)?;
203                }
204                self.last = Last::Hash;
205            }
206            Token::String(v) => write_string(out, v)?,
207            // What makes these bad is gone, so they're rebuilt from the
208            // smallest text that is bad the same way.
209            Token::BadString => out.write_str("\"\n")?,
210            Token::Url(v) => {
211                out.write_str("url(")?;
212                write_url(out, v)?;
213                out.write_char(')')?;
214            }
215            Token::BadUrl => out.write_str("url(()")?,
216            Token::Delim(c) => {
217                // A lone backslash reads back as one only before a newline.
218                if *c == '\\' {
219                    out.write_str("\\\n")?;
220                } else {
221                    out.write_char(*c)?;
222                    self.last = Last::Delim(*c);
223                }
224            }
225            Token::Number(n) => {
226                out.write_str(n.repr)?;
227                self.last = Last::Number;
228            }
229            Token::Percentage(n) => {
230                out.write_str(n.repr)?;
231                out.write_char('%')?;
232            }
233            Token::Dimension { number, unit } => {
234                out.write_str(number.repr)?;
235                write_unit(out, unit)?;
236                self.last = Last::Dimension;
237            }
238            Token::UnicodeRange { start, end } if start == end => write!(out, "U+{start:X}")?,
239            Token::UnicodeRange { start, end } => write!(out, "U+{start:X}-{end:X}")?,
240            Token::Whitespace => out.write_char(' ')?,
241            Token::Cdo => out.write_str("<!--")?,
242            Token::Cdc => out.write_str("-->")?,
243            Token::Colon => out.write_char(':')?,
244            Token::Semicolon => out.write_char(';')?,
245            Token::Comma => out.write_char(',')?,
246            Token::LeftBracket => out.write_char('[')?,
247            Token::RightBracket => out.write_char(']')?,
248            Token::LeftParen => out.write_char('(')?,
249            Token::RightParen => out.write_char(')')?,
250            Token::LeftBrace => out.write_char('{')?,
251            Token::RightBrace => out.write_char('}')?,
252        }
253        Ok(())
254    }
255
256    /// Writes a list, keeping a stack of the functions and blocks it's in
257    /// rather than recursing into them.
258    fn values(&mut self, values: &[ComponentValue<'_>]) -> fmt::Result {
259        let mut stack: Vec<(std::slice::Iter<'_, ComponentValue<'_>>, char)> =
260            vec![(values.iter(), '\0')];
261        while let Some((iter, close)) = stack.last_mut() {
262            let close = *close;
263            let Some(value) = iter.next() else {
264                stack.pop();
265                if close != '\0' {
266                    self.token(&close_token(close))?;
267                }
268                continue;
269            };
270            match value {
271                ComponentValue::Token(t, _) => self.token(t)?,
272                ComponentValue::Function(f) => {
273                    self.token(&Token::Function(f.name.clone()))?;
274                    stack.push((f.arguments.iter(), ')'));
275                }
276                ComponentValue::Block(b) => {
277                    self.token(&open_token(b.bracket.open()))?;
278                    stack.push((b.contents.iter(), b.bracket.close()));
279                }
280            }
281        }
282        Ok(())
283    }
284
285    fn block(&mut self, block: &SimpleBlock<'_>) -> fmt::Result {
286        self.token(&open_token(block.bracket.open()))?;
287        self.values(&block.contents)?;
288        self.token(&close_token(block.bracket.close()))
289    }
290
291    fn rule(&mut self, rule: &Rule<'_>) -> fmt::Result {
292        match rule {
293            Rule::At(r) => {
294                self.token(&Token::AtKeyword(r.name.clone()))?;
295                self.values(&r.prelude)?;
296                match &r.block {
297                    Some(b) => self.block(b),
298                    None => self.token(&Token::Semicolon),
299                }
300            }
301            Rule::Qualified(r) => {
302                self.values(&r.prelude)?;
303                self.block(&r.block)
304            }
305        }
306    }
307
308    fn declaration(&mut self, d: &Declaration<'_>) -> fmt::Result {
309        self.token(&Token::Ident(d.name.clone()))?;
310        self.token(&Token::Colon)?;
311        self.values(&d.value)?;
312        if d.important {
313            self.token(&Token::Delim('!'))?;
314            self.token(&Token::Ident("important".into()))?;
315        }
316        Ok(())
317    }
318
319    fn items(&mut self, items: &[Item<'_>]) -> fmt::Result {
320        for item in items {
321            match item {
322                Item::Declaration(d) => {
323                    self.declaration(d)?;
324                    self.token(&Token::Semicolon)?;
325                }
326                Item::Rule(r) => self.rule(r)?,
327            }
328        }
329        Ok(())
330    }
331}
332
333impl<'b, W: Write> Writer<'_, W> {
334    /// Writes `rule`, then closes the blocks in `stack`, with a stack of
335    /// the blocks it's in rather than recursing into them.
336    fn deep(
337        &mut self,
338        mut rule: Option<&'b Rule<'b, Block<'b>>>,
339        mut stack: Vec<std::slice::Iter<'b, Item<'b, Block<'b>>>>,
340    ) -> fmt::Result {
341        loop {
342            if let Some(rule) = rule.take() {
343                let block = match rule {
344                    Rule::At(r) => {
345                        self.token(&Token::AtKeyword(r.name.clone()))?;
346                        self.values(&r.prelude)?;
347                        r.block.as_ref()
348                    }
349                    Rule::Qualified(r) => {
350                        self.values(&r.prelude)?;
351                        Some(&r.block)
352                    }
353                };
354                match block {
355                    Some(b) => {
356                        self.token(&Token::LeftBrace)?;
357                        stack.push(b.items.iter());
358                    }
359                    None => self.token(&Token::Semicolon)?,
360                }
361            }
362            let Some(items) = stack.last_mut() else {
363                return Ok(());
364            };
365            match items.next() {
366                None => {
367                    stack.pop();
368                    self.token(&Token::RightBrace)?;
369                }
370                Some(Item::Declaration(d)) => {
371                    self.declaration(d)?;
372                    self.token(&Token::Semicolon)?;
373                }
374                Some(Item::Rule(r)) => rule = Some(r),
375            }
376        }
377    }
378}
379
380fn open_token(c: char) -> Token<'static> {
381    match c {
382        '(' => Token::LeftParen,
383        '[' => Token::LeftBracket,
384        _ => Token::LeftBrace,
385    }
386}
387
388fn close_token(c: char) -> Token<'static> {
389    match c {
390        ')' => Token::RightParen,
391        ']' => Token::RightBracket,
392        _ => Token::RightBrace,
393    }
394}
395
396/// Writes component values as CSS text.
397///
398/// ```
399/// let values = parsec_css::parse_component_values("a  b(c) d e");
400/// assert_eq!(parsec_css::to_css(&values), "a b(c) d e");
401/// ```
402pub fn write_values(out: &mut impl Write, values: &[ComponentValue<'_>]) -> fmt::Result {
403    writer(out).values(values)
404}
405
406/// [`write_values`] into a new string.
407pub fn to_css(values: &[ComponentValue<'_>]) -> String {
408    let mut out = String::new();
409    write_values(&mut out, values).unwrap();
410    out
411}
412
413impl<W: Write> Writer<'_, W> {
414    fn rules(&mut self, rules: &[Rule<'_>]) -> fmt::Result {
415        rules.iter().try_for_each(|r| self.rule(r))
416    }
417}
418
419fn writer<W: Write>(out: &mut W) -> Writer<'_, W> {
420    Writer {
421        out,
422        last: Last::Other,
423    }
424}
425
426impl fmt::Display for ComponentValue<'_> {
427    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428        writer(f).values(std::slice::from_ref(self))
429    }
430}
431
432impl fmt::Display for SimpleBlock<'_> {
433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434        writer(f).block(self)
435    }
436}
437
438impl fmt::Display for Declaration<'_> {
439    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
440        writer(f).declaration(self)
441    }
442}
443
444impl fmt::Display for Rule<'_> {
445    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446        writer(f).rule(self)
447    }
448}
449
450impl fmt::Display for AtRule<'_> {
451    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
452        let mut w = writer(f);
453        w.token(&Token::AtKeyword(self.name.clone()))?;
454        w.values(&self.prelude)?;
455        match &self.block {
456            Some(b) => w.block(b),
457            None => w.token(&Token::Semicolon),
458        }
459    }
460}
461
462impl fmt::Display for QualifiedRule<'_> {
463    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
464        let mut w = writer(f);
465        w.values(&self.prelude)?;
466        w.block(&self.block)
467    }
468}
469
470impl fmt::Display for Stylesheet<'_> {
471    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472        writer(f).rules(&self.rules)
473    }
474}
475
476impl fmt::Display for Rule<'_, Block<'_>> {
477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478        writer(f).deep(Some(self), Vec::new())
479    }
480}
481
482impl fmt::Display for Block<'_> {
483    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484        let mut w = writer(f);
485        w.token(&Token::LeftBrace)?;
486        w.deep(None, vec![self.items.iter()])
487    }
488}
489
490impl fmt::Display for Stylesheet<'_, Block<'_>> {
491    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492        let mut w = writer(f);
493        self.rules
494            .iter()
495            .try_for_each(|r| w.deep(Some(r), Vec::new()))
496    }
497}
498
499impl fmt::Display for BlockContents<'_> {
500    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501        writer(f).items(&self.items)
502    }
503}
504
505#[cfg(test)]
506mod tests {
507    use crate::*;
508
509    #[test]
510    fn tokens_that_would_merge_get_a_comment() {
511        let v = parse_component_values("a/**/b 1/**/px #x/**/-y a/**/(b) @a(b) -/**/-");
512        assert_eq!(to_css(&v), "a/**/b 1/**/px #x/**/-y a/**/(b) @a(b) -/**/-");
513    }
514
515    #[test]
516    fn escapes_come_back_as_the_same_values() {
517        let css = r#"\31 a "q\"\\" url(a\)b) 1\65 3 \- \0 #\31 x"#;
518        let first = parse_component_values(css);
519        let again = to_css(&first);
520        let second = parse_component_values(&again);
521        let tokens = |v: &[ComponentValue<'_>]| -> Vec<Token<'static>> {
522            v.iter()
523                .filter_map(|v| v.token().map(|t| owned(t.clone())))
524                .collect()
525        };
526        assert_eq!(tokens(&first), tokens(&second), "{again}");
527    }
528
529    fn owned(t: Token<'_>) -> Token<'static> {
530        // Spans and borrowing aside, the tokens must match; Debug text is
531        // the simplest owned form of one.
532        Token::String(format!("{t:?}").into())
533    }
534
535    #[test]
536    fn rules_and_declarations() {
537        let css = "a>b{c:d!important;e:f}@m x{y{}}@i 'u';";
538        let sheet = parse_stylesheet(css);
539        assert_eq!(sheet.to_string(), css.replace('\'', "\""));
540        let block = parse_block_contents("c: d !important; e{f:g}");
541        assert_eq!(block.to_string(), "c:d!important;e{f:g}");
542    }
543}