quickjs-compile 0.4.0

Bytecode compiler for the pure-Rust QuickJS port
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! The bytecode representation of a function.
//!
//! Compilation happens in two phases, exactly as in the reference implementation:
//!
//! * **Unresolved** ([`FunctionBuilder`]): jump targets are label ids and every
//!   variable is still described by its declaration, not its storage class.
//! * **Resolved** ([`Function`]): jump targets are byte offsets and every
//!   variable reference names its storage class (`arg`, `loc`, `var_ref` or
//!   `var`), so the bytecode can be executed and serialised.
//!
//! The split matters for testing: each phase can be compared against the
//! corresponding pass of the reference compiler.

use crate::opcode::Opcode;
use std::fmt;

/// One entry of a function's atom table.
///
/// The reference keeps two kinds of atom in one namespace, and the distinction is
/// visible in the bytecode: an *array-index* atom is not a string at all but a
/// tagged `uint32`, which is why `{ 2: x }` disassembles as `define_field 2` while
/// `{ "1.5": x }` prints `define_field "1.5"`. Collapsing the two would make the
/// disassembly wrong and lose information on the way back in, so the kind is
/// carried here.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Atom {
    /// An interned string.
    Str(String),
    /// A canonical array index, held as a number rather than a string.
    Index(u32),
}

impl Atom {
    /// The atom the reference's `JS_NewAtomStr` would make of `text`.
    ///
    /// A canonical array index no greater than `2^31 - 1` is never interned as a
    /// string: the reference returns a tagged integer instead. Anything else —
    /// `"007"`, `"1e2"`, `"-0"`, or an index past the tag range — stays a string.
    pub fn from_text(text: &str) -> Atom {
        match canonical_array_index(text) {
            Some(index) => Atom::Index(index),
            None => Atom::Str(text.to_string()),
        }
    }

    /// The text form, for callers that only care about the name.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Atom::Str(text) => Some(text),
            Atom::Index(_) => None,
        }
    }
}

impl fmt::Display for Atom {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Atom::Str(text) => write!(f, "{text}"),
            Atom::Index(index) => write!(f, "{index}"),
        }
    }
}

/// `is_num_string` from the reference: the canonical decimal spelling of an index
/// small enough to be tagged (at most `2^31 - 1`).
///
/// Canonical means no sign, no leading zeros and no other characters, so `"10"`
/// qualifies while `"007"`, `"-0"` and `"1e2"` do not.
fn canonical_array_index(text: &str) -> Option<u32> {
    // `2^31 - 1` has ten digits, which bounds how long a canonical index can be.
    if text.is_empty() || text.len() > 10 {
        return None;
    }
    let bytes = text.as_bytes();
    if !bytes.iter().all(u8::is_ascii_digit) {
        return None;
    }
    if bytes[0] == b'0' && bytes.len() != 1 {
        return None;
    }
    let value: u32 = text.parse().ok()?;
    (value <= 0x7fff_ffff).then_some(value)
}

/// How a function was declared. Determines the calling convention.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FunctionKind {
    /// A plain function.
    Normal,
    /// `function*`
    Generator,
    /// `async function`
    Async,
    /// `async function*`
    AsyncGenerator,
}

impl FunctionKind {
    /// Whether the function is a generator (plain or async).
    pub fn is_generator(self) -> bool {
        matches!(self, FunctionKind::Generator | FunctionKind::AsyncGenerator)
    }

    /// Whether the function is async (plain or generator).
    pub fn is_async(self) -> bool {
        matches!(self, FunctionKind::Async | FunctionKind::AsyncGenerator)
    }
}

/// What a declared name is used for, which decides how it is displayed and how
/// the function prologue initialises it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VarKind {
    /// An ordinary binding.
    Normal,
    /// A lexical binding holding a hoisted function declaration.
    FunctionDecl,
    /// A lexical binding holding a hoisted async/generator function declaration.
    NewFunctionDecl,
    /// A `catch` parameter.
    Catch,
    /// The name bound to a named function expression, visible inside itself.
    FunctionName,
    /// A private class field.
    PrivateField,
    /// A private class method.
    PrivateMethod,
    /// A private class getter.
    PrivateGetter,
    /// A private class setter.
    PrivateSetter,
    /// A private class accessor pair (`get` and `set` sharing one name).
    PrivateGetterSetter,
    /// A global function declaration.
    GlobalFunctionDecl,
    /// A `using` declaration's binding.
    Using,
    /// The hidden local holding a `using` declaration's cached dispose method.
    UsingMethod,
    /// The hidden local holding a `with` statement's boxed object.
    ///
    /// Marked rather than merely named so the runtime can find the active ones without
    /// guessing from a name prefix: an `eval` inside a `with` has to resolve names
    /// against these objects before it reaches the realm.
    With,
}

impl VarKind {
    /// The word the disassembler prints for this kind.
    pub fn label(self) -> &'static str {
        match self {
            VarKind::Catch => "catch",
            VarKind::FunctionDecl | VarKind::NewFunctionDecl | VarKind::GlobalFunctionDecl => {
                "function"
            }
            _ => "",
        }
    }

    /// Whether the binding is initialised when the function is entered.
    pub fn is_hoisted_declaration(self) -> bool {
        matches!(self, VarKind::FunctionDecl | VarKind::NewFunctionDecl)
    }
}

/// A declared variable: an argument or a local.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VarDef {
    /// The name, as written.
    pub name: String,
    /// Whether the binding is immutable.
    pub is_const: bool,
    /// Whether the binding is block-scoped (`let`/`const`/`class`).
    pub is_lexical: bool,
    /// What the binding is used for.
    pub kind: VarKind,
    /// Whether a closure captures this variable, which forces it into a
    /// heap-allocated reference cell.
    pub is_captured: bool,
    /// The lexical scope the binding belongs to.
    ///
    /// Scope 0 is the function scope, where `var` and hoisted function
    /// declarations live; the body and every block introduce a child scope. A
    /// binding only exists between its scope's entry and exit, which is what the
    /// runtime uses to swap `let`/`const` bindings in and out.
    pub scope_level: u32,
    /// Index of the next block-scoped variable in the enclosing scope chain, or
    /// `None` for a `var` (which is visible in the whole function).
    ///
    /// The reference stores this in `JSVarDef::scope_next` and only fills it in
    /// when `scope_level != 0`; the interpreter walks the chain to instantiate
    /// and close the `let`/`const` bindings that are live at a given point.
    pub scope_next: Option<i32>,
}

impl VarDef {
    /// A plain `var` binding.
    pub fn var(name: impl Into<String>) -> VarDef {
        VarDef {
            name: name.into(),
            is_const: false,
            is_lexical: false,
            kind: VarKind::Normal,
            is_captured: false,
            scope_level: 0,
            scope_next: None,
        }
    }

    /// Whether reading this binding can hit the temporal dead zone, i.e. it is
    /// `let`/`const`/`class` and therefore starts out uninitialised.
    pub fn needs_check(&self) -> bool {
        self.is_lexical
    }

    /// A `let` binding.
    pub fn lexical(name: impl Into<String>) -> VarDef {
        VarDef {
            is_lexical: true,
            ..VarDef::var(name)
        }
    }

    /// A `const` binding.
    pub fn constant(name: impl Into<String>) -> VarDef {
        VarDef {
            is_lexical: true,
            is_const: true,
            ..VarDef::var(name)
        }
    }

    /// The word the disassembler prints for this definition.
    pub fn label(&self) -> &'static str {
        let kind = self.kind.label();
        if !kind.is_empty() {
            return kind;
        }
        if self.is_const {
            "const"
        } else if self.is_lexical {
            "let"
        } else {
            "var"
        }
    }
}

/// Where a captured variable actually lives, and therefore how a closure
/// reaches it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClosureType {
    /// A local of the parent function (`[loc<n>]`).
    Local,
    /// An argument of the parent function (`[arg<n>]`).
    Arg,
    /// A reference cell in the parent function (`[ref<n>]`).
    Ref,
    /// A global, reached through the reference table by index.
    GlobalRef,
    /// A global declared in this script.
    GlobalDecl,
    /// A global reached by name.
    Global,
    /// A module-level declaration.
    ModuleDecl,
    /// A module import binding.
    ModuleImport,
}

impl ClosureType {
    /// The suffix the disassembler prints.
    pub fn describe(self) -> &'static str {
        match self {
            ClosureType::Local => "loc",
            ClosureType::Arg => "arg",
            ClosureType::Ref => "ref",
            ClosureType::GlobalDecl => "global_decl",
            ClosureType::Global => "global",
            ClosureType::ModuleDecl => "module_decl",
            ClosureType::ModuleImport => "module_import",
            ClosureType::GlobalRef => "global_ref",
        }
    }
}

/// One captured variable of a function.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClosureVar {
    /// The name, as written in the enclosing function.
    pub name: String,
    /// Whether the captured binding is immutable.
    pub is_const: bool,
    /// Whether the captured binding is block-scoped.
    pub is_lexical: bool,
    /// How the closure reaches it.
    pub closure_type: ClosureType,
    /// Index into the parent's locals, arguments or reference cells.
    pub var_idx: u16,
}

/// A constant in the pool.
#[derive(Debug, Clone, PartialEq)]
pub enum Constant {
    /// A number.
    Number(f64),
    /// A string.
    String(String),
    /// A BigInt literal: digits and radix.
    BigInt {
        /// Digits, without prefix or separators.
        digits: String,
        /// 2, 8, 10 or 16.
        radix: u32,
    },
    /// A nested function, referenced by `fclosure`.
    Function(Box<Function>),
    /// A template object: one call site's chunks.
    ///
    /// The *raw* text is carried as well as the cooked text because `String.raw` reads
    /// it back verbatim, and a tagged template may legally contain an invalid escape
    /// sequence whose cooked form is `undefined`.
    Template {
        /// Cooked text; `None` for a chunk with an invalid escape sequence.
        cooked: Vec<Option<String>>,
        /// Source text of each chunk, verbatim.
        raw: Vec<String>,
    },
}

impl Constant {
    /// A short description for disassembly, matching the reference's
    /// `JS_PrintValue` for the cases the compiler can produce.
    pub fn describe(&self) -> String {
        match self {
            Constant::Number(n) => format_number(*n),
            Constant::String(s) => format!("\"{}\"", escape_js_string(s)),
            // The reference prints BigInts in decimal, whatever the source radix.
            Constant::BigInt { digits, .. } => format!("{digits}n"),
            Constant::Function(f) => {
                // The reference prints the function's name atom, which is `<null>`
                // for an anonymous function expression.
                if f.name.is_empty() {
                    "[bytecode <null>]".to_string()
                } else {
                    format!("[bytecode {}]", f.name)
                }
            }
            Constant::Template { cooked, .. } => {
                let parts: Vec<String> = cooked
                    .iter()
                    .map(|q| q.clone().unwrap_or_else(|| "undefined".to_string()))
                    .collect();
                format!("template object [{}]", parts.join(", "))
            }
        }
    }
}

/// Format a number the way the reference implementation prints it.
fn format_number(value: f64) -> String {
    if value.is_nan() {
        return "NaN".to_string();
    }
    if value.is_infinite() {
        return if value > 0.0 {
            "inf".to_string()
        } else {
            "-inf".to_string()
        };
    }
    if value == value.trunc() && value.abs() < 1e21 {
        return format!("{}", value as i64);
    }
    format!("{value}")
}

/// Escape a string for the double-quoted form the disassembler prints.
fn escape_js_string(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out
}

/// An operand of an instruction during compilation, before addresses are known.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Operand {
    /// No operand.
    None,
    /// A label, resolved to a byte offset.
    Label(u32),
    /// A local slot index.
    Loc(u32),
    /// An argument slot index.
    Arg(u32),
    /// A closure variable index.
    VarRef(u32),
    /// A constant pool index.
    Const(u32),
    /// An atom (an interned name), stored as its UTF-8 text before interning.
    Atom(String),
    /// A small unsigned immediate.
    U8(u8),
    /// A small signed immediate.
    I8(i8),
    /// A medium unsigned immediate.
    U16(u16),
    /// A medium signed immediate.
    I16(i16),
    /// A signed 32-bit immediate.
    I32(i32),
    /// An unsigned 32-bit immediate.
    U32(u32),
}

/// A resolved instruction: opcode plus the operands encoded in its payload.
#[derive(Debug, Clone, PartialEq)]
pub struct Instruction {
    /// The instruction.
    pub op: Opcode,
    /// Operands in the order the encoding stores them.
    pub operands: Vec<Operand>,
}

impl Instruction {
    /// An instruction with no operands.
    pub fn new(op: Opcode) -> Instruction {
        Instruction {
            op,
            operands: Vec::new(),
        }
    }

    /// An instruction with one operand.
    pub fn with(op: Opcode, operand: Operand) -> Instruction {
        Instruction {
            op,
            operands: vec![operand],
        }
    }
}

/// Where a variable lives in the resolved function.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Storage {
    /// Argument slot.
    Arg(u32),
    /// Local slot.
    Loc(u32),
    /// Closure reference.
    VarRef(u32),
    /// Global, by atom.
    Global,
}

/// A stretch of bytecode and the source position it came from.
///
/// One entry per run of instructions that share a position, ordered by `pc`, which is
/// what [`Function::position_at`] binary searches. This is the port of the reference's
/// `pc2line` table: it is how a stack trace says `file:line:col` for a frame that is
/// deep inside a function rather than at its first statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LineCol {
    /// Byte offset in [`Function::code`] where this position takes over.
    pub pc: u32,
    /// 1-based line.
    pub line: u32,
    /// 1-based column, in UTF-16 code units like every other position here.
    pub column: u32,
}

/// A compiled function.
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
    /// The function's name; `<eval>` for a script body.
    pub name: String,
    /// The declaration form.
    pub kind: FunctionKind,
    /// Whether the body is strict.
    pub strict: bool,
    /// Whether this came from an arrow function.
    ///
    /// An arrow has no `this` and no `new.target` of its own, so the runtime has to know
    /// to look outward for both — an `eval` inside an arrow sees the enclosing function's
    /// receiver, not the arrow's.
    pub is_arrow: bool,
    /// Whether the parameter list contains a default expression, and so gets a variable
    /// environment of its own (`PARAM_SCOPE` in the compiler).
    ///
    /// The runtime needs this for two things a direct `eval` can observe: where a `var`
    /// it declares belongs (the parameter environment, while the defaults are still being
    /// evaluated), and which bindings a closure created there may see.
    pub has_parameter_expressions: bool,
    /// Where the body begins in source order, as `(line, column)`.
    ///
    /// A closure whose creation site is before this was created by a default expression,
    /// so it sees the parameter environment and not the body's. Recorded as a position
    /// rather than a bytecode offset because the instruction stream is rebuilt (frame
    /// prologues are prepended) after the point where the compiler knows the boundary.
    /// `(0, 0)` means "unknown", which is read as "the whole function is its body".
    pub body_start: (u32, u32),
    /// Parameters.
    pub args: Vec<VarDef>,
    /// How many parameters count towards `Function.prototype.length`.
    ///
    /// A parameter with a default or a rest parameter ends the count, because `.length`
    /// is the arity the function can be called with before anything is substituted.
    pub defined_args: u32,
    /// Locals, including the implicit return-value slot named `<ret>`.
    pub vars: Vec<VarDef>,
    /// Captured variables of enclosing functions.
    pub closure_vars: Vec<ClosureVar>,
    /// Constant pool.
    pub cpool: Vec<Constant>,
    /// Atom table: the names this function mentions. The runtime shares one
    /// interned table across the whole program; indexing it per function keeps
    /// the bytecode self-contained and makes disassembly readable.
    pub atoms: Vec<Atom>,
    /// Resolved bytecode.
    pub code: Vec<u8>,
    /// Maximum value-stack depth.
    pub stack_size: u32,
    /// Source positions, ordered by bytecode offset.
    pub positions: Vec<LineCol>,
    /// Number of reference cells allocated on entry.
    pub var_ref_count: u32,
    /// Source text, kept for `Function.prototype.toString` and stack traces.
    pub source: Option<String>,
    /// Line of the function's declaration.
    pub line: u32,
    /// Column of the function's declaration.
    pub column: u32,
    /// File name, if known.
    pub filename: Option<String>,
    /// What each direct `eval(...)` call in this function can see.
    ///
    /// Slot resolution for ordinary code happens at compile time, but a direct `eval`
    /// resolves names at *run* time, from a string the compiler never reads. Without
    /// this table the runtime has to guess by name across the whole frame, which picks
    /// the wrong binding when a name is declared twice in sibling scopes:
    ///
    /// ```text
    /// for (let i = 0; i < 3; i++) f(eval);   // this `i`
    /// for (let i = 0; i < 3; i++) f(eval);   // and this one
    /// ```
    ///
    /// The compiler knows exactly which of them is in scope at each call, so it records
    /// the answer here. It is data, not an instruction, so the bytecode stays identical
    /// to the reference's.
    pub eval_sites: Vec<EvalSite>,
    /// The module this body is, when it is one.
    ///
    /// `None` for a script and for every nested function. A module's *requests*,
    /// *imports* and *exports* are data rather than instructions — the body itself reads
    /// its bindings through ordinary closure-variable opcodes, and this is what the host
    /// needs in order to wire those cells up before the body runs.
    pub module: Option<Box<ModuleMeta>>,
}

/// What a module body needs from the host, recorded at compile time.
///
/// The three tables mirror §16.2.1.5's `[[RequestedModules]]`, `[[ImportEntries]]` and
/// `[[LocalExportEntries]]`/`[[IndirectExportEntries]]`/`[[StarExportEntries]]`. They are
/// kept as plain data so linking can be done without looking at bytecode.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ModuleMeta {
    /// The modules this one asks for, in source order and de-duplicated by specifier.
    pub requests: Vec<ModuleRequest>,
    /// Where each imported binding lands.
    pub imports: Vec<ImportEntry>,
    /// What this module offers.
    pub exports: Vec<ExportEntry>,
}

/// One `from "…"` of a module.
#[derive(Debug, Clone, PartialEq)]
pub struct ModuleRequest {
    /// The specifier as written.
    pub specifier: String,
    /// `with { type: "json" }` and friends, in source order.
    pub attributes: Vec<(String, String)>,
}

/// One imported binding.
#[derive(Debug, Clone, PartialEq)]
pub struct ImportEntry {
    /// Index into [`ModuleMeta::requests`].
    pub module: u32,
    /// The name imported from it; ignored when `is_star`.
    pub name: String,
    /// Which module variable holds it — the closure-variable index in the body.
    pub var_idx: u32,
    /// `import * as ns from "m"`: the binding is the module's namespace object.
    pub is_star: bool,
}

/// One exported name.
///
/// The four forms are the ones §16.2.1.5 distinguishes, and they resolve differently:
/// a local export names a variable of this module, an indirect one names a name in
/// another module, a star export forwards everything, and a star-as export forwards the
/// whole namespace under one name.
#[derive(Debug, Clone, PartialEq)]
pub enum ExportEntry {
    /// `export { a }` / `export var a` / `export default …`
    Local {
        /// The name the outside sees.
        export_name: String,
        /// The module variable behind it.
        var_idx: u32,
    },
    /// `export { a as b } from "m"`
    Indirect {
        /// The name the outside sees.
        export_name: String,
        /// Index into [`ModuleMeta::requests`].
        module: u32,
        /// The name to look up in that module.
        import_name: String,
    },
    /// `export * from "m"`
    Star {
        /// Index into [`ModuleMeta::requests`].
        module: u32,
    },
    /// `export * as ns from "m"`
    StarAs {
        /// The name the outside sees.
        export_name: String,
        /// Index into [`ModuleMeta::requests`].
        module: u32,
    },
}

/// One direct `eval(...)` call site and the bindings visible at it.
#[derive(Debug, Clone, PartialEq)]
pub struct EvalSite {
    /// Source position of the call, which is how the runtime finds the site: it asks
    /// for the position of the `call` instruction it is executing.
    pub line: u32,
    /// Column of the call.
    pub column: u32,
    /// Visible bindings, innermost scope first, so the first name match wins.
    pub bindings: Vec<EvalVisible>,
}

/// One binding an `eval` can see.
#[derive(Debug, Clone, PartialEq)]
pub struct EvalVisible {
    /// The name the eval would write.
    pub name: String,
    /// Whether it is a parameter of the function rather than a local.
    pub is_arg: bool,
    /// The slot index within that table.
    pub index: u32,
    /// How many frames up the binding lives: `0` is the function containing the
    /// `eval`, `1` its caller's definition and so on. A direct `eval` sees the whole
    /// chain, and the slot for a name declared in an enclosing function is only known
    /// at compile time.
    pub owner: u32,
}

impl Function {
    /// Name the script this function belongs to.
    ///
    /// Nested functions inherit it, because a stack trace names every frame with the
    /// file the code came from and the parser does not know file names — the host
    /// does, after the source has already been compiled.
    pub fn set_filename(&mut self, name: &str) {
        self.filename = Some(name.to_string());
        for constant in &mut self.cpool {
            if let Constant::Function(inner) = constant {
                inner.set_filename(name);
            }
        }
    }

    /// The source position of the instruction at `pc`.
    ///
    /// The last entry at or before `pc` wins, so a position applies until the next one
    /// starts. `None` when the function carries no positions at all — a script compiled
    /// without source information.
    pub fn position_at(&self, pc: u32) -> Option<(u32, u32)> {
        let index = match self.positions.binary_search_by_key(&pc, |entry| entry.pc) {
            Ok(index) => index,
            Err(0) => return None,
            Err(index) => index - 1,
        };
        self.positions
            .get(index)
            .map(|entry| (entry.line, entry.column))
    }

    /// Decode the instruction stream back into instructions.
    ///
    /// Labels are already resolved, so a `label` operand is an absolute byte
    /// offset.
    pub fn instructions(&self) -> Vec<(usize, Instruction)> {
        let mut out = Vec::new();
        let mut pos = 0usize;
        while pos < self.code.len() {
            let Some(op) = Opcode::from_u8(self.code[pos]) else {
                break;
            };
            let info = op.info();
            let mut operands = Vec::new();
            let payload = &self.code[pos + 1..(pos + info.size as usize).min(self.code.len())];
            crate::disasm::decode_operands(info.format, payload, &mut operands);
            out.push((pos, Instruction { op, operands }));
            pos += info.size as usize;
        }
        out
    }

    /// Byte offsets that are the target of a jump, which the disassembler marks.
    pub fn jump_targets(&self) -> Vec<usize> {
        let mut targets = Vec::new();
        for (pc, instruction) in self.instructions() {
            if instruction.op.info().format.is_label()
                && let Some(target) = instruction.jump_target(pc)
            {
                targets.push(target as usize);
            }
        }
        targets
    }

    /// Total number of variable slots, as the serialiser stores them.
    pub fn slot_count(&self) -> u32 {
        self.args.len() as u32 + self.vars.len() as u32
    }
}

impl fmt::Display for FunctionKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let text = match self {
            FunctionKind::Normal => "function",
            FunctionKind::Generator => "generator",
            FunctionKind::Async => "async function",
            FunctionKind::AsyncGenerator => "async generator",
        };
        f.write_str(text)
    }
}