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::{Atom, ClosureType, Constant, Function, Instruction, Operand};
13use crate::opcode::{OpFormat, Opcode};
14use std::fmt::Write;
15
16/// Print a function the way `js_dump_function_bytecode` does.
17pub fn disassemble_function(out: &mut String, function: &Function) {
18    if let Some(filename) = &function.filename {
19        let _ = write!(out, "{filename}:{}:{}: ", function.line, function.column);
20    }
21    let star = if function.kind.is_generator() {
22        "*"
23    } else {
24        ""
25    };
26    // An anonymous function has no name atom, which the reference prints as
27    // `<null>`.
28    let name = if function.name.is_empty() {
29        "<null>"
30    } else {
31        function.name.as_str()
32    };
33    let _ = writeln!(out, "function: {star}{name}");
34    if function.strict {
35        let _ = writeln!(out, "  mode: strict");
36    }
37    if !function.args.is_empty() {
38        let names: Vec<&str> = function.args.iter().map(|a| a.name.as_str()).collect();
39        let _ = writeln!(out, "  args: {}", names.join(" "));
40    }
41    if !function.vars.is_empty() {
42        let _ = writeln!(out, "  locals:");
43        for (index, var) in function.vars.iter().enumerate() {
44            let _ = write!(out, "{index:5}: {} {}", var.label(), var.name);
45            // The scope chain is printed for every binding outside the function
46            // scope, i.e. everything the runtime has to instantiate per block.
47            // `-1` means "no further binding visible from this scope".
48            if var.scope_level != 0 {
49                let _ = write!(out, " [next:{}]", var.scope_next.unwrap_or(-1));
50            }
51            let _ = writeln!(out);
52        }
53    }
54    if !function.closure_vars.is_empty() {
55        let _ = writeln!(out, "  closure vars:");
56        for (index, closure) in function.closure_vars.iter().enumerate() {
57            let kind = if closure.is_const {
58                "const"
59            } else if closure.is_lexical {
60                "let"
61            } else {
62                "var"
63            };
64            let suffix = match closure.closure_type {
65                ClosureType::GlobalDecl
66                | ClosureType::Global
67                | ClosureType::ModuleDecl
68                | ClosureType::ModuleImport => {
69                    format!(" [{}]", closure.closure_type.describe())
70                }
71                other => format!(" [{}{}]", other.describe(), closure.var_idx),
72            };
73            let _ = writeln!(out, "{index:5}: {kind} {}{suffix}", closure.name);
74        }
75    }
76    let _ = writeln!(out, "  stack_size: {}", function.stack_size);
77    let _ = writeln!(out, "  var_ref_count: {}", function.var_ref_count);
78    let _ = writeln!(out, "  opcodes:");
79    disassemble_code(out, function);
80    let _ = writeln!(out);
81}
82
83/// Print a whole program in the order the reference emits it.
84///
85/// The reference dumps each function as its bytecode object is created, which
86/// happens while the parent is still being compiled, so nested functions come
87/// out innermost-first and the top-level function comes last.
88pub fn disassemble_program(function: &Function) -> String {
89    let mut out = String::new();
90    disassemble_children(&mut out, function);
91    disassemble_function(&mut out, function);
92    out
93}
94
95fn disassemble_children(out: &mut String, function: &Function) {
96    for constant in &function.cpool {
97        if let Constant::Function(child) = constant {
98            disassemble_children(out, child);
99            disassemble_function(out, child);
100        }
101    }
102}
103
104/// Print the instruction stream.
105pub fn disassemble_code(out: &mut String, function: &Function) {
106    let targets = function.jump_targets();
107    for (pc, instruction) in function.instructions() {
108        if targets.contains(&pc) {
109            let _ = write!(out, "{pc:5}:  ");
110        } else {
111            out.push_str("        ");
112        }
113        let _ = write!(out, "{}", instruction.op.name());
114        format_operands(out, function, pc, &instruction);
115        let _ = writeln!(out);
116    }
117}
118
119/// Print an instruction's operands, following `dump_byte_code`'s switch.
120fn format_operands(out: &mut String, function: &Function, pc: usize, instruction: &Instruction) {
121    let info = instruction.op.info();
122
123    // The short forms carry their operand in the opcode number itself.
124    if let Some(index) = instruction.op.specialised_index() {
125        match info.format {
126            OpFormat::NoneInt | OpFormat::Npopx => {
127                let _ = write!(out, " {index}");
128                return;
129            }
130            OpFormat::NoneLoc => {
131                let _ = write!(out, " {index}: ");
132                print_var_name(out, function, Slot::Loc(index as u32));
133                return;
134            }
135            OpFormat::NoneArg => {
136                let _ = write!(out, " {index}: ");
137                print_var_name(out, function, Slot::Arg(index as u32));
138                return;
139            }
140            OpFormat::NoneVarRef => {
141                let _ = write!(out, " {index}: ");
142                print_var_name(out, function, Slot::VarRef(index as u32));
143                return;
144            }
145            _ => {}
146        }
147    }
148
149    let first = instruction.operands.first();
150    match info.format {
151        OpFormat::None
152        | OpFormat::NoneInt
153        | OpFormat::NoneLoc
154        | OpFormat::NoneArg
155        | OpFormat::NoneVarRef
156        | OpFormat::Npopx => {}
157        OpFormat::U8 => {
158            if let Some(Operand::U32(value)) = first {
159                let _ = write!(out, " {value}");
160            }
161        }
162        OpFormat::Const8 | OpFormat::Const => {
163            if let Some(Operand::U32(index)) = first {
164                let _ = write!(out, " {index}: ");
165                if let Some(constant) = function.cpool.get(*index as usize) {
166                    let _ = write!(out, "{}", constant.describe());
167                }
168            }
169        }
170        OpFormat::I8 | OpFormat::I16 | OpFormat::I32 => match first {
171            Some(Operand::I32(value)) => {
172                let _ = write!(out, " {value}");
173            }
174            Some(Operand::U32(value)) => {
175                let _ = write!(out, " {value}");
176            }
177            _ => {}
178        },
179        OpFormat::U16 | OpFormat::U32 | OpFormat::Npop => {
180            if let Some(Operand::U32(value)) = first {
181                let _ = write!(out, " {value}");
182            }
183        }
184        OpFormat::NpopU16 => {
185            if let (Some(Operand::U32(a)), Some(Operand::U32(b))) =
186                (first, instruction.operands.get(1))
187            {
188                let _ = write!(out, " {a},{b}");
189            }
190        }
191        // `loc8` is the narrow form of `loc`: same operand, same name, one byte.
192        OpFormat::Loc | OpFormat::Loc8 => {
193            if let Some(Operand::U32(index)) = first {
194                let _ = write!(out, " {index}: ");
195                print_var_name(out, function, Slot::Loc(*index));
196            }
197        }
198        OpFormat::Arg => {
199            if let Some(Operand::U32(index)) = first {
200                let _ = write!(out, " {index}: ");
201                print_var_name(out, function, Slot::Arg(*index));
202            }
203        }
204        OpFormat::VarRef => {
205            if let Some(Operand::U32(index)) = first {
206                let _ = write!(out, " {index}: ");
207                print_var_name(out, function, Slot::VarRef(*index));
208            }
209        }
210        OpFormat::Atom => {
211            if let Some(atom) = instruction.atom(function, 0) {
212                let _ = write!(out, " {}", print_atom(&atom));
213            }
214        }
215        OpFormat::AtomU8 | OpFormat::AtomU16 => {
216            if let (Some(atom), Some(Operand::U32(value))) =
217                (instruction.atom(function, 0), instruction.operands.get(1))
218            {
219                let _ = write!(out, " {},{}", print_atom(&atom), value);
220            }
221        }
222        OpFormat::AtomLabelU8 | OpFormat::AtomLabelU16 => {
223            if let (Some(atom), Some(Operand::I32(target))) =
224                (instruction.atom(function, 0), instruction.operands.get(1))
225            {
226                let _ = write!(out, " {},{}", print_atom(&atom), target);
227                if let Some(Operand::U32(value)) = instruction.operands.get(2) {
228                    let _ = write!(out, ",{value}");
229                }
230            }
231        }
232        OpFormat::LabelU16 => {
233            if let (Some(Operand::I32(target)), Some(Operand::U32(value))) =
234                (first, instruction.operands.get(1))
235            {
236                let _ = write!(out, " {target},{value}");
237            }
238        }
239        OpFormat::Label | OpFormat::Label8 | OpFormat::Label16 => {
240            // The reference prints an absolute address, computed as
241            // "operand position + relative offset".
242            if let Some(target) = instruction.jump_target(pc) {
243                let _ = write!(out, " {target}");
244            }
245        }
246    }
247}
248
249/// Which slot table a variable index refers to.
250#[derive(Debug, Clone, Copy)]
251enum Slot {
252    Loc(u32),
253    Arg(u32),
254    VarRef(u32),
255}
256
257/// Print the name a variable slot refers to, if it is in range.
258fn print_var_name(out: &mut String, function: &Function, slot: Slot) {
259    let name = match slot {
260        Slot::Loc(index) => function.vars.get(index as usize).map(|v| v.name.as_str()),
261        Slot::Arg(index) => function.args.get(index as usize).map(|v| v.name.as_str()),
262        Slot::VarRef(index) => function
263            .closure_vars
264            .get(index as usize)
265            .map(|c| c.name.as_str()),
266    };
267    if let Some(name) = name {
268        // The reference prints variable names as atoms, so `<ret>` comes out
269        // quoted and `a` does not. A variable can never be named with a bare
270        // index, so the string form is always the right one here.
271        let _ = write!(out, "{}", print_atom(&Atom::Str(name.to_string())));
272    }
273}
274
275/// Print an atom the way `js_print_atom2` does.
276///
277/// A tagged array index prints as a bare number — that is the whole point of
278/// tagging it — while a string atom prints bare only if it is an ASCII
279/// identifier, and double-quoted otherwise.
280pub fn print_atom(atom: &Atom) -> String {
281    if let Atom::Index(index) = atom {
282        return index.to_string();
283    }
284    let text = atom.as_str().unwrap_or_default();
285    if is_ascii_ident(text) {
286        return text.to_string();
287    }
288    let mut out = String::with_capacity(text.len() + 2);
289    out.push('"');
290    out.push_str(&escape_string(text));
291    out.push('"');
292    out
293}
294
295/// Whether an atom needs no quoting.
296fn is_ascii_ident(text: &str) -> bool {
297    let mut chars = text.chars();
298    let Some(first) = chars.next() else {
299        return false;
300    };
301    if !(first.is_ascii_alphabetic() || first == '_' || first == '$') {
302        return false;
303    }
304    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
305}
306
307/// The escapes `js_print_string1` produces.
308fn escape_string(text: &str) -> String {
309    let mut out = String::with_capacity(text.len());
310    for c in text.chars() {
311        match c {
312            '"' => out.push_str("\\\""),
313            '\\' => out.push_str("\\\\"),
314            '\n' => out.push_str("\\n"),
315            '\r' => out.push_str("\\r"),
316            '\t' => out.push_str("\\t"),
317            '\u{8}' => out.push_str("\\b"),
318            '\u{c}' => out.push_str("\\f"),
319            '\u{b}' => out.push_str("\\v"),
320            '\0' => out.push_str("\\0"),
321            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
322            c => out.push(c),
323        }
324    }
325    out
326}
327
328/// Decode one instruction's operands from its payload bytes.
329///
330/// Jump targets stay relative here; [`Instruction::jump_target`] resolves them
331/// against the instruction's position, which is what the reference prints.
332pub fn decode_operands(format: OpFormat, payload: &[u8], out: &mut Vec<Operand>) {
333    let be = |offset: usize, count: usize| -> u32 {
334        let mut value = 0u32;
335        for i in 0..count {
336            value = (value << 8) | payload.get(offset + i).copied().unwrap_or(0) as u32;
337        }
338        value
339    };
340    match format {
341        OpFormat::None
342        | OpFormat::NoneInt
343        | OpFormat::NoneLoc
344        | OpFormat::NoneArg
345        | OpFormat::NoneVarRef
346        | OpFormat::Npopx => {}
347        OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => {
348            out.push(Operand::U32(be(0, 1)));
349        }
350        OpFormat::I8 | OpFormat::Label8 => {
351            out.push(Operand::I32(be(0, 1) as u8 as i8 as i32));
352        }
353        OpFormat::U16 | OpFormat::Npop => out.push(Operand::U32(be(0, 2))),
354        OpFormat::I16 | OpFormat::Label16 => {
355            out.push(Operand::I32(be(0, 2) as u16 as i16 as i32));
356        }
357        OpFormat::NpopU16 => {
358            out.push(Operand::U32(be(0, 2)));
359            out.push(Operand::U32(be(2, 2)));
360        }
361        OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => out.push(Operand::U32(be(0, 2))),
362        OpFormat::U32 | OpFormat::Const | OpFormat::Atom => out.push(Operand::U32(be(0, 4))),
363        OpFormat::I32 | OpFormat::Label => out.push(Operand::I32(be(0, 4) as i32)),
364        OpFormat::AtomU8 | OpFormat::AtomLabelU8 => {
365            out.push(Operand::U32(be(0, 4)));
366            out.push(Operand::U32(be(4, 1)));
367        }
368        OpFormat::AtomU16 | OpFormat::AtomLabelU16 | OpFormat::LabelU16 => {
369            out.push(Operand::U32(be(0, 4)));
370            out.push(Operand::U32(be(4, 2)));
371        }
372    }
373}
374
375impl Instruction {
376    /// The atom named by operand `index`, looked up in the function's table.
377    pub fn atom(&self, function: &Function, index: usize) -> Option<Atom> {
378        let Some(Operand::U32(atom)) = self.operands.get(index) else {
379            return None;
380        };
381        function.atoms.get(*atom as usize).cloned()
382    }
383}
384
385/// Resolve a relative jump operand into the absolute address the reference
386/// prints.
387impl Instruction {
388    /// The absolute target of a jump, if this instruction has one.
389    pub fn jump_target(&self, pc: usize) -> Option<i64> {
390        // The operand follows the opcode byte, and the reference computes the
391        // target as `operand_position + offset`.
392        let operand_position = pc as i64 + 1;
393        match self.op.info().format {
394            OpFormat::Label8 | OpFormat::Label16 | OpFormat::Label => match self.operands.first() {
395                Some(Operand::I32(offset)) => Some(operand_position + *offset as i64),
396                Some(Operand::U32(offset)) => Some(operand_position + *offset as i64),
397                _ => None,
398            },
399            _ => None,
400        }
401    }
402}
403
404/// The short form a long instruction folds into, for the assembler.
405pub fn long_to_short(op: Opcode) -> Option<Opcode> {
406    use Opcode::*;
407    Some(match op {
408        GetLoc => GetLoc0,
409        PutLoc => PutLoc0,
410        SetLoc => SetLoc0,
411        GetArg => GetArg0,
412        PutArg => PutArg0,
413        SetArg => SetArg0,
414        GetVarRef => GetVarRef0,
415        PutVarRef => PutVarRef0,
416        SetVarRef => SetVarRef0,
417        Call => Call0,
418        PushI32 => Push0,
419        IfFalse => IfFalse8,
420        IfTrue => IfTrue8,
421        Goto => Goto8,
422        _ => return None,
423    })
424}