1use super::instruction::{CompiledProgram, ConstIdx, Constant, Op, Reg};
8
9#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct DisasmLine {
12 pub pc: usize,
13 pub text: String,
14 pub targets: Vec<usize>,
17}
18
19pub 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
33pub 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 other => format!("{other:?}"),
142 }
143}
144
145pub 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
160pub struct OpIo {
161 pub writes: Option<Reg>,
162 pub reads: Vec<Reg>,
163}
164
165pub 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
235pub 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;