revm_interpreter/
function_stack.rs

1use std::vec::Vec;
2
3/// Function return frame.
4/// Needed information for returning from a function.
5#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7pub struct FunctionReturnFrame {
8    /// The index of the code container that this frame is executing.
9    pub idx: usize,
10    /// The program counter where frame execution should continue.
11    pub pc: usize,
12}
13
14impl FunctionReturnFrame {
15    /// Return new function frame.
16    pub fn new(idx: usize, pc: usize) -> Self {
17        Self { idx, pc }
18    }
19}
20
21/// Function Stack
22#[derive(Clone, Debug, Default, PartialEq, Eq)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub struct FunctionStack {
25    pub return_stack: Vec<FunctionReturnFrame>,
26    pub current_code_idx: usize,
27}
28
29impl FunctionStack {
30    /// Returns new function stack.
31    pub fn new() -> Self {
32        Self {
33            return_stack: Vec::new(),
34            current_code_idx: 0,
35        }
36    }
37
38    /// Pushes a new frame to the stack. and sets current_code_idx to new value.
39    pub fn push(&mut self, program_counter: usize, new_idx: usize) {
40        self.return_stack.push(FunctionReturnFrame {
41            idx: self.current_code_idx,
42            pc: program_counter,
43        });
44        self.current_code_idx = new_idx;
45    }
46
47    /// Return stack length
48    pub fn return_stack_len(&self) -> usize {
49        self.return_stack.len()
50    }
51
52    /// Pops a frame from the stack and sets current_code_idx to the popped frame's idx.
53    pub fn pop(&mut self) -> Option<FunctionReturnFrame> {
54        self.return_stack
55            .pop()
56            .inspect(|frame| self.current_code_idx = frame.idx)
57    }
58
59    /// Sets current_code_idx, this is needed for JUMPF opcode.
60    pub fn set_current_code_idx(&mut self, idx: usize) {
61        self.current_code_idx = idx;
62    }
63}