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