1use num_rational::Ratio;
2use uuid::Uuid;
3
4use crate::ast::Number;
5
6pub type Fraction = Ratio<i64>;
7
8#[derive(Debug, Clone, PartialEq)]
9pub enum Value {
10 Nil,
11 T,
12 Number(Number),
13 String(String),
14 Symbol(String),
15 Bytes(Vec<u8>),
16 Pair(Box<Pair>),
17 Vector(Vec<Value>),
18 Closure(Closure),
19 Condition,
21 Struct {
24 name: String,
25 fields: Vec<(String, Value)>,
26 },
27 Commodity {
34 amount: Fraction,
35 commodity_id: Uuid,
36 },
37}
38
39impl Value {
40 #[must_use]
42 pub fn is_nil(&self) -> bool {
43 matches!(self, Value::Nil)
44 }
45
46 #[must_use]
47 pub fn type_name(&self) -> &'static str {
48 match self {
49 Value::Nil => "nil",
50 Value::T => "boolean",
51 Value::Number(_) => "number",
52 Value::String(_) => "string",
53 Value::Symbol(_) => "symbol",
54 Value::Bytes(_) => "bytes",
55 Value::Pair(_) => "pair",
56 Value::Vector(_) => "vector",
57 Value::Closure(_) => "closure",
58 Value::Condition => "condition",
59 Value::Struct { .. } => "struct",
60 Value::Commodity { .. } => "commodity",
61 }
62 }
63
64 #[must_use]
65 pub fn as_bytes(&self) -> Option<&[u8]> {
66 match self {
67 Value::Bytes(b) => Some(b),
68 _ => None,
69 }
70 }
71
72 #[must_use]
73 pub fn from_bytes(b: impl Into<Vec<u8>>) -> Self {
74 Value::Bytes(b.into())
75 }
76}
77
78#[derive(Debug)]
79pub struct Pair {
80 pub car: Value,
81 pub cdr: Value,
82}
83
84impl Pair {
85 #[must_use]
86 pub fn new(car: Value, cdr: Value) -> Self {
87 Self { car, cdr }
88 }
89
90 #[must_use]
91 pub fn cons(car: Value, cdr: Value) -> Value {
92 Value::Pair(Box::new(Self::new(car, cdr)))
93 }
94}
95
96impl Drop for Pair {
99 fn drop(&mut self) {
100 let mut rest = std::mem::replace(&mut self.cdr, Value::Nil);
101 while let Value::Pair(mut cell) = rest {
102 rest = std::mem::replace(&mut cell.cdr, Value::Nil);
103 }
104 }
105}
106
107impl Clone for Pair {
108 fn clone(&self) -> Self {
109 let mut cars = Vec::new();
110 let mut tail = &self.cdr;
111 while let Value::Pair(next) = tail {
112 cars.push(next.car.clone());
113 tail = &next.cdr;
114 }
115 let rest = cars
116 .into_iter()
117 .rev()
118 .fold(tail.clone(), |acc, car| Pair::cons(car, acc));
119 Self::new(self.car.clone(), rest)
120 }
121}
122
123impl PartialEq for Pair {
124 fn eq(&self, other: &Self) -> bool {
125 let (mut left, mut right) = (self, other);
126 loop {
127 if left.car != right.car {
128 return false;
129 }
130 match (&left.cdr, &right.cdr) {
131 (Value::Pair(l), Value::Pair(r)) => (left, right) = (l, r),
132 (l, r) => return l == r,
133 }
134 }
135 }
136}
137
138#[derive(Debug, Clone, PartialEq)]
139pub struct Closure {
140 pub code_id: Option<u32>,
142 pub env: Vec<Value>,
143}
144
145impl Closure {
146 #[must_use]
147 pub fn new(code_id: u32, env: Vec<Value>) -> Self {
148 Self {
149 code_id: Some(code_id),
150 env,
151 }
152 }
153
154 #[must_use]
155 pub fn siteless() -> Self {
156 Self {
157 code_id: None,
158 env: Vec::new(),
159 }
160 }
161}
162
163#[must_use]
164pub fn list_to_vec(mut val: &Value) -> Option<Vec<Value>> {
165 let mut result = Vec::new();
166 loop {
167 match val {
168 Value::Nil => return Some(result),
169 Value::Pair(pair) => {
170 result.push(pair.car.clone());
171 val = &pair.cdr;
172 }
173 _ => return None,
174 }
175 }
176}
177
178#[must_use]
179pub fn vec_to_list(vec: Vec<Value>) -> Value {
180 vec.into_iter()
181 .rev()
182 .fold(Value::Nil, |acc, v| Pair::cons(v, acc))
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
190 fn only_nil_is_nil() {
191 assert!(Value::Nil.is_nil());
192 assert!(!Value::T.is_nil());
193 assert!(!Value::Number(Number::Index(0)).is_nil());
194 assert!(!Value::String(String::new()).is_nil());
195 assert!(
196 !Value::Struct {
197 name: "test".to_string(),
198 fields: vec![]
199 }
200 .is_nil()
201 );
202 }
203
204 #[test]
205 fn test_list_conversion() {
206 let list = Pair::cons(
207 Value::Number(Number::Index(1)),
208 Pair::cons(
209 Value::Number(Number::Index(2)),
210 Pair::cons(Value::Number(Number::Index(3)), Value::Nil),
211 ),
212 );
213
214 let vec = list_to_vec(&list).unwrap();
215 assert_eq!(vec.len(), 3);
216
217 let back = vec_to_list(vec);
218 assert_eq!(back, list);
219 }
220
221 #[test]
222 fn test_improper_list() {
223 let improper = Pair::cons(
224 Value::Number(Number::Index(1)),
225 Value::Number(Number::Index(2)),
226 );
227 assert!(list_to_vec(&improper).is_none());
228 }
229
230 #[test]
231 fn bytes_are_never_nil() {
232 assert!(!Value::Bytes(Vec::new()).is_nil());
233 assert!(!Value::Bytes(vec![0]).is_nil());
234 }
235
236 #[test]
237 fn test_bytes_type_name() {
238 assert_eq!(Value::Bytes(vec![1, 2, 3]).type_name(), "bytes");
239 }
240
241 #[test]
242 fn test_bytes_accessors() {
243 let v = Value::from_bytes(vec![0xCA, 0xFE]);
244 assert_eq!(v.as_bytes(), Some(&[0xCA, 0xFE][..]));
245 assert_eq!(Value::Nil.as_bytes(), None);
246 }
247}