Skip to main content

cbcl_core/
serializer.rs

1//! Canonical S-expression serialization.
2//!
3//! Mirrors `Serializer.lean` from the Lean 4 proof library.
4
5#![forbid(unsafe_code)]
6
7use crate::sexpr::{Atom, SExpr};
8use alloc::string::String;
9
10/// Serialize an S-expression to canonical text (REQ-050).
11///
12/// Round-trip guarantee: `parse(serialize(e)) == Ok(e)` for all valid `e`.
13pub fn serialize(sexpr: &SExpr) -> String {
14    let mut buf = String::new();
15    write_sexpr(sexpr, &mut buf);
16    buf
17}
18
19fn write_sexpr(sexpr: &SExpr, buf: &mut String) {
20    match sexpr {
21        SExpr::Atom(atom) => write_atom(atom, buf),
22        SExpr::List(items) => {
23            buf.push('(');
24            for (i, item) in items.iter().enumerate() {
25                if i > 0 {
26                    buf.push(' ');
27                }
28                write_sexpr(item, buf);
29            }
30            buf.push(')');
31        }
32    }
33}
34
35fn write_atom(atom: &Atom, buf: &mut String) {
36    match atom {
37        Atom::Symbol(s) => buf.push_str(s),
38        Atom::Str(s) => {
39            buf.push('"');
40            for ch in s.chars() {
41                match ch {
42                    '"' => buf.push_str("\\\""),
43                    '\\' => buf.push_str("\\\\"),
44                    '\n' => buf.push_str("\\n"),
45                    '\r' => buf.push_str("\\r"),
46                    '\t' => buf.push_str("\\t"),
47                    c => buf.push(c),
48                }
49            }
50            buf.push('"');
51        }
52        Atom::Float(n) => {
53            use core::fmt::Write;
54            let _ = write!(buf, "{n}");
55        }
56        Atom::Decimal(n) => {
57            use core::fmt::Write;
58            let _ = write!(buf, "{n}");
59        }
60        Atom::Num(n) => {
61            use alloc::format;
62            buf.push_str(&format!("{n}"));
63        }
64        Atom::Bool(b) => buf.push_str(if *b { "#t" } else { "#f" }),
65        Atom::Keyword(k) => {
66            buf.push(':');
67            buf.push_str(k);
68        }
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use alloc::vec;
76
77    #[test]
78    fn serialize_atom_types() {
79        assert_eq!(
80            serialize(&SExpr::Atom(Atom::Symbol("hello".into()))),
81            "hello"
82        );
83        assert_eq!(serialize(&SExpr::Atom(Atom::Num(42))), "42");
84        assert_eq!(serialize(&SExpr::Atom(Atom::Num(-7))), "-7");
85        assert_eq!(serialize(&SExpr::Atom(Atom::Bool(true))), "#t");
86        assert_eq!(serialize(&SExpr::Atom(Atom::Bool(false))), "#f");
87        assert_eq!(serialize(&SExpr::Atom(Atom::Keyword("key".into()))), ":key");
88    }
89
90    #[test]
91    fn serialize_string_escapes() {
92        assert_eq!(
93            serialize(&SExpr::Atom(Atom::Str("a\"b\\c\n".into()))),
94            "\"a\\\"b\\\\c\\n\""
95        );
96    }
97
98    #[test]
99    fn serialize_list() {
100        let l = SExpr::List(vec![
101            SExpr::Atom(Atom::Symbol("tell".into())),
102            SExpr::Atom(Atom::Str("hi".into())),
103        ]);
104        assert_eq!(serialize(&l), "(tell \"hi\")");
105    }
106
107    #[test]
108    fn serialize_empty_list() {
109        assert_eq!(serialize(&SExpr::List(vec![])), "()");
110    }
111}