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