Skip to main content

byteflow/bytecode/
disasm.rs

1use std::fmt::Write as _;
2
3use super::asm::write_constant;
4use super::chunk::Chunk;
5use super::format::module_abi;
6
7/// Assemblable listing of a [`Chunk`]. [`super::assemble`] reads it back.
8///
9/// The `.abi` line is the version [`super::encode`] would write, not a
10/// hardcoded v5.
11pub fn disassemble(chunk: &Chunk) -> String {
12    let mut out = String::new();
13    let _ = writeln!(out, ".chunk {}", quote(&chunk.name));
14    let _ = writeln!(out, ".abi {}", module_abi(&chunk.constants));
15    for value in &chunk.constants {
16        write_constant(&mut out, value);
17    }
18    for def in &chunk.functions {
19        let _ = writeln!(
20            out,
21            ".fn {} entry={} arity={} regs={}",
22            quote(&def.name),
23            def.entry,
24            def.arity,
25            def.num_registers
26        );
27    }
28    for (i, instr) in chunk.code.iter().enumerate() {
29        let label = match chunk.functions.iter().find(|f| f.entry as usize == i) {
30            Some(f) => format!("  ; {}", one_line(&f.name)),
31            None => String::new(),
32        };
33        let _ = writeln!(out, "{i:04}  {instr}{label}");
34    }
35    out
36}
37
38/// Comment text must stay on the instruction line. A raw newline in a
39/// function name would otherwise become a second listing line and be parsed
40/// as an opcode.
41fn one_line(text: &str) -> String {
42    let mut out = String::new();
43    for c in text.chars() {
44        match c {
45            '\n' => out.push_str("\\n"),
46            '\r' => out.push_str("\\r"),
47            c => out.push(c),
48        }
49    }
50    out
51}
52
53fn quote(text: &str) -> String {
54    let mut out = String::from("\"");
55    for c in text.chars() {
56        match c {
57            '\\' => out.push_str("\\\\"),
58            '"' => out.push_str("\\\""),
59            '\n' => out.push_str("\\n"),
60            '\r' => out.push_str("\\r"),
61            c => out.push(c),
62        }
63    }
64    out.push('"');
65    out
66}
67
68#[cfg(test)]
69mod tests {
70    use crate::bytecode::builder::ChunkBuilder;
71
72    #[test]
73    fn lists_main() {
74        let mut b = ChunkBuilder::new("d");
75        b.begin_function("main", 0, 1);
76        b.emit_load_imm(0, 1);
77        b.emit_return(0);
78        let text = super::disassemble(&b.finish());
79        assert!(text.contains("LoadImm r0, 1"));
80        assert!(text.contains("main"));
81        assert!(text.contains(".abi 5"));
82    }
83
84    #[test]
85    fn call_native_names_the_native_table() {
86        let mut b = ChunkBuilder::new("n");
87        b.begin_function("main", 0, 2);
88        b.emit_call_native(0, 6, 1);
89        b.emit_native1_from(1, 0, 7);
90        b.emit_return(1);
91        let text = super::disassemble(&b.finish());
92        assert!(text.contains("CallNative r0, native[6], argc=1"));
93        assert!(text.contains("CallNativeFrom r1, r0, native[7]"));
94        assert!(!text.contains("CallNative r0, fn["));
95    }
96}