1use crate::ast::{Expr, Fraction};
4use crate::runtime::with_sufficient_stack;
5
6impl Expr {
7 #[must_use]
13 pub fn quoted(datum: Expr) -> Self {
14 Self::wrapped(datum.into_datum_member(), Expr::Datum)
15 }
16
17 #[must_use]
20 pub fn quoted_code(code: Expr) -> Self {
21 Self::wrapped(code, Expr::Quote)
22 }
23
24 fn wrapped(expr: Expr, wrap: fn(Box<Expr>) -> Expr) -> Self {
25 match expr {
26 Expr::Nil | Expr::T | Expr::Number(_) | Expr::String(_) | Expr::Keyword(_) => expr,
27 Expr::List(items) if items.is_empty() => Expr::Nil,
28 other => wrap(Box::new(other)),
29 }
30 }
31
32 #[must_use]
35 pub fn into_code(self) -> Self {
36 match self {
37 Expr::Datum(datum) => datum.into_form(),
38 other => other,
39 }
40 }
41
42 fn into_form(self) -> Self {
45 with_sufficient_stack(|| match self {
46 Expr::List(items) => match <[Expr; 2]>::try_from(items) {
47 Ok([Expr::Symbol(head), inner]) if head == "QUOTE" => Expr::quoted_code(inner),
48 Ok(pair) => Expr::List(pair.into_iter().map(Expr::into_form).collect()),
49 Err(items) => Expr::List(items.into_iter().map(Expr::into_form).collect()),
50 },
51 Expr::Cons(car, cdr) => Expr::cons(car.into_form(), cdr.into_form()),
52 other => other,
53 })
54 }
55
56 #[must_use]
59 pub fn into_data(self) -> Self {
60 with_sufficient_stack(|| match self {
61 Expr::List(items) => {
62 Expr::List(items.into_iter().map(Expr::into_datum_member).collect())
63 }
64 Expr::Cons(car, cdr) => Expr::cons(car.into_datum_member(), cdr.into_datum_member()),
65 other => other,
66 })
67 }
68
69 #[must_use]
72 pub fn into_datum_member(self) -> Self {
73 match self {
74 Expr::Datum(inner) => inner.into_datum_member(),
75 Expr::Quote(inner) => Expr::List(vec![
76 Expr::Symbol("QUOTE".to_string()),
77 inner.into_datum_member(),
78 ]),
79 other => other.into_data(),
80 }
81 }
82
83 #[must_use]
85 pub fn exact_number(&self) -> Option<Fraction> {
86 match self {
87 Expr::Number(n) => Some(n.value()),
88 _ => None,
89 }
90 }
91
92 #[must_use]
93 pub fn quoted_list(items: Vec<Expr>) -> Self {
94 Expr::quoted(Expr::List(items))
95 }
96}