1
//! Debug / display formatting for `Expr` and `RuntimeValue`.
2
//!
3
//! `format_expr` is the main entry. The `RuntimeValue` and bytes
4
//! literals route through internal helpers; `format_lambda_params`
5
//! renders parameter lists in the printed-lambda surface syntax.
6

            
7
use crate::ast::{Expr, KeyParam, LambdaParams};
8
use crate::error::Error;
9
use crate::runtime::{SymbolTable, Value};
10

            
11
/// How strings print: `Princ` bare (program output), `Prin1` quoted and
12
/// escaped (diagnostics, where a string must differ from a symbol).
13
#[derive(Clone, Copy)]
14
enum Mode {
15
    Princ,
16
    Prin1,
17
}
18

            
19
183291
pub(crate) fn format_expr(expr: &Expr) -> String {
20
183291
    render(expr, Mode::Princ)
21
183291
}
22

            
23
/// Prints a user form for a diagnostic, strings quoted at any depth.
24
21974
pub fn format_form(expr: &Expr) -> String {
25
21974
    render(expr, Mode::Prin1)
26
21974
}
27

            
28
54325
fn render_string(s: &str, mode: Mode) -> String {
29
54325
    match mode {
30
53254
        Mode::Princ => s.to_string(),
31
1071
        Mode::Prin1 => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
32
    }
33
54325
}
34

            
35
254636
fn render(expr: &Expr, mode: Mode) -> String {
36
49368
    let again = |e: &Expr| render(e, mode);
37
254636
    match expr {
38
1053
        Expr::Nil => "nil".to_string(),
39
1889
        Expr::T => "t".to_string(),
40
58738
        Expr::Number(n) => n.to_string(),
41
54325
        Expr::String(s) => render_string(s, mode),
42
80582
        Expr::Symbol(s) => SymbolTable::local_alias_origin(s).unwrap_or(s).to_string(),
43
16176
        Expr::Keyword(s) => format!(":{s}"),
44
        Expr::Bytes(b) => format_bytes_literal(b),
45
2303
        Expr::Cons(car, cdr) => format_cons(car, cdr, again),
46
12220
        Expr::List(elems) if elems.is_empty() => "nil".to_string(),
47
        Expr::List(elems) => {
48
12219
            let inner: Vec<_> = elems.iter().map(again).collect();
49
12219
            format!("({})", inner.join(" "))
50
        }
51
10085
        Expr::Quote(e) | Expr::Datum(e) => format!("'{}", again(e)),
52
210
        Expr::Quasiquote(e) => format!("`{}", again(e)),
53
        Expr::Unquote(e) => format!(",{}", again(e)),
54
        Expr::UnquoteSplicing(e) => format!(",@{}", again(e)),
55
        Expr::Lambda(params, body) => {
56
5833
            format!(
57
                "(LAMBDA ({}) {})",
58
5833
                format_lambda_params(params, mode),
59
5833
                again(body)
60
            )
61
        }
62
        Expr::RuntimeValue(val) => format_runtime_value(val),
63
7195
        Expr::WasmRuntime(ty) => format!("#<wasm:{ty}>"),
64
51
        Expr::WasmLocal(idx, ty) => format!("#<local:{idx}:{ty}>"),
65
3976
        Expr::WasmGlobal(idx, ty) => format!("#<global:{idx}:{ty}>"),
66
        Expr::Instance(serial, id) => format!("#<instance:{serial}:{id}>"),
67
    }
68
254636
}
69

            
70
10538
pub(super) fn not_callable(head: &Expr) -> Error {
71
10538
    match head {
72
1488
        Expr::Quote(inner) => match inner.as_ref() {
73
22
            Expr::Symbol(name) => Error::Compile(format!(
74
22
                "illegal function call: ('{name} …); use (funcall '{} …)",
75
22
                name.to_lowercase()
76
22
            )),
77
1466
            _ => plain_not_callable(head),
78
        },
79
9050
        _ => plain_not_callable(head),
80
    }
81
10538
}
82

            
83
10516
fn plain_not_callable(head: &Expr) -> Error {
84
10516
    Error::Compile(format!("not callable: {}", format_form(head)))
85
10516
}
86

            
87
/// Prints a value as the datum it is: a quoted member of list data is the
88
/// data it quotes (`(1 '(2))` holds the list `(2)`, printed `(1 (2))`), so no
89
/// quote mark is printed at any depth. Everything else prints as
90
/// [`format_expr`] does.
91
4236
pub(crate) fn format_datum(datum: &Expr) -> String {
92
4236
    match datum {
93
        Expr::Quote(inner) | Expr::Datum(inner) => format_datum(inner),
94
1056
        Expr::List(elems) if !elems.is_empty() => {
95
1056
            let inner: Vec<_> = elems.iter().map(format_datum).collect();
96
1056
            format!("({})", inner.join(" "))
97
        }
98
        Expr::Cons(car, cdr) => format_cons(car, cdr, format_datum),
99
3180
        other => format_expr(other),
100
    }
101
4236
}
102

            
103
/// Prints a cons chain as a list, keeping the dot only before a non-list tail.
104
2303
fn format_cons(car: &Expr, cdr: &Expr, member: impl Fn(&Expr) -> String) -> String {
105
2303
    let mut parts = vec![member(car)];
106
2303
    let mut tail = cdr;
107
2305
    while let Expr::Cons(next_car, next_cdr) = tail {
108
2
        parts.push(member(next_car));
109
2
        tail = next_cdr;
110
    }
111
2303
    match tail {
112
210
        Expr::Nil => {}
113
208
        Expr::List(items) => parts.extend(items.iter().map(member)),
114
1885
        other => return format!("({} . {})", parts.join(" "), member(other)),
115
    }
116
418
    format!("({})", parts.join(" "))
117
2303
}
118

            
119
2
pub(super) fn format_runtime_value(val: &Value) -> String {
120
2
    match val {
121
1
        Value::Nil => "nil".to_string(),
122
        Value::T => "t".to_string(),
123
        Value::Number(n) => n.to_string(),
124
        Value::String(s) => format!("\"{s}\""),
125
        Value::Symbol(s) => s.clone(),
126
        Value::Bytes(b) => format_bytes_literal(b),
127
        Value::Pair(_) | Value::Vector(_) => format!("#<{}>", val.type_name()),
128
        Value::Struct { .. } | Value::Closure(_) | Value::Condition => {
129
1
            crate::runtime::format_value(val)
130
        }
131
        Value::Commodity {
132
            amount,
133
            commodity_id,
134
        } => {
135
            let amt = crate::runtime::format_amount(*amount);
136
            format!("(:commodity {amt} :id \"{commodity_id}\")")
137
        }
138
    }
139
2
}
140

            
141
fn format_bytes_literal(bytes: &[u8]) -> String {
142
    let parts: Vec<String> = bytes.iter().map(u8::to_string).collect();
143
    format!("#u8({})", parts.join(" "))
144
}
145

            
146
5833
fn format_lambda_params(params: &LambdaParams, mode: Mode) -> String {
147
5833
    let mut parts = Vec::new();
148

            
149
    // Required parameters
150
5833
    parts.extend(params.required.iter().cloned());
151

            
152
    // Optional parameters
153
5833
    if !params.optional.is_empty() {
154
2
        parts.push("&optional".to_string());
155
2
        for (name, default) in &params.optional {
156
2
            if let Some(default_expr) = default {
157
2
                parts.push(format!("({} {})", name, render(default_expr, mode)));
158
            } else {
159
                parts.push(name.clone());
160
            }
161
        }
162
5831
    }
163

            
164
    // Rest parameter
165
5833
    if let Some(rest) = &params.rest {
166
        parts.push("&rest".to_string());
167
        parts.push(rest.clone());
168
5833
    }
169

            
170
    // Key parameters
171
5833
    if !params.key.is_empty() {
172
209
        parts.push("&key".to_string());
173
        for KeyParam {
174
            name,
175
            keyword,
176
            default,
177
209
        } in &params.key
178
        {
179
210
            let spelled = if *keyword == name.to_uppercase() {
180
209
                name.clone()
181
            } else {
182
1
                format!("(:{} {name})", keyword.to_lowercase())
183
            };
184
210
            match default {
185
                Some(default_expr) => {
186
1
                    parts.push(format!("({spelled} {})", render(default_expr, mode)));
187
                }
188
209
                None => parts.push(spelled),
189
            }
190
        }
191
5624
    }
192

            
193
    // Aux parameters
194
5833
    if !params.aux.is_empty() {
195
        parts.push("&aux".to_string());
196
        for (name, init) in &params.aux {
197
            if let Some(init_expr) = init {
198
                parts.push(format!("({} {})", name, render(init_expr, mode)));
199
            } else {
200
                parts.push(name.clone());
201
            }
202
        }
203
5833
    }
204

            
205
5833
    parts.join(" ")
206
5833
}
207

            
208
#[cfg(test)]
209
#[path = "format_tests.rs"]
210
mod tests;