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    /// How the closure reaches it.
345    pub closure_type: ClosureType,
346    /// Index into the parent's locals, arguments or reference cells.
347    pub var_idx: u16,
348}
349
350/// A constant in the pool.
351#[derive(Debug, Clone, PartialEq)]
352pub enum Constant {
353    /// A number.
354    Number(f64),
355    /// A string.
356    ///
357    /// A [`Wtf8`] for the same reason an atom is one: the literal may hold an unpaired
358    /// surrogate, and the constant is the literal.
359    String(Wtf8),
360    /// A BigInt literal: digits and radix.
361    BigInt {
362        /// Digits, without prefix or separators.
363        digits: String,
364        /// 2, 8, 10 or 16.
365        radix: u32,
366    },
367    /// A nested function, referenced by `fclosure`.
368    Function(Box<Function>),
369    /// A template object: one call site's chunks.
370    ///
371    /// The *raw* text is carried as well as the cooked text because `String.raw` reads
372    /// it back verbatim, and a tagged template may legally contain an invalid escape
373    /// sequence whose cooked form is `undefined`.
374    Template {
375        /// Cooked text; `None` for a chunk with an invalid escape sequence.
376        cooked: Vec<Option<Wtf8>>,
377        /// Source text of each chunk, verbatim.
378        raw: Vec<String>,
379    },
380}
381
382impl Constant {
383    /// A short description for disassembly, matching the reference's
384    /// `JS_PrintValue` for the cases the compiler can produce.
385    pub fn describe(&self) -> String {
386        match self {
387            Constant::Number(n) => format_number(*n),
388            Constant::String(s) => format!("\"{}\"", escape_js_string(&s.to_string_lossy())),
389            // The reference prints BigInts in decimal, whatever the source radix.
390            Constant::BigInt { digits, .. } => format!("{digits}n"),
391            Constant::Function(f) => {
392                // The reference prints the function's name atom, which is `<null>`
393                // for an anonymous function expression.
394                if f.name.is_empty() {
395                    "[bytecode <null>]".to_string()
396                } else {
397                    format!("[bytecode {}]", f.name)
398                }
399            }
400            Constant::Template { cooked, .. } => {
401                let parts: Vec<String> = cooked
402                    .iter()
403                    .map(|q| {
404                        q.clone()
405                            .map(|text| text.to_string_lossy().into_owned())
406                            .unwrap_or_else(|| "undefined".to_string())
407                    })
408                    .collect();
409                format!("template object [{}]", parts.join(", "))
410            }
411        }
412    }
413}
414
415/// Format a number the way the reference implementation prints it.
416fn format_number(value: f64) -> String {
417    if value.is_nan() {
418        return "NaN".to_string();
419    }
420    if value.is_infinite() {
421        return if value > 0.0 {
422            "inf".to_string()
423        } else {
424            "-inf".to_string()
425        };
426    }
427    if value == value.trunc() && value.abs() < 1e21 {
428        return format!("{}", value as i64);
429    }
430    format!("{value}")
431}
432
433/// Escape a string for the double-quoted form the disassembler prints.
434fn escape_js_string(text: &str) -> String {
435    let mut out = String::with_capacity(text.len());
436    for c in text.chars() {
437        match c {
438            '"' => out.push_str("\\\""),
439            '\\' => out.push_str("\\\\"),
440            '\n' => out.push_str("\\n"),
441            '\r' => out.push_str("\\r"),
442            '\t' => out.push_str("\\t"),
443            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
444            c => out.push(c),
445        }
446    }
447    out
448}
449
450/// An operand of an instruction during compilation, before addresses are known.
451#[derive(Debug, Clone, PartialEq, Eq)]
452pub enum Operand {
453    /// No operand.
454    None,
455    /// A label, resolved to a byte offset.
456    Label(u32),
457    /// A local slot index.
458    Loc(u32),
459    /// An argument slot index.
460    Arg(u32),
461    /// A closure variable index.
462    VarRef(u32),
463    /// A constant pool index.
464    Const(u32),
465    /// An atom (an interned name), stored as its UTF-8 text before interning.
466    Atom(String),
467    /// A small unsigned immediate.
468    U8(u8),
469    /// A small signed immediate.
470    I8(i8),
471    /// A medium unsigned immediate.
472    U16(u16),
473    /// A medium signed immediate.
474    I16(i16),
475    /// A signed 32-bit immediate.
476    I32(i32),
477    /// An unsigned 32-bit immediate.
478    U32(u32),
479}
480
481/// A resolved instruction: opcode plus the operands encoded in its payload.
482#[derive(Debug, Clone, PartialEq)]
483pub struct Instruction {
484    /// The instruction.
485    pub op: Opcode,
486    /// Operands in the order the encoding stores them.
487    pub operands: Vec<Operand>,
488}
489
490impl Instruction {
491    /// An instruction with no operands.
492    pub fn new(op: Opcode) -> Instruction {
493        Instruction {
494            op,
495            operands: Vec::new(),
496        }
497    }
498
499    /// An instruction with one operand.
500    pub fn with(op: Opcode, operand: Operand) -> Instruction {
501        Instruction {
502            op,
503            operands: vec![operand],
504        }
505    }
506}
507
508/// Where a variable lives in the resolved function.
509#[derive(Debug, Clone, Copy, PartialEq, Eq)]
510pub enum Storage {
511    /// Argument slot.
512    Arg(u32),
513    /// Local slot.
514    Loc(u32),
515    /// Closure reference.
516    VarRef(u32),
517    /// Global, by atom.
518    Global,
519}
520
521/// A stretch of bytecode and the source position it came from.
522///
523/// One entry per run of instructions that share a position, ordered by `pc`, which is
524/// what [`Function::position_at`] binary searches. This is the port of the reference's
525/// `pc2line` table: it is how a stack trace says `file:line:col` for a frame that is
526/// deep inside a function rather than at its first statement.
527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
528pub struct LineCol {
529    /// Byte offset in [`Function::code`] where this position takes over.
530    pub pc: u32,
531    /// 1-based line.
532    pub line: u32,
533    /// 1-based column, in UTF-16 code units like every other position here.
534    pub column: u32,
535}
536
537/// A compiled function.
538#[derive(Debug, Clone, PartialEq)]
539pub struct Function {
540    /// The function's name; `<eval>` for a script body.
541    pub name: String,
542    /// The declaration form.
543    pub kind: FunctionKind,
544    /// Whether the body is strict.
545    pub strict: bool,
546    /// Whether this came from an arrow function.
547    ///
548    /// An arrow has no `this` and no `new.target` of its own, so the runtime has to know
549    /// to look outward for both — an `eval` inside an arrow sees the enclosing function's
550    /// receiver, not the arrow's.
551    pub is_arrow: bool,
552    /// Whether the parameter list contains a default expression, and so gets a variable
553    /// environment of its own (`PARAM_SCOPE` in the compiler).
554    ///
555    /// The runtime needs this for two things a direct `eval` can observe: where a `var`
556    /// it declares belongs (the parameter environment, while the defaults are still being
557    /// evaluated), and which bindings a closure created there may see.
558    pub has_parameter_expressions: bool,
559    /// Whether the parameter list is *simple* in the spec's sense
560    /// (`IsSimpleParameterList`): every parameter is a plain binding identifier, with no
561    /// default, no rest and no destructuring.
562    ///
563    /// This is what decides whether a sloppy-mode `arguments` is *mapped*. It is not the
564    /// same question as `has_parameter_expressions`, which is about the separate
565    /// parameter environment: `function f([a])` has no default expression yet is still a
566    /// non-simple list, and its `arguments` must not alias the parameter.
567    pub simple_parameter_list: bool,
568    /// Where the body begins in source order, as `(line, column)`.
569    ///
570    /// A closure whose creation site is before this was created by a default expression,
571    /// so it sees the parameter environment and not the body's. Recorded as a position
572    /// rather than a bytecode offset because the instruction stream is rebuilt (frame
573    /// prologues are prepended) after the point where the compiler knows the boundary.
574    /// `(0, 0)` means "unknown", which is read as "the whole function is its body".
575    pub body_start: (u32, u32),
576    /// Parameters.
577    pub args: Vec<VarDef>,
578    /// How many parameters count towards `Function.prototype.length`.
579    ///
580    /// A parameter with a default or a rest parameter ends the count, because `.length`
581    /// is the arity the function can be called with before anything is substituted.
582    pub defined_args: u32,
583    /// Locals, including the implicit return-value slot named `<ret>`.
584    pub vars: Vec<VarDef>,
585    /// Captured variables of enclosing functions.
586    pub closure_vars: Vec<ClosureVar>,
587    /// Constant pool.
588    pub cpool: Vec<Constant>,
589    /// Atom table: the names this function mentions. The runtime shares one
590    /// interned table across the whole program; indexing it per function keeps
591    /// the bytecode self-contained and makes disassembly readable.
592    pub atoms: Vec<Atom>,
593    /// Resolved bytecode.
594    pub code: Vec<u8>,
595    /// Maximum value-stack depth.
596    pub stack_size: u32,
597    /// Source positions, ordered by bytecode offset.
598    pub positions: Vec<LineCol>,
599    /// Number of reference cells allocated on entry.
600    pub var_ref_count: u32,
601    /// Source text, kept for `Function.prototype.toString` and stack traces.
602    pub source: Option<String>,
603    /// Line of the function's declaration.
604    pub line: u32,
605    /// Column of the function's declaration.
606    pub column: u32,
607    /// File name, if known.
608    pub filename: Option<String>,
609    /// What each direct `eval(...)` call in this function can see.
610    ///
611    /// Slot resolution for ordinary code happens at compile time, but a direct `eval`
612    /// resolves names at *run* time, from a string the compiler never reads. Without
613    /// this table the runtime has to guess by name across the whole frame, which picks
614    /// the wrong binding when a name is declared twice in sibling scopes:
615    ///
616    /// ```text
617    /// for (let i = 0; i < 3; i++) f(eval);   // this `i`
618    /// for (let i = 0; i < 3; i++) f(eval);   // and this one
619    /// ```
620    ///
621    /// The compiler knows exactly which of them is in scope at each call, so it records
622    /// the answer here. It is data, not an instruction, so the bytecode stays identical
623    /// to the reference's.
624    pub eval_sites: Vec<EvalSite>,
625    /// The module this body is, when it is one.
626    ///
627    /// `None` for a script and for every nested function. A module's *requests*,
628    /// *imports* and *exports* are data rather than instructions — the body itself reads
629    /// its bindings through ordinary closure-variable opcodes, and this is what the host
630    /// needs in order to wire those cells up before the body runs.
631    pub module: Option<Box<ModuleMeta>>,
632}
633
634/// What a module body needs from the host, recorded at compile time.
635///
636/// The three tables mirror §16.2.1.5's `[[RequestedModules]]`, `[[ImportEntries]]` and
637/// `[[LocalExportEntries]]`/`[[IndirectExportEntries]]`/`[[StarExportEntries]]`. They are
638/// kept as plain data so linking can be done without looking at bytecode.
639#[derive(Debug, Clone, PartialEq, Default)]
640pub struct ModuleMeta {
641    /// The modules this one asks for, in source order and de-duplicated by specifier.
642    pub requests: Vec<ModuleRequest>,
643    /// Where each imported binding lands.
644    pub imports: Vec<ImportEntry>,
645    /// What this module offers.
646    pub exports: Vec<ExportEntry>,
647}
648
649/// One `from "…"` of a module.
650#[derive(Debug, Clone, PartialEq)]
651pub struct ModuleRequest {
652    /// The specifier as written.
653    pub specifier: String,
654    /// `with { type: "json" }` and friends, in source order.
655    pub attributes: Vec<(String, String)>,
656}
657
658/// One imported binding.
659#[derive(Debug, Clone, PartialEq)]
660pub struct ImportEntry {
661    /// Index into [`ModuleMeta::requests`].
662    pub module: u32,
663    /// The name imported from it; ignored when `is_star`.
664    pub name: String,
665    /// Which module variable holds it — the closure-variable index in the body.
666    pub var_idx: u32,
667    /// `import * as ns from "m"`: the binding is the module's namespace object.
668    pub is_star: bool,
669}
670
671/// One exported name.
672///
673/// The four forms are the ones §16.2.1.5 distinguishes, and they resolve differently:
674/// a local export names a variable of this module, an indirect one names a name in
675/// another module, a star export forwards everything, and a star-as export forwards the
676/// whole namespace under one name.
677#[derive(Debug, Clone, PartialEq)]
678pub enum ExportEntry {
679    /// `export { a }` / `export var a` / `export default …`
680    Local {
681        /// The name the outside sees.
682        export_name: String,
683        /// The module variable behind it.
684        var_idx: u32,
685    },
686    /// `export { a as b } from "m"`
687    Indirect {
688        /// The name the outside sees.
689        export_name: String,
690        /// Index into [`ModuleMeta::requests`].
691        module: u32,
692        /// The name to look up in that module.
693        import_name: String,
694    },
695    /// `export * from "m"`
696    Star {
697        /// Index into [`ModuleMeta::requests`].
698        module: u32,
699    },
700    /// `export * as ns from "m"`
701    StarAs {
702        /// The name the outside sees.
703        export_name: String,
704        /// Index into [`ModuleMeta::requests`].
705        module: u32,
706    },
707}
708
709/// One direct `eval(...)` call site and the bindings visible at it.
710#[derive(Debug, Clone, PartialEq)]
711pub struct EvalSite {
712    /// Source position of the call, which is how the runtime finds the site: it asks
713    /// for the position of the `call` instruction it is executing.
714    pub line: u32,
715    /// Column of the call.
716    pub column: u32,
717    /// Visible bindings, innermost scope first, so the first name match wins.
718    pub bindings: Vec<EvalVisible>,
719}
720
721/// One binding an `eval` can see.
722#[derive(Debug, Clone, PartialEq)]
723pub struct EvalVisible {
724    /// The name the eval would write.
725    pub name: String,
726    /// Whether it is a parameter of the function rather than a local.
727    pub is_arg: bool,
728    /// The slot index within that table.
729    pub index: u32,
730    /// How many frames up the binding lives: `0` is the function containing the
731    /// `eval`, `1` its caller's definition and so on. A direct `eval` sees the whole
732    /// chain, and the slot for a name declared in an enclosing function is only known
733    /// at compile time.
734    pub owner: u32,
735}
736
737impl Function {
738    /// Name the script this function belongs to.
739    ///
740    /// Nested functions inherit it, because a stack trace names every frame with the
741    /// file the code came from and the parser does not know file names — the host
742    /// does, after the source has already been compiled.
743    pub fn set_filename(&mut self, name: &str) {
744        self.filename = Some(name.to_string());
745        for constant in &mut self.cpool {
746            if let Constant::Function(inner) = constant {
747                inner.set_filename(name);
748            }
749        }
750    }
751
752    /// The source position of the instruction at `pc`.
753    ///
754    /// The last entry at or before `pc` wins, so a position applies until the next one
755    /// starts. `None` when the function carries no positions at all — a script compiled
756    /// without source information.
757    pub fn position_at(&self, pc: u32) -> Option<(u32, u32)> {
758        let index = match self.positions.binary_search_by_key(&pc, |entry| entry.pc) {
759            Ok(index) => index,
760            Err(0) => return None,
761            Err(index) => index - 1,
762        };
763        self.positions
764            .get(index)
765            .map(|entry| (entry.line, entry.column))
766    }
767
768    /// Decode the instruction stream back into instructions.
769    ///
770    /// Labels are already resolved, so a `label` operand is an absolute byte
771    /// offset.
772    pub fn instructions(&self) -> Vec<(usize, Instruction)> {
773        let mut out = Vec::new();
774        let mut pos = 0usize;
775        while pos < self.code.len() {
776            let Some(op) = Opcode::from_u8(self.code[pos]) else {
777                break;
778            };
779            let info = op.info();
780            let mut operands = Vec::new();
781            let payload = &self.code[pos + 1..(pos + info.size as usize).min(self.code.len())];
782            crate::disasm::decode_operands(info.format, payload, &mut operands);
783            out.push((pos, Instruction { op, operands }));
784            pos += info.size as usize;
785        }
786        out
787    }
788
789    /// Byte offsets that are the target of a jump, which the disassembler marks.
790    pub fn jump_targets(&self) -> Vec<usize> {
791        let mut targets = Vec::new();
792        for (pc, instruction) in self.instructions() {
793            if instruction.op.info().format.is_label()
794                && let Some(target) = instruction.jump_target(pc)
795            {
796                targets.push(target as usize);
797            }
798        }
799        targets
800    }
801
802    /// Total number of variable slots, as the serialiser stores them.
803    pub fn slot_count(&self) -> u32 {
804        self.args.len() as u32 + self.vars.len() as u32
805    }
806}
807
808impl fmt::Display for FunctionKind {
809    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
810        let text = match self {
811            FunctionKind::Normal => "function",
812            FunctionKind::Generator => "generator",
813            FunctionKind::Async => "async function",
814            FunctionKind::AsyncGenerator => "async generator",
815        };
816        f.write_str(text)
817    }
818}