Lines
100 %
Functions
95.45 %
Branches
//! Constructors and conversions between a datum (a value) and code.
use crate::ast::{Expr, Fraction};
use crate::runtime::with_sufficient_stack;
impl Expr {
/// The one constructor for a value that is a datum (a `'x` datum is the
/// list `(QUOTE x)`): `nil`, `t`, the empty
/// list, numbers, strings and keywords are the values themselves, anything else
/// is wrapped in `Datum`. A list datum holds
/// its `'x` members as the lists `(QUOTE x)`, at every depth.
#[must_use]
pub fn quoted(datum: Expr) -> Self {
Self::wrapped(datum.into_datum_member(), Expr::Datum)
}
/// The code form `'x`, as the reader makes it: the expression is code,
/// whose `'x` members stay quotes.
pub fn quoted_code(code: Expr) -> Self {
Self::wrapped(code, Expr::Quote)
fn wrapped(expr: Expr, wrap: fn(Box<Expr>) -> Expr) -> Self {
match expr {
Expr::Nil | Expr::T | Expr::Number(_) | Expr::String(_) | Expr::Keyword(_) => expr,
Expr::List(items) if items.is_empty() => Expr::Nil,
other => wrap(Box::new(other)),
/// A computed value where code is wanted: a datum is the form it holds,
/// the exact inverse of [`Expr::into_data`], any other value is itself.
pub fn into_code(self) -> Self {
match self {
Expr::Datum(datum) => datum.into_form(),
other => other,
/// Datum to code: a `(QUOTE x)` list is the quote node `'x`, at every
/// depth; the inside of a quote stays datum.
fn into_form(self) -> Self {
with_sufficient_stack(|| match self {
Expr::List(items) => match <[Expr; 2]>::try_from(items) {
Ok([Expr::Symbol(head), inner]) if head == "QUOTE" => Expr::quoted_code(inner),
Ok(pair) => Expr::List(pair.into_iter().map(Expr::into_form).collect()),
Err(items) => Expr::List(items.into_iter().map(Expr::into_form).collect()),
},
Expr::Cons(car, cdr) => Expr::cons(car.into_form(), cdr.into_form()),
})
/// The datum of a quoted list: a `'x` member is the list `(QUOTE x)`, at
/// every depth. The outermost expression is not wrapped.
pub fn into_data(self) -> Self {
Expr::List(items) => {
Expr::List(items.into_iter().map(Expr::into_datum_member).collect())
Expr::Cons(car, cdr) => Expr::cons(car.into_datum_member(), cdr.into_datum_member()),
/// A value as a member of list data: its `Datum` wrapper goes and a quote
/// is the list `(QUOTE x)`, at every depth.
pub fn into_datum_member(self) -> Self {
Expr::Datum(inner) => inner.into_datum_member(),
Expr::Quote(inner) => Expr::List(vec![
Expr::Symbol("QUOTE".to_string()),
inner.into_datum_member(),
]),
other => other.into_data(),
/// The exact value of a numeric constant, whatever its dimension.
pub fn exact_number(&self) -> Option<Fraction> {
Expr::Number(n) => Some(n.value()),
_ => None,
pub fn quoted_list(items: Vec<Expr>) -> Self {
Expr::quoted(Expr::List(items))