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