Skip to main content

js_compile/
bytecode.rs

1//! The bytecode representation of a function.
2//!
3//! Compilation happens in two phases, exactly as in the reference implementation:
4//!
5//! * **Unresolved** ([`FunctionBuilder`]): jump targets are label ids and every
6//!   variable is still described by its declaration, not its storage class.
7//! * **Resolved** ([`Function`]): jump targets are byte offsets and every
8//!   variable reference names its storage class (`arg`, `loc`, `var_ref` or
9//!   `var`), so the bytecode can be executed and serialised.
10//!
11//! The split matters for testing: each phase can be compared against the
12//! corresponding pass of the reference compiler.
13
14use crate::opcode::Opcode;
15use std::fmt;
16
17/// One entry of a function's atom table.
18///
19/// The reference keeps two kinds of atom in one namespace, and the distinction is
20/// visible in the bytecode: an *array-index* atom is not a string at all but a
21/// tagged `uint32`, which is why `{ 2: x }` disassembles as `define_field 2` while
22/// `{ "1.5": x }` prints `define_field "1.5"`. Collapsing the two would make the
23/// disassembly wrong and lose information on the way back in, so the kind is
24/// carried here.
25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26pub enum Atom {
27    /// An interned string.
28    Str(String),
29    /// A canonical array index, held as a number rather than a string.
30    Index(u32),
31}
32
33impl Atom {
34    /// The atom the reference's `JS_NewAtomStr` would make of `text`.
35    ///
36    /// A canonical array index no greater than `2^31 - 1` is never interned as a
37    /// string: the reference returns a tagged integer instead. Anything else —
38    /// `"007"`, `"1e2"`, `"-0"`, or an index past the tag range — stays a string.
39    pub fn from_text(text: &str) -> Atom {
40        match canonical_array_index(text) {
41            Some(index) => Atom::Index(index),
42            None => Atom::Str(text.to_string()),
43        }
44    }
45
46    /// The text form, for callers that only care about the name.
47    pub fn as_str(&self) -> Option<&str> {
48        match self {
49            Atom::Str(text) => Some(text),
50            Atom::Index(_) => None,
51        }
52    }
53}
54
55impl fmt::Display for Atom {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            Atom::Str(text) => write!(f, "{text}"),
59            Atom::Index(index) => write!(f, "{index}"),
60        }
61    }
62}
63
64/// `is_num_string` from the reference: the canonical decimal spelling of an index
65/// small enough to be tagged (at most `2^31 - 1`).
66///
67/// Canonical means no sign, no leading zeros and no other characters, so `"10"`
68/// qualifies while `"007"`, `"-0"` and `"1e2"` do not.
69fn canonical_array_index(text: &str) -> Option<u32> {
70    // `2^31 - 1` has ten digits, which bounds how long a canonical index can be.
71    if text.is_empty() || text.len() > 10 {
72        return None;
73    }
74    let bytes = text.as_bytes();
75    if !bytes.iter().all(u8::is_ascii_digit) {
76        return None;
77    }
78    if bytes[0] == b'0' && bytes.len() != 1 {
79        return None;
80    }
81    let value: u32 = text.parse().ok()?;
82    (value <= 0x7fff_ffff).then_some(value)
83}
84
85/// How a function was declared. Determines the calling convention.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum FunctionKind {
88    /// A plain function.
89    Normal,
90    /// `function*`
91    Generator,
92    /// `async function`
93    Async,
94    /// `async function*`
95    AsyncGenerator,
96}
97
98impl FunctionKind {
99    /// Whether the function is a generator (plain or async).
100    pub fn is_generator(self) -> bool {
101        matches!(self, FunctionKind::Generator | FunctionKind::AsyncGenerator)
102    }
103
104    /// Whether the function is async (plain or generator).
105    pub fn is_async(self) -> bool {
106        matches!(self, FunctionKind::Async | FunctionKind::AsyncGenerator)
107    }
108}
109
110/// What a declared name is used for, which decides how it is displayed and how
111/// the function prologue initialises it.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum VarKind {
114    /// An ordinary binding.
115    Normal,
116    /// A lexical binding holding a hoisted function declaration.
117    FunctionDecl,
118    /// A lexical binding holding a hoisted async/generator function declaration.
119    NewFunctionDecl,
120    /// A `catch` parameter.
121    Catch,
122    /// The name bound to a named function expression, visible inside itself.
123    FunctionName,
124    /// A private class field.
125    PrivateField,
126    /// A private class method.
127    PrivateMethod,
128    /// A private class getter.
129    PrivateGetter,
130    /// A private class setter.
131    PrivateSetter,
132    /// A private class accessor pair (`get` and `set` sharing one name).
133    PrivateGetterSetter,
134    /// A global function declaration.
135    GlobalFunctionDecl,
136    /// A `using` declaration's binding.
137    Using,
138    /// The hidden local holding a `using` declaration's cached dispose method.
139    UsingMethod,
140}
141
142impl VarKind {
143    /// The word the disassembler prints for this kind.
144    pub fn label(self) -> &'static str {
145        match self {
146            VarKind::Catch => "catch",
147            VarKind::FunctionDecl | VarKind::NewFunctionDecl | VarKind::GlobalFunctionDecl => {
148                "function"
149            }
150            _ => "",
151        }
152    }
153
154    /// Whether the binding is initialised when the function is entered.
155    pub fn is_hoisted_declaration(self) -> bool {
156        matches!(self, VarKind::FunctionDecl | VarKind::NewFunctionDecl)
157    }
158}
159
160/// A declared variable: an argument or a local.
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct VarDef {
163    /// The name, as written.
164    pub name: String,
165    /// Whether the binding is immutable.
166    pub is_const: bool,
167    /// Whether the binding is block-scoped (`let`/`const`/`class`).
168    pub is_lexical: bool,
169    /// What the binding is used for.
170    pub kind: VarKind,
171    /// Whether a closure captures this variable, which forces it into a
172    /// heap-allocated reference cell.
173    pub is_captured: bool,
174    /// The lexical scope the binding belongs to.
175    ///
176    /// Scope 0 is the function scope, where `var` and hoisted function
177    /// declarations live; the body and every block introduce a child scope. A
178    /// binding only exists between its scope's entry and exit, which is what the
179    /// runtime uses to swap `let`/`const` bindings in and out.
180    pub scope_level: u32,
181    /// Index of the next block-scoped variable in the enclosing scope chain, or
182    /// `None` for a `var` (which is visible in the whole function).
183    ///
184    /// The reference stores this in `JSVarDef::scope_next` and only fills it in
185    /// when `scope_level != 0`; the interpreter walks the chain to instantiate
186    /// and close the `let`/`const` bindings that are live at a given point.
187    pub scope_next: Option<i32>,
188}
189
190impl VarDef {
191    /// A plain `var` binding.
192    pub fn var(name: impl Into<String>) -> VarDef {
193        VarDef {
194            name: name.into(),
195            is_const: false,
196            is_lexical: false,
197            kind: VarKind::Normal,
198            is_captured: false,
199            scope_level: 0,
200            scope_next: None,
201        }
202    }
203
204    /// Whether reading this binding can hit the temporal dead zone, i.e. it is
205    /// `let`/`const`/`class` and therefore starts out uninitialised.
206    pub fn needs_check(&self) -> bool {
207        self.is_lexical
208    }
209
210    /// A `let` binding.
211    pub fn lexical(name: impl Into<String>) -> VarDef {
212        VarDef {
213            is_lexical: true,
214            ..VarDef::var(name)
215        }
216    }
217
218    /// A `const` binding.
219    pub fn constant(name: impl Into<String>) -> VarDef {
220        VarDef {
221            is_lexical: true,
222            is_const: true,
223            ..VarDef::var(name)
224        }
225    }
226
227    /// The word the disassembler prints for this definition.
228    pub fn label(&self) -> &'static str {
229        let kind = self.kind.label();
230        if !kind.is_empty() {
231            return kind;
232        }
233        if self.is_const {
234            "const"
235        } else if self.is_lexical {
236            "let"
237        } else {
238            "var"
239        }
240    }
241}
242
243/// Where a captured variable actually lives, and therefore how a closure
244/// reaches it.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub enum ClosureType {
247    /// A local of the parent function (`[loc<n>]`).
248    Local,
249    /// An argument of the parent function (`[arg<n>]`).
250    Arg,
251    /// A reference cell in the parent function (`[ref<n>]`).
252    Ref,
253    /// A global, reached through the reference table by index.
254    GlobalRef,
255    /// A global declared in this script.
256    GlobalDecl,
257    /// A global reached by name.
258    Global,
259    /// A module-level declaration.
260    ModuleDecl,
261    /// A module import binding.
262    ModuleImport,
263}
264
265impl ClosureType {
266    /// The suffix the disassembler prints.
267    pub fn describe(self) -> &'static str {
268        match self {
269            ClosureType::Local => "loc",
270            ClosureType::Arg => "arg",
271            ClosureType::Ref => "ref",
272            ClosureType::GlobalDecl => "global_decl",
273            ClosureType::Global => "global",
274            ClosureType::ModuleDecl => "module_decl",
275            ClosureType::ModuleImport => "module_import",
276            ClosureType::GlobalRef => "global_ref",
277        }
278    }
279}
280
281/// One captured variable of a function.
282#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct ClosureVar {
284    /// The name, as written in the enclosing function.
285    pub name: String,
286    /// Whether the captured binding is immutable.
287    pub is_const: bool,
288    /// Whether the captured binding is block-scoped.
289    pub is_lexical: bool,
290    /// How the closure reaches it.
291    pub closure_type: ClosureType,
292    /// Index into the parent's locals, arguments or reference cells.
293    pub var_idx: u16,
294}
295
296/// A constant in the pool.
297#[derive(Debug, Clone, PartialEq)]
298pub enum Constant {
299    /// A number.
300    Number(f64),
301    /// A string.
302    String(String),
303    /// A BigInt literal: digits and radix.
304    BigInt {
305        /// Digits, without prefix or separators.
306        digits: String,
307        /// 2, 8, 10 or 16.
308        radix: u32,
309    },
310    /// A nested function, referenced by `fclosure`.
311    Function(Box<Function>),
312    /// A template object: the cooked strings of one call site.
313    Template(Vec<Option<String>>),
314}
315
316impl Constant {
317    /// A short description for disassembly, matching the reference's
318    /// `JS_PrintValue` for the cases the compiler can produce.
319    pub fn describe(&self) -> String {
320        match self {
321            Constant::Number(n) => format_number(*n),
322            Constant::String(s) => format!("\"{}\"", escape_js_string(s)),
323            // The reference prints BigInts in decimal, whatever the source radix.
324            Constant::BigInt { digits, .. } => format!("{digits}n"),
325            Constant::Function(f) => {
326                // The reference prints the function's name atom, which is `<null>`
327                // for an anonymous function expression.
328                if f.name.is_empty() {
329                    "[bytecode <null>]".to_string()
330                } else {
331                    format!("[bytecode {}]", f.name)
332                }
333            }
334            Constant::Template(quasis) => {
335                let parts: Vec<String> = quasis
336                    .iter()
337                    .map(|q| q.clone().unwrap_or_else(|| "undefined".to_string()))
338                    .collect();
339                format!("template object [{}]", parts.join(", "))
340            }
341        }
342    }
343}
344
345/// Format a number the way the reference implementation prints it.
346fn format_number(value: f64) -> String {
347    if value.is_nan() {
348        return "NaN".to_string();
349    }
350    if value.is_infinite() {
351        return if value > 0.0 {
352            "inf".to_string()
353        } else {
354            "-inf".to_string()
355        };
356    }
357    if value == value.trunc() && value.abs() < 1e21 {
358        return format!("{}", value as i64);
359    }
360    format!("{value}")
361}
362
363/// Escape a string for the double-quoted form the disassembler prints.
364fn escape_js_string(text: &str) -> String {
365    let mut out = String::with_capacity(text.len());
366    for c in text.chars() {
367        match c {
368            '"' => out.push_str("\\\""),
369            '\\' => out.push_str("\\\\"),
370            '\n' => out.push_str("\\n"),
371            '\r' => out.push_str("\\r"),
372            '\t' => out.push_str("\\t"),
373            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
374            c => out.push(c),
375        }
376    }
377    out
378}
379
380/// An operand of an instruction during compilation, before addresses are known.
381#[derive(Debug, Clone, PartialEq, Eq)]
382pub enum Operand {
383    /// No operand.
384    None,
385    /// A label, resolved to a byte offset.
386    Label(u32),
387    /// A local slot index.
388    Loc(u32),
389    /// An argument slot index.
390    Arg(u32),
391    /// A closure variable index.
392    VarRef(u32),
393    /// A constant pool index.
394    Const(u32),
395    /// An atom (an interned name), stored as its UTF-8 text before interning.
396    Atom(String),
397    /// A small unsigned immediate.
398    U8(u8),
399    /// A small signed immediate.
400    I8(i8),
401    /// A medium unsigned immediate.
402    U16(u16),
403    /// A medium signed immediate.
404    I16(i16),
405    /// A signed 32-bit immediate.
406    I32(i32),
407    /// An unsigned 32-bit immediate.
408    U32(u32),
409}
410
411/// A resolved instruction: opcode plus the operands encoded in its payload.
412#[derive(Debug, Clone, PartialEq)]
413pub struct Instruction {
414    /// The instruction.
415    pub op: Opcode,
416    /// Operands in the order the encoding stores them.
417    pub operands: Vec<Operand>,
418}
419
420impl Instruction {
421    /// An instruction with no operands.
422    pub fn new(op: Opcode) -> Instruction {
423        Instruction {
424            op,
425            operands: Vec::new(),
426        }
427    }
428
429    /// An instruction with one operand.
430    pub fn with(op: Opcode, operand: Operand) -> Instruction {
431        Instruction {
432            op,
433            operands: vec![operand],
434        }
435    }
436}
437
438/// Where a variable lives in the resolved function.
439#[derive(Debug, Clone, Copy, PartialEq, Eq)]
440pub enum Storage {
441    /// Argument slot.
442    Arg(u32),
443    /// Local slot.
444    Loc(u32),
445    /// Closure reference.
446    VarRef(u32),
447    /// Global, by atom.
448    Global,
449}
450
451/// A stretch of bytecode and the source position it came from.
452///
453/// One entry per run of instructions that share a position, ordered by `pc`, which is
454/// what [`Function::position_at`] binary searches. This is the port of the reference's
455/// `pc2line` table: it is how a stack trace says `file:line:col` for a frame that is
456/// deep inside a function rather than at its first statement.
457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
458pub struct LineCol {
459    /// Byte offset in [`Function::code`] where this position takes over.
460    pub pc: u32,
461    /// 1-based line.
462    pub line: u32,
463    /// 1-based column, in UTF-16 code units like every other position here.
464    pub column: u32,
465}
466
467/// A compiled function.
468#[derive(Debug, Clone, PartialEq)]
469pub struct Function {
470    /// The function's name; `<eval>` for a script body.
471    pub name: String,
472    /// The declaration form.
473    pub kind: FunctionKind,
474    /// Whether the body is strict.
475    pub strict: bool,
476    /// Parameters.
477    pub args: Vec<VarDef>,
478    /// Locals, including the implicit return-value slot named `<ret>`.
479    pub vars: Vec<VarDef>,
480    /// Captured variables of enclosing functions.
481    pub closure_vars: Vec<ClosureVar>,
482    /// Constant pool.
483    pub cpool: Vec<Constant>,
484    /// Atom table: the names this function mentions. The runtime shares one
485    /// interned table across the whole program; indexing it per function keeps
486    /// the bytecode self-contained and makes disassembly readable.
487    pub atoms: Vec<Atom>,
488    /// Resolved bytecode.
489    pub code: Vec<u8>,
490    /// Maximum value-stack depth.
491    pub stack_size: u32,
492    /// Source positions, ordered by bytecode offset.
493    pub positions: Vec<LineCol>,
494    /// Number of reference cells allocated on entry.
495    pub var_ref_count: u32,
496    /// Source text, kept for `Function.prototype.toString` and stack traces.
497    pub source: Option<String>,
498    /// Line of the function's declaration.
499    pub line: u32,
500    /// Column of the function's declaration.
501    pub column: u32,
502    /// File name, if known.
503    pub filename: Option<String>,
504}
505
506impl Function {
507    /// Name the script this function belongs to.
508    ///
509    /// Nested functions inherit it, because a stack trace names every frame with the
510    /// file the code came from and the parser does not know file names — the host
511    /// does, after the source has already been compiled.
512    pub fn set_filename(&mut self, name: &str) {
513        self.filename = Some(name.to_string());
514        for constant in &mut self.cpool {
515            if let Constant::Function(inner) = constant {
516                inner.set_filename(name);
517            }
518        }
519    }
520
521    /// The source position of the instruction at `pc`.
522    ///
523    /// The last entry at or before `pc` wins, so a position applies until the next one
524    /// starts. `None` when the function carries no positions at all — a script compiled
525    /// without source information.
526    pub fn position_at(&self, pc: u32) -> Option<(u32, u32)> {
527        let index = match self.positions.binary_search_by_key(&pc, |entry| entry.pc) {
528            Ok(index) => index,
529            Err(0) => return None,
530            Err(index) => index - 1,
531        };
532        self.positions
533            .get(index)
534            .map(|entry| (entry.line, entry.column))
535    }
536
537    /// Decode the instruction stream back into instructions.
538    ///
539    /// Labels are already resolved, so a `label` operand is an absolute byte
540    /// offset.
541    pub fn instructions(&self) -> Vec<(usize, Instruction)> {
542        let mut out = Vec::new();
543        let mut pos = 0usize;
544        while pos < self.code.len() {
545            let Some(op) = Opcode::from_u8(self.code[pos]) else {
546                break;
547            };
548            let info = op.info();
549            let mut operands = Vec::new();
550            let payload = &self.code[pos + 1..(pos + info.size as usize).min(self.code.len())];
551            crate::disasm::decode_operands(info.format, payload, &mut operands);
552            out.push((pos, Instruction { op, operands }));
553            pos += info.size as usize;
554        }
555        out
556    }
557
558    /// Byte offsets that are the target of a jump, which the disassembler marks.
559    pub fn jump_targets(&self) -> Vec<usize> {
560        let mut targets = Vec::new();
561        for (pc, instruction) in self.instructions() {
562            if instruction.op.info().format.is_label()
563                && let Some(target) = instruction.jump_target(pc)
564            {
565                targets.push(target as usize);
566            }
567        }
568        targets
569    }
570
571    /// Total number of variable slots, as the serialiser stores them.
572    pub fn slot_count(&self) -> u32 {
573        self.args.len() as u32 + self.vars.len() as u32
574    }
575}
576
577impl fmt::Display for FunctionKind {
578    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579        let text = match self {
580            FunctionKind::Normal => "function",
581            FunctionKind::Generator => "generator",
582            FunctionKind::Async => "async function",
583            FunctionKind::AsyncGenerator => "async generator",
584        };
585        f.write_str(text)
586    }
587}