mirascript-vm 0.1.89

Native Rust virtual machine for MiraScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use std::fmt;

use crate::{MiraType, value::arena::MiraHandle};

use super::{MiraArray, MiraExtern, MiraFunction, MiraModule, MiraRecord};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ValueTag {
    Nil,
    Boolean,
    StaticStr,
    String,
    Array,
    Record,
    Function,
    Module,
    Extern,
    Uninitialized,
}

impl ValueTag {
    #[inline]
    fn header(self) -> u16 {
        let (negative, value) = match self {
            Self::Nil => (false, 1),
            Self::Boolean => (false, 2),
            Self::StaticStr => (false, 3),
            Self::String => (false, 4),
            Self::Array => (false, 5),
            Self::Record => (false, 6),
            Self::Function => (false, 7),
            Self::Module => (true, 1),
            Self::Extern => (true, 2),
            Self::Uninitialized => (true, 3),
        };
        0x7FF8 | (u16::from(negative) << 15) | value
    }

    #[inline]
    fn from_header(header: u16) -> Option<Self> {
        if header & 0x7FF8 != 0x7FF8 {
            return None;
        }
        Some(match (header & 0x8000 != 0, (header & 0x0007) as u8) {
            (false, 1) => Self::Nil,
            (false, 2) => Self::Boolean,
            (false, 3) => Self::StaticStr,
            (false, 4) => Self::String,
            (false, 5) => Self::Array,
            (false, 6) => Self::Record,
            (false, 7) => Self::Function,
            (true, 1) => Self::Module,
            (true, 2) => Self::Extern,
            (true, 3) => Self::Uninitialized,
            _ => return None,
        })
    }
}

/// The raw bit representation used by [`MiraValue`].
///
/// Numeric values use their `f64` bit pattern. Tagged values use a quiet NaN
/// header and store a fixed little-endian six-byte payload in the low 48 bits.
#[repr(transparent)]
#[derive(Clone, Copy)]
struct RawValue(u64);

impl RawValue {
    const QUIET_NAN: u64 = 0x7FF8_0000_0000_0000;
    const SIGN_MASK: u64 = 0x8000_0000_0000_0000;
    const PAYLOAD_MASK: u64 = 0x0000_FFFF_FFFF_FFFF;

    #[inline]
    fn number(value: f64) -> Self {
        let bits = value.to_bits();
        if value.is_nan() {
            Self(Self::QUIET_NAN | (bits & Self::SIGN_MASK))
        } else {
            Self(bits)
        }
    }

    #[inline]
    fn tagged(tag: ValueTag, payload: [u8; 6]) -> Self {
        Self((u64::from(tag.header()) << 48) | Self::payload_bits(payload))
    }

    #[inline]
    fn empty(tag: ValueTag) -> Self {
        Self::tagged(tag, [0; 6])
    }

    #[inline]
    fn tag(self) -> Option<ValueTag> {
        ValueTag::from_header((self.0 >> 48) as u16)
    }

    #[inline]
    fn payload(self) -> [u8; 6] {
        let bytes = (self.0 & Self::PAYLOAD_MASK).to_le_bytes();
        bytes[..6].try_into().expect("six-byte MiraValue payload")
    }

    #[inline]
    fn payload_bits(payload: [u8; 6]) -> u64 {
        u64::from_le_bytes([
            payload[0], payload[1], payload[2], payload[3], payload[4], payload[5], 0, 0,
        ])
    }
}

/// A decoded view of a compact [`MiraValue`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum MiraValueKind {
    Nil,
    Boolean(bool),
    Number(f64),
    StaticStr(&'static &'static str),
    String(MiraHandle<String>),
    Array(MiraHandle<dyn MiraArray>),
    Record(MiraHandle<dyn MiraRecord>),
    Function(MiraHandle<dyn MiraFunction>),
    Module(MiraHandle<dyn MiraModule>),
    Extern(MiraHandle<dyn MiraExtern>),
}

/// A compact value understood by the Rust VM.
///
/// Numbers are stored inline as `f64`. Other values use checked tags and a
/// 48-bit payload in a NaN-box. Runtime-owned payloads remain checked handles
/// into a [`crate::Runtime`] arena.
#[repr(C, align(8))]
#[derive(Clone, Copy)]
pub struct MiraValue(u64);

const _: () = assert!(std::mem::size_of::<MiraValue>() == 8);
const _: () = assert!(std::mem::align_of::<MiraValue>() == 8);

impl MiraValue {
    #[inline]
    fn from_raw(raw: RawValue) -> Self {
        Self(raw.0)
    }

    #[inline]
    fn raw(self) -> RawValue {
        RawValue(self.0)
    }

    #[inline]
    fn empty(tag: ValueTag) -> Self {
        Self::from_raw(RawValue::empty(tag))
    }

    #[inline]
    fn handle<T: std::any::Any + ?Sized>(tag: ValueTag, handle: MiraHandle<T>) -> Self {
        Self::from_raw(RawValue::tagged(tag, handle.payload()))
    }

    #[inline]
    pub(super) fn boxed_nil() -> Self {
        Self::empty(ValueTag::Nil)
    }

    #[inline]
    pub(super) fn boxed_boolean(value: bool) -> Self {
        Self::from_raw(RawValue::tagged(
            ValueTag::Boolean,
            [u8::from(value), 0, 0, 0, 0, 0],
        ))
    }

    #[inline]
    pub(super) fn boxed_number(value: f64) -> Self {
        Self::from_raw(RawValue::number(value))
    }

    #[inline]
    pub(super) fn boxed_static_str(value: &'static &'static str) -> Self {
        let address = (value as *const &'static str).expose_provenance();
        assert!(
            (address as u64) <= RawValue::PAYLOAD_MASK,
            "Pointer too large to store in MiraValue"
        );
        Self::from_raw(RawValue::tagged(
            ValueTag::StaticStr,
            Self::address_payload(address),
        ))
    }

    #[inline]
    pub(crate) fn from_string_handle(handle: MiraHandle<String>) -> Self {
        Self::handle(ValueTag::String, handle)
    }

    #[inline]
    pub(crate) fn from_array_handle(handle: MiraHandle<dyn MiraArray>) -> Self {
        Self::handle(ValueTag::Array, handle)
    }

    #[inline]
    pub(crate) fn from_record_handle(handle: MiraHandle<dyn MiraRecord>) -> Self {
        Self::handle(ValueTag::Record, handle)
    }

    #[inline]
    pub(crate) fn from_function_handle(handle: MiraHandle<dyn MiraFunction>) -> Self {
        Self::handle(ValueTag::Function, handle)
    }

    #[inline]
    pub(crate) fn from_module_handle(handle: MiraHandle<dyn MiraModule>) -> Self {
        Self::handle(ValueTag::Module, handle)
    }

    #[inline]
    #[allow(dead_code)]
    pub(crate) fn from_extern_handle(handle: MiraHandle<dyn MiraExtern>) -> Self {
        Self::handle(ValueTag::Extern, handle)
    }

    #[inline]
    pub(crate) fn uninitialized() -> Self {
        Self::empty(ValueTag::Uninitialized)
    }

    #[inline]
    pub(crate) fn is_uninitialized(&self) -> bool {
        self.tag() == Some(ValueTag::Uninitialized)
    }

    #[inline]
    pub(super) fn is_float(&self) -> bool {
        self.tag().is_none()
    }

    #[inline]
    fn tag(&self) -> Option<ValueTag> {
        self.raw().tag()
    }

    #[inline]
    pub(super) fn boxed_is_nil(&self) -> bool {
        self.tag() == Some(ValueTag::Nil)
    }

    #[inline]
    pub(super) fn boxed_boolean_value(&self) -> Option<bool> {
        (self.tag() == Some(ValueTag::Boolean)).then(|| self.raw().payload()[0] != 0)
    }

    #[inline]
    pub(super) fn boxed_number_value(&self) -> Option<f64> {
        self.is_float().then_some(f64::from_bits(self.0))
    }

    fn address_payload(address: usize) -> [u8; 6] {
        let bytes = (address as u64).to_le_bytes();
        bytes[..6].try_into().expect("six-byte pointer payload")
    }

    fn payload_address(payload: [u8; 6]) -> usize {
        usize::try_from(RawValue::payload_bits(payload)).expect("pointer payload fits usize")
    }

    #[inline]
    pub(crate) fn kind(&self) -> MiraValueKind {
        let Some(tag) = self.tag() else {
            return MiraValueKind::Number(f64::from_bits(self.0));
        };

        let payload = self.raw().payload();
        match tag {
            ValueTag::Nil => MiraValueKind::Nil,
            ValueTag::Boolean => MiraValueKind::Boolean(payload[0] != 0),
            ValueTag::StaticStr => {
                let address = Self::payload_address(payload);
                let pointer = std::ptr::with_exposed_provenance::<&'static str>(address);
                // SAFETY: `str` only accepts an outer static reference. Its
                // provenance was exposed by the constructor and restored here,
                // and the checked tag prevents interpreting another payload.
                MiraValueKind::StaticStr(unsafe { &*pointer })
            }
            ValueTag::String => MiraValueKind::String(MiraHandle::from_payload(payload)),
            ValueTag::Array => MiraValueKind::Array(MiraHandle::from_payload(payload)),
            ValueTag::Record => MiraValueKind::Record(MiraHandle::from_payload(payload)),
            ValueTag::Function => MiraValueKind::Function(MiraHandle::from_payload(payload)),
            ValueTag::Module => MiraValueKind::Module(MiraHandle::from_payload(payload)),
            ValueTag::Extern => MiraValueKind::Extern(MiraHandle::from_payload(payload)),
            ValueTag::Uninitialized => panic!("uninitialized register escaped as MiraValue"),
        }
    }

    /// Return this value's MiraScript category.
    #[inline]
    pub fn value_type(&self) -> MiraType {
        match self.kind() {
            MiraValueKind::Nil => MiraType::Nil,
            MiraValueKind::Boolean(_) => MiraType::Boolean,
            MiraValueKind::Number(_) => MiraType::Number,
            MiraValueKind::StaticStr(_) | MiraValueKind::String(_) => MiraType::String,
            MiraValueKind::Array(_) => MiraType::Array,
            MiraValueKind::Record(_) => MiraType::Record,
            MiraValueKind::Function(_) => MiraType::Function,
            MiraValueKind::Module(_) => MiraType::Module,
            MiraValueKind::Extern(_) => MiraType::Extern,
        }
    }

    /// Return the MiraScript type name for this value.
    #[inline]
    pub fn type_name(&self) -> &'static str {
        self.value_type().name()
    }
}

impl Default for MiraValue {
    #[inline]
    fn default() -> Self {
        Self::empty(ValueTag::Nil)
    }
}

impl PartialEq for MiraValue {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.kind() == other.kind()
    }
}

impl fmt::Debug for MiraValue {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind() {
            MiraValueKind::Nil => formatter.write_str("Nil"),
            MiraValueKind::Boolean(value) => {
                formatter.debug_tuple("Boolean").field(&value).finish()
            }
            MiraValueKind::Number(value) => formatter.debug_tuple("Number").field(&value).finish(),
            MiraValueKind::StaticStr(value) => {
                formatter.debug_tuple("StaticStr").field(&value).finish()
            }
            MiraValueKind::String(value) => formatter.debug_tuple("String").field(&value).finish(),
            MiraValueKind::Array(value) => formatter.debug_tuple("Array").field(&value).finish(),
            MiraValueKind::Record(value) => formatter.debug_tuple("Record").field(&value).finish(),
            MiraValueKind::Function(value) => {
                formatter.debug_tuple("Function").field(&value).finish()
            }
            MiraValueKind::Module(value) => formatter.debug_tuple("Module").field(&value).finish(),
            MiraValueKind::Extern(value) => formatter.debug_tuple("Extern").field(&value).finish(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Runtime;

    static STATIC_TEXT: &str = "static text";

    #[test]
    fn raw_value_layout_roundtrips() {
        let payload = [1, 2, 3, 4, 5, 6];
        let raw = RawValue::tagged(ValueTag::Nil, payload);

        assert_eq!(raw.0, 0x7FF9_0605_0403_0201);
        assert_eq!(raw.tag(), Some(ValueTag::Nil));
        assert_eq!(raw.payload(), payload);

        for tag in [
            ValueTag::Boolean,
            ValueTag::StaticStr,
            ValueTag::String,
            ValueTag::Array,
            ValueTag::Record,
            ValueTag::Function,
            ValueTag::Module,
            ValueTag::Extern,
            ValueTag::Uninitialized,
        ] {
            let raw = RawValue::tagged(tag, payload);
            assert_eq!(raw.tag(), Some(tag));
            assert_eq!(raw.payload(), payload);
        }
    }

    #[test]
    fn scalar_nan_box_roundtrips() {
        for number in [0.0, -0.0, 42.5, f64::INFINITY, f64::NEG_INFINITY] {
            assert_eq!(
                MiraValue::number(number).as_number().unwrap().to_bits(),
                number.to_bits()
            );
        }

        for nan in [f64::NAN, -f64::NAN] {
            let decoded = MiraValue::number(nan).as_number().unwrap();
            assert!(decoded.is_nan());
            assert_eq!(decoded.is_sign_negative(), nan.is_sign_negative());
        }

        assert!(MiraValue::nil().is_nil());
        assert_eq!(MiraValue::boolean(false).as_boolean(), Some(false));
        assert_eq!(MiraValue::boolean(true).as_boolean(), Some(true));
    }

    #[test]
    fn static_string_pointer_roundtrips() {
        let runtime = Runtime::new();
        let value = MiraValue::str(&STATIC_TEXT);

        assert_eq!(value.as_str(&runtime).unwrap(), Some(STATIC_TEXT));
    }
}