miden_core/operations/
mod.rs

1use core::fmt;
2
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5
6mod decorators;
7pub use decorators::{AssemblyOp, DebugOptions, Decorator, DecoratorIdIterator, DecoratorList};
8use opcode_constants::*;
9
10use crate::{
11    Felt,
12    utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
13};
14
15// OPERATIONS OP CODES
16// ================================================================================================
17
18/// Opcode patterns have the following meanings:
19/// - 00xxxxx operations do not shift the stack; constraint degree can be up to 2.
20/// - 010xxxx operations shift the stack the left; constraint degree can be up to 2.
21/// - 011xxxx operations shift the stack to the right; constraint degree can be up to 2.
22/// - 100xxx-: operations consume 4 range checks; constraint degree can be up to 3. These are used
23///   to encode most u32 operations.
24/// - 101xxx-: operations where constraint degree can be up to 3. These include control flow
25///   operations and some other operations requiring high degree constraints.
26/// - 11xxx--: operations where constraint degree can be up to 5. These include control flow
27///   operations and some other operations requiring very high degree constraints.
28#[rustfmt::skip]
29pub(super) mod opcode_constants {
30    pub const OPCODE_NOOP: u8           = 0b0000_0000;
31    pub const OPCODE_EQZ: u8            = 0b0000_0001;
32    pub const OPCODE_NEG: u8            = 0b0000_0010;
33    pub const OPCODE_INV: u8            = 0b0000_0011;
34    pub const OPCODE_INCR: u8           = 0b0000_0100;
35    pub const OPCODE_NOT: u8            = 0b0000_0101;
36    pub const OPCODE_FMPADD: u8         = 0b0000_0110;
37    pub const OPCODE_MLOAD: u8          = 0b0000_0111;
38    pub const OPCODE_SWAP: u8           = 0b0000_1000;
39    pub const OPCODE_CALLER: u8         = 0b0000_1001;
40    pub const OPCODE_MOVUP2: u8         = 0b0000_1010;
41    pub const OPCODE_MOVDN2: u8         = 0b0000_1011;
42    pub const OPCODE_MOVUP3: u8         = 0b0000_1100;
43    pub const OPCODE_MOVDN3: u8         = 0b0000_1101;
44    pub const OPCODE_ADVPOPW: u8        = 0b0000_1110;
45    pub const OPCODE_EXPACC: u8         = 0b0000_1111;
46
47    pub const OPCODE_MOVUP4: u8         = 0b0001_0000;
48    pub const OPCODE_MOVDN4: u8         = 0b0001_0001;
49    pub const OPCODE_MOVUP5: u8         = 0b0001_0010;
50    pub const OPCODE_MOVDN5: u8         = 0b0001_0011;
51    pub const OPCODE_MOVUP6: u8         = 0b0001_0100;
52    pub const OPCODE_MOVDN6: u8         = 0b0001_0101;
53    pub const OPCODE_MOVUP7: u8         = 0b0001_0110;
54    pub const OPCODE_MOVDN7: u8         = 0b0001_0111;
55    pub const OPCODE_SWAPW: u8          = 0b0001_1000;
56    pub const OPCODE_EXT2MUL: u8        = 0b0001_1001;
57    pub const OPCODE_MOVUP8: u8         = 0b0001_1010;
58    pub const OPCODE_MOVDN8: u8         = 0b0001_1011;
59    pub const OPCODE_SWAPW2: u8         = 0b0001_1100;
60    pub const OPCODE_SWAPW3: u8         = 0b0001_1101;
61    pub const OPCODE_SWAPDW: u8         = 0b0001_1110;
62    pub const OPCODE_EMIT: u8           = 0b0001_1111;
63
64    pub const OPCODE_ASSERT: u8         = 0b0010_0000;
65    pub const OPCODE_EQ: u8             = 0b0010_0001;
66    pub const OPCODE_ADD: u8            = 0b0010_0010;
67    pub const OPCODE_MUL: u8            = 0b0010_0011;
68    pub const OPCODE_AND: u8            = 0b0010_0100;
69    pub const OPCODE_OR: u8             = 0b0010_0101;
70    pub const OPCODE_U32AND: u8         = 0b0010_0110;
71    pub const OPCODE_U32XOR: u8         = 0b0010_0111;
72    pub const OPCODE_FRIE2F4: u8        = 0b0010_1000;
73    pub const OPCODE_DROP: u8           = 0b0010_1001;
74    pub const OPCODE_CSWAP: u8          = 0b0010_1010;
75    pub const OPCODE_CSWAPW: u8         = 0b0010_1011;
76    pub const OPCODE_MLOADW: u8         = 0b0010_1100;
77    pub const OPCODE_MSTORE: u8         = 0b0010_1101;
78    pub const OPCODE_MSTOREW: u8        = 0b0010_1110;
79    pub const OPCODE_FMPUPDATE: u8      = 0b0010_1111;
80
81    pub const OPCODE_PAD: u8            = 0b0011_0000;
82    pub const OPCODE_DUP0: u8           = 0b0011_0001;
83    pub const OPCODE_DUP1: u8           = 0b0011_0010;
84    pub const OPCODE_DUP2: u8           = 0b0011_0011;
85    pub const OPCODE_DUP3: u8           = 0b0011_0100;
86    pub const OPCODE_DUP4: u8           = 0b0011_0101;
87    pub const OPCODE_DUP5: u8           = 0b0011_0110;
88    pub const OPCODE_DUP6: u8           = 0b0011_0111;
89    pub const OPCODE_DUP7: u8           = 0b0011_1000;
90    pub const OPCODE_DUP9: u8           = 0b0011_1001;
91    pub const OPCODE_DUP11: u8          = 0b0011_1010;
92    pub const OPCODE_DUP13: u8          = 0b0011_1011;
93    pub const OPCODE_DUP15: u8          = 0b0011_1100;
94    pub const OPCODE_ADVPOP: u8         = 0b0011_1101;
95    pub const OPCODE_SDEPTH: u8         = 0b0011_1110;
96    pub const OPCODE_CLK: u8            = 0b0011_1111;
97
98    pub const OPCODE_U32ADD: u8         = 0b0100_0000;
99    pub const OPCODE_U32SUB: u8         = 0b0100_0010;
100    pub const OPCODE_U32MUL: u8         = 0b0100_0100;
101    pub const OPCODE_U32DIV: u8         = 0b0100_0110;
102    pub const OPCODE_U32SPLIT: u8       = 0b0100_1000;
103    pub const OPCODE_U32ASSERT2: u8     = 0b0100_1010;
104    pub const OPCODE_U32ADD3: u8        = 0b0100_1100;
105    pub const OPCODE_U32MADD: u8        = 0b0100_1110;
106
107    pub const OPCODE_HPERM: u8          = 0b0101_0000;
108    pub const OPCODE_MPVERIFY: u8       = 0b0101_0001;
109    pub const OPCODE_PIPE: u8           = 0b0101_0010;
110    pub const OPCODE_MSTREAM: u8        = 0b0101_0011;
111    pub const OPCODE_SPLIT: u8          = 0b0101_0100;
112    pub const OPCODE_LOOP: u8           = 0b0101_0101;
113    pub const OPCODE_SPAN: u8           = 0b0101_0110;
114    pub const OPCODE_JOIN: u8           = 0b0101_0111;
115    pub const OPCODE_DYN: u8            = 0b0101_1000;
116    pub const OPCODE_HORNEREXT: u8      = 0b0101_1001;
117    pub const OPCODE_PUSH: u8           = 0b0101_1011;
118    pub const OPCODE_DYNCALL: u8        = 0b0101_1100;
119    pub const OPCODE_EVALCIRCUIT: u8    = 0b0101_1101;
120
121    pub const OPCODE_MRUPDATE: u8       = 0b0110_0000;
122    pub const OPCODE_HORNERBASE: u8     = 0b0110_0100;
123    pub const OPCODE_SYSCALL: u8        = 0b0110_1000;
124    pub const OPCODE_CALL: u8           = 0b0110_1100;
125    pub const OPCODE_END: u8            = 0b0111_0000;
126    pub const OPCODE_REPEAT: u8         = 0b0111_0100;
127    pub const OPCODE_RESPAN: u8         = 0b0111_1000;
128    pub const OPCODE_HALT: u8           = 0b0111_1100;
129}
130
131// OPERATIONS
132// ================================================================================================
133
134/// A set of native VM operations which take exactly one cycle to execute.
135#[derive(Copy, Clone, Debug, Eq, PartialEq)]
136#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
137#[repr(u8)]
138pub enum Operation {
139    // ----- system operations -------------------------------------------------------------------
140    /// Advances cycle counter, but does not change the state of user stack.
141    Noop = OPCODE_NOOP,
142
143    /// Pops the stack; if the popped value is not 1, execution fails.
144    ///
145    /// The internal value specifies an error code associated with the error in case when the
146    /// execution fails.
147    Assert(Felt) = OPCODE_ASSERT,
148
149    /// Pops an element off the stack, adds the current value of the `fmp` register to it, and
150    /// pushes the result back onto the stack.
151    FmpAdd = OPCODE_FMPADD,
152
153    /// Pops an element off the stack and adds it to the current value of `fmp` register.
154    FmpUpdate = OPCODE_FMPUPDATE,
155
156    /// Pushes the current depth of the stack onto the stack.
157    SDepth = OPCODE_SDEPTH,
158
159    /// Overwrites the top four stack items with the hash of a function which initiated the current
160    /// SYSCALL. Thus, this operation can be executed only inside a SYSCALL code block.
161    Caller = OPCODE_CALLER,
162
163    /// Pushes the current value of the clock cycle onto the stack. This operation can be used to
164    /// measure the number of cycles it has taken to execute the program up to the current
165    /// instruction.
166    Clk = OPCODE_CLK,
167
168    /// Emits an event to the host.
169    ///
170    /// Semantics:
171    /// - Reads the event id from the top of the stack (as a `Felt`) without consuming it; the
172    ///   caller is responsible for pushing and later dropping the id.
173    /// - User-defined events are conventionally derived from strings via
174    ///   `hash_string_to_word(name)[0]` (Blake3-based) and may be emitted via immediate forms in
175    ///   assembly (`emit.event("...")` or `emit.CONST` where `CONST=event("...")`).
176    /// - System events are still identified by specific 32-bit codes; the VM attempts to interpret
177    ///   the stack `Felt` as `u32` to dispatch known system events, and otherwise forwards the
178    ///   event to the host.
179    ///
180    /// This operation does not change the state of the user stack aside from reading the value.
181    Emit = OPCODE_EMIT,
182
183    // ----- flow control operations -------------------------------------------------------------
184    /// Marks the beginning of a join block.
185    Join = OPCODE_JOIN,
186
187    /// Marks the beginning of a split block.
188    Split = OPCODE_SPLIT,
189
190    /// Marks the beginning of a loop block.
191    Loop = OPCODE_LOOP,
192
193    /// Marks the beginning of a function call.
194    Call = OPCODE_CALL,
195
196    /// Marks the beginning of a dynamic code block, where the target is specified by the stack.
197    Dyn = OPCODE_DYN,
198
199    /// Marks the beginning of a dynamic function call, where the target is specified by the stack.
200    Dyncall = OPCODE_DYNCALL,
201
202    /// Marks the beginning of a kernel call.
203    SysCall = OPCODE_SYSCALL,
204
205    /// Marks the beginning of a span code block.
206    Span = OPCODE_SPAN,
207
208    /// Marks the end of a program block.
209    End = OPCODE_END,
210
211    /// Indicates that body of an executing loop should be executed again.
212    Repeat = OPCODE_REPEAT,
213
214    /// Starts processing a new operation batch.
215    Respan = OPCODE_RESPAN,
216
217    /// Indicates the end of the program. This is used primarily to pad the execution trace to
218    /// the required length. Once HALT operation is executed, no other operations can be executed
219    /// by the VM (HALT operation itself excepted).
220    Halt = OPCODE_HALT,
221
222    // ----- field operations --------------------------------------------------------------------
223    /// Pops two elements off the stack, adds them, and pushes the result back onto the stack.
224    Add = OPCODE_ADD,
225
226    /// Pops an element off the stack, negates it, and pushes the result back onto the stack.
227    Neg = OPCODE_NEG,
228
229    /// Pops two elements off the stack, multiplies them, and pushes the result back onto the
230    /// stack.
231    Mul = OPCODE_MUL,
232
233    /// Pops an element off the stack, computes its multiplicative inverse, and pushes the result
234    /// back onto the stack.
235    Inv = OPCODE_INV,
236
237    /// Pops an element off the stack, adds 1 to it, and pushes the result back onto the stack.
238    Incr = OPCODE_INCR,
239
240    /// Pops two elements off the stack, multiplies them, and pushes the result back onto the
241    /// stack.
242    ///
243    /// If either of the elements is greater than 1, execution fails. This operation is equivalent
244    /// to boolean AND.
245    And = OPCODE_AND,
246
247    /// Pops two elements off the stack and subtracts their product from their sum.
248    ///
249    /// If either of the elements is greater than 1, execution fails. This operation is equivalent
250    /// to boolean OR.
251    Or = OPCODE_OR,
252
253    /// Pops an element off the stack and subtracts it from 1.
254    ///
255    /// If the element is greater than one, the execution fails. This operation is equivalent to
256    /// boolean NOT.
257    Not = OPCODE_NOT,
258
259    /// Pops two elements off the stack and compares them. If the elements are equal, pushes 1
260    /// onto the stack, otherwise pushes 0 onto the stack.
261    Eq = OPCODE_EQ,
262
263    /// Pops an element off the stack and compares it to 0. If the element is 0, pushes 1 onto
264    /// the stack, otherwise pushes 0 onto the stack.
265    Eqz = OPCODE_EQZ,
266
267    /// Computes a single turn of exponent accumulation for the given inputs. This operation can be
268    /// be used to compute a single turn of power of a field element.
269    ///
270    /// The top 4 elements of the stack are expected to be arranged as follows (form the top):
271    /// - least significant bit of the exponent in the previous trace if there's an expacc call,
272    ///   otherwise ZERO
273    /// - exponent of base number `a` for this turn
274    /// - accumulated power of base number `a` so far
275    /// - number which needs to be shifted to the right
276    ///
277    /// At the end of the operation, exponent is replaced with its square, current value of power
278    /// of base number `a` on exponent is incorporated into the accumulator and the number is
279    /// shifted to the right by one bit.
280    Expacc = OPCODE_EXPACC,
281
282    // ----- ext2 operations ---------------------------------------------------------------------
283    /// Computes the product of two elements in the extension field of degree 2 and pushes the
284    /// result back onto the stack as the third and fourth elements. Pushes 0 onto the stack as
285    /// the first and second elements.
286    Ext2Mul = OPCODE_EXT2MUL,
287
288    // ----- u32 operations ----------------------------------------------------------------------
289    /// Pops an element off the stack, splits it into upper and lower 32-bit values, and pushes
290    /// these values back onto the stack.
291    U32split = OPCODE_U32SPLIT,
292
293    /// Pops two elements off the stack, adds them, and splits the result into upper and lower
294    /// 32-bit values. Then pushes these values back onto the stack.
295    ///
296    /// If either of these elements is greater than or equal to 2^32, the result of this
297    /// operation is undefined.
298    U32add = OPCODE_U32ADD,
299
300    /// Pops two elements off the stack and checks if each of them represents a 32-bit value.
301    /// If both of them are, they are pushed back onto the stack, otherwise an error is returned.
302    ///
303    /// The internal value specifies an error code associated with the error in case when the
304    /// assertion fails.
305    U32assert2(Felt) = OPCODE_U32ASSERT2,
306
307    /// Pops three elements off the stack, adds them together, and splits the result into upper
308    /// and lower 32-bit values. Then pushes the result back onto the stack.
309    U32add3 = OPCODE_U32ADD3,
310
311    /// Pops two elements off the stack and subtracts the first element from the second. Then,
312    /// the result, together with a flag indicating whether subtraction underflowed is pushed
313    /// onto the stack.
314    ///
315    /// If their of the values is greater than or equal to 2^32, the result of this operation is
316    /// undefined.
317    U32sub = OPCODE_U32SUB,
318
319    /// Pops two elements off the stack, multiplies them, and splits the result into upper and
320    /// lower 32-bit values. Then pushes these values back onto the stack.
321    ///
322    /// If their of the values is greater than or equal to 2^32, the result of this operation is
323    /// undefined.
324    U32mul = OPCODE_U32MUL,
325
326    /// Pops two elements off the stack and multiplies them. Then pops the third element off the
327    /// stack, and adds it to the result. Finally, splits the result into upper and lower 32-bit
328    /// values, and pushes them onto the stack.
329    ///
330    /// If any of the three values is greater than or equal to 2^32, the result of this operation
331    /// is undefined.
332    U32madd = OPCODE_U32MADD,
333
334    /// Pops two elements off the stack and divides the second element by the first. Then pushes
335    /// the integer result of the division, together with the remainder, onto the stack.
336    ///
337    /// If their of the values is greater than or equal to 2^32, the result of this operation is
338    /// undefined.
339    U32div = OPCODE_U32DIV,
340
341    /// Pops two elements off the stack, computes their binary AND, and pushes the result back
342    /// onto the stack.
343    ///
344    /// If either of the elements is greater than or equal to 2^32, execution fails.
345    U32and = OPCODE_U32AND,
346
347    /// Pops two elements off the stack, computes their binary XOR, and pushes the result back
348    /// onto the stack.
349    ///
350    /// If either of the elements is greater than or equal to 2^32, execution fails.
351    U32xor = OPCODE_U32XOR,
352
353    // ----- stack manipulation ------------------------------------------------------------------
354    /// Pushes 0 onto the stack.
355    Pad = OPCODE_PAD,
356
357    /// Removes to element from the stack.
358    Drop = OPCODE_DROP,
359
360    /// Pushes a copy of stack element 0 onto the stack.
361    Dup0 = OPCODE_DUP0,
362
363    /// Pushes a copy of stack element 1 onto the stack.
364    Dup1 = OPCODE_DUP1,
365
366    /// Pushes a copy of stack element 2 onto the stack.
367    Dup2 = OPCODE_DUP2,
368
369    /// Pushes a copy of stack element 3 onto the stack.
370    Dup3 = OPCODE_DUP3,
371
372    /// Pushes a copy of stack element 4 onto the stack.
373    Dup4 = OPCODE_DUP4,
374
375    /// Pushes a copy of stack element 5 onto the stack.
376    Dup5 = OPCODE_DUP5,
377
378    /// Pushes a copy of stack element 6 onto the stack.
379    Dup6 = OPCODE_DUP6,
380
381    /// Pushes a copy of stack element 7 onto the stack.
382    Dup7 = OPCODE_DUP7,
383
384    /// Pushes a copy of stack element 9 onto the stack.
385    Dup9 = OPCODE_DUP9,
386
387    /// Pushes a copy of stack element 11 onto the stack.
388    Dup11 = OPCODE_DUP11,
389
390    /// Pushes a copy of stack element 13 onto the stack.
391    Dup13 = OPCODE_DUP13,
392
393    /// Pushes a copy of stack element 15 onto the stack.
394    Dup15 = OPCODE_DUP15,
395
396    /// Swaps stack elements 0 and 1.
397    Swap = OPCODE_SWAP,
398
399    /// Swaps stack elements 0, 1, 2, and 3 with elements 4, 5, 6, and 7.
400    SwapW = OPCODE_SWAPW,
401
402    /// Swaps stack elements 0, 1, 2, and 3 with elements 8, 9, 10, and 11.
403    SwapW2 = OPCODE_SWAPW2,
404
405    /// Swaps stack elements 0, 1, 2, and 3, with elements 12, 13, 14, and 15.
406    SwapW3 = OPCODE_SWAPW3,
407
408    /// Swaps the top two words pair wise.
409    ///
410    /// Input: [D, C, B, A, ...]
411    /// Output: [B, A, D, C, ...]
412    SwapDW = OPCODE_SWAPDW,
413
414    /// Moves stack element 2 to the top of the stack.
415    MovUp2 = OPCODE_MOVUP2,
416
417    /// Moves stack element 3 to the top of the stack.
418    MovUp3 = OPCODE_MOVUP3,
419
420    /// Moves stack element 4 to the top of the stack.
421    MovUp4 = OPCODE_MOVUP4,
422
423    /// Moves stack element 5 to the top of the stack.
424    MovUp5 = OPCODE_MOVUP5,
425
426    /// Moves stack element 6 to the top of the stack.
427    MovUp6 = OPCODE_MOVUP6,
428
429    /// Moves stack element 7 to the top of the stack.
430    MovUp7 = OPCODE_MOVUP7,
431
432    /// Moves stack element 8 to the top of the stack.
433    MovUp8 = OPCODE_MOVUP8,
434
435    /// Moves the top stack element to position 2 on the stack.
436    MovDn2 = OPCODE_MOVDN2,
437
438    /// Moves the top stack element to position 3 on the stack.
439    MovDn3 = OPCODE_MOVDN3,
440
441    /// Moves the top stack element to position 4 on the stack.
442    MovDn4 = OPCODE_MOVDN4,
443
444    /// Moves the top stack element to position 5 on the stack.
445    MovDn5 = OPCODE_MOVDN5,
446
447    /// Moves the top stack element to position 6 on the stack.
448    MovDn6 = OPCODE_MOVDN6,
449
450    /// Moves the top stack element to position 7 on the stack.
451    MovDn7 = OPCODE_MOVDN7,
452
453    /// Moves the top stack element to position 8 on the stack.
454    MovDn8 = OPCODE_MOVDN8,
455
456    /// Pops an element off the stack, and if the element is 1, swaps the top two remaining
457    /// elements on the stack. If the popped element is 0, the stack remains unchanged.
458    ///
459    /// If the popped element is neither 0 nor 1, execution fails.
460    CSwap = OPCODE_CSWAP,
461
462    /// Pops an element off the stack, and if the element is 1, swaps the remaining elements
463    /// 0, 1, 2, and 3 with elements 4, 5, 6, and 7. If the popped element is 0, the stack
464    /// remains unchanged.
465    ///
466    /// If the popped element is neither 0 nor 1, execution fails.
467    CSwapW = OPCODE_CSWAPW,
468
469    // ----- input / output ----------------------------------------------------------------------
470    /// Pushes the immediate value onto the stack.
471    Push(Felt) = OPCODE_PUSH,
472
473    /// Removes the next element from the advice stack and pushes it onto the operand stack.
474    AdvPop = OPCODE_ADVPOP,
475
476    /// Removes a word (4 elements) from the advice stack and overwrites the top four operand
477    /// stack elements with it.
478    AdvPopW = OPCODE_ADVPOPW,
479
480    /// Pops an element off the stack, interprets it as a memory address, and replaces the
481    /// remaining 4 elements at the top of the stack with values located at the specified address.
482    MLoadW = OPCODE_MLOADW,
483
484    /// Pops an element off the stack, interprets it as a memory address, and writes the remaining
485    /// 4 elements at the top of the stack into memory at the specified address.
486    MStoreW = OPCODE_MSTOREW,
487
488    /// Pops an element off the stack, interprets it as a memory address, and pushes the first
489    /// element of the word located at the specified address to the stack.
490    MLoad = OPCODE_MLOAD,
491
492    /// Pops an element off the stack, interprets it as a memory address, and writes the remaining
493    /// element at the top of the stack into the first element of the word located at the specified
494    /// memory address. The remaining 3 elements of the word are not affected.
495    MStore = OPCODE_MSTORE,
496
497    /// Loads two words from memory, and replaces the top 8 elements of the stack with them,
498    /// element-wise, in stack order.
499    ///
500    /// The operation works as follows:
501    /// - The memory address of the first word is retrieved from 13th stack element (position 12).
502    /// - Two consecutive words, starting at this address, are loaded from memory.
503    /// - The top 8 elements of the stack are overwritten with these words (element-wise, in stack
504    ///   order).
505    /// - Memory address (in position 12) is incremented by 2.
506    /// - All other stack elements remain the same.
507    MStream = OPCODE_MSTREAM,
508
509    /// Pops two words from the advice stack, writes them to memory, and replaces the top 8
510    /// elements of the stack with them, element-wise, in stack order.
511    ///
512    /// The operation works as follows:
513    /// - Two words are popped from the advice stack.
514    /// - The destination memory address for the first word is retrieved from the 13th stack element
515    ///   (position 12).
516    /// - The two words are written to memory consecutively, starting at this address.
517    /// - The top 8 elements of the stack are overwritten with these words (element-wise, in stack
518    ///   order).
519    /// - Memory address (in position 12) is incremented by 2.
520    /// - All other stack elements remain the same.
521    Pipe = OPCODE_PIPE,
522
523    // ----- cryptographic operations ------------------------------------------------------------
524    /// Performs a Rescue Prime Optimized permutation on the top 3 words of the operand stack,
525    /// where the top 2 words are the rate (words C and B), the deepest word is the capacity (word
526    /// A), and the digest output is the middle word E.
527    ///
528    /// Stack transition:
529    /// [C, B, A, ...] -> [F, E, D, ...]
530    HPerm = OPCODE_HPERM,
531
532    /// Verifies that a Merkle path from the specified node resolves to the specified root. This
533    /// operation can be used to prove that the prover knows a path in the specified Merkle tree
534    /// which starts with the specified node.
535    ///
536    /// The stack is expected to be arranged as follows (from the top):
537    /// - value of the node, 4 elements.
538    /// - depth of the path, 1 element.
539    /// - index of the node, 1 element.
540    /// - root of the tree, 4 elements.
541    ///
542    /// The Merkle path itself is expected to be provided by the prover non-deterministically (via
543    /// merkle sets). If the prover is not able to provide the required path, the operation fails.
544    /// The state of the stack does not change.
545    ///
546    /// The internal value specifies an error code associated with the error in case when the
547    /// assertion fails.
548    MpVerify(Felt) = OPCODE_MPVERIFY,
549
550    /// Computes a new root of a Merkle tree where a node at the specified position is updated to
551    /// the specified value.
552    ///
553    /// The stack is expected to be arranged as follows (from the top):
554    /// - old value of the node, 4 element
555    /// - depth of the node, 1 element
556    /// - index of the node, 1 element
557    /// - current root of the tree, 4 elements
558    /// - new value of the node, 4 element
559    ///
560    /// The Merkle path for the node is expected to be provided by the prover non-deterministically
561    /// via the advice provider. At the end of the operation, the old node value is replaced with
562    /// the new root value, that is computed based on the provided path. Everything else on the
563    /// stack remains the same.
564    ///
565    /// The tree will always be copied into a new instance, meaning the advice provider will keep
566    /// track of both the old and new Merkle trees.
567    MrUpdate = OPCODE_MRUPDATE,
568
569    /// Performs FRI (Fast Reed-Solomon Interactive Oracle Proofs) layer folding by a factor of 4
570    /// for FRI protocol executed in a degree 2 extension of the base field.
571    ///
572    /// This operation:
573    /// - Folds 4 query values (v0, v1), (v2, v3), (v4, v5), (v6, v7) into a single value (ne0, ne1)
574    /// - Computes new value of the domain generator power: poe' = poe^4
575    /// - Increments layer pointer (cptr) by 2
576    /// - Checks that the previous folding was done correctly
577    /// - Shifts the stack to move an item from the overflow table to stack position 15
578    ///
579    /// Stack transition:
580    /// Input: [v7, v6, v5, v4, v3, v2, v1, v0, f_pos, d_seg, poe, pe1, pe0, a1, a0, cptr, ...]
581    /// Output: [t1, t0, s1, s0, df3, df2, df1, df0, poe^2, f_tau, cptr+2, poe^4, f_pos, ne1, ne0,
582    /// eptr, ...] where eptr is moved from the stack overflow table and is the address of the
583    /// final FRI layer.
584    FriE2F4 = OPCODE_FRIE2F4,
585
586    /// Performs 8 steps of the Horner evaluation method on a polynomial with coefficients over
587    /// the base field, i.e., it computes
588    ///
589    /// acc' = (((acc_tmp * alpha + c3) * alpha + c2) * alpha + c1) * alpha + c0
590    ///
591    /// where
592    ///
593    /// acc_tmp := (((acc * alpha + c7) * alpha + c6) * alpha + c5) * alpha + c4
594    ///
595    ///
596    /// In other words, the intsruction computes the evaluation at alpha of the polynomial
597    ///
598    /// P(X) := c7 * X^7 + c6 * X^6 + ... + c1 * X + c0
599    HornerBase = OPCODE_HORNERBASE,
600
601    /// Performs 4 steps of the Horner evaluation method on a polynomial with coefficients over
602    /// the extension field, i.e., it computes
603    ///
604    /// acc' = (((acc * alpha + c3) * alpha + c2) * alpha + c1) * alpha + c0
605    ///
606    /// In other words, the intsruction computes the evaluation at alpha of the polynomial
607    ///
608    /// P(X) := c3 * X^3 + c2 * X^2 + c1 * X + c0
609    HornerExt = OPCODE_HORNEREXT,
610
611    /// Evaluates an arithmetic circuit given a pointer to its description in memory, the number
612    /// of arithmetic gates, and the sum of the input and constant gates.
613    EvalCircuit = OPCODE_EVALCIRCUIT,
614}
615
616impl Operation {
617    pub const OP_BITS: usize = 7;
618
619    /// Returns the opcode of this operation.
620    #[rustfmt::skip]
621    pub fn op_code(&self) -> u8 {
622        // SAFETY: This is safe because we have given this enum a primitive representation with
623        // #[repr(u8)], with the first field of the underlying union-of-structs the discriminant.
624        //
625        // See the section on "accessing the numeric value of the discriminant"
626        // here: https://doc.rust-lang.org/std/mem/fn.discriminant.html
627        unsafe { *<*const _>::from(self).cast::<u8>() }
628    }
629
630    /// Returns an immediate value carried by this operation.
631    // Proptest generators for operations in crate::mast::node::basic_block_node::tests discriminate
632    // on this flag, please update them when you modify the semantics of this method.
633    pub fn imm_value(&self) -> Option<Felt> {
634        match *self {
635            Self::Push(imm) => Some(imm),
636            _ => None,
637        }
638    }
639
640    /// Returns true if this operation writes any data to the decoder hasher registers.
641    ///
642    /// In other words, if so, then the user op helper registers are not available.
643    pub fn populates_decoder_hasher_registers(&self) -> bool {
644        matches!(
645            self,
646            Self::End
647                | Self::Join
648                | Self::Split
649                | Self::Loop
650                | Self::Repeat
651                | Self::Respan
652                | Self::Span
653                | Self::Halt
654                | Self::Call
655                | Self::SysCall
656        )
657    }
658}
659
660impl crate::prettier::PrettyPrint for Operation {
661    fn render(&self) -> crate::prettier::Document {
662        crate::prettier::display(self)
663    }
664}
665
666impl fmt::Display for Operation {
667    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
668        match self {
669            // ----- system operations ------------------------------------------------------------
670            Self::Noop => write!(f, "noop"),
671            Self::Assert(err_code) => write!(f, "assert({err_code})"),
672
673            Self::FmpAdd => write!(f, "fmpadd"),
674            Self::FmpUpdate => write!(f, "fmpupdate"),
675
676            Self::SDepth => write!(f, "sdepth"),
677            Self::Caller => write!(f, "caller"),
678
679            Self::Clk => write!(f, "clk"),
680
681            // ----- flow control operations ------------------------------------------------------
682            Self::Join => write!(f, "join"),
683            Self::Split => write!(f, "split"),
684            Self::Loop => write!(f, "loop"),
685            Self::Call => writeln!(f, "call"),
686            Self::Dyncall => writeln!(f, "dyncall"),
687            Self::SysCall => writeln!(f, "syscall"),
688            Self::Dyn => writeln!(f, "dyn"),
689            Self::Span => write!(f, "span"),
690            Self::End => write!(f, "end"),
691            Self::Repeat => write!(f, "repeat"),
692            Self::Respan => write!(f, "respan"),
693            Self::Halt => write!(f, "halt"),
694
695            // ----- field operations -------------------------------------------------------------
696            Self::Add => write!(f, "add"),
697            Self::Neg => write!(f, "neg"),
698            Self::Mul => write!(f, "mul"),
699            Self::Inv => write!(f, "inv"),
700            Self::Incr => write!(f, "incr"),
701
702            Self::And => write!(f, "and"),
703            Self::Or => write!(f, "or"),
704            Self::Not => write!(f, "not"),
705
706            Self::Eq => write!(f, "eq"),
707            Self::Eqz => write!(f, "eqz"),
708
709            Self::Expacc => write!(f, "expacc"),
710
711            // ----- ext2 operations --------------------------------------------------------------
712            Self::Ext2Mul => write!(f, "ext2mul"),
713
714            // ----- u32 operations ---------------------------------------------------------------
715            Self::U32assert2(err_code) => write!(f, "u32assert2({err_code})"),
716            Self::U32split => write!(f, "u32split"),
717            Self::U32add => write!(f, "u32add"),
718            Self::U32add3 => write!(f, "u32add3"),
719            Self::U32sub => write!(f, "u32sub"),
720            Self::U32mul => write!(f, "u32mul"),
721            Self::U32madd => write!(f, "u32madd"),
722            Self::U32div => write!(f, "u32div"),
723
724            Self::U32and => write!(f, "u32and"),
725            Self::U32xor => write!(f, "u32xor"),
726
727            // ----- stack manipulation -----------------------------------------------------------
728            Self::Drop => write!(f, "drop"),
729            Self::Pad => write!(f, "pad"),
730
731            Self::Dup0 => write!(f, "dup0"),
732            Self::Dup1 => write!(f, "dup1"),
733            Self::Dup2 => write!(f, "dup2"),
734            Self::Dup3 => write!(f, "dup3"),
735            Self::Dup4 => write!(f, "dup4"),
736            Self::Dup5 => write!(f, "dup5"),
737            Self::Dup6 => write!(f, "dup6"),
738            Self::Dup7 => write!(f, "dup7"),
739            Self::Dup9 => write!(f, "dup9"),
740            Self::Dup11 => write!(f, "dup11"),
741            Self::Dup13 => write!(f, "dup13"),
742            Self::Dup15 => write!(f, "dup15"),
743
744            Self::Swap => write!(f, "swap"),
745            Self::SwapW => write!(f, "swapw"),
746            Self::SwapW2 => write!(f, "swapw2"),
747            Self::SwapW3 => write!(f, "swapw3"),
748            Self::SwapDW => write!(f, "swapdw"),
749
750            Self::MovUp2 => write!(f, "movup2"),
751            Self::MovUp3 => write!(f, "movup3"),
752            Self::MovUp4 => write!(f, "movup4"),
753            Self::MovUp5 => write!(f, "movup5"),
754            Self::MovUp6 => write!(f, "movup6"),
755            Self::MovUp7 => write!(f, "movup7"),
756            Self::MovUp8 => write!(f, "movup8"),
757
758            Self::MovDn2 => write!(f, "movdn2"),
759            Self::MovDn3 => write!(f, "movdn3"),
760            Self::MovDn4 => write!(f, "movdn4"),
761            Self::MovDn5 => write!(f, "movdn5"),
762            Self::MovDn6 => write!(f, "movdn6"),
763            Self::MovDn7 => write!(f, "movdn7"),
764            Self::MovDn8 => write!(f, "movdn8"),
765
766            Self::CSwap => write!(f, "cswap"),
767            Self::CSwapW => write!(f, "cswapw"),
768
769            // ----- input / output ---------------------------------------------------------------
770            Self::Push(value) => write!(f, "push({value})"),
771
772            Self::AdvPop => write!(f, "advpop"),
773            Self::AdvPopW => write!(f, "advpopw"),
774
775            Self::MLoadW => write!(f, "mloadw"),
776            Self::MStoreW => write!(f, "mstorew"),
777
778            Self::MLoad => write!(f, "mload"),
779            Self::MStore => write!(f, "mstore"),
780
781            Self::MStream => write!(f, "mstream"),
782            Self::Pipe => write!(f, "pipe"),
783
784            Self::Emit => write!(f, "emit"),
785
786            // ----- cryptographic operations -----------------------------------------------------
787            Self::HPerm => write!(f, "hperm"),
788            Self::MpVerify(err_code) => write!(f, "mpverify({err_code})"),
789            Self::MrUpdate => write!(f, "mrupdate"),
790
791            // ----- STARK proof verification -----------------------------------------------------
792            Self::FriE2F4 => write!(f, "frie2f4"),
793            Self::HornerBase => write!(f, "horner_eval_base"),
794            Self::HornerExt => write!(f, "horner_eval_ext"),
795            Self::EvalCircuit => write!(f, "eval_circuit"),
796        }
797    }
798}
799
800impl Serializable for Operation {
801    fn write_into<W: ByteWriter>(&self, target: &mut W) {
802        target.write_u8(self.op_code());
803
804        // For operations that have extra data, encode it in `data`.
805        match self {
806            Operation::Assert(err_code)
807            | Operation::MpVerify(err_code)
808            | Operation::U32assert2(err_code) => {
809                err_code.write_into(target);
810            },
811            Operation::Push(value) => value.as_int().write_into(target),
812
813            // Note: we explicitly write out all the operations so that whenever we make a
814            // modification to the `Operation` enum, we get a compile error here. This
815            // should help us remember to properly encode/decode each operation variant.
816            Operation::Noop
817            | Operation::FmpAdd
818            | Operation::FmpUpdate
819            | Operation::SDepth
820            | Operation::Caller
821            | Operation::Clk
822            | Operation::Join
823            | Operation::Split
824            | Operation::Loop
825            | Operation::Call
826            | Operation::Dyn
827            | Operation::Dyncall
828            | Operation::SysCall
829            | Operation::Span
830            | Operation::End
831            | Operation::Repeat
832            | Operation::Respan
833            | Operation::Halt
834            | Operation::Add
835            | Operation::Neg
836            | Operation::Mul
837            | Operation::Inv
838            | Operation::Incr
839            | Operation::And
840            | Operation::Or
841            | Operation::Not
842            | Operation::Eq
843            | Operation::Eqz
844            | Operation::Expacc
845            | Operation::Ext2Mul
846            | Operation::U32split
847            | Operation::U32add
848            | Operation::U32add3
849            | Operation::U32sub
850            | Operation::U32mul
851            | Operation::U32madd
852            | Operation::U32div
853            | Operation::U32and
854            | Operation::U32xor
855            | Operation::Pad
856            | Operation::Drop
857            | Operation::Dup0
858            | Operation::Dup1
859            | Operation::Dup2
860            | Operation::Dup3
861            | Operation::Dup4
862            | Operation::Dup5
863            | Operation::Dup6
864            | Operation::Dup7
865            | Operation::Dup9
866            | Operation::Dup11
867            | Operation::Dup13
868            | Operation::Dup15
869            | Operation::Swap
870            | Operation::SwapW
871            | Operation::SwapW2
872            | Operation::SwapW3
873            | Operation::SwapDW
874            | Operation::Emit
875            | Operation::MovUp2
876            | Operation::MovUp3
877            | Operation::MovUp4
878            | Operation::MovUp5
879            | Operation::MovUp6
880            | Operation::MovUp7
881            | Operation::MovUp8
882            | Operation::MovDn2
883            | Operation::MovDn3
884            | Operation::MovDn4
885            | Operation::MovDn5
886            | Operation::MovDn6
887            | Operation::MovDn7
888            | Operation::MovDn8
889            | Operation::CSwap
890            | Operation::CSwapW
891            | Operation::AdvPop
892            | Operation::AdvPopW
893            | Operation::MLoadW
894            | Operation::MStoreW
895            | Operation::MLoad
896            | Operation::MStore
897            | Operation::MStream
898            | Operation::Pipe
899            | Operation::HPerm
900            | Operation::MrUpdate
901            | Operation::FriE2F4
902            | Operation::HornerBase
903            | Operation::HornerExt
904            | Operation::EvalCircuit => (),
905        }
906    }
907}
908
909impl Deserializable for Operation {
910    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
911        let op_code = source.read_u8()?;
912
913        let operation = match op_code {
914            OPCODE_NOOP => Self::Noop,
915            OPCODE_EQZ => Self::Eqz,
916            OPCODE_NEG => Self::Neg,
917            OPCODE_INV => Self::Inv,
918            OPCODE_INCR => Self::Incr,
919            OPCODE_NOT => Self::Not,
920            OPCODE_FMPADD => Self::FmpAdd,
921            OPCODE_MLOAD => Self::MLoad,
922            OPCODE_SWAP => Self::Swap,
923            OPCODE_CALLER => Self::Caller,
924            OPCODE_MOVUP2 => Self::MovUp2,
925            OPCODE_MOVDN2 => Self::MovDn2,
926            OPCODE_MOVUP3 => Self::MovUp3,
927            OPCODE_MOVDN3 => Self::MovDn3,
928            OPCODE_ADVPOPW => Self::AdvPopW,
929            OPCODE_EXPACC => Self::Expacc,
930
931            OPCODE_MOVUP4 => Self::MovUp4,
932            OPCODE_MOVDN4 => Self::MovDn4,
933            OPCODE_MOVUP5 => Self::MovUp5,
934            OPCODE_MOVDN5 => Self::MovDn5,
935            OPCODE_MOVUP6 => Self::MovUp6,
936            OPCODE_MOVDN6 => Self::MovDn6,
937            OPCODE_MOVUP7 => Self::MovUp7,
938            OPCODE_MOVDN7 => Self::MovDn7,
939            OPCODE_SWAPW => Self::SwapW,
940            OPCODE_EXT2MUL => Self::Ext2Mul,
941            OPCODE_MOVUP8 => Self::MovUp8,
942            OPCODE_MOVDN8 => Self::MovDn8,
943            OPCODE_SWAPW2 => Self::SwapW2,
944            OPCODE_SWAPW3 => Self::SwapW3,
945            OPCODE_SWAPDW => Self::SwapDW,
946            OPCODE_EMIT => Self::Emit,
947
948            OPCODE_ASSERT => Self::Assert(Felt::read_from(source)?),
949            OPCODE_EQ => Self::Eq,
950            OPCODE_ADD => Self::Add,
951            OPCODE_MUL => Self::Mul,
952            OPCODE_AND => Self::And,
953            OPCODE_OR => Self::Or,
954            OPCODE_U32AND => Self::U32and,
955            OPCODE_U32XOR => Self::U32xor,
956            OPCODE_FRIE2F4 => Self::FriE2F4,
957            OPCODE_DROP => Self::Drop,
958            OPCODE_CSWAP => Self::CSwap,
959            OPCODE_CSWAPW => Self::CSwapW,
960            OPCODE_MLOADW => Self::MLoadW,
961            OPCODE_MSTORE => Self::MStore,
962            OPCODE_MSTOREW => Self::MStoreW,
963            OPCODE_FMPUPDATE => Self::FmpUpdate,
964
965            OPCODE_PAD => Self::Pad,
966            OPCODE_DUP0 => Self::Dup0,
967            OPCODE_DUP1 => Self::Dup1,
968            OPCODE_DUP2 => Self::Dup2,
969            OPCODE_DUP3 => Self::Dup3,
970            OPCODE_DUP4 => Self::Dup4,
971            OPCODE_DUP5 => Self::Dup5,
972            OPCODE_DUP6 => Self::Dup6,
973            OPCODE_DUP7 => Self::Dup7,
974            OPCODE_DUP9 => Self::Dup9,
975            OPCODE_DUP11 => Self::Dup11,
976            OPCODE_DUP13 => Self::Dup13,
977            OPCODE_DUP15 => Self::Dup15,
978            OPCODE_ADVPOP => Self::AdvPop,
979            OPCODE_SDEPTH => Self::SDepth,
980            OPCODE_CLK => Self::Clk,
981
982            OPCODE_U32ADD => Self::U32add,
983            OPCODE_U32SUB => Self::U32sub,
984            OPCODE_U32MUL => Self::U32mul,
985            OPCODE_U32DIV => Self::U32div,
986            OPCODE_U32SPLIT => Self::U32split,
987            OPCODE_U32ASSERT2 => Self::U32assert2(Felt::read_from(source)?),
988            OPCODE_U32ADD3 => Self::U32add3,
989            OPCODE_U32MADD => Self::U32madd,
990
991            OPCODE_HPERM => Self::HPerm,
992            OPCODE_MPVERIFY => Self::MpVerify(Felt::read_from(source)?),
993            OPCODE_PIPE => Self::Pipe,
994            OPCODE_MSTREAM => Self::MStream,
995            OPCODE_SPLIT => Self::Split,
996            OPCODE_LOOP => Self::Loop,
997            OPCODE_SPAN => Self::Span,
998            OPCODE_JOIN => Self::Join,
999            OPCODE_DYN => Self::Dyn,
1000            OPCODE_DYNCALL => Self::Dyncall,
1001            OPCODE_HORNERBASE => Self::HornerBase,
1002            OPCODE_HORNEREXT => Self::HornerExt,
1003            OPCODE_EVALCIRCUIT => Self::EvalCircuit,
1004
1005            OPCODE_MRUPDATE => Self::MrUpdate,
1006            OPCODE_PUSH => Self::Push(Felt::read_from(source)?),
1007            OPCODE_SYSCALL => Self::SysCall,
1008            OPCODE_CALL => Self::Call,
1009            OPCODE_END => Self::End,
1010            OPCODE_REPEAT => Self::Repeat,
1011            OPCODE_RESPAN => Self::Respan,
1012            OPCODE_HALT => Self::Halt,
1013            _ => {
1014                return Err(DeserializationError::InvalidValue(format!(
1015                    "Invalid opcode '{op_code}'"
1016                )));
1017            },
1018        };
1019
1020        Ok(operation)
1021    }
1022}