stack_vm/code/
debug.rs

1use super::Code;
2use std::fmt;
3
4impl<T: fmt::Debug> fmt::Debug for Code<T> {
5    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6        let mut result = String::new();
7
8        // Write out constant data into the header.
9        for i in 0..self.data.len() {
10            result.push_str(&format!("@{} = {:?}\n", i, self.data[i]));
11        }
12
13        // Loop through the code and print out useful stuff.
14        let mut ip = 0;
15        let len = self.code.len();
16        loop {
17            // If this IP has a label, then print it out.
18            for label in self.labels() {
19                if ip == label.0 {
20                    result.push_str(&format!("\n.{}:\n", label.1));
21                    break;
22                }
23            }
24
25            if ip == len {
26                break;
27            }
28
29            let op_code = self.code[ip];
30            let arity = self.code[ip + 1];
31            ip += 2;
32
33            // Print this instruction's name
34            for symbol in self.symbols() {
35                if op_code == symbol.0 {
36                    result.push_str(&format!("\t{}", symbol.1));
37                    break;
38                }
39            }
40
41            for _i in 0..arity {
42                let const_idx = self.code[ip];
43                ip += 1;
44                result.push_str(&format!(" @{}", const_idx));
45            }
46            result.push_str("\n");
47        }
48
49        write!(f, "{}", result)
50    }
51}