zingen/
backtrace.rs

1//! Backtrace support for the code generation.
2use std::collections::BTreeMap;
3
4/// Backtrace implementation for the code generation.
5///
6/// TODO: full implementation (#21)
7#[derive(Debug, Default)]
8pub struct Backtrace {
9    /// Compiled instructions.
10    ///
11    /// TODO: Transform this into Opcodes. (#21)
12    instrs: BTreeMap<usize, Vec<u8>>,
13}
14
15impl Backtrace {
16    /// Pushes a new instruction set to the backtrace.
17    pub fn push(&mut self, bytes: impl AsRef<[u8]>) {
18        self.instrs.insert(self.instrs.len(), bytes.as_ref().into());
19    }
20
21    /// Pops the last instruction from the backtrace.
22    pub fn pop(&mut self) -> Vec<u8> {
23        self.instrs.pop_last().unwrap_or_default().1
24    }
25
26    /// Get the last byte
27    pub fn last(&self) -> Option<Vec<u8>> {
28        self.instrs.last_key_value().map(|(_, op)| op.clone())
29    }
30
31    /// Pop the last `n` operands from the backtrace.
32    pub fn popn(&mut self, n: usize) -> Vec<Vec<u8>> {
33        let mut r: Vec<Vec<u8>> = Default::default();
34
35        while r.len() < n {
36            r.push(self.pop())
37        }
38
39        r
40    }
41}