luna_lib/lang/
value.rs

1use crate::luna_impl::{
2    interpreter::{Interpreter, RunTimeError},
3    position::Located,
4};
5
6use super::code::Closure;
7use std::{
8    cell::RefCell,
9    collections::HashMap,
10    error::Error,
11    fmt::{Debug, Display},
12    rc::Rc,
13};
14
15pub const META_NAME: &str = "__name";
16pub const META_TYPE: &str = "__type";
17pub const META_TOSTRING: &str = "__str";
18pub const META_CALL: &str = "__call";
19pub const META_GET: &str = "__get";
20pub const META_SET: &str = "__set";
21pub const META_NEXT: &str = "__next";
22
23#[derive(Clone, Default)]
24pub enum Value {
25    #[default]
26    Null,
27    Int(i64),
28    Float(f64),
29    Bool(bool),
30    Char(char),
31    String(String),
32    Vector(Rc<RefCell<Vec<Self>>>),
33    Object(Rc<RefCell<Object>>),
34    UserObject(Rc<RefCell<Box<dyn UserObject>>>),
35    Function(FunctionKind),
36}
37#[derive(Debug, Clone, Default)]
38pub struct Object {
39    pub fields: HashMap<String, Value>,
40    pub meta: Option<Rc<RefCell<Self>>>,
41}
42pub trait UserObject {
43    fn typ(&self) -> &'static str;
44    #[allow(unused_variables)]
45    fn get(&self, key: &str) -> Option<Value> {
46        None
47    }
48    #[allow(unused_variables)]
49    fn set(&mut self, key: &str, value: Value) -> Result<(), UserObjectError> {
50        Err(UserObjectError::InvalidField(key.into()))
51    }
52    #[allow(unused_variables)]
53    fn call(&self, key: &str, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
54        Err(Box::new(UserObjectError::CannotCallNull))
55    }
56    #[allow(unused_variables)]
57    fn call_mut(&mut self, key: &str, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
58        Err(Box::new(UserObjectError::CannotCallNull))
59    }
60}
61#[derive(Debug, Clone, PartialEq)]
62pub enum UserObjectError {
63    ExpectedSelf(&'static str),
64    CannotCallNull,
65    InvalidField(String),
66}
67impl Display for UserObjectError {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        match self {
70            Self::ExpectedSelf(got) => {
71                write!(f, "expected self for argument #1, got {got}")
72            }
73            Self::CannotCallNull => {
74                write!(f, "can not call null")
75            }
76            Self::InvalidField(field) => {
77                write!(f, "invalid field {field:?}")
78            }
79        }
80    }
81}
82impl Error for UserObjectError {}
83#[derive(Clone)]
84pub enum FunctionKind {
85    Function(Rc<Function>),
86    UserFunction(Rc<UserFunction>),
87}
88#[derive(Debug, Clone, Default)]
89pub struct Function {
90    pub closure: Rc<RefCell<Closure>>,
91    pub upvalues: Vec<Rc<RefCell<Value>>>,
92}
93pub type UserFunction = dyn Fn(&mut Interpreter, Vec<Value>) -> Result<Value, Box<dyn Error>>;
94
95impl Default for FunctionKind {
96    #[inline(always)]
97    fn default() -> Self {
98        Self::Function(Default::default())
99    }
100}
101impl Object {
102    #[inline(always)]
103    pub fn new(fields: HashMap<String, Value>) -> Self {
104        Self { fields, meta: None }
105    }
106    #[inline(always)]
107    pub fn get(&self, k: &str) -> Option<Value> {
108        self.fields.get(k).cloned()
109    }
110    #[inline(always)]
111    pub fn set(&mut self, k: String, v: Value) {
112        self.fields.insert(k, v);
113    }
114    #[inline(always)]
115    pub fn get_meta(&self, k: &str) -> Option<Value> {
116        self.meta.as_ref()?.borrow().get(k)
117    }
118}
119impl Value {
120    #[inline(always)]
121    pub fn typ(&self) -> &'static str {
122        match self {
123            Value::Null => "null",
124            Value::Int(_) => "int",
125            Value::Float(_) => "float",
126            Value::Bool(_) => "bool",
127            Value::Char(_) => "char",
128            Value::String(_) => "string",
129            Value::Vector(_) => "vector",
130            Value::Object(_) => "object",
131            Value::UserObject(object) => object.borrow().typ(),
132            Value::Function(_) => "fn",
133        }
134    }
135    #[inline(always)]
136    pub fn dynamic_typ(&self) -> String {
137        match self {
138            Value::Object(object) => {
139                let object = object.borrow();
140                if let Some(value) = object.get_meta(META_TYPE) {
141                    value.to_string()
142                } else {
143                    self.typ().to_string()
144                }
145            }
146            _ => self.typ().to_string(),
147        }
148    }
149    #[inline(always)]
150    pub fn call_tostring(
151        &self,
152        interpreter: &mut Interpreter,
153    ) -> Result<String, Located<RunTimeError>> {
154        match self {
155            Value::Object(object) => {
156                let func = object.borrow().get_meta(META_TOSTRING);
157                if let Some(Value::Function(FunctionKind::Function(func))) = func {
158                    interpreter.call(&func, vec![self.clone()], None);
159                    let value = interpreter.run()?;
160                    Ok(value.unwrap_or_default().to_string())
161                } else {
162                    Ok(self.to_string())
163                }
164            }
165            value => Ok(value.to_string()),
166        }
167    }
168}
169impl Debug for Value {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        match self {
172            Value::Null => write!(f, "null"),
173            Value::Int(v) => write!(f, "{v:?}"),
174            Value::Float(v) => write!(f, "{v:?}"),
175            Value::Bool(v) => write!(f, "{v:?}"),
176            Value::Char(v) => write!(f, "{v:?}"),
177            Value::String(v) => write!(f, "{v:?}"),
178            Value::Vector(v) => write!(f, "{:?}", v.borrow()),
179            Value::Object(v) => write!(
180                f,
181                "{}:{:08x?}",
182                if let Some(value) = v.borrow().get_meta(META_TYPE) {
183                    value.to_string()
184                } else if let Some(value) = v.borrow().get_meta(META_NAME) {
185                    value.to_string()
186                } else {
187                    "object".to_string()
188                },
189                v.as_ptr()
190            ),
191            Value::UserObject(v) => write!(f, "{}:{:08x?}", v.borrow().typ(), v.as_ptr()),
192            Value::Function(FunctionKind::Function(function)) => {
193                write!(f, "fn:{:08x?}", Rc::as_ptr(function))
194            }
195            Value::Function(FunctionKind::UserFunction(func)) => {
196                write!(f, "fn:{:08x?}", Rc::as_ptr(func))
197            }
198        }
199    }
200}
201impl Display for Value {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        match self {
204            Value::Int(v) => write!(f, "{v}"),
205            Value::Float(v) => write!(f, "{v}"),
206            Value::Bool(v) => write!(f, "{v}"),
207            Value::Char(v) => write!(f, "{v}"),
208            Value::String(v) => write!(f, "{v}"),
209            _ => write!(f, "{self:?}"),
210        }
211    }
212}
213impl PartialEq for Value {
214    #[inline(always)]
215    fn eq(&self, other: &Self) -> bool {
216        match (self, other) {
217            (Self::Null, Self::Null) => true,
218            (Self::Int(a), Self::Int(b)) => a == b,
219            (Self::Float(a), Self::Float(b)) => a == b,
220            (Self::Int(a), Self::Float(b)) => *a as f64 == *b,
221            (Self::Float(a), Self::Int(b)) => *a == *b as f64,
222            (Self::Bool(a), Self::Bool(b)) => a == b,
223            (Self::Char(a), Self::Char(b)) => a == b,
224            (Self::String(a), Self::String(b)) => a == b,
225            (Self::Vector(a), Self::Vector(b)) => Rc::as_ptr(a) == Rc::as_ptr(b),
226            (Self::Object(a), Self::Object(b)) => Rc::as_ptr(a) == Rc::as_ptr(b),
227            (Self::UserObject(a), Self::UserObject(b)) => Rc::as_ptr(a) == Rc::as_ptr(b),
228            (
229                Self::Function(FunctionKind::Function(a)),
230                Self::Function(FunctionKind::Function(b)),
231            ) => Rc::as_ptr(a) == Rc::as_ptr(b),
232            (
233                Self::Function(FunctionKind::UserFunction(a)),
234                Self::Function(FunctionKind::UserFunction(b)),
235            ) => std::ptr::eq(a, b),
236            _ => false,
237        }
238    }
239}
240impl From<Value> for bool {
241    fn from(value: Value) -> Self {
242        match value {
243            Value::Null => false,
244            Value::Int(v) => v != 0,
245            Value::Float(v) => v != 0.,
246            Value::Bool(v) => v,
247            Value::Char(v) => v != 0 as char,
248            Value::String(string) => !string.is_empty(),
249            Value::Vector(vector) => !vector.borrow().is_empty(),
250            Value::Object(_) => true,
251            Value::UserObject(_) => true,
252            Value::Function(_) => true,
253        }
254    }
255}
256
257impl From<u8> for Value {
258    fn from(value: u8) -> Self {
259        Self::Int(value as i64)
260    }
261}
262impl From<u16> for Value {
263    fn from(value: u16) -> Self {
264        Self::Int(value as i64)
265    }
266}
267impl From<u32> for Value {
268    fn from(value: u32) -> Self {
269        Self::Int(value as i64)
270    }
271}
272impl From<usize> for Value {
273    fn from(value: usize) -> Self {
274        Self::Int(value as i64)
275    }
276}
277impl From<u64> for Value {
278    fn from(value: u64) -> Self {
279        Self::Int(value as i64)
280    }
281}
282impl From<u128> for Value {
283    fn from(value: u128) -> Self {
284        Self::Int(value as i64)
285    }
286}
287impl From<i8> for Value {
288    fn from(value: i8) -> Self {
289        Self::Int(value as i64)
290    }
291}
292impl From<i16> for Value {
293    fn from(value: i16) -> Self {
294        Self::Int(value as i64)
295    }
296}
297impl From<i32> for Value {
298    fn from(value: i32) -> Self {
299        Self::Int(value as i64)
300    }
301}
302impl From<isize> for Value {
303    fn from(value: isize) -> Self {
304        Self::Int(value as i64)
305    }
306}
307impl From<i64> for Value {
308    fn from(value: i64) -> Self {
309        Self::Int(value)
310    }
311}
312impl From<i128> for Value {
313    fn from(value: i128) -> Self {
314        Self::Int(value as i64)
315    }
316}
317impl From<f32> for Value {
318    fn from(value: f32) -> Self {
319        Self::Float(value as f64)
320    }
321}
322impl From<f64> for Value {
323    fn from(value: f64) -> Self {
324        Self::Float(value)
325    }
326}
327impl From<bool> for Value {
328    fn from(value: bool) -> Self {
329        Self::Bool(value)
330    }
331}
332impl From<char> for Value {
333    fn from(value: char) -> Self {
334        Self::Char(value)
335    }
336}
337impl From<String> for Value {
338    fn from(value: String) -> Self {
339        Self::String(value)
340    }
341}
342impl From<&str> for Value {
343    fn from(value: &str) -> Self {
344        Self::String(value.to_string())
345    }
346}
347impl<V: Into<Value>> From<Vec<V>> for Value {
348    fn from(value: Vec<V>) -> Self {
349        Self::Vector(Rc::new(RefCell::new(
350            value.into_iter().map(|v| v.into()).collect(),
351        )))
352    }
353}
354impl<V: Into<Value>> From<HashMap<String, V>> for Value {
355    fn from(value: HashMap<String, V>) -> Self {
356        Self::Object(Rc::new(RefCell::new(Object::new(
357            value.into_iter().map(|(k, v)| (k, v.into())).collect(),
358        ))))
359    }
360}
361impl From<Rc<UserFunction>> for Value {
362    fn from(value: Rc<UserFunction>) -> Self {
363        Self::Function(FunctionKind::UserFunction(value))
364    }
365}
366impl From<Box<UserFunction>> for Value {
367    fn from(value: Box<UserFunction>) -> Self {
368        Self::Function(FunctionKind::UserFunction(Rc::new(value)))
369    }
370}
371
372#[derive(Debug, Clone, PartialEq)]
373pub enum FromValueError<E> {
374    ConversionError(E),
375    InvalidType(&'static str),
376}
377impl<E: Display> Display for FromValueError<E> {
378    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
379        match self {
380            FromValueError::ConversionError(err) => write!(f, "error while converting {err}"),
381            FromValueError::InvalidType(typ) => write!(f, "cannot transform from {typ}"),
382        }
383    }
384}
385impl<E: Display + Debug> Error for FromValueError<E> {}
386impl TryInto<u8> for Value {
387    type Error = FromValueError<<u8 as TryFrom<i64>>::Error>;
388    fn try_into(self) -> Result<u8, Self::Error> {
389        match self {
390            Value::Int(v) => v.try_into().map_err(FromValueError::ConversionError),
391            value => Err(FromValueError::InvalidType(value.typ())),
392        }
393    }
394}
395impl TryInto<u16> for Value {
396    type Error = FromValueError<<u16 as TryFrom<i64>>::Error>;
397    fn try_into(self) -> Result<u16, Self::Error> {
398        match self {
399            Value::Int(v) => v.try_into().map_err(FromValueError::ConversionError),
400            value => Err(FromValueError::InvalidType(value.typ())),
401        }
402    }
403}
404impl TryInto<u32> for Value {
405    type Error = FromValueError<<u32 as TryFrom<i64>>::Error>;
406    fn try_into(self) -> Result<u32, Self::Error> {
407        match self {
408            Value::Int(v) => v.try_into().map_err(FromValueError::ConversionError),
409            value => Err(FromValueError::InvalidType(value.typ())),
410        }
411    }
412}
413impl TryInto<u64> for Value {
414    type Error = FromValueError<<u64 as TryFrom<i64>>::Error>;
415    fn try_into(self) -> Result<u64, Self::Error> {
416        match self {
417            Value::Int(v) => v.try_into().map_err(FromValueError::ConversionError),
418            value => Err(FromValueError::InvalidType(value.typ())),
419        }
420    }
421}
422impl TryInto<u128> for Value {
423    type Error = FromValueError<<u128 as TryFrom<i64>>::Error>;
424    fn try_into(self) -> Result<u128, Self::Error> {
425        match self {
426            Value::Int(v) => v.try_into().map_err(FromValueError::ConversionError),
427            value => Err(FromValueError::InvalidType(value.typ())),
428        }
429    }
430}
431impl TryInto<i8> for Value {
432    type Error = FromValueError<<i8 as TryFrom<i64>>::Error>;
433    fn try_into(self) -> Result<i8, Self::Error> {
434        match self {
435            Value::Int(v) => v.try_into().map_err(FromValueError::ConversionError),
436            value => Err(FromValueError::InvalidType(value.typ())),
437        }
438    }
439}
440impl TryInto<i16> for Value {
441    type Error = FromValueError<<i16 as TryFrom<i64>>::Error>;
442    fn try_into(self) -> Result<i16, Self::Error> {
443        match self {
444            Value::Int(v) => v.try_into().map_err(FromValueError::ConversionError),
445            value => Err(FromValueError::InvalidType(value.typ())),
446        }
447    }
448}
449impl TryInto<i32> for Value {
450    type Error = FromValueError<<i32 as TryFrom<i64>>::Error>;
451    fn try_into(self) -> Result<i32, Self::Error> {
452        match self {
453            Value::Int(v) => v.try_into().map_err(FromValueError::ConversionError),
454            value => Err(FromValueError::InvalidType(value.typ())),
455        }
456    }
457}
458impl TryInto<i64> for Value {
459    type Error = FromValueError<<i64 as TryFrom<i64>>::Error>;
460    fn try_into(self) -> Result<i64, Self::Error> {
461        match self {
462            Value::Int(v) => Ok(v),
463            value => Err(FromValueError::InvalidType(value.typ())),
464        }
465    }
466}
467impl TryInto<i128> for Value {
468    type Error = FromValueError<<i128 as TryFrom<i64>>::Error>;
469    fn try_into(self) -> Result<i128, Self::Error> {
470        match self {
471            Value::Int(v) => Ok(v as i128),
472            value => Err(FromValueError::InvalidType(value.typ())),
473        }
474    }
475}
476impl TryInto<isize> for Value {
477    type Error = FromValueError<<isize as TryFrom<i64>>::Error>;
478    fn try_into(self) -> Result<isize, Self::Error> {
479        match self {
480            Value::Int(v) => v.try_into().map_err(FromValueError::ConversionError),
481            value => Err(FromValueError::InvalidType(value.typ())),
482        }
483    }
484}
485impl TryInto<char> for Value {
486    type Error = FromValueError<<char as TryFrom<char>>::Error>;
487    fn try_into(self) -> Result<char, Self::Error> {
488        match self {
489            Value::Char(v) => Ok(v),
490            value => Err(FromValueError::InvalidType(value.typ())),
491        }
492    }
493}
494impl TryInto<String> for Value {
495    type Error = FromValueError<<String as TryFrom<String>>::Error>;
496    fn try_into(self) -> Result<String, Self::Error> {
497        match self {
498            Value::String(v) => Ok(v),
499            value => Err(FromValueError::InvalidType(value.typ())),
500        }
501    }
502}
503impl<V: From<Value>> TryInto<Vec<V>> for Value {
504    type Error = FromValueError<<V as TryFrom<V>>::Error>;
505    fn try_into(self) -> Result<Vec<V>, Self::Error> {
506        match self {
507            Value::Vector(vector) => Ok(vector.take().into_iter().map(|v| v.into()).collect()),
508            value => Err(FromValueError::InvalidType(value.typ())),
509        }
510    }
511}
512impl<V: From<Value>> TryInto<HashMap<String, V>> for Value {
513    type Error = FromValueError<<V as TryFrom<V>>::Error>;
514    fn try_into(self) -> Result<HashMap<String, V>, Self::Error> {
515        match self {
516            Value::Object(object) => Ok(object
517                .take()
518                .fields
519                .into_iter()
520                .map(|(k, v)| (k, v.into()))
521                .collect()),
522            value => Err(FromValueError::InvalidType(value.typ())),
523        }
524    }
525}