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 js_parse::Wtf8;
16use std::fmt;
17
18/// One entry of a function's atom table.
19///
20/// The reference keeps two kinds of atom in one namespace, and the distinction is
21/// visible in the bytecode: an *array-index* atom is not a string at all but a
22/// tagged `uint32`, which is why `{ 2: x }` disassembles as `define_field 2` while
23/// `{ "1.5": x }` prints `define_field "1.5"`. Collapsing the two would make the
24/// disassembly wrong and lose information on the way back in, so the kind is
25/// carried here.
26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
27pub enum Atom {
28    /// An interned string.
29    ///
30    /// A [`Wtf8`], because a string *literal* is interned as an atom and may hold an
31    /// unpaired surrogate (`"\uD800"`). Every other atom is an identifier or a property
32    /// name taken from source text, which is valid UTF-8 by construction.
33    Str(Wtf8),
34    /// A canonical array index, held as a number rather than a string.
35    Index(u32),
36    /// The reference's `JS_ATOM_NULL`: no name at all.
37    ///
38    /// Only a handful of opcodes take one — `throw_error` with the generic message, and
39    /// `delete super.x` — and the dump prints it as `<null>` rather than as an empty string,
40    /// which is why it is a variant instead of `Str(String::new())`.
41    Null,
42}
43
44impl Atom {
45    /// The atom the reference's `JS_NewAtomStr` would make of `text`.
46    ///
47    /// A canonical array index no greater than `2^31 - 1` is never interned as a
48    /// string: the reference returns a tagged integer instead. Anything else —
49    /// `"007"`, `"1e2"`, `"-0"`, or an index past the tag range — stays a string.
50    pub fn from_text(text: &str) -> Atom {
51        match canonical_array_index(text) {
52            Some(index) => Atom::Index(index),
53            None => Atom::Str(Wtf8::new(text)),
54        }
55    }
56
57    /// The same, for a string that may hold an unpaired surrogate.
58    ///
59    /// The index rule still applies, and only to text that has a `&str` form at all: a
60    /// surrogate-containing string cannot be a canonical array index, so it keeps its
61    /// bytes and is interned as a string.
62    pub fn from_wtf8(text: &Wtf8) -> Atom {
63        match text.as_str() {
64            Some(plain) => Atom::from_text(plain),
65            None => Atom::Str(text.clone()),
66        }
67    }
68
69    /// The text form, for callers that only care about the name.
70    pub fn as_str(&self) -> Option<&str> {
71        match self {
72            Atom::Str(text) => text.as_str(),
73            Atom::Index(_) | Atom::Null => None,
74        }
75    }
76
77    /// The text form even when it holds an unpaired surrogate.
78    pub fn as_wtf8(&self) -> Option<&Wtf8> {
79        match self {
80            Atom::Str(text) => Some(text),
81            Atom::Index(_) | Atom::Null => None,
82        }
83    }
84}
85
86impl fmt::Display for Atom {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        match self {
89            Atom::Str(text) => write!(f, "{}", text.to_string_lossy()),
90            Atom::Index(index) => write!(f, "{index}"),
91            Atom::Null => write!(f, "null"),
92        }
93    }
94}
95
96/// `is_num_string` from the reference: the canonical decimal spelling of an index
97/// small enough to be tagged (at most `2^31 - 1`).
98///
99/// Canonical means no sign, no leading zeros and no other characters, so `"10"`
100/// qualifies while `"007"`, `"-0"` and `"1e2"` do not.
101fn canonical_array_index(text: &str) -> Option<u32> {
102    // `2^31 - 1` has ten digits, which bounds how long a canonical index can be.
103    if text.is_empty() || text.len() > 10 {
104        return None;
105    }
106    let bytes = text.as_bytes();
107    if !bytes.iter().all(u8::is_ascii_digit) {
108        return None;
109    }
110    if bytes[0] == b'0' && bytes.len() != 1 {
111        return None;
112    }
113    let value: u32 = text.parse().ok()?;
114    (value <= 0x7fff_ffff).then_some(value)
115}
116
117/// How a function was declared. Determines the calling convention.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum FunctionKind {
120    /// A plain function.
121    Normal,
122    /// `function*`
123    Generator,
124    /// `async function`
125    Async,
126    /// `async function*`
127    AsyncGenerator,
128}
129
130impl FunctionKind {
131    /// Whether the function is a generator (plain or async).
132    pub fn is_generator(self) -> bool {
133        matches!(self, FunctionKind::Generator | FunctionKind::AsyncGenerator)
134    }
135
136    /// Whether the function is async (plain or generator).
137    pub fn is_async(self) -> bool {
138        matches!(self, FunctionKind::Async | FunctionKind::AsyncGenerator)
139    }
140}
141
142/// What a declared name is used for, which decides how it is displayed and how
143/// the function prologue initialises it.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum VarKind {
146    /// An ordinary binding.
147    Normal,
148    /// A lexical binding holding a hoisted function declaration.
149    FunctionDecl,
150    /// A lexical binding holding a hoisted async/generator function declaration.
151    NewFunctionDecl,
152    /// A `catch` parameter.
153    Catch,
154    /// A name bound by a *destructuring* `catch` parameter.
155    ///
156    /// It is a `let` in every way that decides scope — the reference's dump prints
157    /// `0: let e` for `catch ({e})` — except that it is initialised as the handler is
158    /// entered, so neither a read nor a write needs the dead-zone check that an ordinary
159    /// `let` does.
160    LexicalCatch,
161    /// The name bound to a named function expression, visible inside itself.
162    FunctionName,
163    /// A private class field.
164    PrivateField,
165    /// A private class method.
166    PrivateMethod,
167    /// A private class getter.
168    PrivateGetter,
169    /// A private class setter.
170    PrivateSetter,
171    /// A private class accessor pair (`get` and `set` sharing one name).
172    PrivateGetterSetter,
173    /// A global function declaration.
174    GlobalFunctionDecl,
175    /// A `using` declaration's binding.
176    Using,
177    /// The hidden local holding a `using` declaration's cached dispose method.
178    UsingMethod,
179    /// The hidden local holding a `with` statement's boxed object.
180    ///
181    /// Marked rather than merely named so the runtime can find the active ones without
182    /// guessing from a name prefix: an `eval` inside a `with` has to resolve names
183    /// against these objects before it reaches the realm.
184    With,
185}
186
187impl VarKind {
188    /// The word the disassembler prints for this kind.
189    pub fn label(self) -> &'static str {
190        match self {
191            VarKind::Catch => "catch",
192            VarKind::LexicalCatch => "let",
193            VarKind::FunctionDecl | VarKind::NewFunctionDecl | VarKind::GlobalFunctionDecl => {
194                "function"
195            }
196            _ => "",
197        }
198    }
199
200    /// Whether the binding is initialised when the function is entered.
201    pub fn is_hoisted_declaration(self) -> bool {
202        matches!(self, VarKind::FunctionDecl | VarKind::NewFunctionDecl)
203    }
204}
205
206/// The name of a binding the source never named.
207///
208/// A pattern parameter occupies one argument slot but binds several names, so the slot
209/// itself has no name; the reference gives it `JS_ATOM_NULL`, which its dump prints as
210/// `<null>`. Keeping the same spelling here keeps the dump byte-identical and makes the
211/// anonymous slots easy to spot.
212pub const ANONYMOUS_BINDING: &str = "<null>";
213
214/// A declared variable: an argument or a local.
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct VarDef {
217    /// The name, as written.
218    pub name: String,
219    /// Whether the binding is immutable.
220    pub is_const: bool,
221    /// Whether the binding is block-scoped (`let`/`const`/`class`).
222    pub is_lexical: bool,
223    /// What the binding is used for.
224    pub kind: VarKind,
225    /// Whether a closure captures this variable, which forces it into a
226    /// heap-allocated reference cell.
227    pub is_captured: bool,
228    /// The lexical scope the binding belongs to.
229    ///
230    /// Scope 0 is the function scope, where `var` and hoisted function
231    /// declarations live; the body and every block introduce a child scope. A
232    /// binding only exists between its scope's entry and exit, which is what the
233    /// runtime uses to swap `let`/`const` bindings in and out.
234    pub scope_level: u32,
235    /// Index of the next block-scoped variable in the enclosing scope chain, or
236    /// `None` for a `var` (which is visible in the whole function).
237    ///
238    /// The reference stores this in `JSVarDef::scope_next` and only fills it in
239    /// when `scope_level != 0`; the interpreter walks the chain to instantiate
240    /// and close the `let`/`const` bindings that are live at a given point.
241    pub scope_next: Option<i32>,
242}
243
244impl VarDef {
245    /// A plain `var` binding.
246    pub fn var(name: impl Into<String>) -> VarDef {
247        VarDef {
248            name: name.into(),
249            is_const: false,
250            is_lexical: false,
251            kind: VarKind::Normal,
252            is_captured: false,
253            scope_level: 0,
254            scope_next: None,
255        }
256    }
257
258    /// Whether reading this binding can hit the temporal dead zone, i.e. it is
259    /// `let`/`const`/`class` and therefore starts out uninitialised.
260    pub fn needs_check(&self) -> bool {
261        self.is_lexical && self.kind != VarKind::LexicalCatch
262    }
263
264    /// A `let` binding.
265    pub fn lexical(name: impl Into<String>) -> VarDef {
266        VarDef {
267            is_lexical: true,
268            ..VarDef::var(name)
269        }
270    }
271
272    /// A `const` binding.
273    pub fn constant(name: impl Into<String>) -> VarDef {
274        VarDef {
275            is_lexical: true,
276            is_const: true,
277            ..VarDef::var(name)
278        }
279    }
280
281    /// The word the disassembler prints for this definition.
282    pub fn label(&self) -> &'static str {
283        let kind = self.kind.label();
284        if !kind.is_empty() {
285            return kind;
286        }
287        if self.is_const {
288            "const"
289        } else if self.is_lexical {
290            "let"
291        } else {
292            "var"
293        }
294    }
295}
296
297/// Where a captured variable actually lives, and therefore how a closure
298/// reaches it.
299#[derive(Debug, Clone, Copy, PartialEq, Eq)]
300pub enum ClosureType {
301    /// A local of the parent function (`[loc<n>]`).
302    Local,
303    /// An argument of the parent function (`[arg<n>]`).
304    Arg,
305    /// A reference cell in the parent function (`[ref<n>]`).
306    Ref,
307    /// A global, reached through the reference table by index.
308    GlobalRef,
309    /// A global declared in this script.
310    GlobalDecl,
311    /// A global reached by name.
312    Global,
313    /// A module-level declaration.
314    ModuleDecl,
315    /// A module import binding.
316    ModuleImport,
317}
318
319impl ClosureType {
320    /// The suffix the disassembler prints.
321    pub fn describe(self) -> &'static str {
322        match self {
323            ClosureType::Local => "loc",
324            ClosureType::Arg => "arg",
325            ClosureType::Ref => "ref",
326            ClosureType::GlobalDecl => "global_decl",
327            ClosureType::Global => "global",
328            ClosureType::ModuleDecl => "module_decl",
329            ClosureType::ModuleImport => "module_import",
330            ClosureType::GlobalRef => "global_ref",
331        }
332    }
333}
334
335/// One captured variable of a function.
336#[derive(Debug, Clone, PartialEq, Eq)]
337pub struct ClosureVar {
338    /// The name, as written in the enclosing function.
339    pub name: String,
340    /// Whether the captured binding is immutable.
341    pub is_const: bool,
342    /// Whether the captured binding is block-scoped.
343    pub is_lexical: bool,
344    /// Whether the captured binding is a hoisted **function declaration**.
345    ///
346    /// Only the *global* case needs to know: an `eval` that declares a function
347    /// establishes it with `CanDeclareGlobalFunction`, which refuses a non-configurable
348    /// property unless it is a writable, enumerable data property. `CanDeclareGlobalVar`
349    /// — the `var` rule — accepts anything that merely exists. `eval("function NaN(){}")`
350    /// is therefore a `TypeError` while `eval("var NaN")` is fine
351    /// (`eval-code/direct/non-definable-global-function`).
352    pub is_function_decl: bool,
353    /// How the closure reaches it.
354    pub closure_type: ClosureType,
355    /// Index into the parent's locals, arguments or reference cells.
356    pub var_idx: u16,
357}
358
359/// A constant in the pool.
360#[derive(Debug, Clone, PartialEq)]
361pub enum Constant {
362    /// A number.
363    Number(f64),
364    /// A string.
365    ///
366    /// A [`Wtf8`] for the same reason an atom is one: the literal may hold an unpaired
367    /// surrogate, and the constant is the literal.
368    String(Wtf8),
369    /// A BigInt literal: digits and radix.
370    BigInt {
371        /// Digits, without prefix or separators.
372        digits: String,
373        /// 2, 8, 10 or 16.
374        radix: u32,
375    },
376    /// A nested function, referenced by `fclosure`.
377    Function(Box<Function>),
378    /// A template object: one call site's chunks.
379    ///
380    /// The *raw* text is carried as well as the cooked text because `String.raw` reads
381    /// it back verbatim, and a tagged template may legally contain an invalid escape
382    /// sequence whose cooked form is `undefined`.
383    Template {
384        /// A realm-wide identity for this source location.
385        ///
386        /// §13.2.8.1 keys the template registry by *parse node*, and the runtime needs
387        /// something equally stable: two closures made from one function body must share
388        /// the template object, while two `eval` calls of the same text must not. A closure
389        /// gets a freshly built `CompiledCode` in this engine, so the code object cannot be
390        /// the key; a counter taken at compile time is stable for every closure of the site
391        /// and fresh for every compilation unit.
392        site: u32,
393        /// Cooked text; `None` for a chunk with an invalid escape sequence.
394        cooked: Vec<Option<Wtf8>>,
395        /// Source text of each chunk, verbatim.
396        raw: Vec<String>,
397    },
398}
399
400impl Constant {
401    /// A short description for disassembly, matching the reference's
402    /// `JS_PrintValue` for the cases the compiler can produce.
403    pub fn describe(&self) -> String {
404        match self {
405            Constant::Number(n) => format_number(*n),
406            Constant::String(s) => format!("\"{}\"", escape_js_string(&s.to_string_lossy())),
407            // The reference prints BigInts in decimal, whatever the source radix.
408            Constant::BigInt { digits, .. } => format!("{digits}n"),
409            Constant::Function(f) => {
410                // The reference prints the function's name atom, which is `<null>`
411                // for an anonymous function expression.
412                if f.name.is_empty() {
413                    "[bytecode <null>]".to_string()
414                } else {
415                    format!("[bytecode {}]", f.name)
416                }
417            }
418            Constant::Template { cooked, .. } => {
419                let parts: Vec<String> = cooked
420                    .iter()
421                    .map(|q| {
422                        q.clone()
423                            .map(|text| text.to_string_lossy().into_owned())
424                            .unwrap_or_else(|| "undefined".to_string())
425                    })
426                    .collect();
427                format!("template object [{}]", parts.join(", "))
428            }
429        }
430    }
431}
432
433/// Format a number the way the reference implementation prints it.
434fn format_number(value: f64) -> String {
435    if value.is_nan() {
436        return "NaN".to_string();
437    }
438    if value.is_infinite() {
439        return if value > 0.0 {
440            "inf".to_string()
441        } else {
442            "-inf".to_string()
443        };
444    }
445    if value == value.trunc() && value.abs() < 1e21 {
446        return format!("{}", value as i64);
447    }
448    format!("{value}")
449}
450
451/// Escape a string for the double-quoted form the disassembler prints.
452fn escape_js_string(text: &str) -> String {
453    let mut out = String::with_capacity(text.len());
454    for c in text.chars() {
455        match c {
456            '"' => out.push_str("\\\""),
457            '\\' => out.push_str("\\\\"),
458            '\n' => out.push_str("\\n"),
459            '\r' => out.push_str("\\r"),
460            '\t' => out.push_str("\\t"),
461            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
462            c => out.push(c),
463        }
464    }
465    out
466}
467
468/// An operand of an instruction during compilation, before addresses are known.
469#[derive(Debug, Clone, PartialEq, Eq)]
470pub enum Operand {
471    /// No operand.
472    None,
473    /// A label, resolved to a byte offset.
474    Label(u32),
475    /// A local slot index.
476    Loc(u32),
477    /// An argument slot index.
478    Arg(u32),
479    /// A closure variable index.
480    VarRef(u32),
481    /// A constant pool index.
482    Const(u32),
483    /// An atom (an interned name), stored as its UTF-8 text before interning.
484    Atom(String),
485    /// A small unsigned immediate.
486    U8(u8),
487    /// A small signed immediate.
488    I8(i8),
489    /// A medium unsigned immediate.
490    U16(u16),
491    /// A medium signed immediate.
492    I16(i16),
493    /// A signed 32-bit immediate.
494    I32(i32),
495    /// An unsigned 32-bit immediate.
496    U32(u32),
497}
498
499/// A resolved instruction: opcode plus the operands encoded in its payload.
500#[derive(Debug, Clone, PartialEq)]
501pub struct Instruction {
502    /// The instruction.
503    pub op: Opcode,
504    /// Operands in the order the encoding stores them.
505    pub operands: Vec<Operand>,
506}
507
508impl Instruction {
509    /// An instruction with no operands.
510    pub fn new(op: Opcode) -> Instruction {
511        Instruction {
512            op,
513            operands: Vec::new(),
514        }
515    }
516
517    /// An instruction with one operand.
518    pub fn with(op: Opcode, operand: Operand) -> Instruction {
519        Instruction {
520            op,
521            operands: vec![operand],
522        }
523    }
524}
525
526/// Where a variable lives in the resolved function.
527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
528pub enum Storage {
529    /// Argument slot.
530    Arg(u32),
531    /// Local slot.
532    Loc(u32),
533    /// Closure reference.
534    VarRef(u32),
535    /// Global, by atom.
536    Global,
537}
538
539/// A stretch of bytecode and the source position it came from.
540///
541/// One entry per run of instructions that share a position, ordered by `pc`, which is
542/// what [`Function::position_at`] binary searches. This is the port of the reference's
543/// `pc2line` table: it is how a stack trace says `file:line:col` for a frame that is
544/// deep inside a function rather than at its first statement.
545#[derive(Debug, Clone, Copy, PartialEq, Eq)]
546pub struct LineCol {
547    /// Byte offset in [`Function::code`] where this position takes over.
548    pub pc: u32,
549    /// 1-based line.
550    pub line: u32,
551    /// 1-based column, in UTF-16 code units like every other position here.
552    pub column: u32,
553}
554
555/// A compiled function.
556#[derive(Debug, Clone, PartialEq)]
557pub struct Function {
558    /// The function's name; `<eval>` for a script body.
559    pub name: String,
560    /// The declaration form.
561    pub kind: FunctionKind,
562    /// Whether the body is strict.
563    pub strict: bool,
564    /// Whether this is a **derived** class constructor (`class D extends B`).
565    ///
566    /// §15.7.1 step 12: a derived constructor that returns a non-object is a `TypeError`,
567    /// where a base one silently keeps `this`. The runtime cannot tell the two apart from
568    /// the bytecode alone, so the flag rides along.
569    pub is_derived_constructor: bool,
570    /// Whether this is a **script**, `eval` or module body rather than a function.
571    ///
572    /// The distinction is observable to an `eval` inside it: §19.2.1.1 asks the *caller's*
573    /// function for `new.target`, and a script body has none — `eval('new.target')` at the
574    /// top level is a `SyntaxError`, not `undefined`.
575    pub is_script_body: bool,
576    /// Whether this came from an arrow function.
577    ///
578    /// An arrow has no `this` and no `new.target` of its own, so the runtime has to know
579    /// to look outward for both — an `eval` inside an arrow sees the enclosing function's
580    /// receiver, not the arrow's.
581    pub is_arrow: bool,
582    /// Whether the parameter list contains a default expression, and so gets a variable
583    /// environment of its own (`PARAM_SCOPE` in the compiler).
584    ///
585    /// The runtime needs this for two things a direct `eval` can observe: where a `var`
586    /// it declares belongs (the parameter environment, while the defaults are still being
587    /// evaluated), and which bindings a closure created there may see.
588    pub has_parameter_expressions: bool,
589    /// Whether the parameter list is *simple* in the spec's sense
590    /// (`IsSimpleParameterList`): every parameter is a plain binding identifier, with no
591    /// default, no rest and no destructuring.
592    ///
593    /// This is what decides whether a sloppy-mode `arguments` is *mapped*. It is not the
594    /// same question as `has_parameter_expressions`, which is about the separate
595    /// parameter environment: `function f([a])` has no default expression yet is still a
596    /// non-simple list, and its `arguments` must not alias the parameter.
597    pub simple_parameter_list: bool,
598    /// Where the body begins in source order, as `(line, column)`.
599    ///
600    /// A closure whose creation site is before this was created by a default expression,
601    /// so it sees the parameter environment and not the body's. Recorded as a position
602    /// rather than a bytecode offset because the instruction stream is rebuilt (frame
603    /// prologues are prepended) after the point where the compiler knows the boundary.
604    /// `(0, 0)` means "unknown", which is read as "the whole function is its body".
605    pub body_start: (u32, u32),
606    /// Parameters.
607    pub args: Vec<VarDef>,
608    /// How many parameters count towards `Function.prototype.length`.
609    ///
610    /// A parameter with a default or a rest parameter ends the count, because `.length`
611    /// is the arity the function can be called with before anything is substituted.
612    pub defined_args: u32,
613    /// Locals, including the implicit return-value slot named `<ret>`.
614    pub vars: Vec<VarDef>,
615    /// Captured variables of enclosing functions.
616    pub closure_vars: Vec<ClosureVar>,
617    /// Constant pool.
618    pub cpool: Vec<Constant>,
619    /// Atom table: the names this function mentions. The runtime shares one
620    /// interned table across the whole program; indexing it per function keeps
621    /// the bytecode self-contained and makes disassembly readable.
622    pub atoms: Vec<Atom>,
623    /// Resolved bytecode.
624    pub code: Vec<u8>,
625    /// Maximum value-stack depth.
626    pub stack_size: u32,
627    /// Source positions, ordered by bytecode offset.
628    pub positions: Vec<LineCol>,
629    /// Number of reference cells allocated on entry.
630    pub var_ref_count: u32,
631    /// Source text, kept for `Function.prototype.toString` and stack traces.
632    pub source: Option<String>,
633    /// Line of the function's declaration.
634    pub line: u32,
635    /// Column of the function's declaration.
636    pub column: u32,
637    /// File name, if known.
638    pub filename: Option<String>,
639    /// What each direct `eval(...)` call in this function can see.
640    ///
641    /// Slot resolution for ordinary code happens at compile time, but a direct `eval`
642    /// resolves names at *run* time, from a string the compiler never reads. Without
643    /// this table the runtime has to guess by name across the whole frame, which picks
644    /// the wrong binding when a name is declared twice in sibling scopes:
645    ///
646    /// ```text
647    /// for (let i = 0; i < 3; i++) f(eval);   // this `i`
648    /// for (let i = 0; i < 3; i++) f(eval);   // and this one
649    /// ```
650    ///
651    /// The compiler knows exactly which of them is in scope at each call, so it records
652    /// the answer here. It is data, not an instruction, so the bytecode stays identical
653    /// to the reference's.
654    pub eval_sites: Vec<EvalSite>,
655    /// The module this body is, when it is one.
656    ///
657    /// `None` for a script and for every nested function. A module's *requests*,
658    /// *imports* and *exports* are data rather than instructions — the body itself reads
659    /// its bindings through ordinary closure-variable opcodes, and this is what the host
660    /// needs in order to wire those cells up before the body runs.
661    pub module: Option<Box<ModuleMeta>>,
662}
663
664/// What a module body needs from the host, recorded at compile time.
665///
666/// The three tables mirror §16.2.1.5's `[[RequestedModules]]`, `[[ImportEntries]]` and
667/// `[[LocalExportEntries]]`/`[[IndirectExportEntries]]`/`[[StarExportEntries]]`. They are
668/// kept as plain data so linking can be done without looking at bytecode.
669#[derive(Debug, Clone, PartialEq, Default)]
670pub struct ModuleMeta {
671    /// The modules this one asks for, in source order and de-duplicated by specifier.
672    pub requests: Vec<ModuleRequest>,
673    /// Where each imported binding lands.
674    pub imports: Vec<ImportEntry>,
675    /// What this module offers.
676    pub exports: Vec<ExportEntry>,
677}
678
679/// One `from "…"` of a module.
680#[derive(Debug, Clone, PartialEq)]
681pub struct ModuleRequest {
682    /// The specifier as written.
683    pub specifier: String,
684    /// `with { type: "json" }` and friends, in source order.
685    pub attributes: Vec<(String, String)>,
686    /// Which phase of the module is wanted.
687    ///
688    /// §16.2.1.5 de-duplicates `[[RequestedModules]]` on the specifier *and* the phase, so
689    /// `import * as a from "m"` next to `import defer * as b from "m"` is two requests for
690    /// one module — which is what lets the same module have both an eager and a deferred
691    /// namespace.
692    pub phase: js_parse::ast::ImportPhase,
693}
694
695/// One imported binding.
696#[derive(Debug, Clone, PartialEq)]
697pub struct ImportEntry {
698    /// Index into [`ModuleMeta::requests`].
699    pub module: u32,
700    /// The name imported from it; ignored when `is_star`.
701    pub name: String,
702    /// Which module variable holds it — the closure-variable index in the body.
703    pub var_idx: u32,
704    /// `import * as ns from "m"`: the binding is the module's namespace object.
705    pub is_star: bool,
706    /// Which phase of the module the binding reads.
707    ///
708    /// Only `import defer * as ns` is both `is_star` and `Defer`; every other combination
709    /// either does not exist in the grammar or is the evaluation phase.
710    pub phase: js_parse::ast::ImportPhase,
711}
712
713/// One exported name.
714///
715/// The four forms are the ones §16.2.1.5 distinguishes, and they resolve differently:
716/// a local export names a variable of this module, an indirect one names a name in
717/// another module, a star export forwards everything, and a star-as export forwards the
718/// whole namespace under one name.
719#[derive(Debug, Clone, PartialEq)]
720pub enum ExportEntry {
721    /// `export { a }` / `export var a` / `export default …`
722    Local {
723        /// The name the outside sees.
724        export_name: String,
725        /// The module variable behind it.
726        var_idx: u32,
727    },
728    /// `export { a as b } from "m"`
729    Indirect {
730        /// The name the outside sees.
731        export_name: String,
732        /// Index into [`ModuleMeta::requests`].
733        module: u32,
734        /// The name to look up in that module.
735        import_name: String,
736    },
737    /// `export * from "m"`
738    Star {
739        /// Index into [`ModuleMeta::requests`].
740        module: u32,
741    },
742    /// `export * as ns from "m"`
743    StarAs {
744        /// The name the outside sees.
745        export_name: String,
746        /// Index into [`ModuleMeta::requests`].
747        module: u32,
748    },
749}
750
751/// One direct `eval(...)` call site and the bindings visible at it.
752#[derive(Debug, Clone, PartialEq)]
753pub struct EvalSite {
754    /// Source position of the call, which is how the runtime finds the site: it asks
755    /// for the position of the `call` instruction it is executing.
756    pub line: u32,
757    /// Column of the call.
758    pub column: u32,
759    /// Visible bindings, innermost scope first, so the first name match wins.
760    pub bindings: Vec<EvalVisible>,
761    /// The private names the calling code can see, for an `eval` inside a class body.
762    ///
763    /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal: private names are
764    /// lexically scoped and the eval runs inside the caller's scope. The names come from the
765    /// *call site's* class, not from the eval'd source, so they have to travel with the site.
766    pub private_names: Vec<EvalPrivate>,
767    /// Whether `arguments` is a binding at the call site.
768    ///
769    /// A class field initializer and a static block have none, so `eval('arguments')` in one
770    /// is a `SyntaxError`. The eval'd source cannot know that; the call site can.
771    pub arguments_allowed: bool,
772}
773
774/// One private name an `eval` at a given site can see.
775///
776/// The same three facts the compiler needs to compile a use of it: what kind of thing the
777/// binding holds, and — for an accessor — the companion setter binding.
778#[derive(Debug, Clone, PartialEq)]
779pub struct EvalPrivate {
780    /// The binding name, `#x`.
781    pub name: String,
782    /// What the binding holds.
783    pub kind: EvalPrivateKind,
784    /// `#x<set>`, when the class defines a setter for this name.
785    pub setter: Option<String>,
786}
787
788/// What a private binding holds — the shape [`EvalPrivate`] carries.
789#[derive(Debug, Clone, Copy, PartialEq, Eq)]
790pub enum EvalPrivateKind {
791    /// `#x = 1`: a property key.
792    Field,
793    /// `#m() {}`: the function.
794    Method,
795    /// `get #a() {}`: the getter function.
796    Getter,
797    /// `set #a(v) {}` with no getter: a binding that is declared but never filled.
798    Setter,
799}
800
801/// One binding an `eval` can see.
802#[derive(Debug, Clone, PartialEq)]
803pub struct EvalVisible {
804    /// The name the eval would write.
805    pub name: String,
806    /// Whether it is a parameter of the function rather than a local.
807    pub is_arg: bool,
808    /// The slot index within that table.
809    pub index: u32,
810    /// How many frames up the binding lives: `0` is the function containing the
811    /// `eval`, `1` its caller's definition and so on. A direct `eval` sees the whole
812    /// chain, and the slot for a name declared in an enclosing function is only known
813    /// at compile time.
814    pub owner: u32,
815}
816
817impl Function {
818    /// Name the script this function belongs to.
819    ///
820    /// Nested functions inherit it, because a stack trace names every frame with the
821    /// file the code came from and the parser does not know file names — the host
822    /// does, after the source has already been compiled.
823    pub fn set_filename(&mut self, name: &str) {
824        self.filename = Some(name.to_string());
825        for constant in &mut self.cpool {
826            if let Constant::Function(inner) = constant {
827                inner.set_filename(name);
828            }
829        }
830    }
831
832    /// The source position of the instruction at `pc`.
833    ///
834    /// The last entry at or before `pc` wins, so a position applies until the next one
835    /// starts. `None` when the function carries no positions at all — a script compiled
836    /// without source information.
837    pub fn position_at(&self, pc: u32) -> Option<(u32, u32)> {
838        let index = match self.positions.binary_search_by_key(&pc, |entry| entry.pc) {
839            Ok(index) => index,
840            Err(0) => return None,
841            Err(index) => index - 1,
842        };
843        self.positions
844            .get(index)
845            .map(|entry| (entry.line, entry.column))
846    }
847
848    /// Decode the instruction stream back into instructions.
849    ///
850    /// Labels are already resolved, so a `label` operand is an absolute byte
851    /// offset.
852    pub fn instructions(&self) -> Vec<(usize, Instruction)> {
853        let mut out = Vec::new();
854        let mut pos = 0usize;
855        while pos < self.code.len() {
856            let Some(op) = Opcode::from_u8(self.code[pos]) else {
857                break;
858            };
859            let info = op.info();
860            let mut operands = Vec::new();
861            let payload = &self.code[pos + 1..(pos + info.size as usize).min(self.code.len())];
862            crate::disasm::decode_operands(info.format, payload, &mut operands);
863            out.push((pos, Instruction { op, operands }));
864            pos += info.size as usize;
865        }
866        out
867    }
868
869    /// Byte offsets that are the target of a jump, which the disassembler marks.
870    pub fn jump_targets(&self) -> Vec<usize> {
871        let mut targets = Vec::new();
872        for (pc, instruction) in self.instructions() {
873            if instruction.op.info().format.is_label()
874                && let Some(target) = instruction.jump_target(pc)
875            {
876                targets.push(target as usize);
877            }
878        }
879        targets
880    }
881
882    /// Total number of variable slots, as the serialiser stores them.
883    pub fn slot_count(&self) -> u32 {
884        self.args.len() as u32 + self.vars.len() as u32
885    }
886}
887
888impl fmt::Display for FunctionKind {
889    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
890        let text = match self {
891            FunctionKind::Normal => "function",
892            FunctionKind::Generator => "generator",
893            FunctionKind::Async => "async function",
894            FunctionKind::AsyncGenerator => "async generator",
895        };
896        f.write_str(text)
897    }
898}