snix_eval/
opcode.rs

1//! This module implements the instruction set running on the abstract
2//! machine implemented by snix.
3
4use std::ops::{AddAssign, Sub};
5
6/// Index of a constant in the current code chunk.
7#[repr(transparent)]
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub struct ConstantIdx(pub usize);
10
11/// Index of an instruction in the current code chunk.
12#[repr(transparent)]
13#[derive(Clone, Copy, Debug)]
14pub struct CodeIdx(pub usize);
15
16impl AddAssign<usize> for CodeIdx {
17    fn add_assign(&mut self, rhs: usize) {
18        *self = CodeIdx(self.0 + rhs)
19    }
20}
21
22impl Sub<usize> for CodeIdx {
23    type Output = Self;
24
25    fn sub(self, rhs: usize) -> Self::Output {
26        CodeIdx(self.0 - rhs)
27    }
28}
29
30/// Index of a value in the runtime stack.  This is an offset
31/// *relative to* the VM value stack_base of the CallFrame
32/// containing the opcode which contains this StackIdx.
33#[repr(transparent)]
34#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd)]
35pub struct StackIdx(pub usize);
36
37/// Index of an upvalue within a closure's bound-variable upvalue
38/// list.  This is an absolute index into the Upvalues of the
39/// CallFrame containing the opcode which contains this UpvalueIdx.
40#[repr(transparent)]
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct UpvalueIdx(pub usize);
43
44/// Offset by which an instruction pointer should change in a jump.
45#[repr(transparent)]
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub struct JumpOffset(pub usize);
48
49/// Provided count for an instruction (could represent e.g. a number
50/// of elements).
51#[repr(transparent)]
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub struct Count(pub usize);
54
55/// Op represents all instructions in the Snix abstract machine.
56///
57/// In documentation comments, stack positions are referred to by
58/// indices written in `{}` as such, where required:
59///
60/// ```notrust
61///                             --- top of the stack
62///                            /
63///                           v
64///       [ ... | 3 | 2 | 1 | 0 ]
65///                   ^
66///                  /
67/// 2 values deep ---
68/// ```
69///
70/// Unless otherwise specified, operations leave their result at the
71/// top of the stack.
72#[repr(u8)]
73#[derive(Debug, PartialEq, Eq)]
74pub enum Op {
75    /// Push a constant onto the stack.
76    Constant,
77
78    /// Discard the value on top of the stack.
79    Pop,
80
81    /// Invert the boolean at the top of the stack.
82    Invert,
83
84    /// Invert the sign of the number at the top of the stack.
85    Negate,
86
87    /// Sum up the two numbers at the top of the stack.
88    Add,
89
90    /// Subtract the number at {1} from the number at {2}.
91    Sub,
92
93    /// Multiply the two numbers at the top of the stack.
94    Mul,
95
96    /// Divide the two numbers at the top of the stack.
97    Div,
98
99    /// Check the two values at the top of the stack for Nix-equality.
100    Equal,
101
102    /// Check whether the value at {2} is less than {1}.
103    Less,
104
105    /// Check whether the value at {2} is less than or equal to {1}.
106    LessOrEq,
107
108    /// Check whether the value at {2} is greater than {1}.
109    More,
110
111    /// Check whether the value at {2} is greater than or equal to {1}.
112    MoreOrEq,
113
114    /// Jump forward in the bytecode specified by the number of
115    /// instructions in its usize operand.
116    Jump,
117
118    /// Jump forward in the bytecode specified by the number of
119    /// instructions in its usize operand, *if* the value at the top
120    /// of the stack is `true`.
121    JumpIfTrue,
122
123    /// Jump forward in the bytecode specified by the number of
124    /// instructions in its usize operand, *if* the value at the top
125    /// of the stack is `false`.
126    JumpIfFalse,
127
128    /// Pop one stack item and jump forward in the bytecode
129    /// specified by the number of instructions in its usize
130    /// operand, *if* the value at the top of the stack is a
131    /// Value::Catchable.
132    JumpIfCatchable,
133
134    /// Jump forward in the bytecode specified by the number of
135    /// instructions in its usize operand, *if* the value at the top
136    /// of the stack is the internal value representing a missing
137    /// attribute set key.
138    JumpIfNotFound,
139
140    /// Jump forward in the bytecode specified by the number of
141    /// instructions in its usize operand, *if* the value at the top
142    /// of the stack is *not* the internal value requesting a
143    /// stack value finalisation.
144    JumpIfNoFinaliseRequest,
145
146    /// Construct an attribute set from the given number of key-value pairs on
147    /// the top of the stack. The operand gives the count of *pairs*, not the
148    /// number of *stack values* - the actual number of values popped off the
149    /// stack will be twice the argument to this op.
150    Attrs,
151
152    /// Merge the attribute set at {2} into the attribute set at {1},
153    /// and leave the new set at the top of the stack.
154    AttrsUpdate,
155
156    /// Select the attribute with the name at {1} from the set at {2}.
157    AttrsSelect,
158
159    /// Select the attribute with the name at {1} from the set at {2}, but leave
160    /// a `Value::AttrNotFound` in the stack instead of failing if it is
161    /// missing.
162    AttrsTrySelect,
163
164    /// Check for the presence of the attribute with the name at {1} in the set
165    /// at {2}.
166    HasAttr,
167
168    /// Throw an error if the attribute set at the top of the stack has any attributes
169    /// other than those listed in the formals of the current lambda
170    ///
171    /// Panics if the current frame is not a lambda with formals
172    ValidateClosedFormals,
173
174    /// Push a value onto the runtime `with`-stack to enable dynamic identifier
175    /// resolution. The absolute stack index of the value is supplied as a usize
176    /// operand.
177    PushWith,
178
179    /// Pop the last runtime `with`-stack element.
180    PopWith,
181
182    /// Dynamically resolve an identifier with the name at {1} from the runtime
183    /// `with`-stack.
184    ResolveWith,
185
186    // Lists
187    /// Construct a list from the given number of values at the top of the
188    /// stack.
189    List,
190
191    /// Concatenate the lists at {2} and {1}.
192    Concat,
193
194    // Strings
195    /// Interpolate the given number of string fragments into a single string.
196    Interpolate,
197
198    /// Force the Value on the stack and coerce it to a string
199    CoerceToString,
200
201    // Paths
202    /// Attempt to resolve the Value on the stack using the configured [`NixSearchPath`][]
203    ///
204    /// [`NixSearchPath`]: crate::nix_search_path::NixSearchPath
205    FindFile,
206
207    /// Attempt to resolve a path literal relative to the home dir
208    ResolveHomePath,
209
210    // Type assertion operators
211    /// Assert that the value at {1} is a boolean, and fail with a runtime error
212    /// otherwise.
213    AssertBool,
214    AssertAttrs,
215
216    /// Access local identifiers with statically known positions.
217    GetLocal,
218
219    /// Close scopes while leaving their expression value around.
220    CloseScope,
221
222    /// Return an error indicating that an `assert` failed
223    AssertFail,
224
225    // Lambdas & closures
226    /// Call the value at {1} in a new VM callframe
227    Call,
228
229    /// Retrieve the upvalue at the given index from the closure or thunk
230    /// currently under evaluation.
231    GetUpvalue,
232
233    /// Construct a closure which has upvalues but no self-references
234    Closure,
235
236    /// Construct a closure which has self-references (direct or via upvalues)
237    ThunkClosure,
238
239    /// Construct a suspended thunk, used to delay a computation for laziness.
240    ThunkSuspended,
241
242    /// Force the value at {1} until it is a `Thunk::Evaluated`.
243    Force,
244
245    /// Finalise initialisation of the upvalues of the value in the given stack
246    /// index (which must be a Value::Thunk) after the scope is fully bound.
247    Finalise,
248
249    /// Final instruction emitted in a chunk. Does not have an
250    /// inherent effect, but can simplify VM logic as a marker in some
251    /// cases.
252    ///
253    /// Can be thought of as "returning" the value to the parent
254    /// frame, hence the name.
255    Return,
256
257    /// Sentinel value to signal invalid bytecode. This MUST always be the last
258    /// value in the enum. Do not move it!
259    Invalid,
260}
261
262const _ASSERT_SMALL_OP: () = assert!(std::mem::size_of::<Op>() == 1);
263
264impl From<u8> for Op {
265    fn from(num: u8) -> Self {
266        if num >= Self::Invalid as u8 {
267            return Self::Invalid;
268        }
269
270        // SAFETY: As long as `Invalid` remains the last variant of the enum,
271        // and as long as variant values are not specified manually, this
272        // conversion is safe.
273        unsafe { std::mem::transmute(num) }
274    }
275}
276
277pub enum OpArg {
278    None,
279    Uvarint,
280    Fixed,
281    Custom,
282}
283
284impl Op {
285    pub fn arg_type(&self) -> OpArg {
286        match self {
287            Op::Constant
288            | Op::Attrs
289            | Op::PushWith
290            | Op::List
291            | Op::Interpolate
292            | Op::GetLocal
293            | Op::CloseScope
294            | Op::GetUpvalue
295            | Op::Finalise => OpArg::Uvarint,
296
297            Op::Jump
298            | Op::JumpIfTrue
299            | Op::JumpIfFalse
300            | Op::JumpIfCatchable
301            | Op::JumpIfNotFound
302            | Op::JumpIfNoFinaliseRequest => OpArg::Fixed,
303
304            Op::CoerceToString | Op::Closure | Op::ThunkClosure | Op::ThunkSuspended => {
305                OpArg::Custom
306            }
307            _ => OpArg::None,
308        }
309    }
310}
311
312/// Position is used to represent where to capture an upvalue from.
313#[derive(Clone, Copy)]
314pub struct Position(pub u64);
315
316impl Position {
317    pub fn stack_index(idx: StackIdx) -> Self {
318        Position((idx.0 as u64) << 2)
319    }
320
321    pub fn deferred_local(idx: StackIdx) -> Self {
322        Position(((idx.0 as u64) << 2) | 1)
323    }
324
325    pub fn upvalue_index(idx: UpvalueIdx) -> Self {
326        Position(((idx.0 as u64) << 2) | 2)
327    }
328
329    pub fn runtime_stack_index(&self) -> Option<StackIdx> {
330        if (self.0 & 0b11) == 0 {
331            return Some(StackIdx((self.0 >> 2) as usize));
332        }
333
334        None
335    }
336
337    pub fn runtime_deferred_local(&self) -> Option<StackIdx> {
338        if (self.0 & 0b11) == 1 {
339            return Some(StackIdx((self.0 >> 2) as usize));
340        }
341
342        None
343    }
344
345    pub fn runtime_upvalue_index(&self) -> Option<UpvalueIdx> {
346        if (self.0 & 0b11) == 2 {
347            return Some(UpvalueIdx((self.0 >> 2) as usize));
348        }
349
350        None
351    }
352}
353
354#[cfg(test)]
355mod position_tests {
356    use super::Position; // he-he
357    use super::{StackIdx, UpvalueIdx};
358
359    #[test]
360    fn test_stack_index_position() {
361        let idx = StackIdx(42);
362        let pos = Position::stack_index(idx);
363        let result = pos.runtime_stack_index();
364
365        assert_eq!(result, Some(idx));
366        assert_eq!(pos.runtime_deferred_local(), None);
367        assert_eq!(pos.runtime_upvalue_index(), None);
368    }
369
370    #[test]
371    fn test_deferred_local_position() {
372        let idx = StackIdx(42);
373        let pos = Position::deferred_local(idx);
374        let result = pos.runtime_deferred_local();
375
376        assert_eq!(result, Some(idx));
377        assert_eq!(pos.runtime_stack_index(), None);
378        assert_eq!(pos.runtime_upvalue_index(), None);
379    }
380
381    #[test]
382    fn test_upvalue_index_position() {
383        let idx = UpvalueIdx(42);
384        let pos = Position::upvalue_index(idx);
385        let result = pos.runtime_upvalue_index();
386
387        assert_eq!(result, Some(idx));
388        assert_eq!(pos.runtime_stack_index(), None);
389        assert_eq!(pos.runtime_deferred_local(), None);
390    }
391}