1use crate::bytecode::{Atom, ClosureType, Constant, Function, Instruction, Operand};
13use crate::opcode::{OpFormat, Opcode};
14use std::fmt::Write;
15
16pub fn disassemble_function(out: &mut String, function: &Function) {
18 if let Some(filename) = &function.filename {
19 let _ = write!(out, "{filename}:{}:{}: ", function.line, function.column);
20 }
21 let star = if function.kind.is_generator() {
22 "*"
23 } else {
24 ""
25 };
26 let name = if function.name.is_empty() {
29 "<null>"
30 } else {
31 function.name.as_str()
32 };
33 let _ = writeln!(out, "function: {star}{name}");
34 if function.strict {
35 let _ = writeln!(out, " mode: strict");
36 }
37 if !function.args.is_empty() {
38 let names: Vec<&str> = function.args.iter().map(|a| a.name.as_str()).collect();
39 let _ = writeln!(out, " args: {}", names.join(" "));
40 }
41 if !function.vars.is_empty() {
42 let _ = writeln!(out, " locals:");
43 for (index, var) in function.vars.iter().enumerate() {
44 let _ = write!(out, "{index:5}: {} {}", var.label(), var.name);
45 if var.scope_level != 0 {
49 let _ = write!(out, " [next:{}]", var.scope_next.unwrap_or(-1));
50 }
51 let _ = writeln!(out);
52 }
53 }
54 if !function.closure_vars.is_empty() {
55 let _ = writeln!(out, " closure vars:");
56 for (index, closure) in function.closure_vars.iter().enumerate() {
57 let kind = if closure.is_const {
58 "const"
59 } else if closure.is_lexical {
60 "let"
61 } else {
62 "var"
63 };
64 let suffix = match closure.closure_type {
65 ClosureType::GlobalDecl
66 | ClosureType::Global
67 | ClosureType::ModuleDecl
68 | ClosureType::ModuleImport => {
69 format!(" [{}]", closure.closure_type.describe())
70 }
71 other => format!(" [{}{}]", other.describe(), closure.var_idx),
72 };
73 let _ = writeln!(out, "{index:5}: {kind} {}{suffix}", closure.name);
74 }
75 }
76 let _ = writeln!(out, " stack_size: {}", function.stack_size);
77 let _ = writeln!(out, " var_ref_count: {}", function.var_ref_count);
78 let _ = writeln!(out, " opcodes:");
79 disassemble_code(out, function);
80 let _ = writeln!(out);
81}
82
83pub fn disassemble_program(function: &Function) -> String {
89 let mut out = String::new();
90 disassemble_children(&mut out, function);
91 disassemble_function(&mut out, function);
92 out
93}
94
95fn disassemble_children(out: &mut String, function: &Function) {
96 for constant in &function.cpool {
97 if let Constant::Function(child) = constant {
98 disassemble_children(out, child);
99 disassemble_function(out, child);
100 }
101 }
102}
103
104pub fn disassemble_code(out: &mut String, function: &Function) {
106 let targets = function.jump_targets();
107 for (pc, instruction) in function.instructions() {
108 if targets.contains(&pc) {
109 let _ = write!(out, "{pc:5}: ");
110 } else {
111 out.push_str(" ");
112 }
113 let _ = write!(out, "{}", instruction.op.name());
114 format_operands(out, function, pc, &instruction);
115 let _ = writeln!(out);
116 }
117}
118
119fn format_operands(out: &mut String, function: &Function, pc: usize, instruction: &Instruction) {
121 let info = instruction.op.info();
122
123 if let Some(index) = instruction.op.specialised_index() {
125 match info.format {
126 OpFormat::NoneInt | OpFormat::Npopx => {
127 let _ = write!(out, " {index}");
128 return;
129 }
130 OpFormat::NoneLoc => {
131 let _ = write!(out, " {index}: ");
132 print_var_name(out, function, Slot::Loc(index as u32));
133 return;
134 }
135 OpFormat::NoneArg => {
136 let _ = write!(out, " {index}: ");
137 print_var_name(out, function, Slot::Arg(index as u32));
138 return;
139 }
140 OpFormat::NoneVarRef => {
141 let _ = write!(out, " {index}: ");
142 print_var_name(out, function, Slot::VarRef(index as u32));
143 return;
144 }
145 _ => {}
146 }
147 }
148
149 let first = instruction.operands.first();
150 match info.format {
151 OpFormat::None
152 | OpFormat::NoneInt
153 | OpFormat::NoneLoc
154 | OpFormat::NoneArg
155 | OpFormat::NoneVarRef
156 | OpFormat::Npopx => {}
157 OpFormat::U8 => {
158 if let Some(Operand::U32(value)) = first {
159 let _ = write!(out, " {value}");
160 }
161 }
162 OpFormat::Const8 | OpFormat::Const => {
163 if let Some(Operand::U32(index)) = first {
164 let _ = write!(out, " {index}: ");
165 if let Some(constant) = function.cpool.get(*index as usize) {
166 let _ = write!(out, "{}", constant.describe());
167 }
168 }
169 }
170 OpFormat::I8 | OpFormat::I16 | OpFormat::I32 => match first {
171 Some(Operand::I32(value)) => {
172 let _ = write!(out, " {value}");
173 }
174 Some(Operand::U32(value)) => {
175 let _ = write!(out, " {value}");
176 }
177 _ => {}
178 },
179 OpFormat::U16 | OpFormat::U32 | OpFormat::Npop => {
180 if let Some(Operand::U32(value)) = first {
181 let _ = write!(out, " {value}");
182 }
183 }
184 OpFormat::NpopU16 => {
185 if let (Some(Operand::U32(a)), Some(Operand::U32(b))) =
186 (first, instruction.operands.get(1))
187 {
188 let _ = write!(out, " {a},{b}");
189 }
190 }
191 OpFormat::Loc | OpFormat::Loc8 => {
193 if let Some(Operand::U32(index)) = first {
194 let _ = write!(out, " {index}: ");
195 print_var_name(out, function, Slot::Loc(*index));
196 }
197 }
198 OpFormat::Arg => {
199 if let Some(Operand::U32(index)) = first {
200 let _ = write!(out, " {index}: ");
201 print_var_name(out, function, Slot::Arg(*index));
202 }
203 }
204 OpFormat::VarRef => {
205 if let Some(Operand::U32(index)) = first {
206 let _ = write!(out, " {index}: ");
207 print_var_name(out, function, Slot::VarRef(*index));
208 }
209 }
210 OpFormat::Atom => {
211 if let Some(atom) = instruction.atom(function, 0) {
212 let _ = write!(out, " {}", print_atom(&atom));
213 }
214 }
215 OpFormat::AtomU8 | OpFormat::AtomU16 => {
216 if let (Some(atom), Some(Operand::U32(value))) =
217 (instruction.atom(function, 0), instruction.operands.get(1))
218 {
219 let _ = write!(out, " {},{}", print_atom(&atom), value);
220 }
221 }
222 OpFormat::AtomLabelU8 | OpFormat::AtomLabelU16 => {
223 if let (Some(atom), Some(Operand::I32(target))) =
224 (instruction.atom(function, 0), instruction.operands.get(1))
225 {
226 let _ = write!(out, " {},{}", print_atom(&atom), target);
227 if let Some(Operand::U32(value)) = instruction.operands.get(2) {
228 let _ = write!(out, ",{value}");
229 }
230 }
231 }
232 OpFormat::LabelU16 => {
233 if let (Some(Operand::I32(target)), Some(Operand::U32(value))) =
234 (first, instruction.operands.get(1))
235 {
236 let _ = write!(out, " {target},{value}");
237 }
238 }
239 OpFormat::Label | OpFormat::Label8 | OpFormat::Label16 => {
240 if let Some(target) = instruction.jump_target(pc) {
243 let _ = write!(out, " {target}");
244 }
245 }
246 }
247}
248
249#[derive(Debug, Clone, Copy)]
251enum Slot {
252 Loc(u32),
253 Arg(u32),
254 VarRef(u32),
255}
256
257fn print_var_name(out: &mut String, function: &Function, slot: Slot) {
259 let name = match slot {
260 Slot::Loc(index) => function.vars.get(index as usize).map(|v| v.name.as_str()),
261 Slot::Arg(index) => function.args.get(index as usize).map(|v| v.name.as_str()),
262 Slot::VarRef(index) => function
263 .closure_vars
264 .get(index as usize)
265 .map(|c| c.name.as_str()),
266 };
267 if let Some(name) = name {
268 let _ = write!(out, "{}", print_atom(&Atom::Str(name.to_string())));
272 }
273}
274
275pub fn print_atom(atom: &Atom) -> String {
281 if let Atom::Index(index) = atom {
282 return index.to_string();
283 }
284 let text = atom.as_str().unwrap_or_default();
285 if is_ascii_ident(text) {
286 return text.to_string();
287 }
288 let mut out = String::with_capacity(text.len() + 2);
289 out.push('"');
290 out.push_str(&escape_string(text));
291 out.push('"');
292 out
293}
294
295fn is_ascii_ident(text: &str) -> bool {
297 let mut chars = text.chars();
298 let Some(first) = chars.next() else {
299 return false;
300 };
301 if !(first.is_ascii_alphabetic() || first == '_' || first == '$') {
302 return false;
303 }
304 chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
305}
306
307fn escape_string(text: &str) -> String {
309 let mut out = String::with_capacity(text.len());
310 for c in text.chars() {
311 match c {
312 '"' => out.push_str("\\\""),
313 '\\' => out.push_str("\\\\"),
314 '\n' => out.push_str("\\n"),
315 '\r' => out.push_str("\\r"),
316 '\t' => out.push_str("\\t"),
317 '\u{8}' => out.push_str("\\b"),
318 '\u{c}' => out.push_str("\\f"),
319 '\u{b}' => out.push_str("\\v"),
320 '\0' => out.push_str("\\0"),
321 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
322 c => out.push(c),
323 }
324 }
325 out
326}
327
328pub fn decode_operands(format: OpFormat, payload: &[u8], out: &mut Vec<Operand>) {
333 let be = |offset: usize, count: usize| -> u32 {
334 let mut value = 0u32;
335 for i in 0..count {
336 value = (value << 8) | payload.get(offset + i).copied().unwrap_or(0) as u32;
337 }
338 value
339 };
340 match format {
341 OpFormat::None
342 | OpFormat::NoneInt
343 | OpFormat::NoneLoc
344 | OpFormat::NoneArg
345 | OpFormat::NoneVarRef
346 | OpFormat::Npopx => {}
347 OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => {
348 out.push(Operand::U32(be(0, 1)));
349 }
350 OpFormat::I8 | OpFormat::Label8 => {
351 out.push(Operand::I32(be(0, 1) as u8 as i8 as i32));
352 }
353 OpFormat::U16 | OpFormat::Npop => out.push(Operand::U32(be(0, 2))),
354 OpFormat::I16 | OpFormat::Label16 => {
355 out.push(Operand::I32(be(0, 2) as u16 as i16 as i32));
356 }
357 OpFormat::NpopU16 => {
358 out.push(Operand::U32(be(0, 2)));
359 out.push(Operand::U32(be(2, 2)));
360 }
361 OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => out.push(Operand::U32(be(0, 2))),
362 OpFormat::U32 | OpFormat::Const | OpFormat::Atom => out.push(Operand::U32(be(0, 4))),
363 OpFormat::I32 | OpFormat::Label => out.push(Operand::I32(be(0, 4) as i32)),
364 OpFormat::AtomU8 | OpFormat::AtomLabelU8 => {
365 out.push(Operand::U32(be(0, 4)));
366 out.push(Operand::U32(be(4, 1)));
367 }
368 OpFormat::AtomU16 | OpFormat::AtomLabelU16 | OpFormat::LabelU16 => {
369 out.push(Operand::U32(be(0, 4)));
370 out.push(Operand::U32(be(4, 2)));
371 }
372 }
373}
374
375impl Instruction {
376 pub fn atom(&self, function: &Function, index: usize) -> Option<Atom> {
378 let Some(Operand::U32(atom)) = self.operands.get(index) else {
379 return None;
380 };
381 function.atoms.get(*atom as usize).cloned()
382 }
383}
384
385impl Instruction {
388 pub fn jump_target(&self, pc: usize) -> Option<i64> {
390 let operand_position = pc as i64 + 1;
393 match self.op.info().format {
394 OpFormat::Label8 | OpFormat::Label16 | OpFormat::Label => match self.operands.first() {
395 Some(Operand::I32(offset)) => Some(operand_position + *offset as i64),
396 Some(Operand::U32(offset)) => Some(operand_position + *offset as i64),
397 _ => None,
398 },
399 _ => None,
400 }
401 }
402}
403
404pub fn long_to_short(op: Opcode) -> Option<Opcode> {
406 use Opcode::*;
407 Some(match op {
408 GetLoc => GetLoc0,
409 PutLoc => PutLoc0,
410 SetLoc => SetLoc0,
411 GetArg => GetArg0,
412 PutArg => PutArg0,
413 SetArg => SetArg0,
414 GetVarRef => GetVarRef0,
415 PutVarRef => PutVarRef0,
416 SetVarRef => SetVarRef0,
417 Call => Call0,
418 PushI32 => Push0,
419 IfFalse => IfFalse8,
420 IfTrue => IfTrue8,
421 Goto => Goto8,
422 _ => return None,
423 })
424}