Skip to main content

logicaffeine_compile/vm/
disasm.rs

1//! Bytecode disassembler — renders a [`CompiledProgram`]'s `Op` stream as readable
2//! text for the debugger (status line, bytecode tape) and any future
3//! `largo --disasm`. Common ops get a clean infix form (constants resolved,
4//! registers as `R{n}`, jump targets inline); the long tail falls back to the
5//! `Op` `Debug` form, so a newly added op is never a panic — just a plainer line.
6
7use super::instruction::{CompiledProgram, ConstIdx, Constant, Op, Reg};
8
9/// One disassembled instruction.
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct DisasmLine {
12    pub pc: usize,
13    pub text: String,
14    /// Absolute jump/branch targets this op can transfer control to (for the
15    /// bytecode tape's arrows). Empty for straight-line ops.
16    pub targets: Vec<usize>,
17}
18
19/// Disassemble every instruction in `prog.code` (Main first, then the function
20/// bodies, which share the one `code` vector).
21pub fn disassemble(prog: &CompiledProgram) -> Vec<DisasmLine> {
22    prog.code
23        .iter()
24        .enumerate()
25        .map(|(pc, op)| DisasmLine {
26            pc,
27            text: format_op(op, prog),
28            targets: op_targets(op),
29        })
30        .collect()
31}
32
33/// Render one instruction. Registers print as `R{n}`; constants and global names
34/// are resolved against `prog`.
35pub fn format_op(op: &Op, prog: &CompiledProgram) -> String {
36    let r = |reg: Reg| format!("R{reg}");
37    let k = |idx: ConstIdx| format_const(prog.constants.get(idx as usize));
38    let g = |idx: u16| {
39        prog.globals
40            .get(idx as usize)
41            .cloned()
42            .unwrap_or_else(|| format!("global#{idx}"))
43    };
44    match *op {
45        Op::LoadConst { dst, idx } => format!("LoadConst {} = {}", r(dst), k(idx)),
46        Op::Move { dst, src } => format!("Move {} = {}", r(dst), r(src)),
47        Op::EnsureOwned { reg } => format!("EnsureOwned {}", r(reg)),
48        Op::Add { dst, lhs, rhs } => format!("Add {} = {} + {}", r(dst), r(lhs), r(rhs)),
49        Op::AddAssign { dst, src } => format!("AddAssign {} += {}", r(dst), r(src)),
50        Op::Sub { dst, lhs, rhs } => format!("Sub {} = {} - {}", r(dst), r(lhs), r(rhs)),
51        Op::Mul { dst, lhs, rhs } => format!("Mul {} = {} * {}", r(dst), r(lhs), r(rhs)),
52        Op::Div { dst, lhs, rhs } => format!("Div {} = {} / {}", r(dst), r(lhs), r(rhs)),
53        Op::FloorDiv { dst, lhs, rhs } => format!("FloorDiv {} = {} // {}", r(dst), r(lhs), r(rhs)),
54        Op::Mod { dst, lhs, rhs } => format!("Mod {} = {} % {}", r(dst), r(lhs), r(rhs)),
55        Op::Lt { dst, lhs, rhs } => format!("Lt {} = {} < {}", r(dst), r(lhs), r(rhs)),
56        Op::Gt { dst, lhs, rhs } => format!("Gt {} = {} > {}", r(dst), r(lhs), r(rhs)),
57        Op::LtEq { dst, lhs, rhs } => format!("LtEq {} = {} <= {}", r(dst), r(lhs), r(rhs)),
58        Op::GtEq { dst, lhs, rhs } => format!("GtEq {} = {} >= {}", r(dst), r(lhs), r(rhs)),
59        Op::Eq { dst, lhs, rhs } => format!("Eq {} = {} == {}", r(dst), r(lhs), r(rhs)),
60        Op::NotEq { dst, lhs, rhs } => format!("NotEq {} = {} != {}", r(dst), r(lhs), r(rhs)),
61        Op::Not { dst, src } => format!("Not {} = !{}", r(dst), r(src)),
62        Op::Concat { dst, lhs, rhs } => format!("Concat {} = {} ++ {}", r(dst), r(lhs), r(rhs)),
63        Op::Jump { target } => format!("Jump -> {target}"),
64        Op::JumpIfFalse { cond, target } => format!("JumpIfFalse {} -> {target}", r(cond)),
65        Op::JumpIfTrue { cond, target } => format!("JumpIfTrue {} -> {target}", r(cond)),
66        Op::Call {
67            dst,
68            func,
69            args_start,
70            arg_count,
71        } => {
72            format!(
73                "Call {} = fn#{func}({}..+{arg_count})",
74                r(dst),
75                r(args_start)
76            )
77        }
78        Op::Return { src } => format!("Return {}", r(src)),
79        Op::ReturnNothing => "ReturnNothing".to_string(),
80        Op::GlobalGet { dst, idx } => format!("GlobalGet {} = {}", r(dst), g(idx)),
81        Op::GlobalSet { idx, src } => format!("GlobalSet {} = {}", g(idx), r(src)),
82        Op::NewEmptyList { dst } => format!("NewEmptyList {}", r(dst)),
83        Op::NewEmptyListWithCapacity { dst, capacity } => {
84            format!(
85                "NewEmptyListWithCapacity {} capacity={}",
86                r(dst),
87                r(capacity)
88            )
89        }
90        Op::NewEmptyListFixed { dst, capacity } => {
91            format!("NewEmptyListFixed {} capacity={capacity}", r(dst))
92        }
93        Op::NewList { dst, start, count } => {
94            format!("NewList {} = [{}..+{count}]", r(dst), r(start))
95        }
96        Op::NewEmptyMapWithCapacity { dst, capacity } => {
97            format!(
98                "NewEmptyMapWithCapacity {} capacity={}",
99                r(dst),
100                r(capacity)
101            )
102        }
103        Op::NewRange { dst, start, end } => {
104            format!("NewRange {} = {}..={}", r(dst), r(start), r(end))
105        }
106        Op::ListPush { list, value } => format!("ListPush {} <- {}", r(list), r(value)),
107        Op::ListPop { list, dst } => format!("ListPop {} = {}.pop()", r(dst), r(list)),
108        Op::Index {
109            dst,
110            collection,
111            index,
112        } => format!("Index {} = {}[{}]", r(dst), r(collection), r(index)),
113        Op::SetIndex {
114            collection,
115            index,
116            value,
117        } => {
118            format!("SetIndex {}[{}] = {}", r(collection), r(index), r(value))
119        }
120        Op::Length { dst, collection } => format!("Length {} = len {}", r(dst), r(collection)),
121        Op::Contains {
122            dst,
123            collection,
124            value,
125        } => {
126            format!(
127                "Contains {} = {} contains {}",
128                r(dst),
129                r(collection),
130                r(value)
131            )
132        }
133        Op::IterPrepare { iterable } => format!("IterPrepare {}", r(iterable)),
134        Op::IterNext { dst, exit } => format!("IterNext {} (exhausted -> {exit})", r(dst)),
135        Op::IterPop => "IterPop".to_string(),
136        Op::Show { src } => format!("Show {}", r(src)),
137        Op::FailWith { msg } => format!("FailWith {}", k(msg)),
138        Op::Halt => "Halt".to_string(),
139        // The long tail (CRDT, structs, temporal, concurrency, magic-div, …) is
140        // rendered by its derived Debug — correct, just less pretty.
141        other => format!("{other:?}"),
142    }
143}
144
145/// Absolute control-transfer targets of an op (for tape arrows / reachability).
146pub fn op_targets(op: &Op) -> Vec<usize> {
147    match *op {
148        Op::Jump { target } => vec![target],
149        Op::JumpIfFalse { target, .. } | Op::JumpIfTrue { target, .. } => vec![target],
150        Op::IterNext { exit, .. } => vec![exit],
151        _ => Vec::new(),
152    }
153}
154
155/// The registers an op reads (its sources) and the one it writes (its destination).
156/// Drives the debugger's datapath animation — which register cells light up, flow into
157/// the engine, and receive the result — and the plain-English narration. Empty for the
158/// long-tail ops (no animation/narration), which fall back to the disassembly text.
159#[derive(Clone, Debug, Default, PartialEq, Eq)]
160pub struct OpIo {
161    pub writes: Option<Reg>,
162    pub reads: Vec<Reg>,
163}
164
165/// Compute the [`OpIo`] of a bytecode op.
166pub fn op_io(op: &Op) -> OpIo {
167    let rw = |dst: Reg, reads: Vec<Reg>| OpIo {
168        writes: Some(dst),
169        reads,
170    };
171    let ro = |reads: Vec<Reg>| OpIo {
172        writes: None,
173        reads,
174    };
175    match *op {
176        Op::LoadConst { dst, .. } => rw(dst, vec![]),
177        Op::Move { dst, src } => rw(dst, vec![src]),
178        Op::EnsureOwned { reg } => rw(reg, vec![reg]),
179        Op::Add { dst, lhs, rhs }
180        | Op::Sub { dst, lhs, rhs }
181        | Op::Mul { dst, lhs, rhs }
182        | Op::Div { dst, lhs, rhs }
183        | Op::ExactDiv { dst, lhs, rhs }
184        | Op::FloorDiv { dst, lhs, rhs }
185        | Op::Mod { dst, lhs, rhs }
186        | Op::Lt { dst, lhs, rhs }
187        | Op::Gt { dst, lhs, rhs }
188        | Op::LtEq { dst, lhs, rhs }
189        | Op::GtEq { dst, lhs, rhs }
190        | Op::Eq { dst, lhs, rhs }
191        | Op::NotEq { dst, lhs, rhs }
192        | Op::Concat { dst, lhs, rhs }
193        | Op::Pow { dst, lhs, rhs }
194        | Op::BitXor { dst, lhs, rhs }
195        | Op::BitAnd { dst, lhs, rhs }
196        | Op::BitOr { dst, lhs, rhs }
197        | Op::Shl { dst, lhs, rhs }
198        | Op::Shr { dst, lhs, rhs } => rw(dst, vec![lhs, rhs]),
199        Op::AddAssign { dst, src } => rw(dst, vec![dst, src]),
200        Op::Not { dst, src } => rw(dst, vec![src]),
201        Op::Show { src } => ro(vec![src]),
202        Op::Return { src } => ro(vec![src]),
203        Op::JumpIfFalse { cond, .. } | Op::JumpIfTrue { cond, .. } => ro(vec![cond]),
204        Op::Index {
205            dst,
206            collection,
207            index,
208        }
209        | Op::IndexUnchecked {
210            dst,
211            collection,
212            index,
213        } => rw(dst, vec![collection, index]),
214        Op::SetIndex {
215            collection,
216            index,
217            value,
218        }
219        | Op::SetIndexUnchecked {
220            collection,
221            index,
222            value,
223        } => rw(collection, vec![index, value]),
224        Op::Length { dst, collection } => rw(dst, vec![collection]),
225        Op::Contains {
226            dst,
227            collection,
228            value,
229        } => rw(dst, vec![collection, value]),
230        Op::ListPush { list, value } => rw(list, vec![value]),
231        _ => OpIo::default(),
232    }
233}
234
235/// The constant at `idx`, formatted for narration (e.g. `6`, `"hi"`, `nothing`).
236pub fn format_constant(prog: &CompiledProgram, idx: ConstIdx) -> String {
237    format_const(prog.constants.get(idx as usize))
238}
239
240fn format_const(c: Option<&Constant>) -> String {
241    match c {
242        Some(Constant::Int(n)) => n.to_string(),
243        Some(Constant::Float(f)) => format!("{f}"),
244        Some(Constant::Bool(b)) => b.to_string(),
245        Some(Constant::Text(s)) => format!("{s:?}"),
246        Some(Constant::Char(ch)) => format!("'{ch}'"),
247        Some(Constant::Nothing) => "nothing".to_string(),
248        Some(other) => format!("{other:?}"),
249        None => "?".to_string(),
250    }
251}
252
253#[cfg(test)]
254#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/disasm/tests.rs"]
255mod tests;