tvix_eval/
opcode.rs

1//! This module implements the instruction set running on the abstract
2//! machine implemented by tvix.
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 Tvix 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.
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` in the stack instead of failing if it is
150    /// 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    // Type assertion operators
200    /// Assert that the value at {1} is a boolean, and fail with a runtime error
201    /// otherwise.
202    AssertBool,
203    AssertAttrs,
204
205    /// Access local identifiers with statically known positions.
206    GetLocal,
207
208    /// Close scopes while leaving their expression value around.
209    CloseScope,
210
211    /// Return an error indicating that an `assert` failed
212    AssertFail,
213
214    // Lambdas & closures
215    /// Call the value at {1} in a new VM callframe
216    Call,
217
218    /// Retrieve the upvalue at the given index from the closure or thunk
219    /// currently under evaluation.
220    GetUpvalue,
221
222    /// Construct a closure which has upvalues but no self-references
223    Closure,
224
225    /// Construct a closure which has self-references (direct or via upvalues)
226    ThunkClosure,
227
228    /// Construct a suspended thunk, used to delay a computation for laziness.
229    ThunkSuspended,
230
231    /// Force the value at {1} until it is a `Thunk::Evaluated`.
232    Force,
233
234    /// Finalise initialisation of the upvalues of the value in the given stack
235    /// index (which must be a Value::Thunk) after the scope is fully bound.
236    Finalise,
237
238    /// Final instruction emitted in a chunk. Does not have an
239    /// inherent effect, but can simplify VM logic as a marker in some
240    /// cases.
241    ///
242    /// Can be thought of as "returning" the value to the parent
243    /// frame, hence the name.
244    Return,
245
246    /// Sentinel value to signal invalid bytecode. This MUST always be the last
247    /// value in the enum. Do not move it!
248    Invalid,
249}
250
251const _ASSERT_SMALL_OP: () = assert!(std::mem::size_of::<Op>() == 1);
252
253impl From<u8> for Op {
254    fn from(num: u8) -> Self {
255        if num >= Self::Invalid as u8 {
256            return Self::Invalid;
257        }
258
259        // SAFETY: As long as `Invalid` remains the last variant of the enum,
260        // and as long as variant values are not specified manually, this
261        // conversion is safe.
262        unsafe { std::mem::transmute(num) }
263    }
264}
265
266pub enum OpArg {
267    None,
268    Uvarint,
269    Fixed,
270    Custom,
271}
272
273impl Op {
274    pub fn arg_type(&self) -> OpArg {
275        match self {
276            Op::Constant
277            | Op::Attrs
278            | Op::PushWith
279            | Op::List
280            | Op::Interpolate
281            | Op::GetLocal
282            | Op::CloseScope
283            | Op::GetUpvalue
284            | Op::Finalise => OpArg::Uvarint,
285
286            Op::Jump
287            | Op::JumpIfTrue
288            | Op::JumpIfFalse
289            | Op::JumpIfCatchable
290            | Op::JumpIfNotFound
291            | Op::JumpIfNoFinaliseRequest => OpArg::Fixed,
292
293            Op::CoerceToString | Op::Closure | Op::ThunkClosure | Op::ThunkSuspended => {
294                OpArg::Custom
295            }
296            _ => OpArg::None,
297        }
298    }
299}
300
301/// Position is used to represent where to capture an upvalue from.
302#[derive(Clone, Copy)]
303pub struct Position(pub u64);
304
305impl Position {
306    pub fn stack_index(idx: StackIdx) -> Self {
307        Position((idx.0 as u64) << 2)
308    }
309
310    pub fn deferred_local(idx: StackIdx) -> Self {
311        Position(((idx.0 as u64) << 2) | 1)
312    }
313
314    pub fn upvalue_index(idx: UpvalueIdx) -> Self {
315        Position(((idx.0 as u64) << 2) | 2)
316    }
317
318    pub fn runtime_stack_index(&self) -> Option<StackIdx> {
319        if (self.0 & 0b11) == 0 {
320            return Some(StackIdx((self.0 >> 2) as usize));
321        }
322
323        None
324    }
325
326    pub fn runtime_deferred_local(&self) -> Option<StackIdx> {
327        if (self.0 & 0b11) == 1 {
328            return Some(StackIdx((self.0 >> 2) as usize));
329        }
330
331        None
332    }
333
334    pub fn runtime_upvalue_index(&self) -> Option<UpvalueIdx> {
335        if (self.0 & 0b11) == 2 {
336            return Some(UpvalueIdx((self.0 >> 2) as usize));
337        }
338
339        None
340    }
341}
342
343#[cfg(test)]
344mod position_tests {
345    use super::Position; // he-he
346    use super::{StackIdx, UpvalueIdx};
347
348    #[test]
349    fn test_stack_index_position() {
350        let idx = StackIdx(42);
351        let pos = Position::stack_index(idx);
352        let result = pos.runtime_stack_index();
353
354        assert_eq!(result, Some(idx));
355        assert_eq!(pos.runtime_deferred_local(), None);
356        assert_eq!(pos.runtime_upvalue_index(), None);
357    }
358
359    #[test]
360    fn test_deferred_local_position() {
361        let idx = StackIdx(42);
362        let pos = Position::deferred_local(idx);
363        let result = pos.runtime_deferred_local();
364
365        assert_eq!(result, Some(idx));
366        assert_eq!(pos.runtime_stack_index(), None);
367        assert_eq!(pos.runtime_upvalue_index(), None);
368    }
369
370    #[test]
371    fn test_upvalue_index_position() {
372        let idx = UpvalueIdx(42);
373        let pos = Position::upvalue_index(idx);
374        let result = pos.runtime_upvalue_index();
375
376        assert_eq!(result, Some(idx));
377        assert_eq!(pos.runtime_stack_index(), None);
378        assert_eq!(pos.runtime_deferred_local(), None);
379    }
380}