Skip to main content

mirascript_vm/value/types/
value.rs

1use std::fmt;
2
3use crate::{MiraType, value::arena::MiraHandle};
4
5use super::{MiraArray, MiraExtern, MiraFunction, MiraModule, MiraRecord};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8enum ValueTag {
9    Nil,
10    Boolean,
11    StaticStr,
12    String,
13    Array,
14    Record,
15    Function,
16    Module,
17    Extern,
18    Uninitialized,
19}
20
21impl ValueTag {
22    #[inline]
23    fn header(self) -> u16 {
24        let (negative, value) = match self {
25            Self::Nil => (false, 1),
26            Self::Boolean => (false, 2),
27            Self::StaticStr => (false, 3),
28            Self::String => (false, 4),
29            Self::Array => (false, 5),
30            Self::Record => (false, 6),
31            Self::Function => (false, 7),
32            Self::Module => (true, 1),
33            Self::Extern => (true, 2),
34            Self::Uninitialized => (true, 3),
35        };
36        0x7FF8 | (u16::from(negative) << 15) | value
37    }
38
39    #[inline]
40    fn from_header(header: u16) -> Option<Self> {
41        if header & 0x7FF8 != 0x7FF8 {
42            return None;
43        }
44        Some(match (header & 0x8000 != 0, (header & 0x0007) as u8) {
45            (false, 1) => Self::Nil,
46            (false, 2) => Self::Boolean,
47            (false, 3) => Self::StaticStr,
48            (false, 4) => Self::String,
49            (false, 5) => Self::Array,
50            (false, 6) => Self::Record,
51            (false, 7) => Self::Function,
52            (true, 1) => Self::Module,
53            (true, 2) => Self::Extern,
54            (true, 3) => Self::Uninitialized,
55            _ => return None,
56        })
57    }
58}
59
60/// The raw bit representation used by [`MiraValue`].
61///
62/// Numeric values use their `f64` bit pattern. Tagged values use a quiet NaN
63/// header and store a fixed little-endian six-byte payload in the low 48 bits.
64#[repr(transparent)]
65#[derive(Clone, Copy)]
66struct RawValue(u64);
67
68impl RawValue {
69    const QUIET_NAN: u64 = 0x7FF8_0000_0000_0000;
70    const SIGN_MASK: u64 = 0x8000_0000_0000_0000;
71    const PAYLOAD_MASK: u64 = 0x0000_FFFF_FFFF_FFFF;
72
73    #[inline]
74    fn number(value: f64) -> Self {
75        let bits = value.to_bits();
76        if value.is_nan() {
77            Self(Self::QUIET_NAN | (bits & Self::SIGN_MASK))
78        } else {
79            Self(bits)
80        }
81    }
82
83    #[inline]
84    fn tagged(tag: ValueTag, payload: [u8; 6]) -> Self {
85        Self((u64::from(tag.header()) << 48) | Self::payload_bits(payload))
86    }
87
88    #[inline]
89    fn empty(tag: ValueTag) -> Self {
90        Self::tagged(tag, [0; 6])
91    }
92
93    #[inline]
94    fn tag(self) -> Option<ValueTag> {
95        ValueTag::from_header((self.0 >> 48) as u16)
96    }
97
98    #[inline]
99    fn payload(self) -> [u8; 6] {
100        let bytes = (self.0 & Self::PAYLOAD_MASK).to_le_bytes();
101        bytes[..6].try_into().expect("six-byte MiraValue payload")
102    }
103
104    #[inline]
105    fn payload_bits(payload: [u8; 6]) -> u64 {
106        u64::from_le_bytes([
107            payload[0], payload[1], payload[2], payload[3], payload[4], payload[5], 0, 0,
108        ])
109    }
110}
111
112/// A decoded view of a compact [`MiraValue`].
113#[derive(Clone, Copy, Debug, PartialEq)]
114pub(crate) enum MiraValueKind {
115    Nil,
116    Boolean(bool),
117    Number(f64),
118    StaticStr(&'static &'static str),
119    String(MiraHandle<String>),
120    Array(MiraHandle<dyn MiraArray>),
121    Record(MiraHandle<dyn MiraRecord>),
122    Function(MiraHandle<dyn MiraFunction>),
123    Module(MiraHandle<dyn MiraModule>),
124    Extern(MiraHandle<dyn MiraExtern>),
125}
126
127/// A compact value understood by the Rust VM.
128///
129/// Numbers are stored inline as `f64`. Other values use checked tags and a
130/// 48-bit payload in a NaN-box. Runtime-owned payloads remain checked handles
131/// into a [`crate::Runtime`] arena.
132#[repr(C, align(8))]
133#[derive(Clone, Copy)]
134pub struct MiraValue(u64);
135
136const _: () = assert!(std::mem::size_of::<MiraValue>() == 8);
137const _: () = assert!(std::mem::align_of::<MiraValue>() == 8);
138
139impl MiraValue {
140    #[inline]
141    fn from_raw(raw: RawValue) -> Self {
142        Self(raw.0)
143    }
144
145    #[inline]
146    fn raw(self) -> RawValue {
147        RawValue(self.0)
148    }
149
150    #[inline]
151    fn empty(tag: ValueTag) -> Self {
152        Self::from_raw(RawValue::empty(tag))
153    }
154
155    #[inline]
156    fn handle<T: std::any::Any + ?Sized>(tag: ValueTag, handle: MiraHandle<T>) -> Self {
157        Self::from_raw(RawValue::tagged(tag, handle.payload()))
158    }
159
160    #[inline]
161    pub(super) fn boxed_nil() -> Self {
162        Self::empty(ValueTag::Nil)
163    }
164
165    #[inline]
166    pub(super) fn boxed_boolean(value: bool) -> Self {
167        Self::from_raw(RawValue::tagged(
168            ValueTag::Boolean,
169            [u8::from(value), 0, 0, 0, 0, 0],
170        ))
171    }
172
173    #[inline]
174    pub(super) fn boxed_number(value: f64) -> Self {
175        Self::from_raw(RawValue::number(value))
176    }
177
178    #[inline]
179    pub(super) fn boxed_static_str(value: &'static &'static str) -> Self {
180        let address = (value as *const &'static str).expose_provenance();
181        assert!(
182            (address as u64) <= RawValue::PAYLOAD_MASK,
183            "Pointer too large to store in MiraValue"
184        );
185        Self::from_raw(RawValue::tagged(
186            ValueTag::StaticStr,
187            Self::address_payload(address),
188        ))
189    }
190
191    #[inline]
192    pub(crate) fn from_string_handle(handle: MiraHandle<String>) -> Self {
193        Self::handle(ValueTag::String, handle)
194    }
195
196    #[inline]
197    pub(crate) fn from_array_handle(handle: MiraHandle<dyn MiraArray>) -> Self {
198        Self::handle(ValueTag::Array, handle)
199    }
200
201    #[inline]
202    pub(crate) fn from_record_handle(handle: MiraHandle<dyn MiraRecord>) -> Self {
203        Self::handle(ValueTag::Record, handle)
204    }
205
206    #[inline]
207    pub(crate) fn from_function_handle(handle: MiraHandle<dyn MiraFunction>) -> Self {
208        Self::handle(ValueTag::Function, handle)
209    }
210
211    #[inline]
212    pub(crate) fn from_module_handle(handle: MiraHandle<dyn MiraModule>) -> Self {
213        Self::handle(ValueTag::Module, handle)
214    }
215
216    #[inline]
217    #[allow(dead_code)]
218    pub(crate) fn from_extern_handle(handle: MiraHandle<dyn MiraExtern>) -> Self {
219        Self::handle(ValueTag::Extern, handle)
220    }
221
222    #[inline]
223    pub(crate) fn uninitialized() -> Self {
224        Self::empty(ValueTag::Uninitialized)
225    }
226
227    #[inline]
228    pub(crate) fn is_uninitialized(&self) -> bool {
229        self.tag() == Some(ValueTag::Uninitialized)
230    }
231
232    #[inline]
233    pub(super) fn is_float(&self) -> bool {
234        self.tag().is_none()
235    }
236
237    #[inline]
238    fn tag(&self) -> Option<ValueTag> {
239        self.raw().tag()
240    }
241
242    #[inline]
243    pub(super) fn boxed_is_nil(&self) -> bool {
244        self.tag() == Some(ValueTag::Nil)
245    }
246
247    #[inline]
248    pub(super) fn boxed_boolean_value(&self) -> Option<bool> {
249        (self.tag() == Some(ValueTag::Boolean)).then(|| self.raw().payload()[0] != 0)
250    }
251
252    #[inline]
253    pub(super) fn boxed_number_value(&self) -> Option<f64> {
254        self.is_float().then_some(f64::from_bits(self.0))
255    }
256
257    fn address_payload(address: usize) -> [u8; 6] {
258        let bytes = (address as u64).to_le_bytes();
259        bytes[..6].try_into().expect("six-byte pointer payload")
260    }
261
262    fn payload_address(payload: [u8; 6]) -> usize {
263        usize::try_from(RawValue::payload_bits(payload)).expect("pointer payload fits usize")
264    }
265
266    #[inline]
267    pub(crate) fn kind(&self) -> MiraValueKind {
268        let Some(tag) = self.tag() else {
269            return MiraValueKind::Number(f64::from_bits(self.0));
270        };
271
272        let payload = self.raw().payload();
273        match tag {
274            ValueTag::Nil => MiraValueKind::Nil,
275            ValueTag::Boolean => MiraValueKind::Boolean(payload[0] != 0),
276            ValueTag::StaticStr => {
277                let address = Self::payload_address(payload);
278                let pointer = std::ptr::with_exposed_provenance::<&'static str>(address);
279                // SAFETY: `str` only accepts an outer static reference. Its
280                // provenance was exposed by the constructor and restored here,
281                // and the checked tag prevents interpreting another payload.
282                MiraValueKind::StaticStr(unsafe { &*pointer })
283            }
284            ValueTag::String => MiraValueKind::String(MiraHandle::from_payload(payload)),
285            ValueTag::Array => MiraValueKind::Array(MiraHandle::from_payload(payload)),
286            ValueTag::Record => MiraValueKind::Record(MiraHandle::from_payload(payload)),
287            ValueTag::Function => MiraValueKind::Function(MiraHandle::from_payload(payload)),
288            ValueTag::Module => MiraValueKind::Module(MiraHandle::from_payload(payload)),
289            ValueTag::Extern => MiraValueKind::Extern(MiraHandle::from_payload(payload)),
290            ValueTag::Uninitialized => panic!("uninitialized register escaped as MiraValue"),
291        }
292    }
293
294    /// Return this value's MiraScript category.
295    #[inline]
296    pub fn value_type(&self) -> MiraType {
297        match self.kind() {
298            MiraValueKind::Nil => MiraType::Nil,
299            MiraValueKind::Boolean(_) => MiraType::Boolean,
300            MiraValueKind::Number(_) => MiraType::Number,
301            MiraValueKind::StaticStr(_) | MiraValueKind::String(_) => MiraType::String,
302            MiraValueKind::Array(_) => MiraType::Array,
303            MiraValueKind::Record(_) => MiraType::Record,
304            MiraValueKind::Function(_) => MiraType::Function,
305            MiraValueKind::Module(_) => MiraType::Module,
306            MiraValueKind::Extern(_) => MiraType::Extern,
307        }
308    }
309
310    /// Return the MiraScript type name for this value.
311    #[inline]
312    pub fn type_name(&self) -> &'static str {
313        self.value_type().name()
314    }
315}
316
317impl Default for MiraValue {
318    #[inline]
319    fn default() -> Self {
320        Self::empty(ValueTag::Nil)
321    }
322}
323
324impl PartialEq for MiraValue {
325    #[inline]
326    fn eq(&self, other: &Self) -> bool {
327        self.kind() == other.kind()
328    }
329}
330
331impl fmt::Debug for MiraValue {
332    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
333        match self.kind() {
334            MiraValueKind::Nil => formatter.write_str("Nil"),
335            MiraValueKind::Boolean(value) => {
336                formatter.debug_tuple("Boolean").field(&value).finish()
337            }
338            MiraValueKind::Number(value) => formatter.debug_tuple("Number").field(&value).finish(),
339            MiraValueKind::StaticStr(value) => {
340                formatter.debug_tuple("StaticStr").field(&value).finish()
341            }
342            MiraValueKind::String(value) => formatter.debug_tuple("String").field(&value).finish(),
343            MiraValueKind::Array(value) => formatter.debug_tuple("Array").field(&value).finish(),
344            MiraValueKind::Record(value) => formatter.debug_tuple("Record").field(&value).finish(),
345            MiraValueKind::Function(value) => {
346                formatter.debug_tuple("Function").field(&value).finish()
347            }
348            MiraValueKind::Module(value) => formatter.debug_tuple("Module").field(&value).finish(),
349            MiraValueKind::Extern(value) => formatter.debug_tuple("Extern").field(&value).finish(),
350        }
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357    use crate::Runtime;
358
359    static STATIC_TEXT: &str = "static text";
360
361    #[test]
362    fn raw_value_layout_roundtrips() {
363        let payload = [1, 2, 3, 4, 5, 6];
364        let raw = RawValue::tagged(ValueTag::Nil, payload);
365
366        assert_eq!(raw.0, 0x7FF9_0605_0403_0201);
367        assert_eq!(raw.tag(), Some(ValueTag::Nil));
368        assert_eq!(raw.payload(), payload);
369
370        for tag in [
371            ValueTag::Boolean,
372            ValueTag::StaticStr,
373            ValueTag::String,
374            ValueTag::Array,
375            ValueTag::Record,
376            ValueTag::Function,
377            ValueTag::Module,
378            ValueTag::Extern,
379            ValueTag::Uninitialized,
380        ] {
381            let raw = RawValue::tagged(tag, payload);
382            assert_eq!(raw.tag(), Some(tag));
383            assert_eq!(raw.payload(), payload);
384        }
385    }
386
387    #[test]
388    fn scalar_nan_box_roundtrips() {
389        for number in [0.0, -0.0, 42.5, f64::INFINITY, f64::NEG_INFINITY] {
390            assert_eq!(
391                MiraValue::number(number).as_number().unwrap().to_bits(),
392                number.to_bits()
393            );
394        }
395
396        for nan in [f64::NAN, -f64::NAN] {
397            let decoded = MiraValue::number(nan).as_number().unwrap();
398            assert!(decoded.is_nan());
399            assert_eq!(decoded.is_sign_negative(), nan.is_sign_negative());
400        }
401
402        assert!(MiraValue::nil().is_nil());
403        assert_eq!(MiraValue::boolean(false).as_boolean(), Some(false));
404        assert_eq!(MiraValue::boolean(true).as_boolean(), Some(true));
405    }
406
407    #[test]
408    fn static_string_pointer_roundtrips() {
409        let runtime = Runtime::new();
410        let value = MiraValue::str(&STATIC_TEXT);
411
412        assert_eq!(value.as_str(&runtime).unwrap(), Some(STATIC_TEXT));
413    }
414}