Lines
77.87 %
Functions
80.77 %
Branches
100 %
//! Debug / display formatting for `Expr` and `RuntimeValue`.
//!
//! `format_expr` is the main entry. The `RuntimeValue` and bytes
//! literals route through internal helpers; `format_lambda_params`
//! renders parameter lists in the printed-lambda surface syntax.
use crate::ast::{Expr, KeyParam, LambdaParams};
use crate::error::Error;
use crate::runtime::{SymbolTable, Value};
/// How strings print: `Princ` bare (program output), `Prin1` quoted and
/// escaped (diagnostics, where a string must differ from a symbol).
#[derive(Clone, Copy)]
enum Mode {
Princ,
Prin1,
}
pub(crate) fn format_expr(expr: &Expr) -> String {
render(expr, Mode::Princ)
/// Prints a user form for a diagnostic, strings quoted at any depth.
pub fn format_form(expr: &Expr) -> String {
render(expr, Mode::Prin1)
fn render_string(s: &str, mode: Mode) -> String {
match mode {
Mode::Princ => s.to_string(),
Mode::Prin1 => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
fn render(expr: &Expr, mode: Mode) -> String {
let again = |e: &Expr| render(e, mode);
match expr {
Expr::Nil => "nil".to_string(),
Expr::T => "t".to_string(),
Expr::Number(n) => n.to_string(),
Expr::String(s) => render_string(s, mode),
Expr::Symbol(s) => SymbolTable::local_alias_origin(s).unwrap_or(s).to_string(),
Expr::Keyword(s) => format!(":{s}"),
Expr::Bytes(b) => format_bytes_literal(b),
Expr::Cons(car, cdr) => format_cons(car, cdr, again),
Expr::List(elems) if elems.is_empty() => "nil".to_string(),
Expr::List(elems) => {
let inner: Vec<_> = elems.iter().map(again).collect();
format!("({})", inner.join(" "))
Expr::Quote(e) | Expr::Datum(e) => format!("'{}", again(e)),
Expr::Quasiquote(e) => format!("`{}", again(e)),
Expr::Unquote(e) => format!(",{}", again(e)),
Expr::UnquoteSplicing(e) => format!(",@{}", again(e)),
Expr::Lambda(params, body) => {
format!(
"(LAMBDA ({}) {})",
format_lambda_params(params, mode),
again(body)
)
Expr::RuntimeValue(val) => format_runtime_value(val),
Expr::WasmRuntime(ty) => format!("#<wasm:{ty}>"),
Expr::WasmLocal(idx, ty) => format!("#<local:{idx}:{ty}>"),
Expr::WasmGlobal(idx, ty) => format!("#<global:{idx}:{ty}>"),
Expr::Instance(serial, id) => format!("#<instance:{serial}:{id}>"),
pub(super) fn not_callable(head: &Expr) -> Error {
match head {
Expr::Quote(inner) => match inner.as_ref() {
Expr::Symbol(name) => Error::Compile(format!(
"illegal function call: ('{name} …); use (funcall '{} …)",
name.to_lowercase()
)),
_ => plain_not_callable(head),
},
fn plain_not_callable(head: &Expr) -> Error {
Error::Compile(format!("not callable: {}", format_form(head)))
/// Prints a value as the datum it is: a quoted member of list data is the
/// data it quotes (`(1 '(2))` holds the list `(2)`, printed `(1 (2))`), so no
/// quote mark is printed at any depth. Everything else prints as
/// [`format_expr`] does.
pub(crate) fn format_datum(datum: &Expr) -> String {
match datum {
Expr::Quote(inner) | Expr::Datum(inner) => format_datum(inner),
Expr::List(elems) if !elems.is_empty() => {
let inner: Vec<_> = elems.iter().map(format_datum).collect();
Expr::Cons(car, cdr) => format_cons(car, cdr, format_datum),
other => format_expr(other),
/// Prints a cons chain as a list, keeping the dot only before a non-list tail.
fn format_cons(car: &Expr, cdr: &Expr, member: impl Fn(&Expr) -> String) -> String {
let mut parts = vec![member(car)];
let mut tail = cdr;
while let Expr::Cons(next_car, next_cdr) = tail {
parts.push(member(next_car));
tail = next_cdr;
match tail {
Expr::Nil => {}
Expr::List(items) => parts.extend(items.iter().map(member)),
other => return format!("({} . {})", parts.join(" "), member(other)),
format!("({})", parts.join(" "))
pub(super) fn format_runtime_value(val: &Value) -> String {
match val {
Value::Nil => "nil".to_string(),
Value::T => "t".to_string(),
Value::Number(n) => n.to_string(),
Value::String(s) => format!("\"{s}\""),
Value::Symbol(s) => s.clone(),
Value::Bytes(b) => format_bytes_literal(b),
Value::Pair(_) | Value::Vector(_) => format!("#<{}>", val.type_name()),
Value::Struct { .. } | Value::Closure(_) | Value::Condition => {
crate::runtime::format_value(val)
Value::Commodity {
amount,
commodity_id,
} => {
let amt = crate::runtime::format_amount(*amount);
format!("(:commodity {amt} :id \"{commodity_id}\")")
fn format_bytes_literal(bytes: &[u8]) -> String {
let parts: Vec<String> = bytes.iter().map(u8::to_string).collect();
format!("#u8({})", parts.join(" "))
fn format_lambda_params(params: &LambdaParams, mode: Mode) -> String {
let mut parts = Vec::new();
// Required parameters
parts.extend(params.required.iter().cloned());
// Optional parameters
if !params.optional.is_empty() {
parts.push("&optional".to_string());
for (name, default) in ¶ms.optional {
if let Some(default_expr) = default {
parts.push(format!("({} {})", name, render(default_expr, mode)));
} else {
parts.push(name.clone());
// Rest parameter
if let Some(rest) = ¶ms.rest {
parts.push("&rest".to_string());
parts.push(rest.clone());
// Key parameters
if !params.key.is_empty() {
parts.push("&key".to_string());
for KeyParam {
name,
keyword,
default,
} in ¶ms.key
{
let spelled = if *keyword == name.to_uppercase() {
name.clone()
format!("(:{} {name})", keyword.to_lowercase())
};
match default {
Some(default_expr) => {
parts.push(format!("({spelled} {})", render(default_expr, mode)));
None => parts.push(spelled),
// Aux parameters
if !params.aux.is_empty() {
parts.push("&aux".to_string());
for (name, init) in ¶ms.aux {
if let Some(init_expr) = init {
parts.push(format!("({} {})", name, render(init_expr, mode)));
parts.join(" ")
#[cfg(test)]
#[path = "format_tests.rs"]
mod tests;