Skip to main content

js_compile/
disasm.rs

1//! Text disassembly, in exactly the format the reference implementation prints.
2//!
3//! This exists to be *diffed*. The reference compiler, built with
4//! `-DDUMP_BYTECODE=1`, prints its bytecode through `js_dump_function_bytecode`
5//! and `dump_byte_code`, and the differential test compares that text with ours
6//! character by character. Keeping the format identical means a mismatch points
7//! straight at the instruction that differs rather than at a formatting detail.
8//!
9//! Format reference: `js_dump_function_bytecode` and `dump_byte_code` in
10//! `quickjs.c`.
11
12use crate::bytecode::{
13    ANONYMOUS_BINDING, Atom, ClosureType, Constant, Function, FunctionKind, Instruction, Operand,
14};
15use crate::opcode::{OpFormat, Opcode};
16use std::fmt::Write;
17
18/// Print a function the way `js_dump_function_bytecode` does.
19pub 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    // `&"*"[b->func_kind != JS_FUNC_GENERATOR]`: the star marks a *plain* generator only.
24    // An `async function*` prints without one — the reference's own table is what decides,
25    // and matching it is the whole point of this dump.
26    let star = if function.kind == FunctionKind::Generator {
27        "*"
28    } else {
29        ""
30    };
31    // An anonymous function has no name atom, which the reference prints as
32    // `<null>`.
33    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            // The scope chain is printed for every binding outside the function
51            // scope, i.e. everything the runtime has to instantiate per block.
52            // `-1` means "no further binding visible from this scope".
53            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
88/// Print a whole program in the order the reference emits it.
89///
90/// The reference dumps each function as its bytecode object is created, which
91/// happens while the parent is still being compiled, so nested functions come
92/// out innermost-first and the top-level function comes last.
93pub 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
109/// Print the instruction stream.
110pub 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
124/// Print an instruction's operands, following `dump_byte_code`'s switch.
125fn format_operands(out: &mut String, function: &Function, pc: usize, instruction: &Instruction) {
126    let info = instruction.op.info();
127
128    // The short forms carry their operand in the opcode number itself.
129    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        // `loc8` is the narrow form of `loc`: same operand, same name, one byte.
197        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            // The reference prints an absolute address, computed as
246            // "operand position + relative offset".
247            if let Some(target) = instruction.jump_target(pc) {
248                let _ = write!(out, " {target}");
249            }
250        }
251    }
252}
253
254/// Which slot table a variable index refers to.
255#[derive(Debug, Clone, Copy)]
256enum Slot {
257    Loc(u32),
258    Arg(u32),
259    VarRef(u32),
260}
261
262/// Print the name a variable slot refers to, if it is in range.
263fn 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        // An unnamed binding is `JS_ATOM_NULL` in the reference, which prints as
274        // `<null>` — not as the string `"<null>"`. Every pattern parameter's argument
275        // slot is one, so the difference shows up in the header of nearly every function
276        // that destructures.
277        if name == ANONYMOUS_BINDING {
278            let _ = write!(out, "<null>");
279            return;
280        }
281        // Otherwise the reference prints variable names as atoms, so `<ret>` comes out
282        // quoted and `a` does not. A variable can never be named with a bare index, so
283        // the string form is always the right one here.
284        let _ = write!(out, "{}", print_atom(&Atom::Str(name.to_string())));
285    }
286}
287
288/// Print an atom the way `js_print_atom2` does.
289///
290/// A tagged array index prints as a bare number — that is the whole point of
291/// tagging it — while a string atom prints bare only if it is an ASCII
292/// identifier, and double-quoted otherwise.
293pub fn print_atom(atom: &Atom) -> String {
294    match atom {
295        Atom::Index(index) => return index.to_string(),
296        // No name at all, which the reference prints as `<null>`.
297        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
311/// Whether an atom needs no quoting.
312fn 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
323/// The escapes `js_print_string1` produces.
324fn 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
344/// Decode one instruction's operands from its payload bytes.
345///
346/// Jump targets stay relative here; [`Instruction::jump_target`] resolves them
347/// against the instruction's position, which is what the reference prints.
348pub 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    /// The atom named by operand `index`, looked up in the function's table.
393    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
401/// Resolve a relative jump operand into the absolute address the reference
402/// prints.
403impl Instruction {
404    /// The absolute target of a jump, if this instruction has one.
405    pub fn jump_target(&self, pc: usize) -> Option<i64> {
406        // The operand follows the opcode byte, and the reference computes the
407        // target as `operand_position + offset`.
408        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
420/// The short form a long instruction folds into, for the assembler.
421pub 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}