Skip to main content

nomiscript/compiler/expr/
format.rs

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
7use crate::ast::{Expr, KeyParam, LambdaParams};
8use crate::error::Error;
9use 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)]
14enum Mode {
15    Princ,
16    Prin1,
17}
18
19pub(crate) fn format_expr(expr: &Expr) -> String {
20    render(expr, Mode::Princ)
21}
22
23/// Prints a user form for a diagnostic, strings quoted at any depth.
24pub fn format_form(expr: &Expr) -> String {
25    render(expr, Mode::Prin1)
26}
27
28fn render_string(s: &str, mode: Mode) -> String {
29    match mode {
30        Mode::Princ => s.to_string(),
31        Mode::Prin1 => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
32    }
33}
34
35fn render(expr: &Expr, mode: Mode) -> String {
36    let again = |e: &Expr| render(e, mode);
37    match expr {
38        Expr::Nil => "nil".to_string(),
39        Expr::T => "t".to_string(),
40        Expr::Number(n) => n.to_string(),
41        Expr::String(s) => render_string(s, mode),
42        Expr::Symbol(s) => SymbolTable::local_alias_origin(s).unwrap_or(s).to_string(),
43        Expr::Keyword(s) => format!(":{s}"),
44        Expr::Bytes(b) => format_bytes_literal(b),
45        Expr::Cons(car, cdr) => format_cons(car, cdr, again),
46        Expr::List(elems) if elems.is_empty() => "nil".to_string(),
47        Expr::List(elems) => {
48            let inner: Vec<_> = elems.iter().map(again).collect();
49            format!("({})", inner.join(" "))
50        }
51        Expr::Quote(e) | Expr::Datum(e) => format!("'{}", again(e)),
52        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            format!(
57                "(LAMBDA ({}) {})",
58                format_lambda_params(params, mode),
59                again(body)
60            )
61        }
62        Expr::RuntimeValue(val) => format_runtime_value(val),
63        Expr::WasmRuntime(ty) => format!("#<wasm:{ty}>"),
64        Expr::WasmLocal(idx, ty) => format!("#<local:{idx}:{ty}>"),
65        Expr::WasmGlobal(idx, ty) => format!("#<global:{idx}:{ty}>"),
66        Expr::Instance(serial, id) => format!("#<instance:{serial}:{id}>"),
67    }
68}
69
70pub(super) fn not_callable(head: &Expr) -> Error {
71    match head {
72        Expr::Quote(inner) => match inner.as_ref() {
73            Expr::Symbol(name) => Error::Compile(format!(
74                "illegal function call: ('{name} …); use (funcall '{} …)",
75                name.to_lowercase()
76            )),
77            _ => plain_not_callable(head),
78        },
79        _ => plain_not_callable(head),
80    }
81}
82
83fn plain_not_callable(head: &Expr) -> Error {
84    Error::Compile(format!("not callable: {}", format_form(head)))
85}
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.
91pub(crate) fn format_datum(datum: &Expr) -> String {
92    match datum {
93        Expr::Quote(inner) | Expr::Datum(inner) => format_datum(inner),
94        Expr::List(elems) if !elems.is_empty() => {
95            let inner: Vec<_> = elems.iter().map(format_datum).collect();
96            format!("({})", inner.join(" "))
97        }
98        Expr::Cons(car, cdr) => format_cons(car, cdr, format_datum),
99        other => format_expr(other),
100    }
101}
102
103/// Prints a cons chain as a list, keeping the dot only before a non-list tail.
104fn format_cons(car: &Expr, cdr: &Expr, member: impl Fn(&Expr) -> String) -> String {
105    let mut parts = vec![member(car)];
106    let mut tail = cdr;
107    while let Expr::Cons(next_car, next_cdr) = tail {
108        parts.push(member(next_car));
109        tail = next_cdr;
110    }
111    match tail {
112        Expr::Nil => {}
113        Expr::List(items) => parts.extend(items.iter().map(member)),
114        other => return format!("({} . {})", parts.join(" "), member(other)),
115    }
116    format!("({})", parts.join(" "))
117}
118
119pub(super) fn format_runtime_value(val: &Value) -> String {
120    match val {
121        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            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}
140
141fn 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
146fn format_lambda_params(params: &LambdaParams, mode: Mode) -> String {
147    let mut parts = Vec::new();
148
149    // Required parameters
150    parts.extend(params.required.iter().cloned());
151
152    // Optional parameters
153    if !params.optional.is_empty() {
154        parts.push("&optional".to_string());
155        for (name, default) in &params.optional {
156            if let Some(default_expr) = default {
157                parts.push(format!("({} {})", name, render(default_expr, mode)));
158            } else {
159                parts.push(name.clone());
160            }
161        }
162    }
163
164    // Rest parameter
165    if let Some(rest) = &params.rest {
166        parts.push("&rest".to_string());
167        parts.push(rest.clone());
168    }
169
170    // Key parameters
171    if !params.key.is_empty() {
172        parts.push("&key".to_string());
173        for KeyParam {
174            name,
175            keyword,
176            default,
177        } in &params.key
178        {
179            let spelled = if *keyword == name.to_uppercase() {
180                name.clone()
181            } else {
182                format!("(:{} {name})", keyword.to_lowercase())
183            };
184            match default {
185                Some(default_expr) => {
186                    parts.push(format!("({spelled} {})", render(default_expr, mode)));
187                }
188                None => parts.push(spelled),
189            }
190        }
191    }
192
193    // Aux parameters
194    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    }
204
205    parts.join(" ")
206}
207
208#[cfg(test)]
209#[path = "format_tests.rs"]
210mod tests;