Skip to main content

vihaco_parser/
print.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4//! Canonical source printing: the inverse of [`Parse`](crate::Parse).
5//!
6//! Every type with a `Parse` implementation in this crate also implements
7//! [`Print`], and `#[derive(Parse)]` derives both from the same pattern, so
8//! `parse(print(x)) == x` holds for every printable value.
9//!
10//! Output is canonical and minimal: one space between tokens, `, ` between
11//! list items, no newlines, and no leading or trailing whitespace. Layout
12//! (indentation, line breaks) is left to callers, so printed fragments compose.
13//!
14//! Printing fails with [`fmt::Error`] when a value has no source spelling that
15//! parses back to the same value, for example a non-finite `f64`, an empty or
16//! malformed [`Ident`], or `Some(x)` whose spelling of `x` would be read as
17//! `null`.
18
19use crate::impls::{BareToken, Ident, QuotedString};
20use std::fmt;
21
22/// Write a value in the source spelling accepted by its [`Parse`](crate::Parse)
23/// implementation.
24///
25/// Implementations must round-trip: parsing the printed text yields a value
26/// equal to `self`. When no such spelling exists, return [`fmt::Error`] rather
27/// than writing text that would parse differently.
28///
29/// [`fmt::Formatter`] implements [`fmt::Write`], so a `Display` impl can
30/// forward to `print`.
31pub trait Print {
32    /// Write the canonical source spelling of `self` to `out`.
33    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result;
34
35    /// Return the canonical source spelling of `self` as a string.
36    fn to_source(&self) -> eyre::Result<String> {
37        let mut source = String::new();
38        self.print(&mut source)
39            .map_err(|_| eyre::eyre!("value has no source spelling that parses back to itself"))?;
40        Ok(source)
41    }
42}
43
44impl<T: Print + ?Sized> Print for &T {
45    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
46        T::print(self, out)
47    }
48}
49
50impl<T: Print + ?Sized> Print for Box<T> {
51    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
52        T::print(self, out)
53    }
54}
55
56macro_rules! impl_display_print {
57    ($($t:ty),+) => {
58        $(impl Print for $t {
59            fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
60                write!(out, "{self}")
61            }
62        })+
63    };
64}
65impl_display_print!(u64, u32, usize, i64, i32, bool);
66
67macro_rules! impl_float_print {
68    ($($t:ty),+) => {
69        $(impl Print for $t {
70            /// Print the shortest decimal that parses back to the same bits.
71            ///
72            /// Non-finite values have no source spelling and fail.
73            fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
74                if !self.is_finite() {
75                    return Err(fmt::Error);
76                }
77                // `Debug` is the shortest round-tripping form and always
78                // includes a fraction or exponent (`1.0`, `1e-7`), both of
79                // which the float parser accepts.
80                write!(out, "{self:?}")
81            }
82        })+
83    };
84}
85impl_float_print!(f64, f32);
86
87/// Whether the unquoted token parsers accept `c` inside a token.
88fn is_token_char(c: char) -> bool {
89    !c.is_whitespace()
90        && !matches!(
91            c,
92            ',' | ';' | '(' | ')' | '{' | '}' | '[' | ']' | '"' | '\'' | '`'
93        )
94}
95
96/// Write an unquoted token after checking that the token parser reads it back.
97///
98/// Tokens never contain `;`, which starts a line comment.
99fn print_token(text: &str, allow_at: bool, out: &mut dyn fmt::Write) -> fmt::Result {
100    if text.is_empty()
101        || !text
102            .chars()
103            .all(|c| is_token_char(c) && (allow_at || c != '@'))
104    {
105        return Err(fmt::Error);
106    }
107    out.write_str(text)
108}
109
110impl Print for Ident {
111    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
112        print_token(self.as_str(), false, out)
113    }
114}
115
116impl Print for BareToken {
117    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
118        print_token(self.as_str(), true, out)
119    }
120}
121
122/// Write `text` as a double-quoted string literal using the escapes accepted
123/// by the [`QuotedString`] parser.
124pub fn print_quoted(text: &str, out: &mut dyn fmt::Write) -> fmt::Result {
125    out.write_char('"')?;
126    for c in text.chars() {
127        match c {
128            '"' => out.write_str("\\\"")?,
129            '\\' => out.write_str("\\\\")?,
130            '\n' => out.write_str("\\n")?,
131            '\t' => out.write_str("\\t")?,
132            '\r' => out.write_str("\\r")?,
133            '\0' => out.write_str("\\0")?,
134            c => out.write_char(c)?,
135        }
136    }
137    out.write_char('"')
138}
139
140impl Print for QuotedString {
141    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
142        print_quoted(self.as_str(), out)
143    }
144}
145
146impl Print for String {
147    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
148        print_quoted(self, out)
149    }
150}
151
152impl Print for str {
153    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
154        print_quoted(self, out)
155    }
156}
157
158impl<T: Print> Print for Vec<T> {
159    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
160        out.write_char('[')?;
161        for (index, item) in self.iter().enumerate() {
162            if index > 0 {
163                out.write_str(", ")?;
164            }
165            item.print(out)?;
166        }
167        out.write_char(']')
168    }
169}
170
171impl<A: Print, B: Print> Print for (A, B) {
172    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
173        out.write_char('(')?;
174        self.0.print(out)?;
175        out.write_str(", ")?;
176        self.1.print(out)?;
177        out.write_char(')')
178    }
179}
180
181impl<T: Print> Print for Option<T> {
182    /// `None` prints as `null`. `Some(x)` prints as `x`, unless that spelling
183    /// would itself be read as the `null` keyword.
184    fn print(&self, out: &mut dyn fmt::Write) -> fmt::Result {
185        match self {
186            None => out.write_str("null"),
187            Some(value) => {
188                let mut text = String::new();
189                value.print(&mut text)?;
190                // `null` is matched as a whole identifier; conservatively
191                // treat any non-ASCII continuation as possibly ending it.
192                if let Some(rest) = text.strip_prefix("null") {
193                    let continues_ident = rest
194                        .chars()
195                        .next()
196                        .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_');
197                    if !continues_ident {
198                        return Err(fmt::Error);
199                    }
200                }
201                out.write_str(&text)
202            }
203        }
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use crate::Parse;
211    use chumsky::Parser;
212    use std::fmt::Debug;
213
214    fn round_trip<T>(value: T) -> String
215    where
216        T: Print + Debug + PartialEq + for<'src> Parse<'src>,
217    {
218        let source = value.to_source().unwrap();
219        let parsed = T::parser().parse(source.as_str()).into_result();
220        assert_eq!(parsed.as_ref(), Ok(&value), "reparsing {source:?}");
221        source
222    }
223
224    #[test]
225    fn integers_round_trip_at_their_bounds() {
226        for value in [0, 1, i64::MIN, i64::MAX, -42] {
227            round_trip(value);
228        }
229        for value in [i32::MIN, i32::MAX, -7] {
230            round_trip(value);
231        }
232        for value in [0, u64::MAX] {
233            round_trip(value);
234        }
235        for value in [0, u32::MAX] {
236            round_trip(value);
237        }
238        round_trip(usize::MAX);
239        assert_eq!(round_trip(-42_i64), "-42");
240    }
241
242    #[test]
243    fn bools_round_trip() {
244        assert_eq!(round_trip(true), "true");
245        assert_eq!(round_trip(false), "false");
246    }
247
248    #[test]
249    fn floats_round_trip_exactly() {
250        let values = [
251            0.0,
252            -0.0,
253            1.0,
254            -1.5,
255            0.1,
256            1e-7,
257            -1.9999999999998004e-6,
258            1e16,
259            1e300,
260            f64::MIN_POSITIVE,
261            5e-324,
262            f64::MAX,
263            f64::MIN,
264        ];
265        for value in values {
266            let source = value.to_source().unwrap();
267            let parsed = f64::parser().parse(source.as_str()).into_result().unwrap();
268            assert_eq!(parsed.to_bits(), value.to_bits(), "{source}");
269        }
270        for value in [0.0_f32, -0.0, 1.5, -3.25e-12, f32::MAX, f32::MIN_POSITIVE] {
271            let source = value.to_source().unwrap();
272            let parsed = f32::parser().parse(source.as_str()).into_result().unwrap();
273            assert_eq!(parsed.to_bits(), value.to_bits(), "{source}");
274        }
275        assert_eq!(1.0_f64.to_source().unwrap(), "1.0");
276        assert_eq!((-0.5_f64).to_source().unwrap(), "-0.5");
277    }
278
279    #[test]
280    fn non_finite_floats_have_no_spelling() {
281        assert!(f64::NAN.to_source().is_err());
282        assert!(f64::INFINITY.to_source().is_err());
283        assert!(f32::NEG_INFINITY.to_source().is_err());
284    }
285
286    #[test]
287    fn lexical_tokens_round_trip_and_reject_unparseable_text() {
288        assert_eq!(round_trip(Ident("AOD0:T1:A".into())), "AOD0:T1:A");
289        assert_eq!(round_trip(Ident("a.b.c".into())), "a.b.c");
290        assert_eq!(round_trip(BareToken("@target".into())), "@target");
291        for bad in ["", "two words", "a,b", "@x", "q\"", ";c", "x)"] {
292            assert!(Ident(bad.into()).to_source().is_err(), "{bad:?}");
293        }
294        assert!(BareToken("".into()).to_source().is_err());
295        assert!(BareToken("a b".into()).to_source().is_err());
296    }
297
298    #[test]
299    fn strings_escape_exactly_what_the_parser_unescapes() {
300        let text = "quote\" back\\slash\nnew\ttab\rret\0nul é 🦀 '";
301        assert_eq!(
302            round_trip(QuotedString(text.into())),
303            "\"quote\\\" back\\\\slash\\nnew\\ttab\\rret\\0nul é 🦀 '\""
304        );
305        round_trip(String::from(text));
306        assert_eq!(round_trip(String::new()), "\"\"");
307    }
308
309    #[test]
310    fn collections_use_canonical_separators() {
311        assert_eq!(round_trip(vec![1.0, 2.5]), "[1.0, 2.5]");
312        assert_eq!(round_trip(Vec::<u32>::new()), "[]");
313        assert_eq!(round_trip((1_i64, 2.5_f64)), "(1, 2.5)");
314        assert_eq!(
315            round_trip(vec![(1.0, 2.0), (3.0, -4.0)]),
316            "[(1.0, 2.0), (3.0, -4.0)]"
317        );
318        assert_eq!(
319            round_trip(vec![vec![Ident("a".into())], vec![]]),
320            "[[a], []]"
321        );
322    }
323
324    #[test]
325    fn options_print_null_and_reject_ambiguous_values() {
326        assert_eq!(round_trip(None::<u32>), "null");
327        assert_eq!(round_trip(Some(3_u32)), "3");
328        assert_eq!(round_trip(Some(String::from("null"))), "\"null\"");
329        assert_eq!(round_trip(Some(Ident("nullable".into()))), "nullable");
330        assert!(Some(Ident("null".into())).to_source().is_err());
331        assert!(Some(Ident("null.x".into())).to_source().is_err());
332        assert!(Some(None::<u32>).to_source().is_err());
333    }
334}