Skip to main content

mirascript_vm/value/arena/
handle.rs

1use std::{any::Any, fmt, hash, marker::PhantomData};
2
3use crate::MiraExtern;
4
5use super::{ArenaKey, MiraArray, MiraFunction, MiraModule, MiraRecord, MiraValue};
6
7/// A compact, runtime-checked handle to an arena-managed value.
8pub struct MiraHandle<T: Any + ?Sized> {
9    pub(super) key: ArenaKey,
10    marker: PhantomData<&'static T>,
11}
12
13impl<T: Any + ?Sized> Copy for MiraHandle<T> {}
14
15impl<T: Any + ?Sized> Clone for MiraHandle<T> {
16    fn clone(&self) -> Self {
17        *self
18    }
19}
20
21impl<T: Any + ?Sized> fmt::Debug for MiraHandle<T> {
22    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23        formatter
24            .debug_struct("MiraHandle")
25            .field("arena", &self.key.arena_id().get())
26            .field("slot", &self.key.index())
27            .finish()
28    }
29}
30
31impl<T: Any + ?Sized> PartialEq for MiraHandle<T> {
32    fn eq(&self, other: &Self) -> bool {
33        self.key == other.key
34    }
35}
36
37impl<T: Any + ?Sized> Eq for MiraHandle<T> {}
38
39impl<T: Any + ?Sized> hash::Hash for MiraHandle<T> {
40    fn hash<H: hash::Hasher>(&self, state: &mut H) {
41        self.key.hash(state);
42    }
43}
44
45impl<T: Any + ?Sized> MiraHandle<T> {
46    pub(super) const fn new(key: ArenaKey) -> Self {
47        Self {
48            key,
49            marker: PhantomData,
50        }
51    }
52
53    pub(crate) const fn payload(self) -> [u8; 6] {
54        self.key.payload()
55    }
56
57    pub(crate) const fn from_payload(payload: [u8; 6]) -> Self {
58        Self::new(ArenaKey::from_payload(payload))
59    }
60}
61
62macro_rules! impl_cast {
63    ($t:ty, $f:ident) => {
64        impl From<MiraHandle<$t>> for MiraValue {
65            fn from(value: MiraHandle<$t>) -> Self {
66                Self::$f(value)
67            }
68        }
69    };
70}
71
72impl_cast!(dyn MiraArray, array);
73impl_cast!(dyn MiraRecord, record);
74impl_cast!(dyn MiraFunction, function);
75impl_cast!(dyn MiraModule, module);
76impl_cast!(String, string);
77
78macro_rules! impl_handle_cast {
79    ($trait:path, $erase:ident) => {
80        impl<T: $trait + ?Sized> MiraHandle<T> {
81            /// Erase the concrete Rust type while preserving its MiraScript category.
82            pub const fn $erase(self) -> MiraHandle<dyn $trait> {
83                MiraHandle::new(self.key)
84            }
85        }
86
87        impl MiraHandle<dyn $trait> {
88            /// Reinterpret an erased handle as a concrete typed handle.
89            ///
90            /// The subsequent Runtime lookup still validates the concrete type,
91            /// so a wrong generated cast returns an error rather than dereferencing
92            /// an invalid pointer.
93            #[doc(hidden)]
94            pub unsafe fn upcast<T: $trait + ?Sized>(self) -> MiraHandle<T> {
95                MiraHandle::new(self.key)
96            }
97        }
98    };
99}
100
101impl_handle_cast!(MiraArray, erase_array);
102impl_handle_cast!(MiraRecord, erase_record);
103impl_handle_cast!(MiraFunction, erase_function);
104impl_handle_cast!(MiraModule, erase_module);
105
106/// A handle to a MiraScript string value.
107pub type MiraStringHandle = MiraHandle<String>;
108/// A handle to a MiraScript array value.
109pub type MiraArrayHandle = MiraHandle<dyn MiraArray>;
110/// A handle to a MiraScript record value.
111pub type MiraRecordHandle = MiraHandle<dyn MiraRecord>;
112/// A handle to a MiraScript function value.
113pub type MiraFunctionHandle = MiraHandle<dyn MiraFunction>;
114/// A handle to a MiraScript module value.
115pub type MiraModuleHandle = MiraHandle<dyn MiraModule>;
116/// A handle to a MiraScript extern value.
117pub type MiraExternHandle = MiraHandle<dyn MiraExtern>;
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use crate::value::arena::ArenaId;
123
124    impl<T: Any + ?Sized> MiraHandle<T> {
125        pub(crate) fn empty() -> Self {
126            Self {
127                key: ArenaKey::new(ArenaId::from(1), 1, "test").unwrap(),
128                marker: PhantomData,
129            }
130        }
131    }
132
133    #[test]
134    fn test_fmt() {
135        let handle =
136            MiraHandle::<dyn MiraArray>::new(ArenaKey::new(ArenaId::from(1), 2, "array").unwrap());
137        let expected = "MiraHandle { arena: 1, slot: 2 }";
138        assert_eq!(format!("{handle:?}"), expected);
139    }
140}