1
use num_rational::Ratio;
2
use uuid::Uuid;
3

            
4
use crate::ast::Number;
5

            
6
pub type Fraction = Ratio<i64>;
7

            
8
#[derive(Debug, Clone, PartialEq)]
9
pub 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
    /// A caught condition, which prints without its fields.
20
    Condition,
21
    /// A structure instance read back from a run: its name and each field's
22
    /// name (without the keyword colon) and value.
23
    Struct {
24
        name: String,
25
        fields: Vec<(String, Value)>,
26
    },
27
    /// Commodity-bearing amount: rational value tagged with the
28
    /// originating commodity entity id. Distinct from `Number` so the
29
    /// type system refuses cross-strata arithmetic (`Commodity + Ratio`,
30
    /// `Commodity + Commodity` with different commodity_ids) at compile
31
    /// or runtime. Conversion between commodities goes through the
32
    /// Prices table via `(convert-commodity ...)`.
33
    Commodity {
34
        amount: Fraction,
35
        commodity_id: Uuid,
36
    },
37
}
38

            
39
impl Value {
40
    /// The single runtime truth test: a value is false exactly when it is nil.
41
    #[must_use]
42
51383
    pub fn is_nil(&self) -> bool {
43
51383
        matches!(self, Value::Nil)
44
51383
    }
45

            
46
    #[must_use]
47
1665
    pub fn type_name(&self) -> &'static str {
48
1665
        match self {
49
208
            Value::Nil => "nil",
50
208
            Value::T => "boolean",
51
208
            Value::Number(_) => "number",
52
208
            Value::String(_) => "string",
53
208
            Value::Symbol(_) => "symbol",
54
1
            Value::Bytes(_) => "bytes",
55
208
            Value::Pair(_) => "pair",
56
208
            Value::Vector(_) => "vector",
57
208
            Value::Closure(_) => "closure",
58
            Value::Condition => "condition",
59
            Value::Struct { .. } => "struct",
60
            Value::Commodity { .. } => "commodity",
61
        }
62
1665
    }
63

            
64
    #[must_use]
65
2
    pub fn as_bytes(&self) -> Option<&[u8]> {
66
2
        match self {
67
1
            Value::Bytes(b) => Some(b),
68
1
            _ => None,
69
        }
70
2
    }
71

            
72
    #[must_use]
73
1
    pub fn from_bytes(b: impl Into<Vec<u8>>) -> Self {
74
1
        Value::Bytes(b.into())
75
1
    }
76
}
77

            
78
#[derive(Debug)]
79
pub struct Pair {
80
    pub car: Value,
81
    pub cdr: Value,
82
}
83

            
84
impl Pair {
85
    #[must_use]
86
129286581
    pub fn new(car: Value, cdr: Value) -> Self {
87
129286581
        Self { car, cdr }
88
129286581
    }
89

            
90
    #[must_use]
91
124100932
    pub fn cons(car: Value, cdr: Value) -> Value {
92
124100932
        Value::Pair(Box::new(Self::new(car, cdr)))
93
124100932
    }
94
}
95

            
96
/// The cdr spine is walked in loops so a long list costs no native stack
97
/// per cell in drop, clone or comparison.
98
impl Drop for Pair {
99
129786791
    fn drop(&mut self) {
100
129786791
        let mut rest = std::mem::replace(&mut self.cdr, Value::Nil);
101
251170401
        while let Value::Pair(mut cell) = rest {
102
121383610
            rest = std::mem::replace(&mut cell.cdr, Value::Nil);
103
        }
104
129786791
    }
105
}
106

            
107
impl Clone for Pair {
108
5185232
    fn clone(&self) -> Self {
109
5185232
        let mut cars = Vec::new();
110
5185232
        let mut tail = &self.cdr;
111
50807120
        while let Value::Pair(next) = tail {
112
45621888
            cars.push(next.car.clone());
113
45621888
            tail = &next.cdr;
114
        }
115
5185232
        let rest = cars
116
5185232
            .into_iter()
117
5185232
            .rev()
118
45621888
            .fold(tail.clone(), |acc, car| Pair::cons(car, acc));
119
5185232
        Self::new(self.car.clone(), rest)
120
5185232
    }
121
}
122

            
123
impl PartialEq for Pair {
124
29121
    fn eq(&self, other: &Self) -> bool {
125
29121
        let (mut left, mut right) = (self, other);
126
        loop {
127
41657827
            if left.car != right.car {
128
624
                return false;
129
41657203
            }
130
41657203
            match (&left.cdr, &right.cdr) {
131
41628706
                (Value::Pair(l), Value::Pair(r)) => (left, right) = (l, r),
132
28497
                (l, r) => return l == r,
133
            }
134
        }
135
29121
    }
136
}
137

            
138
#[derive(Debug, Clone, PartialEq)]
139
pub struct Closure {
140
    /// `None` for a closure whose source cannot be carried.
141
    pub code_id: Option<u32>,
142
    pub env: Vec<Value>,
143
}
144

            
145
impl Closure {
146
    #[must_use]
147
35779
    pub fn new(code_id: u32, env: Vec<Value>) -> Self {
148
35779
        Self {
149
35779
            code_id: Some(code_id),
150
35779
            env,
151
35779
        }
152
35779
    }
153

            
154
    #[must_use]
155
5201
    pub fn siteless() -> Self {
156
5201
        Self {
157
5201
            code_id: None,
158
5201
            env: Vec::new(),
159
5201
        }
160
5201
    }
161
}
162

            
163
#[must_use]
164
8095362
pub fn list_to_vec(mut val: &Value) -> Option<Vec<Value>> {
165
8095362
    let mut result = Vec::new();
166
    loop {
167
84890006
        match val {
168
8088705
            Value::Nil => return Some(result),
169
            Value::Pair(pair) => {
170
76794644
                result.push(pair.car.clone());
171
76794644
                val = &pair.cdr;
172
            }
173
6657
            _ => return None,
174
        }
175
    }
176
8095362
}
177

            
178
#[must_use]
179
2708993
pub fn vec_to_list(vec: Vec<Value>) -> Value {
180
2708993
    vec.into_iter()
181
2708993
        .rev()
182
78441587
        .fold(Value::Nil, |acc, v| Pair::cons(v, acc))
183
2708993
}
184

            
185
#[cfg(test)]
186
mod tests {
187
    use super::*;
188

            
189
    #[test]
190
1
    fn only_nil_is_nil() {
191
1
        assert!(Value::Nil.is_nil());
192
1
        assert!(!Value::T.is_nil());
193
1
        assert!(!Value::Number(Number::Index(0)).is_nil());
194
1
        assert!(!Value::String(String::new()).is_nil());
195
1
        assert!(
196
1
            !Value::Struct {
197
1
                name: "test".to_string(),
198
1
                fields: vec![]
199
1
            }
200
1
            .is_nil()
201
        );
202
1
    }
203

            
204
    #[test]
205
1
    fn test_list_conversion() {
206
1
        let list = Pair::cons(
207
1
            Value::Number(Number::Index(1)),
208
1
            Pair::cons(
209
1
                Value::Number(Number::Index(2)),
210
1
                Pair::cons(Value::Number(Number::Index(3)), Value::Nil),
211
1
            ),
212
1
        );
213

            
214
1
        let vec = list_to_vec(&list).unwrap();
215
1
        assert_eq!(vec.len(), 3);
216

            
217
1
        let back = vec_to_list(vec);
218
1
        assert_eq!(back, list);
219
1
    }
220

            
221
    #[test]
222
1
    fn test_improper_list() {
223
1
        let improper = Pair::cons(
224
1
            Value::Number(Number::Index(1)),
225
1
            Value::Number(Number::Index(2)),
226
1
        );
227
1
        assert!(list_to_vec(&improper).is_none());
228
1
    }
229

            
230
    #[test]
231
1
    fn bytes_are_never_nil() {
232
1
        assert!(!Value::Bytes(Vec::new()).is_nil());
233
1
        assert!(!Value::Bytes(vec![0]).is_nil());
234
1
    }
235

            
236
    #[test]
237
1
    fn test_bytes_type_name() {
238
1
        assert_eq!(Value::Bytes(vec![1, 2, 3]).type_name(), "bytes");
239
1
    }
240

            
241
    #[test]
242
1
    fn test_bytes_accessors() {
243
1
        let v = Value::from_bytes(vec![0xCA, 0xFE]);
244
1
        assert_eq!(v.as_bytes(), Some(&[0xCA, 0xFE][..]));
245
1
        assert_eq!(Value::Nil.as_bytes(), None);
246
1
    }
247
}