Skip to main content

nu_protocol/engine/
error_handler.rs

1use crate::RegId;
2
3/// Describes where a `catch` or `finally` handler lives during IR evaluation.
4#[derive(Debug, Clone, Copy)]
5pub struct ErrorHandler {
6    /// Instruction index within the block that will handle the error
7    pub handler_index: usize,
8    /// Register to put the error information into, when an error occurs
9    pub error_register: Option<RegId>,
10}
11
12/// An entry on the handler stack maintained while evaluating a `try` expression.
13///
14/// Entries are pushed in the order they are set up, so the innermost handler is always on top.
15/// When control flow unwinds out of a `try` body (an error, `return`, `exit`, `break`, or
16/// `continue`), the evaluator pops entries from the top until one takes over.
17#[derive(Debug, Clone, Copy)]
18pub enum TryHandler {
19    /// A `catch` block. Only errors are directed here; other unwinding just discards the entry.
20    Catch(ErrorHandler),
21    /// A `finally` block that has not run yet. Every kind of unwinding is directed here first,
22    /// and resumes once the block finishes.
23    Finally(ErrorHandler),
24    /// A `finally` block that is currently running. It replaces the [`TryHandler::Finally`]
25    /// entry for the duration of the block so that unwinding out of the block itself (for
26    /// example a `return` inside `finally`) knows to abandon whatever the block was going to
27    /// resume.
28    RunningFinally,
29}
30
31/// Keeps track of handlers pushed during evaluation of an IR block.
32#[derive(Debug, Clone, Default)]
33pub struct ErrorHandlerStack {
34    handlers: Vec<TryHandler>,
35}
36
37impl ErrorHandlerStack {
38    pub const fn new() -> ErrorHandlerStack {
39        ErrorHandlerStack { handlers: vec![] }
40    }
41
42    /// Get the current base of the stack, which establishes a frame.
43    pub fn get_base(&self) -> usize {
44        self.handlers.len()
45    }
46
47    /// Push a new handler onto the stack.
48    pub fn push(&mut self, handler: TryHandler) {
49        self.handlers.push(handler);
50    }
51
52    /// Try to pop a handler from the stack. Won't go below `base`, to avoid retrieving a
53    /// handler belonging to a parent frame.
54    pub fn pop(&mut self, base: usize) -> Option<TryHandler> {
55        if self.handlers.len() > base {
56            self.handlers.pop()
57        } else {
58            None
59        }
60    }
61
62    /// Reset the stack to the state it was in at the beginning of the frame, in preparation to
63    /// return control to the parent frame.
64    pub fn leave_frame(&mut self, base: usize) {
65        if self.handlers.len() >= base {
66            self.handlers.truncate(base);
67        } else {
68            panic!(
69                "ErrorHandlerStack bug: tried to leave frame at {base}, but current base is {}",
70                self.get_base()
71            )
72        }
73    }
74}