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/// Op represents all instructions in the Snix abstract machine.
45///
46/// In documentation comments, stack positions are referred to by
47/// indices written in `{}` as such, where required:
48///
49/// ```notrust
50///                             --- top of the stack
51///                            /
52///                           v
53///       [ ... | 3 | 2 | 1 | 0 ]
54///                   ^
55///                  /
56/// 2 values deep ---
57/// ```
58///
59/// Unless otherwise specified, operations leave their result at the
60/// top of the stack.
61#[repr(u8)]
62#[derive(Debug, PartialEq, Eq)]
63pub enum Op {
64    /// Push a constant onto the stack.
65    Constant,
66
67    /// Discard the value on top of the stack.
68    Pop,
69
70    /// Invert the boolean at the top of the stack.
71    Invert,
72
73    /// Invert the sign of the number at the top of the stack.
74    Negate,
75
76    /// Sum up the two numbers at the top of the stack.
77    Add,
78
79    /// Subtract the number at `{1}` from the number at `{2}`.
80    Sub,
81
82    /// Multiply the two numbers at the top of the stack.
83    Mul,
84
85    /// Divide the two numbers at the top of the stack.
86    Div,
87
88    /// Check the two values at the top of the stack for Nix-equality.
89    Equal,
90
91    /// Check whether the value at `{2}` is less than `{1}`.
92    Less,
93
94    /// Check whether the value at `{2}` is less than or equal to `{1}`.
95    LessOrEq,
96
97    /// Check whether the value at `{2}` is greater than `{1}`.
98    More,
99
100    /// Check whether the value at `{2}` is greater than or equal to `{1}`.
101    MoreOrEq,
102
103    /// Jump forward in the bytecode specified by the number of
104    /// instructions in its usize operand.
105    Jump,
106
107    /// Jump forward in the bytecode specified by the number of
108    /// instructions in its usize operand, *if* the value at the top
109    /// of the stack is `true`.
110    JumpIfTrue,
111
112    /// Jump forward in the bytecode specified by the number of
113    /// instructions in its usize operand, *if* the value at the top
114    /// of the stack is `false`.
115    JumpIfFalse,
116
117    /// Pop one stack item and jump forward in the bytecode
118    /// specified by the number of instructions in its usize
119    /// operand, *if* the value at the top of the stack is a
120    /// [`Value::Catchable`](crate::Value::Catchable).
121    JumpIfCatchable,
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 the internal value representing a missing
126    /// attribute set key.
127    JumpIfNotFound,
128
129    /// Jump forward in the bytecode specified by the number of
130    /// instructions in its usize operand, *if* the value at the top
131    /// of the stack is *not* the internal value requesting a
132    /// stack value finalisation.
133    JumpIfNoFinaliseRequest,
134
135    /// Construct an attribute set from the given number of key-value pairs on
136    /// the top of the stack. The operand gives the count of *pairs*, not the
137    /// number of *stack values* - the actual number of values popped off the
138    /// stack will be twice the argument to this op.
139    Attrs,
140
141    /// Merge the attribute set at `{2}` into the attribute set at `{1}`,
142    /// and leave the new set at the top of the stack.
143    AttrsUpdate,
144
145    /// Select the attribute with the name at `{1}` from the set at `{2}`.
146    AttrsSelect,
147
148    /// Select the attribute with the name at `{1}` from the set at `{2}`, but leave
149    /// a [`Value::AttrNotFound`](crate::Value::AttrNotFound) in the stack instead of failing
150    /// if it is missing.
151    AttrsTrySelect,
152
153    /// Check for the presence of the attribute with the name at `{1}` in the set
154    /// at `{2}`.
155    HasAttr,
156
157    /// Throw an error if the attribute set at the top of the stack has any attributes
158    /// other than those listed in the formals of the current lambda
159    ///
160    /// Panics if the current frame is not a lambda with formals
161    ValidateClosedFormals,
162
163    /// Push a value onto the runtime `with`-stack to enable dynamic identifier
164    /// resolution. The absolute stack index of the value is supplied as a usize
165    /// operand.
166    PushWith,
167
168    /// Pop the last runtime `with`-stack element.
169    PopWith,
170
171    /// Dynamically resolve an identifier with the name at `{1}` from the runtime
172    /// `with`-stack.
173    ResolveWith,
174
175    // Lists
176    /// Construct a list from the given number of values at the top of the
177    /// stack.
178    List,
179
180    /// Concatenate the lists at `{2}` and `{1}`.
181    Concat,
182
183    // Strings
184    /// Interpolate the given number of string fragments into a single string.
185    Interpolate,
186
187    /// Force the Value on the stack and coerce it to a string
188    CoerceToString,
189
190    // Paths
191    /// Attempt to resolve the Value on the stack using the configured [`NixSearchPath`][]
192    ///
193    /// [`NixSearchPath`]: crate::nix_search_path::NixSearchPath
194    FindFile,
195
196    /// Attempt to resolve a path literal relative to the home dir
197    ResolveHomePath,
198
199    /// Interpolate the given number of path fragments into a single path
200    InterpolatePath,
201
202    // Type assertion operators
203    /// Assert that the value at `{1}` is a boolean, and fail with a runtime error
204    /// otherwise.
205    AssertBool,
206    /// Assert that the value at `{1}` is an attribute set, and fail with a runtime error
207    /// otherwise.
208    AssertAttrs,
209
210    /// Access local identifiers with statically known positions.
211    GetLocal,
212
213    /// Close scopes while leaving their expression value around.
214    CloseScope,
215
216    /// Return an error indicating that an `assert` failed
217    AssertFail,
218
219    // Lambdas & closures
220    /// Call the value at `{1}` in a new VM callframe
221    Call,
222
223    /// Retrieve the upvalue at the given index from the closure or thunk
224    /// currently under evaluation.
225    GetUpvalue,
226
227    /// Construct a closure which has upvalues but no self-references
228    Closure,
229
230    /// Construct a closure which has self-references (direct or via upvalues)
231    ThunkClosure,
232
233    /// Construct a suspended thunk, used to delay a computation for laziness.
234    ThunkSuspended,
235
236    /// Force the value at `{1}` until it is a `Thunk::Evaluated`.
237    Force,
238
239    /// Finalise initialisation of the upvalues of the value in the given stack
240    /// index (which must be a [`Value::Thunk`](crate::Value::Thunk)) after the scope is fully bound.
241    Finalise,
242
243    /// Final instruction emitted in a chunk. Does not have an
244    /// inherent effect, but can simplify VM logic as a marker in some
245    /// cases.
246    ///
247    /// Can be thought of as "returning" the value to the parent
248    /// frame, hence the name.
249    Return,
250
251    /// Sentinel value to signal invalid bytecode. This MUST always be the last
252    /// value in the enum. Do not move it!
253    Invalid,
254}
255
256const _ASSERT_SMALL_OP: () = assert!(std::mem::size_of::<Op>() == 1);
257
258impl From<u8> for Op {
259    fn from(num: u8) -> Self {
260        if num >= Self::Invalid as u8 {
261            return Self::Invalid;
262        }
263
264        // SAFETY: As long as `Invalid` remains the last variant of the enum,
265        // and as long as variant values are not specified manually, this
266        // conversion is safe.
267        unsafe { std::mem::transmute(num) }
268    }
269}
270
271/// Type of an [`Op`]'s argument.
272pub enum OpArg {
273    /// No arguments.
274    None,
275    /// Unsigned variable-length integer.
276    Uvarint,
277    /// [`u16`] argument as two bytes.
278    Fixed,
279    /// Operation-dependent type.
280    Custom,
281}
282
283impl Op {
284    pub fn arg_type(&self) -> OpArg {
285        match self {
286            Op::Constant
287            | Op::Attrs
288            | Op::PushWith
289            | Op::List
290            | Op::Interpolate
291            | Op::InterpolatePath
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}