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    /// Where the body begins in source order, as `(line, column)`.
560    ///
561    /// A closure whose creation site is before this was created by a default expression,
562    /// so it sees the parameter environment and not the body's. Recorded as a position
563    /// rather than a bytecode offset because the instruction stream is rebuilt (frame
564    /// prologues are prepended) after the point where the compiler knows the boundary.
565    /// `(0, 0)` means "unknown", which is read as "the whole function is its body".
566    pub body_start: (u32, u32),
567    /// Parameters.
568    pub args: Vec<VarDef>,
569    /// How many parameters count towards `Function.prototype.length`.
570    ///
571    /// A parameter with a default or a rest parameter ends the count, because `.length`
572    /// is the arity the function can be called with before anything is substituted.
573    pub defined_args: u32,
574    /// Locals, including the implicit return-value slot named `<ret>`.
575    pub vars: Vec<VarDef>,
576    /// Captured variables of enclosing functions.
577    pub closure_vars: Vec<ClosureVar>,
578    /// Constant pool.
579    pub cpool: Vec<Constant>,
580    /// Atom table: the names this function mentions. The runtime shares one
581    /// interned table across the whole program; indexing it per function keeps
582    /// the bytecode self-contained and makes disassembly readable.
583    pub atoms: Vec<Atom>,
584    /// Resolved bytecode.
585    pub code: Vec<u8>,
586    /// Maximum value-stack depth.
587    pub stack_size: u32,
588    /// Source positions, ordered by bytecode offset.
589    pub positions: Vec<LineCol>,
590    /// Number of reference cells allocated on entry.
591    pub var_ref_count: u32,
592    /// Source text, kept for `Function.prototype.toString` and stack traces.
593    pub source: Option<String>,
594    /// Line of the function's declaration.
595    pub line: u32,
596    /// Column of the function's declaration.
597    pub column: u32,
598    /// File name, if known.
599    pub filename: Option<String>,
600    /// What each direct `eval(...)` call in this function can see.
601    ///
602    /// Slot resolution for ordinary code happens at compile time, but a direct `eval`
603    /// resolves names at *run* time, from a string the compiler never reads. Without
604    /// this table the runtime has to guess by name across the whole frame, which picks
605    /// the wrong binding when a name is declared twice in sibling scopes:
606    ///
607    /// ```text
608    /// for (let i = 0; i < 3; i++) f(eval);   // this `i`
609    /// for (let i = 0; i < 3; i++) f(eval);   // and this one
610    /// ```
611    ///
612    /// The compiler knows exactly which of them is in scope at each call, so it records
613    /// the answer here. It is data, not an instruction, so the bytecode stays identical
614    /// to the reference's.
615    pub eval_sites: Vec<EvalSite>,
616    /// The module this body is, when it is one.
617    ///
618    /// `None` for a script and for every nested function. A module's *requests*,
619    /// *imports* and *exports* are data rather than instructions — the body itself reads
620    /// its bindings through ordinary closure-variable opcodes, and this is what the host
621    /// needs in order to wire those cells up before the body runs.
622    pub module: Option<Box<ModuleMeta>>,
623}
624
625/// What a module body needs from the host, recorded at compile time.
626///
627/// The three tables mirror §16.2.1.5's `[[RequestedModules]]`, `[[ImportEntries]]` and
628/// `[[LocalExportEntries]]`/`[[IndirectExportEntries]]`/`[[StarExportEntries]]`. They are
629/// kept as plain data so linking can be done without looking at bytecode.
630#[derive(Debug, Clone, PartialEq, Default)]
631pub struct ModuleMeta {
632    /// The modules this one asks for, in source order and de-duplicated by specifier.
633    pub requests: Vec<ModuleRequest>,
634    /// Where each imported binding lands.
635    pub imports: Vec<ImportEntry>,
636    /// What this module offers.
637    pub exports: Vec<ExportEntry>,
638}
639
640/// One `from "…"` of a module.
641#[derive(Debug, Clone, PartialEq)]
642pub struct ModuleRequest {
643    /// The specifier as written.
644    pub specifier: String,
645    /// `with { type: "json" }` and friends, in source order.
646    pub attributes: Vec<(String, String)>,
647}
648
649/// One imported binding.
650#[derive(Debug, Clone, PartialEq)]
651pub struct ImportEntry {
652    /// Index into [`ModuleMeta::requests`].
653    pub module: u32,
654    /// The name imported from it; ignored when `is_star`.
655    pub name: String,
656    /// Which module variable holds it — the closure-variable index in the body.
657    pub var_idx: u32,
658    /// `import * as ns from "m"`: the binding is the module's namespace object.
659    pub is_star: bool,
660}
661
662/// One exported name.
663///
664/// The four forms are the ones §16.2.1.5 distinguishes, and they resolve differently:
665/// a local export names a variable of this module, an indirect one names a name in
666/// another module, a star export forwards everything, and a star-as export forwards the
667/// whole namespace under one name.
668#[derive(Debug, Clone, PartialEq)]
669pub enum ExportEntry {
670    /// `export { a }` / `export var a` / `export default …`
671    Local {
672        /// The name the outside sees.
673        export_name: String,
674        /// The module variable behind it.
675        var_idx: u32,
676    },
677    /// `export { a as b } from "m"`
678    Indirect {
679        /// The name the outside sees.
680        export_name: String,
681        /// Index into [`ModuleMeta::requests`].
682        module: u32,
683        /// The name to look up in that module.
684        import_name: String,
685    },
686    /// `export * from "m"`
687    Star {
688        /// Index into [`ModuleMeta::requests`].
689        module: u32,
690    },
691    /// `export * as ns from "m"`
692    StarAs {
693        /// The name the outside sees.
694        export_name: String,
695        /// Index into [`ModuleMeta::requests`].
696        module: u32,
697    },
698}
699
700/// One direct `eval(...)` call site and the bindings visible at it.
701#[derive(Debug, Clone, PartialEq)]
702pub struct EvalSite {
703    /// Source position of the call, which is how the runtime finds the site: it asks
704    /// for the position of the `call` instruction it is executing.
705    pub line: u32,
706    /// Column of the call.
707    pub column: u32,
708    /// Visible bindings, innermost scope first, so the first name match wins.
709    pub bindings: Vec<EvalVisible>,
710}
711
712/// One binding an `eval` can see.
713#[derive(Debug, Clone, PartialEq)]
714pub struct EvalVisible {
715    /// The name the eval would write.
716    pub name: String,
717    /// Whether it is a parameter of the function rather than a local.
718    pub is_arg: bool,
719    /// The slot index within that table.
720    pub index: u32,
721    /// How many frames up the binding lives: `0` is the function containing the
722    /// `eval`, `1` its caller's definition and so on. A direct `eval` sees the whole
723    /// chain, and the slot for a name declared in an enclosing function is only known
724    /// at compile time.
725    pub owner: u32,
726}
727
728impl Function {
729    /// Name the script this function belongs to.
730    ///
731    /// Nested functions inherit it, because a stack trace names every frame with the
732    /// file the code came from and the parser does not know file names — the host
733    /// does, after the source has already been compiled.
734    pub fn set_filename(&mut self, name: &str) {
735        self.filename = Some(name.to_string());
736        for constant in &mut self.cpool {
737            if let Constant::Function(inner) = constant {
738                inner.set_filename(name);
739            }
740        }
741    }
742
743    /// The source position of the instruction at `pc`.
744    ///
745    /// The last entry at or before `pc` wins, so a position applies until the next one
746    /// starts. `None` when the function carries no positions at all — a script compiled
747    /// without source information.
748    pub fn position_at(&self, pc: u32) -> Option<(u32, u32)> {
749        let index = match self.positions.binary_search_by_key(&pc, |entry| entry.pc) {
750            Ok(index) => index,
751            Err(0) => return None,
752            Err(index) => index - 1,
753        };
754        self.positions
755            .get(index)
756            .map(|entry| (entry.line, entry.column))
757    }
758
759    /// Decode the instruction stream back into instructions.
760    ///
761    /// Labels are already resolved, so a `label` operand is an absolute byte
762    /// offset.
763    pub fn instructions(&self) -> Vec<(usize, Instruction)> {
764        let mut out = Vec::new();
765        let mut pos = 0usize;
766        while pos < self.code.len() {
767            let Some(op) = Opcode::from_u8(self.code[pos]) else {
768                break;
769            };
770            let info = op.info();
771            let mut operands = Vec::new();
772            let payload = &self.code[pos + 1..(pos + info.size as usize).min(self.code.len())];
773            crate::disasm::decode_operands(info.format, payload, &mut operands);
774            out.push((pos, Instruction { op, operands }));
775            pos += info.size as usize;
776        }
777        out
778    }
779
780    /// Byte offsets that are the target of a jump, which the disassembler marks.
781    pub fn jump_targets(&self) -> Vec<usize> {
782        let mut targets = Vec::new();
783        for (pc, instruction) in self.instructions() {
784            if instruction.op.info().format.is_label()
785                && let Some(target) = instruction.jump_target(pc)
786            {
787                targets.push(target as usize);
788            }
789        }
790        targets
791    }
792
793    /// Total number of variable slots, as the serialiser stores them.
794    pub fn slot_count(&self) -> u32 {
795        self.args.len() as u32 + self.vars.len() as u32
796    }
797}
798
799impl fmt::Display for FunctionKind {
800    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
801        let text = match self {
802            FunctionKind::Normal => "function",
803            FunctionKind::Generator => "generator",
804            FunctionKind::Async => "async function",
805            FunctionKind::AsyncGenerator => "async generator",
806        };
807        f.write_str(text)
808    }
809}