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