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