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