Skip to main content

hexicon_vm/
value.rs

1//! Values: what a stack slot, local variable, or property can hold.
2
3use std::fmt;
4
5/// An object ID: an index into the VM's object table.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
7pub struct ObjId(pub u32);
8
9impl ObjId {
10    /// The ID that refers to no object.
11    pub const INVALID: ObjId = ObjId(0);
12
13    /// Whether this ID can refer to an object.
14    pub const fn is_valid(self) -> bool {
15        self.0 != 0
16    }
17}
18
19impl fmt::Display for ObjId {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        write!(f, "{}", self.0)
22    }
23}
24
25/// A property ID.
26pub type PropId = u16;
27
28/// The property ID that refers to no property.
29pub const INVALID_PROP: PropId = 0;
30
31/// The calling interface of a method implemented by the VM itself.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct NativeDesc {
34    /// Number of required arguments.
35    pub min_args: u8,
36    /// Number of optional arguments after the required ones.
37    pub opt_args: u8,
38    /// Whether any number of further arguments is accepted.
39    pub varargs: bool,
40}
41
42impl NativeDesc {
43    /// A method taking exactly `min_args` arguments.
44    pub const fn fixed(min_args: u8) -> Self {
45        Self {
46            min_args,
47            opt_args: 0,
48            varargs: false,
49        }
50    }
51
52    /// A method taking `min_args` to `min_args + opt_args` arguments.
53    pub const fn optional(min_args: u8, opt_args: u8) -> Self {
54        Self {
55            min_args,
56            opt_args,
57            varargs: false,
58        }
59    }
60
61    /// A method taking `min_args` or more arguments.
62    pub const fn variable(min_args: u8) -> Self {
63        Self {
64            min_args,
65            opt_args: 0,
66            varargs: true,
67        }
68    }
69
70    /// Whether a call with `argc` arguments fits this interface.
71    pub const fn accepts(self, argc: u32) -> bool {
72        argc >= self.min_args as u32
73            && (self.varargs || argc <= self.min_args as u32 + self.opt_args as u32)
74    }
75}
76
77/// A value, as the virtual machine holds one.
78///
79/// The variants mirror the reference VM's value types. Strings and lists
80/// appear twice: as constants (an offset into the image's constant pool)
81/// and as objects (an [`ObjId`] of a string or list object).
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum Value {
84    /// `nil`: false, and the absence of a value.
85    Nil,
86    /// `true`.
87    True,
88    /// No value at all. Marks unused slots; programs never see it.
89    Empty,
90    /// A 32-bit integer.
91    Int(i32),
92    /// An object reference.
93    Obj(ObjId),
94    /// A property ID.
95    Prop(PropId),
96    /// A constant string, by constant pool offset.
97    SString(u32),
98    /// A constant string that displays itself when evaluated as a property.
99    DString(u32),
100    /// A constant list, by constant pool offset.
101    List(u32),
102    /// Method code, by code pool offset. Only property values have this
103    /// type; evaluating the property calls the code.
104    CodeOfs(u32),
105    /// A function pointer, by code pool offset.
106    FuncPtr(u32),
107    /// An enumerator.
108    Enum(u32),
109    /// A pointer to a function the VM implements.
110    BifPtr {
111        /// Index of the function set in the image's dependency list.
112        set: u16,
113        /// Index of the function within the set.
114        index: u16,
115    },
116    /// An object to invoke when the property holding it is evaluated.
117    ObjX(ObjId),
118    /// A VM function to call when the property holding it is evaluated.
119    BifPtrX {
120        /// Index of the function set in the image's dependency list.
121        set: u16,
122        /// Index of the function within the set.
123        index: u16,
124    },
125    /// A method the VM implements, as found by a property lookup that asked
126    /// not to call it.
127    NativeCode(NativeDesc),
128}
129
130/// Type codes as programs see them through `dataType()` and as images
131/// store them in data holders.
132pub mod type_code {
133    #![allow(missing_docs)]
134    pub const NIL: i32 = 1;
135    pub const TRUE: i32 = 2;
136    pub const OBJ: i32 = 5;
137    pub const PROP: i32 = 6;
138    pub const INT: i32 = 7;
139    pub const SSTRING: i32 = 8;
140    pub const DSTRING: i32 = 9;
141    pub const LIST: i32 = 10;
142    pub const CODEOFS: i32 = 11;
143    pub const FUNCPTR: i32 = 12;
144    pub const EMPTY: i32 = 13;
145    pub const NATIVE_CODE: i32 = 14;
146    pub const ENUM: i32 = 15;
147    pub const BIFPTR: i32 = 16;
148    pub const OBJX: i32 = 17;
149    pub const BIFPTRX: i32 = 18;
150}
151
152impl Value {
153    /// Size of a value as images encode it: a type byte and four data bytes.
154    pub const HOLDER_SIZE: usize = 5;
155
156    /// `true` or `nil`.
157    pub const fn logical(condition: bool) -> Self {
158        if condition { Self::True } else { Self::Nil }
159    }
160
161    /// An object reference, or `nil` for the invalid ID.
162    pub const fn obj_or_nil(id: ObjId) -> Self {
163        if id.is_valid() {
164            Self::Obj(id)
165        } else {
166            Self::Nil
167        }
168    }
169
170    /// The object ID, if this is an object reference.
171    pub const fn as_obj(self) -> Option<ObjId> {
172        match self {
173            Self::Obj(id) => Some(id),
174            _ => None,
175        }
176    }
177
178    /// The object ID, or the invalid ID for anything but an object.
179    pub const fn obj_id(self) -> ObjId {
180        match self {
181            Self::Obj(id) => id,
182            _ => ObjId::INVALID,
183        }
184    }
185
186    /// Whether this is `nil`.
187    pub const fn is_nil(self) -> bool {
188        matches!(self, Self::Nil)
189    }
190
191    /// Whether evaluating a property with this value runs code.
192    pub const fn is_invocable_prop(self) -> bool {
193        matches!(
194            self,
195            Self::CodeOfs(_) | Self::ObjX(_) | Self::BifPtrX { .. }
196        )
197    }
198
199    /// The type code of this value.
200    pub const fn type_code(self) -> i32 {
201        match self {
202            Self::Nil => type_code::NIL,
203            Self::True => type_code::TRUE,
204            Self::Empty => type_code::EMPTY,
205            Self::Int(_) => type_code::INT,
206            Self::Obj(_) => type_code::OBJ,
207            Self::Prop(_) => type_code::PROP,
208            Self::SString(_) => type_code::SSTRING,
209            Self::DString(_) => type_code::DSTRING,
210            Self::List(_) => type_code::LIST,
211            Self::CodeOfs(_) => type_code::CODEOFS,
212            Self::FuncPtr(_) => type_code::FUNCPTR,
213            Self::Enum(_) => type_code::ENUM,
214            Self::BifPtr { .. } => type_code::BIFPTR,
215            Self::ObjX(_) => type_code::OBJX,
216            Self::BifPtrX { .. } => type_code::BIFPTRX,
217            Self::NativeCode(_) => type_code::NATIVE_CODE,
218        }
219    }
220
221    /// Encode a value in the five-byte form images and saved states use.
222    pub fn to_holder(self) -> [u8; Self::HOLDER_SIZE] {
223        let mut b = [0u8; Self::HOLDER_SIZE];
224        b[0] = self.type_code() as u8;
225        let data: u32 = match self {
226            Self::Obj(id) | Self::ObjX(id) => id.0,
227            Self::Int(n) => n as u32,
228            Self::Prop(prop) => prop.into(),
229            Self::SString(at)
230            | Self::DString(at)
231            | Self::List(at)
232            | Self::CodeOfs(at)
233            | Self::FuncPtr(at)
234            | Self::Enum(at) => at,
235            Self::BifPtr { set, index } | Self::BifPtrX { set, index } => {
236                u32::from(index) | u32::from(set) << 16
237            }
238            _ => 0,
239        };
240        b[1..].copy_from_slice(&data.to_le_bytes());
241        b
242    }
243
244    /// Decode a value from the five-byte form images use.
245    ///
246    /// Type codes that cannot appear in an image decode as `nil`.
247    pub fn from_holder(b: &[u8]) -> Self {
248        let u32_at = || u32::from_le_bytes([b[1], b[2], b[3], b[4]]);
249        let u16_at = |at: usize| u16::from_le_bytes([b[at], b[at + 1]]);
250        match i32::from(b[0]) {
251            type_code::TRUE => Self::True,
252            type_code::OBJ => Self::obj_or_nil(ObjId(u32_at())),
253            type_code::PROP => Self::Prop(u16_at(1)),
254            type_code::INT => Self::Int(u32_at() as i32),
255            type_code::SSTRING => Self::SString(u32_at()),
256            type_code::DSTRING => Self::DString(u32_at()),
257            type_code::LIST => Self::List(u32_at()),
258            type_code::CODEOFS => Self::CodeOfs(u32_at()),
259            type_code::FUNCPTR => Self::FuncPtr(u32_at()),
260            type_code::EMPTY => Self::Empty,
261            type_code::ENUM => Self::Enum(u32_at()),
262            type_code::BIFPTR => Self::BifPtr {
263                index: u16_at(1),
264                set: u16_at(3),
265            },
266            type_code::OBJX => Self::ObjX(ObjId(u32_at())),
267            type_code::BIFPTRX => Self::BifPtrX {
268                index: u16_at(1),
269                set: u16_at(3),
270            },
271            _ => Self::Nil,
272        }
273    }
274}