Skip to main content

revm_bytecode/
opcode.rs

1//! EVM opcode definitions and utilities. It contains opcode information and utilities to work with opcodes.
2
3#[cfg(feature = "parse")]
4pub mod parse;
5
6use core::{fmt, ptr::NonNull};
7
8/// An EVM opcode
9///
10/// This is always a valid opcode, as declared in the [`opcode`][self] module or the
11/// [`OPCODE_INFO`] constant.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
13#[repr(transparent)]
14pub struct OpCode(u8);
15
16impl fmt::Display for OpCode {
17    /// Formats the opcode as a string
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        let n = self.get();
20        if let Some(val) = OPCODE_INFO[n as usize] {
21            f.write_str(val.name())
22        } else {
23            write!(f, "UNKNOWN(0x{n:02X})")
24        }
25    }
26}
27
28impl OpCode {
29    /// Instantiates a new opcode from a u8.
30    ///
31    /// Returns None if the opcode is not valid.
32    #[inline]
33    pub const fn new(opcode: u8) -> Option<Self> {
34        match OPCODE_INFO[opcode as usize] {
35            Some(_) => Some(Self(opcode)),
36            None => None,
37        }
38    }
39
40    /// Returns true if the opcode is a jump destination.
41    #[inline]
42    pub const fn is_jumpdest(&self) -> bool {
43        self.0 == JUMPDEST
44    }
45
46    /// Takes a u8 and returns true if it is a jump destination.
47    #[inline]
48    pub const fn is_jumpdest_by_op(opcode: u8) -> bool {
49        if let Some(opcode) = Self::new(opcode) {
50            opcode.is_jumpdest()
51        } else {
52            false
53        }
54    }
55
56    /// Returns true if the opcode is a legacy jump instruction.
57    #[inline]
58    pub const fn is_jump(self) -> bool {
59        self.0 == JUMP
60    }
61
62    /// Takes a u8 and returns true if it is a jump instruction.
63    #[inline]
64    pub const fn is_jump_by_op(opcode: u8) -> bool {
65        if let Some(opcode) = Self::new(opcode) {
66            opcode.is_jump()
67        } else {
68            false
69        }
70    }
71
72    /// Returns true if the opcode is a `PUSH` instruction.
73    #[inline]
74    pub const fn is_push(self) -> bool {
75        self.0 >= PUSH1 && self.0 <= PUSH32
76    }
77
78    /// Takes a u8 and returns true if it is a push instruction.
79    #[inline]
80    pub fn is_push_by_op(opcode: u8) -> bool {
81        if let Some(opcode) = Self::new(opcode) {
82            opcode.is_push()
83        } else {
84            false
85        }
86    }
87
88    /// Instantiates a new opcode from a u8 without checking if it is valid.
89    ///
90    /// # Safety
91    ///
92    /// All code using `Opcode` values assume that they are valid opcodes, so providing an invalid
93    /// opcode may cause undefined behavior.
94    #[inline]
95    pub unsafe fn new_unchecked(opcode: u8) -> Self {
96        Self(opcode)
97    }
98
99    /// Returns the opcode as a string. This is the inverse of [`parse`](Self::parse).
100    #[doc(alias = "name")]
101    #[inline]
102    pub const fn as_str(self) -> &'static str {
103        self.info().name()
104    }
105
106    /// Returns the opcode name.
107    #[inline]
108    pub const fn name_by_op(opcode: u8) -> &'static str {
109        if let Some(opcode) = Self::new(opcode) {
110            opcode.as_str()
111        } else {
112            "Unknown"
113        }
114    }
115
116    /// Returns the number of input stack elements.
117    #[inline]
118    pub const fn inputs(&self) -> u8 {
119        self.info().inputs()
120    }
121
122    /// Returns the number of output stack elements.
123    #[inline]
124    pub const fn outputs(&self) -> u8 {
125        self.info().outputs()
126    }
127
128    /// Calculates the difference between the number of input and output stack elements.
129    #[inline]
130    pub const fn io_diff(&self) -> i16 {
131        self.info().io_diff()
132    }
133
134    /// Returns the opcode information for the given opcode.
135    /// Check [OpCodeInfo] for more information.
136    #[inline]
137    pub const fn info_by_op(opcode: u8) -> Option<OpCodeInfo> {
138        if let Some(opcode) = Self::new(opcode) {
139            Some(opcode.info())
140        } else {
141            None
142        }
143    }
144
145    /// Returns the opcode as a usize.
146    #[inline]
147    pub const fn as_usize(&self) -> usize {
148        self.0 as usize
149    }
150
151    /// Returns the opcode information.
152    #[inline]
153    pub const fn info(&self) -> OpCodeInfo {
154        if let Some(t) = OPCODE_INFO[self.0 as usize] {
155            t
156        } else {
157            panic!("opcode not found")
158        }
159    }
160
161    /// Returns the number of both input and output stack elements.
162    ///
163    /// Can be slightly faster than calling `inputs` and `outputs` separately.
164    pub const fn input_output(&self) -> (u8, u8) {
165        let info = self.info();
166        (info.inputs, info.outputs)
167    }
168
169    /// Returns the opcode as a u8.
170    #[inline]
171    pub const fn get(self) -> u8 {
172        self.0
173    }
174
175    /// Returns true if the opcode modifies memory.
176    ///
177    /// <https://docs.rs/revm-interpreter/latest/revm_interpreter/instructions/index.html>
178    ///
179    /// <https://github.com/crytic/evm-opcodes>
180    #[inline]
181    pub const fn modifies_memory(&self) -> bool {
182        matches!(
183            *self,
184            OpCode::EXTCODECOPY
185                | OpCode::MLOAD
186                | OpCode::MSTORE
187                | OpCode::MSTORE8
188                | OpCode::MCOPY
189                | OpCode::KECCAK256
190                | OpCode::CODECOPY
191                | OpCode::CALLDATACOPY
192                | OpCode::RETURNDATACOPY
193                | OpCode::CALL
194                | OpCode::CALLCODE
195                | OpCode::DELEGATECALL
196                | OpCode::STATICCALL
197                | OpCode::LOG0
198                | OpCode::LOG1
199                | OpCode::LOG2
200                | OpCode::LOG3
201                | OpCode::LOG4
202                | OpCode::CREATE
203                | OpCode::CREATE2
204        )
205    }
206
207    /// Returns true if the opcode is valid
208    #[inline]
209    pub const fn is_valid(&self) -> bool {
210        OPCODE_INFO[self.0 as usize].is_some()
211    }
212}
213
214impl PartialEq<u8> for OpCode {
215    fn eq(&self, other: &u8) -> bool {
216        self.get().eq(other)
217    }
218}
219
220/// Information about opcode, such as name, and stack inputs and outputs
221#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
222pub struct OpCodeInfo {
223    /// Invariant: `(name_ptr, name_len)` is a [`&'static str`][str].
224    ///
225    /// It is a shorted variant of [`str`] as
226    /// the name length is always less than 256 characters.
227    name_ptr: NonNull<u8>,
228    name_len: u8,
229    /// Stack inputs
230    inputs: u8,
231    /// Stack outputs
232    outputs: u8,
233    /// Number of intermediate bytes
234    immediate_size: u8,
235    /// If the opcode stops execution. aka STOP, RETURN, ..
236    terminating: bool,
237}
238
239// SAFETY: The `NonNull` is just a `&'static str`.
240unsafe impl Send for OpCodeInfo {}
241unsafe impl Sync for OpCodeInfo {}
242
243impl fmt::Debug for OpCodeInfo {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        f.debug_struct("OpCodeInfo")
246            .field("name", &self.name())
247            .field("inputs", &self.inputs())
248            .field("outputs", &self.outputs())
249            .field("terminating", &self.is_terminating())
250            .field("immediate_size", &self.immediate_size())
251            .finish()
252    }
253}
254
255impl OpCodeInfo {
256    /// Creates a new opcode info with the given name and default values.
257    pub const fn new(name: &'static str) -> Self {
258        assert!(name.len() < 256, "opcode name is too long");
259        Self {
260            name_ptr: unsafe { NonNull::new_unchecked(name.as_ptr().cast_mut()) },
261            name_len: name.len() as u8,
262            inputs: 0,
263            outputs: 0,
264            terminating: false,
265            immediate_size: 0,
266        }
267    }
268
269    /// Returns the opcode name.
270    #[inline]
271    pub const fn name(&self) -> &'static str {
272        // SAFETY: `self.name_*` can only be initialized with a valid `&'static str`.
273        unsafe {
274            let slice = std::slice::from_raw_parts(self.name_ptr.as_ptr(), self.name_len as usize);
275            core::str::from_utf8_unchecked(slice)
276        }
277    }
278
279    /// Calculates the difference between the number of input and output stack elements.
280    #[inline]
281    pub const fn io_diff(&self) -> i16 {
282        self.outputs as i16 - self.inputs as i16
283    }
284
285    /// Returns the number of input stack elements.
286    #[inline]
287    pub const fn inputs(&self) -> u8 {
288        self.inputs
289    }
290
291    /// Returns the number of output stack elements.
292    #[inline]
293    pub const fn outputs(&self) -> u8 {
294        self.outputs
295    }
296
297    /// Returns whether this opcode terminates execution, e.g. `STOP`, `RETURN`, etc.
298    #[inline]
299    pub const fn is_terminating(&self) -> bool {
300        self.terminating
301    }
302
303    /// Returns the size of the immediate value in bytes.
304    #[inline]
305    pub const fn immediate_size(&self) -> u8 {
306        self.immediate_size
307    }
308}
309
310/// Used for [`OPCODE_INFO`] to set the immediate bytes number in the [`OpCodeInfo`].
311#[inline]
312pub const fn immediate_size(mut op: OpCodeInfo, n: u8) -> OpCodeInfo {
313    op.immediate_size = n;
314    op
315}
316
317/// Used for [`OPCODE_INFO`] to set the terminating flag to true in the [`OpCodeInfo`].
318#[inline]
319pub const fn terminating(mut op: OpCodeInfo) -> OpCodeInfo {
320    op.terminating = true;
321    op
322}
323
324/// Use for [`OPCODE_INFO`] to sets the number of stack inputs and outputs in the [`OpCodeInfo`].
325#[inline]
326pub const fn stack_io(mut op: OpCodeInfo, inputs: u8, outputs: u8) -> OpCodeInfo {
327    op.inputs = inputs;
328    op.outputs = outputs;
329    op
330}
331
332/// Alias for the [`JUMPDEST`] opcode
333pub const NOP: u8 = JUMPDEST;
334
335/// Created all opcodes constants and two maps:
336///  * `OPCODE_INFO` maps opcode number to the opcode info
337///  * `NAME_TO_OPCODE` that maps opcode name to the opcode number.
338macro_rules! opcodes {
339    ($($val:literal => $name:ident => $($modifier:ident $(( $($modifier_arg:expr),* ))?),*);* $(;)?) => {
340        // Constants for each opcode. This also takes care of duplicate names.
341        $(
342            #[doc = concat!("The `", stringify!($val), "` (\"", stringify!($name),"\") opcode.")]
343            pub const $name: u8 = $val;
344        )*
345        impl OpCode {$(
346            #[doc = concat!("The `", stringify!($val), "` (\"", stringify!($name),"\") opcode.")]
347            pub const $name: Self = Self($val);
348        )*}
349
350        /// Maps each opcode to its info.
351        pub static OPCODE_INFO: [Option<OpCodeInfo>; 256] = {
352            let mut map = [None; 256];
353            let mut prev: u8 = 0;
354            $(
355                let val: u8 = $val;
356                assert!(val == 0 || val > prev, "opcodes must be sorted in ascending order");
357                prev = val;
358                let info = OpCodeInfo::new(stringify!($name));
359                $(
360                let info = $modifier(info, $($($modifier_arg),*)?);
361                )*
362                map[$val] = Some(info);
363            )*
364            let _ = prev;
365            map
366        };
367
368
369        /// Maps each name to its opcode.
370        #[cfg(feature = "parse")]
371        pub(crate) static NAME_TO_OPCODE: phf::Map<&'static str, OpCode> = stringify_with_cb! { phf_map_cb; $($name)* };
372    };
373}
374
375/// Callback for creating a [`phf`] map with `stringify_with_cb`.
376#[cfg(feature = "parse")]
377macro_rules! phf_map_cb {
378    ($(#[doc = $s:literal] $id:ident)*) => {
379        phf::phf_map! {
380            $($s => OpCode::$id),*
381        }
382    };
383}
384
385/// Stringifies identifiers with `paste` so that they are available as literals.
386///
387/// This doesn't work with [`stringify!`] because it cannot be expanded inside of another macro.
388#[cfg(feature = "parse")]
389macro_rules! stringify_with_cb {
390    ($callback:ident; $($id:ident)*) => { paste::paste! {
391        $callback! { $(#[doc = "" $id ""] $id)* }
392    }};
393}
394
395// When adding new opcodes:
396// 1. add the opcode to the list below; make sure it's sorted by opcode value
397// 2. implement the opcode in the corresponding module;
398//    the function signature must be the exact same as the others
399opcodes! {
400    0x00 => STOP     => stack_io(0, 0), terminating;
401    0x01 => ADD      => stack_io(2, 1);
402    0x02 => MUL      => stack_io(2, 1);
403    0x03 => SUB      => stack_io(2, 1);
404    0x04 => DIV      => stack_io(2, 1);
405    0x05 => SDIV     => stack_io(2, 1);
406    0x06 => MOD      => stack_io(2, 1);
407    0x07 => SMOD     => stack_io(2, 1);
408    0x08 => ADDMOD   => stack_io(3, 1);
409    0x09 => MULMOD   => stack_io(3, 1);
410    0x0A => EXP      => stack_io(2, 1);
411    0x0B => SIGNEXTEND => stack_io(2, 1);
412    // 0x0C
413    // 0x0D
414    // 0x0E
415    // 0x0F
416    0x10 => LT   => stack_io(2, 1);
417    0x11 => GT   => stack_io(2, 1);
418    0x12 => SLT  => stack_io(2, 1);
419    0x13 => SGT  => stack_io(2, 1);
420    0x14 => EQ   => stack_io(2, 1);
421    0x15 => ISZERO => stack_io(1, 1);
422    0x16 => AND  => stack_io(2, 1);
423    0x17 => OR   => stack_io(2, 1);
424    0x18 => XOR  => stack_io(2, 1);
425    0x19 => NOT  => stack_io(1, 1);
426    0x1A => BYTE => stack_io(2, 1);
427    0x1B => SHL  => stack_io(2, 1);
428    0x1C => SHR  => stack_io(2, 1);
429    0x1D => SAR  => stack_io(2, 1);
430    0x1E => CLZ => stack_io(1, 1);
431    // 0x1F
432    0x20 => KECCAK256 => stack_io(2, 1);
433    // 0x21
434    // 0x22
435    // 0x23
436    // 0x24
437    // 0x25
438    // 0x26
439    // 0x27
440    // 0x28
441    // 0x29
442    // 0x2A
443    // 0x2B
444    // 0x2C
445    // 0x2D
446    // 0x2E
447    // 0x2F
448    0x30 => ADDRESS    => stack_io(0, 1);
449    0x31 => BALANCE    => stack_io(1, 1);
450    0x32 => ORIGIN     => stack_io(0, 1);
451    0x33 => CALLER     => stack_io(0, 1);
452    0x34 => CALLVALUE  => stack_io(0, 1);
453    0x35 => CALLDATALOAD => stack_io(1, 1);
454    0x36 => CALLDATASIZE => stack_io(0, 1);
455    0x37 => CALLDATACOPY => stack_io(3, 0);
456    0x38 => CODESIZE   => stack_io(0, 1);
457    0x39 => CODECOPY   => stack_io(3, 0);
458
459    0x3A => GASPRICE     => stack_io(0, 1);
460    0x3B => EXTCODESIZE  => stack_io(1, 1);
461    0x3C => EXTCODECOPY  => stack_io(4, 0);
462    0x3D => RETURNDATASIZE => stack_io(0, 1);
463    0x3E => RETURNDATACOPY => stack_io(3, 0);
464    0x3F => EXTCODEHASH  => stack_io(1, 1);
465    0x40 => BLOCKHASH    => stack_io(1, 1);
466    0x41 => COINBASE     => stack_io(0, 1);
467    0x42 => TIMESTAMP    => stack_io(0, 1);
468    0x43 => NUMBER       => stack_io(0, 1);
469    0x44 => DIFFICULTY   => stack_io(0, 1);
470    0x45 => GASLIMIT     => stack_io(0, 1);
471    0x46 => CHAINID      => stack_io(0, 1);
472    0x47 => SELFBALANCE  => stack_io(0, 1);
473    0x48 => BASEFEE      => stack_io(0, 1);
474    0x49 => BLOBHASH     => stack_io(1, 1);
475    0x4A => BLOBBASEFEE  => stack_io(0, 1);
476    0x4B => SLOTNUM      => stack_io(0, 1);
477    // 0x4C
478    // 0x4D
479    // 0x4E
480    // 0x4F
481    0x50 => POP      => stack_io(1, 0);
482    0x51 => MLOAD    => stack_io(1, 1);
483    0x52 => MSTORE   => stack_io(2, 0);
484    0x53 => MSTORE8  => stack_io(2, 0);
485    0x54 => SLOAD    => stack_io(1, 1);
486    0x55 => SSTORE   => stack_io(2, 0);
487    0x56 => JUMP     => stack_io(1, 0);
488    0x57 => JUMPI    => stack_io(2, 0);
489    0x58 => PC       => stack_io(0, 1);
490    0x59 => MSIZE    => stack_io(0, 1);
491    0x5A => GAS      => stack_io(0, 1);
492    0x5B => JUMPDEST => stack_io(0, 0);
493    0x5C => TLOAD    => stack_io(1, 1);
494    0x5D => TSTORE   => stack_io(2, 0);
495    0x5E => MCOPY    => stack_io(3, 0);
496
497    0x5F => PUSH0  => stack_io(0, 1);
498    0x60 => PUSH1  => stack_io(0, 1), immediate_size(1);
499    0x61 => PUSH2  => stack_io(0, 1), immediate_size(2);
500    0x62 => PUSH3  => stack_io(0, 1), immediate_size(3);
501    0x63 => PUSH4  => stack_io(0, 1), immediate_size(4);
502    0x64 => PUSH5  => stack_io(0, 1), immediate_size(5);
503    0x65 => PUSH6  => stack_io(0, 1), immediate_size(6);
504    0x66 => PUSH7  => stack_io(0, 1), immediate_size(7);
505    0x67 => PUSH8  => stack_io(0, 1), immediate_size(8);
506    0x68 => PUSH9  => stack_io(0, 1), immediate_size(9);
507    0x69 => PUSH10 => stack_io(0, 1), immediate_size(10);
508    0x6A => PUSH11 => stack_io(0, 1), immediate_size(11);
509    0x6B => PUSH12 => stack_io(0, 1), immediate_size(12);
510    0x6C => PUSH13 => stack_io(0, 1), immediate_size(13);
511    0x6D => PUSH14 => stack_io(0, 1), immediate_size(14);
512    0x6E => PUSH15 => stack_io(0, 1), immediate_size(15);
513    0x6F => PUSH16 => stack_io(0, 1), immediate_size(16);
514    0x70 => PUSH17 => stack_io(0, 1), immediate_size(17);
515    0x71 => PUSH18 => stack_io(0, 1), immediate_size(18);
516    0x72 => PUSH19 => stack_io(0, 1), immediate_size(19);
517    0x73 => PUSH20 => stack_io(0, 1), immediate_size(20);
518    0x74 => PUSH21 => stack_io(0, 1), immediate_size(21);
519    0x75 => PUSH22 => stack_io(0, 1), immediate_size(22);
520    0x76 => PUSH23 => stack_io(0, 1), immediate_size(23);
521    0x77 => PUSH24 => stack_io(0, 1), immediate_size(24);
522    0x78 => PUSH25 => stack_io(0, 1), immediate_size(25);
523    0x79 => PUSH26 => stack_io(0, 1), immediate_size(26);
524    0x7A => PUSH27 => stack_io(0, 1), immediate_size(27);
525    0x7B => PUSH28 => stack_io(0, 1), immediate_size(28);
526    0x7C => PUSH29 => stack_io(0, 1), immediate_size(29);
527    0x7D => PUSH30 => stack_io(0, 1), immediate_size(30);
528    0x7E => PUSH31 => stack_io(0, 1), immediate_size(31);
529    0x7F => PUSH32 => stack_io(0, 1), immediate_size(32);
530
531    0x80 => DUP1  => stack_io(1, 2);
532    0x81 => DUP2  => stack_io(2, 3);
533    0x82 => DUP3  => stack_io(3, 4);
534    0x83 => DUP4  => stack_io(4, 5);
535    0x84 => DUP5  => stack_io(5, 6);
536    0x85 => DUP6  => stack_io(6, 7);
537    0x86 => DUP7  => stack_io(7, 8);
538    0x87 => DUP8  => stack_io(8, 9);
539    0x88 => DUP9  => stack_io(9, 10);
540    0x89 => DUP10 => stack_io(10, 11);
541    0x8A => DUP11 => stack_io(11, 12);
542    0x8B => DUP12 => stack_io(12, 13);
543    0x8C => DUP13 => stack_io(13, 14);
544    0x8D => DUP14 => stack_io(14, 15);
545    0x8E => DUP15 => stack_io(15, 16);
546    0x8F => DUP16 => stack_io(16, 17);
547
548    0x90 => SWAP1  => stack_io(2, 2);
549    0x91 => SWAP2  => stack_io(3, 3);
550    0x92 => SWAP3  => stack_io(4, 4);
551    0x93 => SWAP4  => stack_io(5, 5);
552    0x94 => SWAP5  => stack_io(6, 6);
553    0x95 => SWAP6  => stack_io(7, 7);
554    0x96 => SWAP7  => stack_io(8, 8);
555    0x97 => SWAP8  => stack_io(9, 9);
556    0x98 => SWAP9  => stack_io(10, 10);
557    0x99 => SWAP10 => stack_io(11, 11);
558    0x9A => SWAP11 => stack_io(12, 12);
559    0x9B => SWAP12 => stack_io(13, 13);
560    0x9C => SWAP13 => stack_io(14, 14);
561    0x9D => SWAP14 => stack_io(15, 15);
562    0x9E => SWAP15 => stack_io(16, 16);
563    0x9F => SWAP16 => stack_io(17, 17);
564
565    0xA0 => LOG0 => stack_io(2, 0);
566    0xA1 => LOG1 => stack_io(3, 0);
567    0xA2 => LOG2 => stack_io(4, 0);
568    0xA3 => LOG3 => stack_io(5, 0);
569    0xA4 => LOG4 => stack_io(6, 0);
570    // 0xA5
571    // 0xA6
572    // 0xA7
573    // 0xA8
574    // 0xA9
575    // 0xAA
576    // 0xAB
577    // 0xAC
578    // 0xAD
579    // 0xAE
580    // 0xAF
581    // 0xB0
582    // 0xB1
583    // 0xB2
584    // 0xB3
585    // 0xB4
586    // 0xB5
587    // 0xB6
588    // 0xB7
589    // 0xB8
590    // 0xB9
591    // 0xBA
592    // 0xBB
593    // 0xBC
594    // 0xBD
595    // 0xBE
596    // 0xBF
597    // 0xC0
598    // 0xC1
599    // 0xC2
600    // 0xC3
601    // 0xC4
602    // 0xC5
603    // 0xC6
604    // 0xC7
605    // 0xC8
606    // 0xC9
607    // 0xCA
608    // 0xCB
609    // 0xCC
610    // 0xCD
611    // 0xCE
612    // 0xCF
613    // 0xD0
614    // 0xD1
615    // 0xD2
616    // 0xD3
617    // 0xD4
618    // 0xD5
619    // 0xD6
620    // 0xD7
621    // 0xD8
622    // 0xD9
623    // 0xDA
624    // 0xDB
625    // 0xDC
626    // 0xDD
627    // 0xDE
628    // 0xDF
629    // 0xE0
630    // 0xE1
631    // 0xE2
632    // 0xE3
633    // 0xE4
634    // 0xE5
635    0xE6 => DUPN     => stack_io(0, 1), immediate_size(1);
636    0xE7 => SWAPN    => stack_io(0, 0), immediate_size(1);
637    0xE8 => EXCHANGE => stack_io(0, 0), immediate_size(1);
638    // 0xE9
639    // 0xEA
640    // 0xEB
641    // 0xEC
642    // 0xED
643    // 0xEE
644    // 0xEF
645    0xF0 => CREATE       => stack_io(3, 1);
646    0xF1 => CALL         => stack_io(7, 1);
647    0xF2 => CALLCODE     => stack_io(7, 1);
648    0xF3 => RETURN       => stack_io(2, 0), terminating;
649    0xF4 => DELEGATECALL => stack_io(6, 1);
650    0xF5 => CREATE2      => stack_io(4, 1);
651    // 0xF6
652    // 0xF7
653    // 0xF8
654    // 0xF9
655    0xFA => STATICCALL      => stack_io(6, 1);
656    // 0xFB
657    // 0xFC
658    0xFD => REVERT       => stack_io(2, 0), terminating;
659    0xFE => INVALID      => stack_io(0, 0), terminating;
660    0xFF => SELFDESTRUCT => stack_io(1, 0), terminating;
661}
662
663#[cfg(test)]
664mod tests {
665    use super::*;
666
667    #[test]
668    fn test_opcode() {
669        let opcode = OpCode::new(0x00).unwrap();
670        assert!(!opcode.is_jumpdest());
671        assert!(!opcode.is_jump());
672        assert!(!opcode.is_push());
673        assert_eq!(opcode.as_str(), "STOP");
674        assert_eq!(opcode.get(), 0x00);
675    }
676
677    #[test]
678    fn test_immediate_size() {
679        let mut expected = [0u8; 256];
680
681        for push in PUSH1..=PUSH32 {
682            expected[push as usize] = push - PUSH1 + 1;
683        }
684
685        for stack_op in [DUPN, SWAPN, EXCHANGE] {
686            expected[stack_op as usize] = 1;
687        }
688
689        for (i, opcode) in OPCODE_INFO.iter().enumerate() {
690            if let Some(opcode) = opcode {
691                assert_eq!(
692                    opcode.immediate_size(),
693                    expected[i],
694                    "immediate_size check failed for {opcode:#?}",
695                );
696            }
697        }
698    }
699
700    #[test]
701    fn test_enabled_opcodes() {
702        // List obtained from https://eips.ethereum.org/EIPS/eip-3670
703        let opcodes = [
704            0x10..=0x1d,
705            0x20..=0x20,
706            0x30..=0x3f,
707            0x40..=0x48,
708            0x50..=0x5b,
709            0x54..=0x5f,
710            0x60..=0x6f,
711            0x70..=0x7f,
712            0x80..=0x8f,
713            0x90..=0x9f,
714            0xa0..=0xa4,
715            0xf0..=0xf5,
716            0xfa..=0xfa,
717            0xfd..=0xfd,
718            //0xfe,
719            0xff..=0xff,
720        ];
721        for i in opcodes {
722            for opcode in i {
723                OpCode::new(opcode).expect("Opcode should be valid and enabled");
724            }
725        }
726    }
727
728    #[test]
729    fn count_opcodes() {
730        let mut opcode_num = 0;
731        for _ in OPCODE_INFO.into_iter().flatten() {
732            opcode_num += 1;
733        }
734        assert_eq!(opcode_num, 154);
735    }
736
737    #[test]
738    fn test_terminating_opcodes() {
739        let terminating = [REVERT, RETURN, INVALID, SELFDESTRUCT, STOP];
740        let mut opcodes = [false; 256];
741        for terminating in terminating.iter() {
742            opcodes[*terminating as usize] = true;
743        }
744
745        for (i, opcode) in OPCODE_INFO.into_iter().enumerate() {
746            assert_eq!(
747                opcode.map(|opcode| opcode.terminating).unwrap_or_default(),
748                opcodes[i],
749                "Opcode {opcode:?} terminating check failed."
750            );
751        }
752    }
753
754    #[test]
755    #[cfg(feature = "parse")]
756    fn test_parsing() {
757        for i in 0..=u8::MAX {
758            if let Some(op) = OpCode::new(i) {
759                assert_eq!(OpCode::parse(op.as_str()), Some(op));
760            }
761        }
762    }
763
764    #[test]
765    #[should_panic(expected = "opcode not found")]
766    fn test_new_unchecked_invalid() {
767        let op = unsafe { OpCode::new_unchecked(0x0C) };
768        op.info();
769    }
770
771    #[test]
772    fn test_op_code_valid() {
773        let op1 = OpCode::new(ADD).unwrap();
774        let op2 = OpCode::new(MUL).unwrap();
775        assert!(op1.is_valid());
776        assert!(op2.is_valid());
777
778        let op3 = unsafe { OpCode::new_unchecked(0x0C) };
779        assert!(!op3.is_valid());
780    }
781
782    #[test]
783    fn test_modifies_memory() {
784        assert!(OpCode::new(MLOAD).unwrap().modifies_memory());
785        assert!(OpCode::new(MSTORE).unwrap().modifies_memory());
786        assert!(OpCode::new(KECCAK256).unwrap().modifies_memory());
787        assert!(!OpCode::new(ADD).unwrap().modifies_memory());
788        assert!(OpCode::new(LOG0).unwrap().modifies_memory());
789        assert!(OpCode::new(LOG1).unwrap().modifies_memory());
790        assert!(OpCode::new(LOG2).unwrap().modifies_memory());
791        assert!(OpCode::new(LOG3).unwrap().modifies_memory());
792        assert!(OpCode::new(LOG4).unwrap().modifies_memory());
793        assert!(OpCode::new(CREATE).unwrap().modifies_memory());
794        assert!(OpCode::new(CREATE2).unwrap().modifies_memory());
795    }
796}