Skip to main content

js_compile/
bytecode.rs

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