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