smpli/
value.rs

1use std::cell::{ RefCell, Ref, RefMut };
2use std::collections::HashMap;
3use std::fmt;
4use std::rc::Rc;
5
6use super::vm_i::FnHandle;
7
8#[derive(Debug, PartialEq)]
9pub struct ReferableValue(Rc<RefCell<Value>>);
10
11impl ReferableValue {
12    pub fn new(v: Value) -> ReferableValue {
13        ReferableValue(Rc::new(RefCell::new(v)))
14    }
15
16    pub fn ref_val(&self) -> Rc<RefCell<Value>> {
17        self.0.clone()
18    }
19
20    pub fn clone_value(&self) -> Value {
21        self.0.borrow().clone()
22    }
23
24    pub fn ref_clone(&self) -> ReferableValue {
25        ReferableValue(self.0.clone())
26    }
27
28    pub fn inner_ref(&self) -> Ref<Value> {
29        self.0.borrow()
30    }
31
32    pub fn inner_ref_mut(&self) -> RefMut<Value> {
33        self.0.borrow_mut()
34    }
35
36    pub fn hard_clone(&self) -> ReferableValue {
37        ReferableValue::new(self.clone_value())
38    }
39}
40
41
42#[derive(Debug, PartialEq)]
43pub enum Value {
44    Int(i64),
45    Float(f64),
46    Bool(bool),
47    String(String),
48    Array(Array),
49    Function(FnHandle),
50    Struct(Struct),
51    Unit,
52}
53
54impl Clone for Value {
55    fn clone(&self) -> Value {
56        match *self {
57            Value::Int(i) => Value::Int(i),
58
59            Value::Float(f) => Value::Float(f),
60
61            Value::Bool(b) => Value::Bool(b),
62
63            Value::String(ref s) => Value::String(s.clone()),
64
65            Value::Array(ref a) => Value::Array(
66                a.into_iter()
67                    .map(|rc| ReferableValue::new(rc.clone_value()))
68                    .collect(),
69            ),
70
71            Value::Function(f) => Value::Function(f),
72
73            Value::Struct(ref s) => Value::Struct(s.clone()),
74
75            Value::Unit => Value::Unit,
76        }
77    }
78}
79
80impl fmt::Display for Value {
81    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
82        match *self {
83            Value::Int(i) => write!(f, "{}", i),
84            Value::Float(flt) => write!(f, "{}", flt),
85            Value::Bool(b) => write!(f, "{}", b),
86            Value::String(ref s) => write!(f, "{}", s),
87            Value::Array(ref a) => {
88                write!(f, "[ ")?;
89                for value in a {
90                    write!(f, "{},", value.0.borrow())?
91                }
92                write!(f, " ]")
93            }
94
95            Value::Struct(ref s) => {
96                write!(f, "{{ ")?;
97                for (k, v) in s.fields() {
98                    write!(f, "{}: {},", k, v.0.borrow())?;
99                }
100                write!(f, " }}")
101            }
102
103            Value::Function(..) => write!(f, "Function"), // TODO: Add more information
104
105            Value::Unit => write!(f, "()"),
106        }
107    }
108}
109
110#[derive(Debug, PartialEq)]
111pub struct Struct(HashMap<String, ReferableValue>);
112
113impl Struct {
114    pub fn new() -> Struct {
115        Struct(HashMap::new())
116    }
117
118    pub fn new_init(init: HashMap<String, ReferableValue>) -> Struct {
119        Struct(init)
120    }
121
122    pub fn set_field(&mut self, name: String, v: Value) -> Option<Value> {
123        self.0
124            .insert(name, ReferableValue::new(v))
125            .map(|rv| rv.clone_value())
126    }
127
128    pub fn get_field(&self, name: &str) -> Option<Value> {
129        self.0.get(name).map(|rv| rv.clone_value())
130    }
131
132    pub fn ref_field(&self, name: &str) -> Option<ReferableValue> {
133        self.0.get(name).map(|rc| rc.ref_clone())
134    }
135
136    pub fn fields(&self) -> impl Iterator<Item = (&str, ReferableValue)> {
137        self.0.iter().map(|(k, v)| (k.as_str(), v.ref_clone()))
138    }
139}
140
141impl Clone for Struct {
142    fn clone(&self) -> Struct {
143        Struct(
144            self.0
145                .iter()
146                .map(|(key, rc)| {
147                    (key.clone(), rc.hard_clone())
148                })
149                .collect(),
150        )
151    }
152}
153
154#[derive(Debug, PartialEq)]
155pub struct Array {
156    vec: Vec<ReferableValue>
157}
158
159impl Array {
160    pub fn new() -> Array {
161        Array {
162            vec: Vec::new(),
163        }
164    }
165
166    pub fn new_init<T: IntoIterator<Item=Value>>(iter: T) -> Array {
167        Array {
168            vec: iter.into_iter().map(|v| ReferableValue::new(v)).collect(),
169        }
170    }
171
172    pub fn with_capacity(capacity: usize) -> Array {
173        Array {
174            vec: Vec::with_capacity(capacity)
175        }
176    }
177
178    pub fn capacity(&self) -> usize {
179        self.vec.capacity()
180    }
181
182    pub fn reserve(&mut self, additional: usize) {
183        self.vec.reserve(additional);
184    }
185
186    pub fn reserve_exact(&mut self, additional: usize) {
187        self.vec.reserve_exact(additional)
188    }
189
190    pub fn shrink_to_fit(&mut self) {
191        self.vec.shrink_to_fit();
192    }
193
194    pub fn into_boxed_slice(self) -> Box<[ReferableValue]> {
195        self.vec.into_boxed_slice()
196    }
197
198    pub fn truncate(&mut self, len: usize) {
199        self.vec.truncate(len)
200    }
201
202    pub fn as_slice(&self) -> &[ReferableValue] {
203        self.vec.as_slice()
204    }
205
206    pub fn as_mut_slice(&mut self) -> &mut [ReferableValue] {
207        self.vec.as_mut_slice()
208    }
209
210    pub fn insert(&mut self, index: usize, value: Value) {
211        self.vec.insert(index, ReferableValue::new(value));
212    }
213
214    pub fn remove(&mut self, index: usize) -> ReferableValue {
215        self.vec.remove(index)
216    }
217
218    pub fn push(&mut self, value: Value) {
219        self.vec.push(ReferableValue::new(value));
220    }
221
222    pub fn pop(&mut self) -> Option<ReferableValue> {
223        self.vec.pop()
224    }
225
226    pub fn append(&mut self, other: &mut Array) {
227        self.vec.append(&mut other.vec);
228    }
229
230    pub fn clear(&mut self) {
231        self.vec.clear();
232    }
233
234    pub fn len(&self) -> usize {
235        self.vec.len()
236    }
237
238    pub fn is_empty(&self) -> bool {
239        self.vec.is_empty()
240    }
241}
242
243impl std::ops::Deref for Array {
244    type Target = [ReferableValue];
245
246    fn deref(&self) -> &Self::Target {
247        &self.vec
248    }
249}
250
251impl std::iter::FromIterator<ReferableValue> for Array {
252    fn from_iter<I: IntoIterator<Item=ReferableValue>>(iter: I) -> Self {
253        let mut vec = Vec::new();
254
255        for v in iter {
256            vec.push(v);
257        }
258
259        Array {
260            vec: vec,
261        }
262    }
263}
264
265impl std::iter::FromIterator<Value> for Array {
266    fn from_iter<I: IntoIterator<Item=Value>>(iter: I) -> Self {
267        let mut vec = Vec::new();
268
269        for v in iter {
270            vec.push(ReferableValue::new(v));
271        }
272
273        Array {
274            vec: vec
275        }
276    }
277}
278
279impl std::iter::IntoIterator for Array {
280    type Item = ReferableValue;
281    type IntoIter = std::vec::IntoIter<Self::Item>;
282
283    fn into_iter(self) -> Self::IntoIter {
284        self.vec.into_iter()
285    }
286}
287
288impl<'a> IntoIterator for &'a Array {
289    type Item = &'a ReferableValue;
290    type IntoIter = std::slice::Iter<'a, ReferableValue>;
291
292    fn into_iter(self) -> Self::IntoIter {
293        self.vec.iter()
294    }
295}
296
297impl<'a> IntoIterator for &'a mut Array {
298    type Item = &'a mut ReferableValue;
299    type IntoIter = std::slice::IterMut<'a, ReferableValue>;
300
301    fn into_iter(self) -> Self::IntoIter {
302        self.vec.iter_mut()
303    }
304}