about summary refs log tree commit diff
path: root/src/interpret/value.rs
blob: d108c68de3f7e45cd1a90df0005442c43161c801 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use crate::parse::ast::{expression::Expression, nodes::FnNode};
use std::{cell::RefCell, fmt::Display, rc::Rc};
use thiserror::Error;

use super::{
    scope::ScopeChain,
    walker::{Walker, WalkerError},
};

type ReferenceOnCopy<T> = Rc<RefCell<T>>;

#[derive(Clone, Debug)]
pub enum Value {
    Str(String),
    Float(f64),
    Int(i64),
    Bool(bool),
    Array(ReferenceOnCopy<Vec<Value>>),
    Fn(ReferenceOnCopy<FnValue>),
    Void,
}

impl Value {
    pub fn add(self, rhs: Value) -> Result<Value, OperationError> {
        match self {
            Value::Str(ref l) => match rhs {
                Value::Str(r) => Ok(Value::Str(format!("{}{}", l, r))),
                Value::Float(r) => Ok(Value::Str(format!("{}{}", l, r))),
                Value::Int(r) => Ok(Value::Str(format!("{}{}", l, r))),
                r => Err(OperationError::AddTypes(self, r)),
            },
            Value::Float(l) => match rhs {
                Value::Str(r) => Ok(Value::Str(l.to_string() + &r)),
                Value::Float(r) => Ok(Value::Float(l + r)),
                Value::Int(r) => Ok(Value::Float(l + r as f64)),
                r => Err(OperationError::AddTypes(self, r)),
            },
            Value::Int(l) => match rhs {
                Value::Str(r) => Ok(Value::Str(l.to_string() + &r)),
                Value::Float(r) => Ok(Value::Float(l as f64 + r)),
                Value::Int(r) => Ok(Value::Int(l + r)),
                r => Err(OperationError::AddTypes(self, r)),
            },
            _ => Err(OperationError::AddTypes(self, rhs)),
        }
    }

    pub fn sub(self, rhs: Value) -> Result<Value, OperationError> {
        match self {
            Value::Float(l) => match rhs {
                Value::Float(r) => Ok(Value::Float(l - r)),
                Value::Int(r) => Ok(Value::Float(l - r as f64)),
                r => Err(OperationError::SubTypes(self, r)),
            },
            Value::Int(l) => match rhs {
                Value::Float(r) => Ok(Value::Float(l as f64 - r)),
                Value::Int(r) => Ok(Value::Int(l - r)),
                r => Err(OperationError::SubTypes(self, r)),
            },
            _ => Err(OperationError::SubTypes(self, rhs)),
        }
    }

    pub fn mul(self, rhs: Value) -> Result<Value, OperationError> {
        match self {
            Value::Float(l) => match rhs {
                Value::Float(r) => Ok(Value::Float(l * r)),
                Value::Int(r) => Ok(Value::Float(l * r as f64)),
                r => Err(OperationError::MulTypes(self, r)),
            },
            Value::Int(l) => match rhs {
                Value::Float(r) => Ok(Value::Float(l as f64 * r)),
                Value::Int(r) => Ok(Value::Int(l * r)),
                r => Err(OperationError::MulTypes(self, r)),
            },
            _ => Err(OperationError::MulTypes(self, rhs)),
        }
    }

    pub fn div(self, rhs: Value) -> Result<Value, OperationError> {
        match self {
            Value::Float(l) => match rhs {
                Value::Float(r) => Ok(Value::Float(l / r)),
                Value::Int(r) => Ok(Value::Float(l / r as f64)),
                r => Err(OperationError::DivTypes(self, r)),
            },
            Value::Int(l) => match rhs {
                Value::Float(r) => Ok(Value::Float(l as f64 / r)),
                Value::Int(r) => Ok(Value::Float(l as f64 / r as f64)),
                r => Err(OperationError::DivTypes(self, r)),
            },
            _ => Err(OperationError::DivTypes(self, rhs)),
        }
    }

    pub fn eq(self, rhs: Value) -> Result<Value, OperationError> {
        match self {
            Value::Str(l) => match rhs {
                Value::Str(r) => Ok(Value::Bool(l == r)),
                _ => Ok(Value::Bool(false)),
            },
            Value::Float(l) => match rhs {
                Value::Float(r) => Ok(Value::Bool(l == r)),
                _ => Ok(Value::Bool(false)),
            },
            Value::Int(l) => match rhs {
                Value::Int(r) => Ok(Value::Bool(l == r)),
                _ => Ok(Value::Bool(false)),
            },
            Value::Bool(l) => match rhs {
                Value::Bool(r) => Ok(Value::Bool(l == r)),
                _ => Ok(Value::Bool(false)),
            },
            _ => Ok(Value::Bool(false)),
        }
    }

    pub fn neq(self, rhs: Value) -> Result<Value, OperationError> {
        if let Ok(Value::Bool(value)) = self.eq(rhs) {
            Ok(Value::Bool(!value))
        } else {
            unreachable!()
        }
    }

    pub fn gt(self, rhs: Value) -> Result<Value, OperationError> {
        match self {
            Value::Float(r) => match rhs {
                Value::Float(l) => Ok(Value::Bool(r > l)),
                Value::Int(l) => Ok(Value::Bool(r > l as f64)),
                r => Err(OperationError::CompareTypes(self, r)),
            },
            Value::Int(r) => match rhs {
                Value::Float(l) => Ok(Value::Bool(r as f64 > l)),
                Value::Int(l) => Ok(Value::Bool(r > l)),
                r => Err(OperationError::CompareTypes(self, r)),
            },
            _ => Err(OperationError::CompareTypes(self, rhs)),
        }
    }

    pub fn gte(self, rhs: Value) -> Result<Value, OperationError> {
        match self {
            Value::Float(r) => match rhs {
                Value::Float(l) => Ok(Value::Bool(r >= l)),
                Value::Int(l) => Ok(Value::Bool(r >= l as f64)),
                r => Err(OperationError::CompareTypes(self, r)),
            },
            Value::Int(r) => match rhs {
                Value::Float(l) => Ok(Value::Bool(r as f64 >= l)),
                Value::Int(l) => Ok(Value::Bool(r >= l)),
                r => Err(OperationError::CompareTypes(self, r)),
            },
            _ => Err(OperationError::CompareTypes(self, rhs)),
        }
    }

    pub fn neg(self) -> Result<Value, OperationError> {
        match self {
            Value::Float(float) => Ok(Value::Float(-float)),
            Value::Int(int) => Ok(Value::Int(-int)),
            _ => Err(OperationError::NegType(self)),
        }
    }

    pub fn not(self) -> Result<Value, OperationError> {
        match self {
            Value::Bool(bool) => Ok(Value::Bool(bool)),
            _ => Err(OperationError::NotType(self)),
        }
    }

    pub fn subscript(self, index: Value) -> Result<Value, OperationError> {
        let index = match index {
            Value::Int(i) => i,
            i => return Err(OperationError::ArrayIndexType(i)),
        };

        match self {
            Value::Array(a) => {
                let array = a.borrow();
                if index < 0 || index as usize >= array.len() {
                    Err(OperationError::ArrayIndexOutOfRange {
                        index,
                        length: array.len(),
                    })
                } else {
                    Ok(array[index as usize].clone())
                }
            }
            // Maybe allow string subscripts?
            x => Err(OperationError::ArrayType(x.clone())),
        }
    }

    pub fn subscript_assign(
        &mut self,
        index: Value,
        value: Value,
    ) -> Result<Value, OperationError> {
        let index = match index {
            Value::Int(i) => i,
            i => return Err(OperationError::ArrayIndexType(i)),
        };

        match self {
            Value::Array(a) => {
                let mut array = a.borrow_mut();
                if index < 0 || index as usize >= array.len() {
                    Err(OperationError::ArrayIndexOutOfRange {
                        index,
                        length: array.len(),
                    })
                } else {
                    array[index as usize] = value;
                    Ok(array[index as usize].clone())
                }
            }
            x => Err(OperationError::ArrayType(x.clone())),
        }
    }

    pub fn call(&self, arguments: Vec<Value>) -> Result<Value, WalkerError> {
        let called = match self {
            Value::Fn(i) => i,
            i => {
                return Err(WalkerError::OperationError(OperationError::CallableType(
                    i.clone(),
                )))
            }
        }
        .borrow();

        // FIXME: Currently closures are able to re-assign values from the upper scopes.
        // This is good behaviour, until a closure re-assigns a value that was declared after
        // the closure even existed.
        // Minimal reproducible example:
        // ```rh
        // closure = fn { y = 10; };
        // y = 1;
        // closure();
        // print y;
        // ```
        // Expected: 1
        // Actual: 10
        let mut scope = called.scope.clone();
        scope.nest();

        let parameters = &called.node.header.parameters;

        if parameters.len() != arguments.len() {
            return Err(WalkerError::OperationError(
                OperationError::WrongArgumentCount(parameters.len(), arguments.len()),
            ));
        }

        for (argument, parameter) in arguments.into_iter().zip(parameters.iter()) {
            scope.set_var_shadowed(&parameter.identifier, argument);
        }

        // Yes, we create a new walker for every function call,
        // it's *way* easier that way.
        let mut walker = Walker::new_with_scope(scope);
        let result = walker.walk_expression(&Expression::Block(Box::new(called.node.body.clone())));

        if let Err(WalkerError::Return(returned)) = result {
            Ok(returned)
        } else {
            result
        }
    }
}

impl Value {
    pub fn type_name(&self) -> &'static str {
        match self {
            Value::Str(_) => "Str",
            Value::Float(_) => "Float",
            Value::Int(_) => "Int",
            Value::Bool(_) => "Bool",
            Value::Array(_) => "Array",
            Value::Fn(_) => "Fn",
            Value::Void => "Void",
        }
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Str(v) => write!(f, "{}", v),
            Value::Float(v) => write!(f, "{}", v),
            Value::Int(v) => write!(f, "{}", v),
            Value::Bool(v) => write!(f, "{}", v),
            Value::Array(a) => {
                write!(
                    f,
                    "[{}]",
                    a.borrow()
                        .iter()
                        .map(|v| format!("{}", v))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
            Value::Fn(v) => write!(f, "<fn {:?}>", v.as_ptr()),
            Value::Void => write!(f, "<void>"),
        }
    }
}

#[derive(Clone, Debug)]
pub struct FnValue {
    pub node: FnNode,
    pub scope: ScopeChain,
}

#[derive(Error, Debug)]
pub enum OperationError {
    #[error("Can't add value '{0}' of type '{}' to value '{1}' of type '{}'.", .0.type_name(), .1.type_name())]
    AddTypes(Value, Value),
    #[error("Can't subtract value '{1}' of type '{}' from value '{0}' of type '{}'.", .1.type_name(), .0.type_name())]
    SubTypes(Value, Value),
    #[error("Can't multiply value '{0}' of type '{}' with value '{1}' of type '{}'.", .0.type_name(), .1.type_name())]
    MulTypes(Value, Value),
    #[error("Can't divide value '{0}' of type '{}' by value '{1}' of type '{}'.", .0.type_name(), .1.type_name())]
    DivTypes(Value, Value),
    #[error("Can't compare value '{0}' of type '{}' with value '{1}' of type '{}'.", .0.type_name(), .1.type_name())]
    CompareTypes(Value, Value),
    #[error("Can't negate value '{0}' of type '{}'.", .0.type_name())]
    NegType(Value),
    #[error("Can't flip value '{0}' of type '{}'.", .0.type_name())]
    NotType(Value),
    #[error("Can't use value '{0}' of type '{}' as a subsript index.", .0.type_name())]
    ArrayIndexType(Value),
    #[error("Can't subscript value '{0}' of type '{}'.", .0.type_name())]
    ArrayType(Value),
    #[error("Array index '{index}' out of range for array of length '{length}'.")]
    ArrayIndexOutOfRange { index: i64, length: usize },
    #[error("Can't call value '{0}' of type '{}'.", .0.type_name())]
    CallableType(Value),
    #[error("Function expects {0} arguments, but {1} were given.")]
    WrongArgumentCount(usize, usize),
}