about summary refs log tree commit diff
path: root/tvix/eval/src/disassembler.rs
blob: bc5a64fe65e8139237b5f4ef57a4c55f707871a2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//! Implements methods for disassembling and printing a representation
//! of compiled code, as well as tracing the runtime stack during
//! execution.
use std::io::{Stderr, Write};
use tabwriter::TabWriter;

use crate::chunk::Chunk;
use crate::opcode::OpCode;
use crate::value::Value;

/// Helper struct to trace runtime values and automatically flush the
/// output after the value is dropped (i.e. in both success and
/// failure exits from the VM).
pub struct Tracer(TabWriter<Stderr>);

impl Tracer {
    pub fn new() -> Self {
        let mut tw = TabWriter::new(std::io::stderr());
        write!(&mut tw, "=== runtime trace ===\n").ok();
        Tracer(tw)
    }

    pub fn trace(&mut self, op: &OpCode, ip: usize, stack: &[Value]) {
        write!(&mut self.0, "{:04} {:?}\t[ ", ip, op).ok();

        for val in stack {
            write!(&mut self.0, "{} ", val).ok();
        }

        write!(&mut self.0, "]\n").ok();
    }
}

impl Drop for Tracer {
    fn drop(&mut self) {
        self.0.flush().ok();
    }
}

fn disassemble_op(tw: &mut TabWriter<Stderr>, chunk: &Chunk, width: usize, offset: usize) {
    write!(tw, "{:0width$}\t ", width = width).ok();

    match chunk.code[offset] {
        OpCode::OpConstant(idx) => write!(tw, "OpConstant({})\n", chunk.constant(idx)).ok(),

        op => write!(tw, "{:?}\n", op).ok(),
    };
}

/// Disassemble a chunk of code, printing out the operations in a
/// reasonable, human-readable format.
pub fn disassemble_chunk(chunk: &Chunk) {
    let mut tw = TabWriter::new(std::io::stderr());

    write!(
        &mut tw,
        "=== compiled bytecode ({} operations) ===\n",
        chunk.code.len()
    )
    .ok();

    let width = format!("{}", chunk.code.len()).len();
    for (idx, _) in chunk.code.iter().enumerate() {
        disassemble_op(&mut tw, chunk, width, idx);
    }

    tw.flush().ok();
}