Skip to main content

mirascript_vm/value/
mod.rs

1mod bridge;
2mod convert;
3mod function;
4mod module;
5mod shared;
6
7use std::fmt;
8use std::rc::Rc;
9
10use indexmap::IndexMap;
11
12use crate::{MiraError, Result};
13
14use bridge::{ArrayObject, ExternObject, RecordObject};
15pub use bridge::{MiraArray, MiraBridge, MiraExtern, MiraRecord};
16pub(crate) use function::NativeRuntime;
17pub use function::{MiraCallContext, MiraFunction, MiraNativeFn};
18pub use module::MiraModule;
19pub(crate) use module::ScriptModule;
20pub use shared::MiraShared;
21
22/// A value understood by the Rust VM.
23#[derive(Clone, Default)]
24pub enum MiraAny {
25    #[doc(hidden)]
26    Uninitialized,
27    /// The MiraScript `nil` value.
28    #[default]
29    Nil,
30    /// A boolean value.
31    Boolean(bool),
32    /// A double-precision numeric value.
33    Number(f64),
34    /// An owned UTF-8 string.
35    String(String),
36    /// An owned MiraScript array.
37    Array(Vec<MiraAny>),
38    /// An owned MiraScript record with insertion-ordered keys.
39    Record(IndexMap<String, MiraAny>),
40    /// A callable native or script function.
41    Function(MiraFunction),
42    /// A native or execution-scoped module.
43    Module(MiraModule),
44    /// A live, mutable Rust extern value.
45    Extern(Rc<dyn ExternObject>),
46    #[doc(hidden)]
47    RustRecord(Rc<dyn RecordObject>),
48    #[doc(hidden)]
49    RustArray(Rc<dyn ArrayObject>),
50}
51
52impl MiraAny {
53    /// Return the MiraScript type name for this value.
54    pub fn type_name(&self) -> &'static str {
55        match self {
56            Self::Uninitialized | Self::Nil => "nil",
57            Self::Boolean(_) => "boolean",
58            Self::Number(_) => "number",
59            Self::String(_) => "string",
60            Self::Array(_) | Self::RustArray(_) => "array",
61            Self::Record(_) | Self::RustRecord(_) => "record",
62            Self::Function(_) => "function",
63            Self::Module(_) => "module",
64            Self::Extern(_) => "extern",
65        }
66    }
67
68    /// Wrap a Rust record in a new [`MiraShared`] allocation.
69    pub fn from_record<T: MiraRecord>(value: T) -> Self {
70        Self::from_record_shared(MiraShared::new(value))
71    }
72
73    /// Wrap an existing shared Rust record as a live read-only view.
74    pub fn from_record_shared<T: MiraRecord>(value: MiraShared<T>) -> Self {
75        Self::RustRecord(Rc::new(value))
76    }
77
78    /// Wrap a Rust array in a new [`MiraShared`] allocation.
79    pub fn from_array<T: MiraArray>(value: T) -> Self {
80        Self::from_array_shared(MiraShared::new(value))
81    }
82
83    /// Wrap an existing shared Rust array as a live read-only view.
84    pub fn from_array_shared<T: MiraArray>(value: MiraShared<T>) -> Self {
85        Self::RustArray(Rc::new(value))
86    }
87
88    /// Wrap a Rust extern in a new [`MiraShared`] allocation.
89    pub fn from_extern<T: MiraExtern>(value: T) -> Self {
90        Self::from_extern_shared(MiraShared::new(value))
91    }
92
93    /// Wrap an existing shared Rust extern as a live mutable object.
94    pub fn from_extern_shared<T: MiraExtern>(value: MiraShared<T>) -> Self {
95        Self::Extern(Rc::new(value))
96    }
97
98    /// Return whether this value is initialized and safe to expose to host code.
99    pub fn is_initialized(&self) -> bool {
100        !matches!(self, Self::Uninitialized)
101    }
102
103    pub(crate) fn into_element(self) -> Result<Self> {
104        match self {
105            Self::Uninitialized => Err(MiraError::runtime("Uninitialized value")),
106            Self::Function(_) | Self::Module(_) | Self::Extern(_) => Ok(Self::Nil),
107            value => Ok(value),
108        }
109    }
110
111    pub(crate) fn contains_script_reference(&self, execution: u64) -> bool {
112        match self {
113            Self::Function(MiraFunction::Script {
114                execution: owner, ..
115            }) => *owner == execution,
116            Self::Module(MiraModule::Script(module)) => module.execution == execution,
117            Self::Array(values) => values
118                .iter()
119                .any(|value| value.contains_script_reference(execution)),
120            Self::Record(values) => values
121                .values()
122                .any(|value| value.contains_script_reference(execution)),
123            _ => false,
124        }
125    }
126
127    pub(crate) fn record_keys(&self) -> Result<Option<Vec<String>>> {
128        match self {
129            Self::Record(record) => Ok(Some(record.keys().cloned().collect())),
130            Self::RustRecord(record) => record.keys().map(Some),
131            _ => Ok(None),
132        }
133    }
134
135    pub(crate) fn record_get(&self, key: &str) -> Result<Option<MiraAny>> {
136        match self {
137            Self::Record(record) => Ok(record.get(key).cloned()),
138            Self::RustRecord(record) => record.get(key),
139            _ => Ok(None),
140        }
141    }
142
143    pub(crate) fn array_len(&self) -> Result<Option<usize>> {
144        match self {
145            Self::Array(array) => Ok(Some(array.len())),
146            Self::RustArray(array) => array.len().map(Some),
147            Self::Extern(value) => value.array_len(),
148            _ => Ok(None),
149        }
150    }
151
152    pub(crate) fn array_get(&self, index: usize) -> Result<Option<MiraAny>> {
153        match self {
154            Self::Array(array) => Ok(array.get(index).cloned()),
155            Self::RustArray(array) => array.get(index),
156            Self::Extern(value) => value.get_index(index),
157            _ => Ok(None),
158        }
159    }
160}
161
162fn same_record(a: &MiraAny, b: &MiraAny) -> bool {
163    let Ok(Some(a_keys)) = a.record_keys() else {
164        return false;
165    };
166    let Ok(Some(b_keys)) = b.record_keys() else {
167        return false;
168    };
169    if a_keys.len() != b_keys.len() {
170        return false;
171    }
172    a_keys.into_iter().all(|key| {
173        if !b_keys.contains(&key) {
174            return false;
175        }
176        match (
177            crate::operations::get(a, &key),
178            crate::operations::get(b, &key),
179        ) {
180            (Ok(a), Ok(b)) => a == b,
181            _ => false,
182        }
183    })
184}
185
186fn same_array(a: &MiraAny, b: &MiraAny) -> bool {
187    let (Ok(Some(a_len)), Ok(Some(b_len))) = (a.array_len(), b.array_len()) else {
188        return false;
189    };
190    if a_len != b_len {
191        return false;
192    }
193    (0..a_len).all(|index| match (a.array_get(index), b.array_get(index)) {
194        (Ok(a), Ok(b)) => a.unwrap_or(MiraAny::Nil) == b.unwrap_or(MiraAny::Nil),
195        _ => false,
196    })
197}
198
199impl PartialEq for MiraAny {
200    fn eq(&self, other: &Self) -> bool {
201        match (self, other) {
202            (Self::Uninitialized, Self::Uninitialized) | (Self::Nil, Self::Nil) => true,
203            (Self::Boolean(a), Self::Boolean(b)) => a == b,
204            (Self::Number(a), Self::Number(b)) => a == b || (a.is_nan() && b.is_nan()),
205            (Self::String(a), Self::String(b)) => a == b,
206            (Self::Array(_), Self::Array(_))
207            | (Self::Array(_), Self::RustArray(_))
208            | (Self::RustArray(_), Self::Array(_))
209            | (Self::RustArray(_), Self::RustArray(_)) => same_array(self, other),
210            (Self::Record(_), Self::Record(_))
211            | (Self::Record(_), Self::RustRecord(_))
212            | (Self::RustRecord(_), Self::Record(_))
213            | (Self::RustRecord(_), Self::RustRecord(_)) => same_record(self, other),
214            (Self::Function(a), Self::Function(b)) => a.same(b),
215            (Self::Module(a), Self::Module(b)) => a.same(b),
216            (Self::Extern(a), Self::Extern(b)) => a.identity() == b.identity(),
217            _ => false,
218        }
219    }
220}
221
222impl fmt::Debug for MiraAny {
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        match self {
225            Self::Uninitialized => f.write_str("Uninitialized"),
226            Self::Nil => f.write_str("Nil"),
227            Self::Boolean(value) => f.debug_tuple("Boolean").field(value).finish(),
228            Self::Number(value) => f.debug_tuple("Number").field(value).finish(),
229            Self::String(value) => f.debug_tuple("String").field(value).finish(),
230            Self::Array(value) => f.debug_tuple("Array").field(value).finish(),
231            Self::Record(value) => f.debug_tuple("Record").field(value).finish(),
232            Self::Function(value) => f.debug_tuple("Function").field(value).finish(),
233            Self::Module(value) => f.debug_tuple("Module").field(value).finish(),
234            Self::Extern(value) => f
235                .debug_struct("Extern")
236                .field("tag", &value.tag().unwrap_or_else(|_| "<borrowed>".into()))
237                .field("identity", &value.identity())
238                .finish(),
239            Self::RustRecord(value) => f
240                .debug_struct("RustRecord")
241                .field("tag", &value.tag())
242                .field("identity", &value.identity())
243                .finish(),
244            Self::RustArray(value) => f
245                .debug_struct("RustArray")
246                .field("tag", &value.tag())
247                .field("identity", &value.identity())
248                .finish(),
249        }
250    }
251}