1use std::fmt::Write as _;
4
5use crate::{BytecodeChunk, Constant, Instruction, Proto};
6
7#[must_use]
9pub fn disassemble_chunk(chunk: &BytecodeChunk) -> String {
10 let mut output = String::new();
11 match chunk {
12 BytecodeChunk::Error { message } => {
13 writeln!(
14 output,
15 "error bytecode: {}",
16 String::from_utf8_lossy(message)
17 )
18 .expect("write to string");
19 }
20 BytecodeChunk::Valid {
21 bytecode_version,
22 type_version,
23 strings,
24 userdata_type_mappings,
25 protos,
26 main_proto,
27 ..
28 } => {
29 writeln!(
30 output,
31 "bytecode v{bytecode_version}, type v{type_version}, main proto {main_proto}"
32 )
33 .expect("write to string");
34 if !strings.is_empty() {
35 output.push_str("strings:\n");
36 for (index, string) in strings.iter().enumerate() {
37 writeln!(
38 output,
39 " S{} = {:?}",
40 index + 1,
41 String::from_utf8_lossy(string)
42 )
43 .expect("write to string");
44 }
45 }
46 if !userdata_type_mappings.is_empty() {
47 output.push_str("userdata mappings:\n");
48 for mapping in userdata_type_mappings {
49 writeln!(output, " type {} -> S{}", mapping.type_index, mapping.name)
50 .expect("write to string");
51 }
52 }
53 for (index, proto) in protos.iter().enumerate() {
54 render_proto(&mut output, index, proto);
55 }
56 }
57 }
58 output
59}
60
61fn render_proto(output: &mut String, index: usize, proto: &Proto) {
62 writeln!(
63 output,
64 "proto {index}: max_stack={}, params={}, upvalues={}, vararg={}, flags={}, line={}, name=S{}",
65 proto.max_stack_size,
66 proto.num_params,
67 proto.num_upvalues,
68 proto.is_vararg,
69 proto.flags,
70 proto.line_defined,
71 proto.debug_name
72 )
73 .expect("write to string");
74 output.push_str(" code:\n");
75 let mut pc = 0usize;
76 for instruction in &proto.code {
77 render_instruction(output, pc, instruction);
78 pc += instruction.word_len() as usize;
79 }
80 if !proto.constants.is_empty() {
81 output.push_str(" constants:\n");
82 for (index, constant) in proto.constants.iter().enumerate() {
83 writeln!(output, " K{index}: {}", render_constant(constant))
84 .expect("write to string");
85 }
86 }
87 if !proto.type_info.raw.is_empty() {
88 writeln!(output, " type_info: {:?}", proto.type_info.raw).expect("write to string");
89 }
90 if let Some(line_info) = &proto.line_info {
91 writeln!(
92 output,
93 " line_info: log2_span={}, deltas={:?}, baselines={:?}",
94 line_info.log2_span, line_info.delta_bytes, line_info.baseline_deltas
95 )
96 .expect("write to string");
97 }
98 if let Some(debug_info) = &proto.debug_info {
99 if !debug_info.locals.is_empty() {
100 output.push_str(" debug_locals:\n");
101 for (index, local) in debug_info.locals.iter().enumerate() {
102 writeln!(
103 output,
104 " L{index}: name=S{}, start={}, end={}, reg={}",
105 local.name, local.start_pc, local.end_pc, local.register
106 )
107 .expect("write to string");
108 }
109 }
110 if !debug_info.upvalues.is_empty() {
111 writeln!(output, " debug_upvalues: {:?}", debug_info.upvalues)
112 .expect("write to string");
113 }
114 }
115}
116
117fn render_instruction(output: &mut String, pc: usize, instruction: &Instruction) {
118 writeln!(
119 output,
120 " {pc:04}: {:?} A={} B={} C={} D={} E={} header=0x{:08x}",
121 instruction.opcode,
122 instruction.a,
123 instruction.b,
124 instruction.c,
125 instruction.d,
126 instruction.e,
127 instruction.header
128 )
129 .expect("write to string");
130 if let Some(aux) = instruction.aux {
131 writeln!(output, " AUX0=0x{aux:08x}").expect("write to string");
132 }
133}
134
135fn render_constant(constant: &Constant) -> String {
136 match constant {
137 Constant::Nil => "nil".to_owned(),
138 Constant::Boolean { value } => value.to_string(),
139 Constant::Number { bits } => format!("number bits=0x{bits:016x}"),
140 Constant::String { string } => format!("string S{string}"),
141 Constant::Import { import_id } => format!("import 0x{import_id:08x}"),
142 Constant::Table { keys } => format!("table keys={keys:?}"),
143 Constant::Closure { proto } => format!("closure proto {proto}"),
144 Constant::Vector { bits } => format!("vector bits={bits:?}"),
145 Constant::TableWithConstants { entries } => {
146 format!("table-with-constants entries={entries:?}")
147 }
148 Constant::Integer { value } => format!("integer {value}"),
149 Constant::ClassShape { shape } => format!(
150 "class S{} props={:?} methods={:?}",
151 shape.class_name, shape.property_names, shape.method_names
152 ),
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use super::disassemble_chunk;
159 use crate::{CompileOptions, compile_source};
160
161 #[test]
162 fn renders_instruction_rows() {
163 let chunk = compile_source("return 5", &CompileOptions::default(), None).expect("compile");
164 let rendered = disassemble_chunk(&chunk);
165 assert!(rendered.contains("0000: PrepVarargs"));
166 assert!(rendered.contains("0001: LoadN"));
167 assert!(rendered.contains("0002: Return"));
168 }
169}