Skip to main content

simple_expressions/types/
object.rs

1use crate::types::coerce::Context;
2use crate::types::error::Result;
3use crate::types::value::Value;
4use std::any::Any;
5use std::fmt::{Debug, Display, Formatter};
6
7pub trait Object: Any {
8    fn type_name(&self) -> &'static str {
9        "object"
10    }
11    fn get_member(&self, name: &str) -> Result<Value> {
12        Err(crate::types::error::Error::ResolveFailed(name.into()))
13    }
14    fn get_index(&self, index: i64) -> Result<Value> {
15        Err(crate::types::error::Error::NotIndexable(index.to_string()))
16    }
17    fn get_key_value(&self, key: &str) -> Result<Value> {
18        Err(crate::types::error::Error::NotIndexable(key.into()))
19    }
20    fn as_string(&self) -> Option<String> {
21        None
22    }
23    fn as_float(&self) -> Option<f64> {
24        None
25    }
26    fn as_int(&self) -> Option<i64> {
27        None
28    }
29    fn as_bool(&self) -> Option<bool> {
30        None
31    }
32    fn call(&self, _args: &[Value], _cx: &Context) -> Result<Value> {
33        Err(crate::types::error::Error::NotCallable)
34    }
35    fn equals(&self, _other: &Value) -> bool {
36        false
37    }
38    fn display(&self) -> String {
39        self.as_string().unwrap_or_else(|| self.type_name().into())
40    }
41    fn debug(&self) -> String {
42        format!("<{}>", self.type_name())
43    }
44
45    fn as_any(&self) -> &dyn Any;
46    fn as_any_mut(&mut self) -> &mut dyn Any;
47}
48
49impl Display for dyn Object {
50    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
51        f.write_str(&self.display())
52    }
53}
54
55impl Debug for dyn Object {
56    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
57        f.write_str(&self.debug())
58    }
59}