js_compile/compiler.rs
1//! The bytecode compiler.
2//!
3//! Compilation is a single walk over the AST that emits *symbolic* instructions
4//! (jump targets are label ids, variable references are names), followed by a
5//! resolution pass that turns them into final bytecode. Splitting it this way
6//! keeps the emitter readable: nothing has to know slot indices or byte offsets
7//! while it is still discovering them.
8//!
9//! Variable resolution follows the reference implementation's model:
10//!
11//! * every function has a flat table of arguments and locals;
12//! * block scopes form a chain through [`VarDef::scope_next`], which is what makes
13//! `let`/`const` bindings visible only inside their block and lets the runtime
14//! put them back into the temporal dead zone on entry;
15//! * a name that is not in the current function is looked up in the enclosing
16//! ones; if found, the variable is marked captured and reached through a
17//! closure reference;
18//! * a name found nowhere is a global, reached through a closure entry as well.
19//!
20//! Emission order and instruction choice deliberately mirror `quickjs.c`: the
21//! differential test compares disassembly with the reference opcode by opcode, so
22//! an unnecessary `dup` or a differently chosen short form shows up immediately.
23
24use crate::bytecode::LineCol;
25use crate::bytecode::{
26 ANONYMOUS_BINDING, Atom, ClosureType, ClosureVar, Constant, EvalSite, EvalVisible, ExportEntry,
27 Function as CompiledFunction, FunctionKind, ImportEntry, ModuleMeta, ModuleRequest, VarDef,
28 VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::ast::{self, *};
36
37/// A label id, local to the function being compiled.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub struct Label(u32);
40
41/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
42///
43/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
44/// is why the brackets are part of the name; nothing a program writes can collide with it.
45const HOME_OBJECT: &str = "<home_object>";
46
47/// The local holding the function `super()` constructs from.
48///
49/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
50/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
51const ACTIVE_FUNC: &str = "this.active_func";
52
53/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
54const NEW_TARGET: &str = "new.target";
55
56/// Stand-in for a constant-pool index that is only known later in the instruction stream.
57///
58/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
59/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
60/// billion members is not a thing — and the compiler patches it before resolution runs, so a
61/// missed patch is a panic-free compiler error rather than a wrong jump.
62const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
63
64/// One step of a class's initialisation, in source order.
65///
66/// A static block is not a member the class keeps — it is a run of statements that executes
67/// at the point the class definition reaches it — so it belongs *inside* the initialiser
68/// function rather than alongside the fields as a separate pass. Merging the two is what
69/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
70/// same way the reference is.
71enum StaticInitItem<'a> {
72 /// `static x = value`, or `x = value` for the instance half.
73 Field(FieldKey<'a>, Option<&'a Expr>),
74 /// `static { … }`
75 Block {
76 body: &'a [Stmt],
77 /// Position of the `{`, which is where the reference puts the function.
78 body_start: Position,
79 },
80}
81
82/// How one field names its property.
83///
84/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
85/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
86/// is fixed when the class is created. Keeping the expression here instead made
87/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
88/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
89/// `{1: "a"}`.
90enum FieldKey<'a> {
91 /// `x`, `"x"`, `0` — the property name is static text.
92 Literal(&'a PropKey),
93 /// `#x`: the class-scope binding that holds the private symbol.
94 Private(String),
95 /// `[expr]`: the class-scope binding that holds the evaluated key.
96 Computed(String),
97}
98
99/// The `var_block` sentinel for a binding that lives at function scope.
100///
101/// It has to be a value a *real* block key can never take. Block keys are source
102/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
103/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
104/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
105/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
106/// sentinel takes the slot below it.
107const FUNCTION_SCOPE: u64 = u64::MAX - 3;
108
109/// The `var_block` sentinel for a binding of the parameter list.
110///
111/// A function whose parameter list contains a default expression gets *two* variable
112/// environments: one for the parameters and one for the body, so a `var` in the body
113/// that shares a name with a parameter is a different binding. The parameter bindings
114/// therefore need a scope key of their own: reachable while the defaults are
115/// evaluated, invisible to the body, and never merged with a body `var` of the same
116/// name.
117///
118/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
119/// the closure and the body shared one slot, when only the parameters were in scope
120/// when it was created.
121const PARAM_SCOPE: u64 = u64::MAX - 4;
122
123/// The name of the hidden local a `using` declaration caches its dispose method in.
124///
125/// It has to be a name no source can produce, because a script may declare anything: the
126/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
127fn using_method_name(name: &str) -> String {
128 format!("<using.method {name}>")
129}
130
131/// The `blocks` parent sentinel for "this block has no enclosing block".
132///
133/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
134/// also the terminator the chain walk from the script body reached the file's
135/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
136/// leaked into the body scope.
137const NO_PARENT: u64 = u64::MAX - 2;
138
139/// The block key for a script body. Distinct from both sentinels and unreachable from
140/// any source offset.
141const SCRIPT_BODY: u64 = u64::MAX - 1;
142
143/// An operand of a symbolic instruction.
144#[derive(Debug, Clone, PartialEq)]
145enum Op {
146 /// An immediate integer.
147 Int(i32),
148 /// A jump target.
149 Label(Label),
150 /// A constant pool index.
151 Const(u32),
152 /// An atom, before interning.
153 Atom(Atom),
154 /// An interned atom, as an index into [`Function::atoms`].
155 AtomId(u32),
156 /// A resolved slot.
157 Slot(Slot),
158}
159
160/// Where a resolved variable lives.
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162enum Slot {
163 Arg(u32),
164 Loc(u32),
165 VarRef(u32),
166 /// A global, by closure-var index.
167 Global(u32),
168 /// A global *declared* in this script. The reference keeps these bindings in
169 /// reference cells so that the script and any closure share one variable, so
170 /// a store goes through `put_var_ref` while a read uses `get_var`.
171 GlobalDecl(u32),
172}
173
174/// What a symbolic variable access does, which decides the final opcode.
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176enum VarAction {
177 /// Read the value.
178 Get,
179 /// Read the value, yielding `undefined` for an undeclared global.
180 GetUndef,
181 /// Write, leaving nothing on the stack.
182 Put,
183 /// Write and initialise, leaving the value on the stack.
184 PutInit,
185 /// Write, leaving the value on the stack.
186 Set,
187 /// Initialise a binding that may only be initialised once, such as a derived
188 /// constructor's `this`.
189 PutInitChecked,
190 /// Initialise, leaving the value on the stack and without the `const` check.
191 ///
192 /// A class's own scope binding is a `const` that has to be initialised in the middle
193 /// of the definition — after the constructor exists but before the static fields run
194 /// — and the value has to survive for the outer store to use.
195 SetInit,
196 /// Write a binding that lives in a reference cell.
197 PutRef,
198}
199
200#[derive(Debug, Clone)]
201enum Insn {
202 /// A fully determined instruction.
203 Fixed { op: Opcode, operands: Vec<Op> },
204 /// A variable access, resolved in the second pass.
205 ///
206 /// `block` is the lexical block the access appears in, which is what makes
207 /// shadowing work: two bindings can share a name, and the one that wins is
208 /// whichever scope encloses the access.
209 Var {
210 action: VarAction,
211 name: String,
212 block: u64,
213 /// Whether the access was written in the parameter list; see
214 /// [`FnState::in_params`].
215 in_params: bool,
216 },
217 /// Close a binding *if* it turned out to be captured.
218 ///
219 /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
220 /// only known once the body has been compiled — a closure created there is the
221 /// thing that makes it necessary. The reference emits `close_loc` exactly in that
222 /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
223 /// of emitted blind.
224 CloseCaptured { name: String, block: u64 },
225 /// `delete name`, which can only answer `false` once the binding is known.
226 ///
227 /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
228 /// looks the name up on the global object, which is what distinguishes an implicit
229 /// global (configurable, deletable) from a declared one (a binding, always `false`).
230 DeleteVar { name: String },
231 /// An instruction that dead-code elimination removed. It keeps its slot so
232 /// that label indices stay valid, and resolves to no bytecode.
233 Dead,
234}
235
236/// Where `break` and `continue` jump to.
237///
238/// Targets are stacked as the compiler enters loops and labelled statements, so a
239/// bare `break` needs no analysis: it is simply the innermost target. A labelled
240/// one searches outward by name.
241#[derive(Debug, Clone)]
242struct JumpTarget {
243 /// The labels attached to this target. `l: for(;;)` gives one name; a bare
244 /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
245 /// same statement and `break a` must reach the same place as `break b`.
246 names: Vec<String>,
247 /// Where `break` lands. `None` for a construct `break` may only leave, not
248 /// target — a `try`, whose entry exists purely to unwind.
249 break_label: Option<Label>,
250 /// Where `continue` lands. `None` for anything that is not a loop.
251 continue_label: Option<Label>,
252 /// Stack slots to discard when control leaves this construct by a jump.
253 ///
254 /// Both `switch` and `try` leave something on the value stack for the duration
255 /// of the construct — the discriminant, or the `catch` offset — and a jump out
256 /// has to take it with it. A loop leaves nothing.
257 drop_count: u32,
258 /// The finalizer to run when control leaves this construct.
259 ///
260 /// Set on a `try` even when it has no `finally`: the label is always emitted and
261 /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
262 /// does not have to know whether a finalizer exists.
263 finally_label: Option<Label>,
264 /// Whether this is a labelled non-loop statement, which an unlabelled `break`
265 /// does not reach.
266 is_regular_stmt: bool,
267 /// Whether leaving this construct has to close an iterator.
268 ///
269 /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
270 /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
271 /// is dropped rather than closed.
272 has_iterator: bool,
273 /// Whether that iterator speaks the *async* protocol.
274 ///
275 /// An async close has to `await` the inner `return`, so it is an inline instruction
276 /// sequence rather than one opcode — the reference's `emit_iterator_close`.
277 is_async_iterator: bool,
278}
279
280/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
281///
282/// Both leave `source value` on the stack, so this is purely which spelling the reference
283/// picked, and it picked it by whether it had to build a *reference* for the target:
284///
285/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
286/// consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
287/// destructures);
288/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
289/// * a `var`, and any assignment target, go through `dup; get_field`, because the
290/// reference builds a reference for them — which is what `with` needs.
291fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
292 nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
293}
294
295/// Whether binding this pattern starts by boxing the value it was handed.
296fn nests_a_pattern(pattern: &Pattern) -> bool {
297 match &pattern.kind {
298 PatternKind::Array { .. } | PatternKind::Object { .. } => true,
299 PatternKind::Assign { target, .. } => nests_a_pattern(target),
300 _ => false,
301 }
302}
303
304/// `copy_data_properties` flags for an object-literal spread.
305///
306/// The byte packs three fields: the low bits are the stack offset of the source,
307/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
308/// as well as string keys. A spread passes a literal `null` exclusion list right
309/// below the source, so that field stays zero and only the source offset and the
310/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
311const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
312
313/// The expression a `...` introduces.
314///
315/// The parser marks the spread in two places — the element/property variant and an
316/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
317/// stepped through before the argument can be compiled.
318fn spread_argument(spread: &Expr) -> &Expr {
319 match &spread.kind {
320 ExprKind::Spread(inner) => inner,
321 _ => spread,
322 }
323}
324
325/// The flag byte `define_method` takes.
326///
327/// The low two bits pick value/getter/setter; bit 2 marks the property
328/// enumerable, which every object-literal method is.
329/// What kind of class constructor a function is being compiled as.
330///
331/// A constructor is not an ordinary method: a base one materialises `this` and refuses
332/// to run without `new`, and a derived one starts with `this` in the dead zone until
333/// `super()` produces it.
334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
335enum CtorKind {
336 /// Not a class constructor.
337 None,
338 /// A constructor of a class without `extends`.
339 Base,
340 /// A constructor of a class with `extends`.
341 Derived,
342}
343
344/// The flag byte `define_method` takes for a class member.
345///
346/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
347/// a class method is *not* — that is the whole difference from an object-literal method,
348/// and the reason `Object.keys(C.prototype)` stays empty.
349fn class_method_flags(kind: MethodKind) -> i32 {
350 match kind {
351 MethodKind::Constructor | MethodKind::Method => 0,
352 MethodKind::Get => 1,
353 MethodKind::Set => 2,
354 }
355}
356
357fn define_method_flags(kind: PropertyKind) -> i32 {
358 let base = match kind {
359 PropertyKind::Value | PropertyKind::Method => 0,
360 PropertyKind::Get => 1,
361 PropertyKind::Set => 2,
362 };
363 base | 4
364}
365
366/// Convert a numeric property key to the text an atom would be made from.
367///
368/// Only the range where Rust and JavaScript agree on the spelling is accepted.
369/// Both print the shortest representation that round-trips, so plain decimal
370/// digits match; they diverge at the extremes, where JavaScript switches to an
371/// exponent (`1e-7`, `1e+21`) and Rust does not. Rather than emit an atom that
372/// differs from the reference, those keys are rejected.
373fn numeric_key_text(value: f64, span: Span) -> Result<String, SyntaxError> {
374 if !value.is_finite() {
375 return Err(SyntaxError::new(
376 "a non-finite numeric property key is not supported by the compiler yet",
377 span,
378 ));
379 }
380 if value == value.trunc() && value.abs() < 1e21 {
381 return Ok(format!("{}", value as i64));
382 }
383 if value.abs() >= 1e-6 && value.abs() < 1e21 {
384 return Ok(format!("{value}"));
385 }
386 Err(SyntaxError::new(
387 "a numeric property key outside [1e-6, 1e21) is not supported by the compiler yet",
388 span,
389 ))
390}
391
392/// Collect the operands of a same-operator logical run, in source order.
393///
394/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
395/// the caller appends `c`. A node with a different operator is one operand.
396fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
397 if let ExprKind::Logical {
398 op: inner_op,
399 left,
400 right,
401 } = &expr.kind
402 && *inner_op == op
403 {
404 collect_same_operator(op, left, out);
405 out.push(right);
406 return;
407 }
408 out.push(expr);
409}
410
411/// The jump a logical assignment or `??` takes when the value is kept.
412///
413/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
414/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
415/// the value when it is *not* null-ish, so it is the `if_false` side.
416fn logical_jump(op: AssignOp) -> Opcode {
417 match op {
418 AssignOp::Or => Opcode::IfTrue,
419 AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
420 _ => Opcode::IfFalse,
421 }
422}
423
424/// Whether a loop enumerates keys or values.
425#[derive(Debug, Clone, Copy, PartialEq, Eq)]
426enum ForLoopKind {
427 /// `for (x in o)` — the keys of an object.
428 In,
429 /// `for (x of o)` — the values of an iterable.
430 Of,
431 /// `for await (x of o)` — the values of an async iterable, or of a sync one.
432 AwaitOf,
433}
434
435/// Which part of a `try` statement a block key refers to.
436#[derive(Debug, Clone, Copy)]
437enum TryPart {
438 /// The guarded block.
439 Block = 0,
440 /// The handler body, excluding the catch parameter.
441 Catch = 1,
442 /// The finalizer block.
443 Finally = 2,
444 /// The catch parameter's own scope.
445 Param = 3,
446}
447
448/// A lexical scope, identified while hoisting and numbered at the end.
449///
450/// Scope identity is needed in two passes that must agree: declarations are
451/// hoisted in source order (so slots come out in source order, as in the
452/// reference), but a binding belongs to the block it was written in, which is only
453/// entered later. Blocks are therefore keyed by the source position of their
454/// opening brace, which is stable across both walks.
455#[derive(Debug, Clone, Copy)]
456struct Block {
457 /// Source position of the block.
458 key: u64,
459 /// The block this one is nested in; `0` for the function scope.
460 parent: u64,
461}
462
463/// One function under construction.
464struct FnState {
465 name: String,
466 kind: FunctionKind,
467 strict: bool,
468 args: Vec<VarDef>,
469 vars: Vec<VarDef>,
470 closure_vars: Vec<ClosureVar>,
471 cpool: Vec<Constant>,
472 atoms: Vec<Atom>,
473 /// Every lexical scope, in creation order.
474 blocks: Vec<Block>,
475 /// The block currently being parsed or compiled.
476 current_block: u64,
477 /// The block a *nested* function was created in, so a capture made from here can be
478 /// resolved against the enclosing function's lexical scopes rather than against a
479 /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
480 /// function's own `let S` instead of the class body's `const S`.
481 created_in_block: u64,
482 /// The block each local was declared in, parallel to `vars`. `0` means the
483 /// function scope, where `var` bindings live.
484 var_block: Vec<u64>,
485 /// Set when the expression just compiled left no value on the stack.
486 ///
487 /// Only a store can do that: `put_field` consumes the object and the value, so
488 /// an assignment whose result is unused emits nothing extra. The expression
489 /// statement then has nothing to drop.
490 no_value: bool,
491 /// Whether a label was placed since the last instruction was emitted.
492 ///
493 /// The `put`/`get` fold is only valid when the two are adjacent in the final
494 /// stream; a label in between means a jump can land on the read, so the store has
495 /// to keep consuming its value. A flag is enough and avoids having to reason about
496 /// which index a label recorded.
497 label_since_insn: bool,
498 /// Whether the value of the expression being compiled is thrown away.
499 ///
500 /// Only an expression *statement* discards its value, and only the outermost
501 /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
502 /// still has to produce a value. Consumed by [`Compiler::assign`], which is
503 /// the one construct whose bytecode depends on it.
504 discard_value: bool,
505 /// The block that holds the function body.
506 body_block: u64,
507 /// Head of each scope's binding chain, indexed by level. Filled in by
508 /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
509 block_heads: Vec<i32>,
510 /// Enclosing `break`/`continue` targets, innermost last.
511 jump_targets: Vec<JumpTarget>,
512 insns: Vec<Insn>,
513 labels: Vec<Option<usize>>,
514 /// Captured locals, which need a reference cell.
515 var_ref_count: u32,
516 line: u32,
517 column: u32,
518 /// Whether this is a script body. A script's top-level declarations create
519 /// global properties rather than locals, which is why they show up as
520 /// closure variables with `[global_decl]`.
521 is_script: bool,
522 /// Whether this is a module body.
523 ///
524 /// A module body is a script in every respect that matters here — no `arguments`,
525 /// no `this` of its own — but its top-level declarations are *module*-scoped
526 /// instead of global, which is what this flag changes.
527 is_module: bool,
528 /// Whether the function is an arrow, which never gets its own `arguments`.
529 is_arrow: bool,
530 /// The name a *named function expression* binds inside its own body.
531 /// How many parameters count towards `.length`.
532 defined_args: u32,
533 /// Parameters that are not a plain name, with the argument slot each came from.
534 param_prologue: Vec<(usize, Pattern)>,
535 /// What kind of class constructor this function is, if any.
536 ctor_kind: CtorKind,
537 /// Whether the class has instance fields, so the constructor has to run their
538 /// initialiser before it returns.
539 /// What the nested function about to be compiled should be told about its class.
540 class_ctor_pending: Option<CtorKind>,
541 /// Whether this function needs the hidden `this` local, because an arrow inside it
542 /// refers to `this`.
543 ///
544 /// An arrow has no `this` of its own, so the reference materialises the enclosing
545 /// function's receiver into a local and lets the arrow capture it as an ordinary
546 /// closure variable. Declaring the local is not enough on its own: the store that
547 /// fills it has to be prepended to the body, which is what this flag arranges.
548 needs_this_local: bool,
549 /// The same, for `arguments`.
550 needs_arguments_local: bool,
551 /// The same, for `new.target`.
552 needs_new_target_local: bool,
553 /// Whether the body already opens by filling a `this` local, which
554 /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
555 has_this_prologue: bool,
556 /// The same, for `<home_object>`: the object `super` resolves against.
557 ///
558 /// An arrow and a static block have no home object of their own — only the method or
559 /// initialiser they were written in does — so `super.x` inside one is a read of the
560 /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
561 /// by `special_object 4`, the same way `this` is.
562 needs_home_object_local: bool,
563 /// The same, for `this.active_func`: the function `super()` constructs from.
564 ///
565 /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
566 /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
567 /// as a local of the enclosing function; an arrow that escaped the constructor
568 /// (`iter.return = () => super()`) then finds it in its closure even with the
569 /// constructor nowhere on the call stack.
570 needs_active_func_local: bool,
571 /// Hidden locals of the `with` blocks currently open, innermost last.
572 with_names: Vec<String>,
573 /// Set while a with-guard is being emitted, so the guard's own accesses are not
574 /// wrapped in another guard.
575 emitting_with_guard: bool,
576 self_name: Option<String>,
577 /// Where the function body starts, in source order; see [`Function::body_start`].
578 body_start: (u32, u32),
579 /// Whether the body contains a *direct* `eval(...)` call.
580 ///
581 /// A direct eval sees every binding of the function that called it, including ones
582 /// no other code mentions. It also hands those bindings to any closure it creates,
583 /// which can outlive the function. Both need the bindings to live in cells, so this
584 /// flag makes the function treat all of them as captured.
585 has_direct_eval: bool,
586 /// Whether the parameter list contains a default expression, which is what gives
587 /// the function a second variable environment (see [`PARAM_SCOPE`]).
588 has_parameter_expressions: bool,
589 /// Whether the instructions being emitted belong to the parameter list.
590 ///
591 /// References made here must not see the body's `var`s: the body has not run yet,
592 /// and the reference's own model keeps the two scopes apart.
593 in_params: bool,
594 /// Whether an arrow created in this function's parameter list needs the parameter
595 /// scope's `arguments` binding.
596 needs_param_arguments: bool,
597 /// Whether this function was *created* inside a parameter list.
598 ///
599 /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
600 /// arrow too. The name reference is the arrow's, but the scope it must not see
601 /// belongs to the function the arrow was born in.
602 created_in_params: bool,
603 /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
604 ///
605 /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
606 /// final while the body is still being compiled: a named function expression declares
607 /// its own name binding *after* the body, and that binding is exactly what
608 /// `eval("myfunc = 1")` has to find.
609 eval_sites: Vec<EvalSite>,
610 /// Direct `eval` call sites seen so far: where, and the block that was current.
611 pending_eval_sites: Vec<(Span, u64, bool)>,
612 /// Whether this body contains `await`.
613 ///
614 /// For a *module* this decides whether its body is an async function: top-level
615 /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
616 /// to survive to the compiled function rather than being a local of the compiler.
617 has_await: bool,
618 /// The module tables, when this body is a module.
619 ///
620 /// Only the top-level state ever has one: `export` and `import` are top-level
621 /// statements, so nothing nested can add to these tables.
622 module: Option<ModuleMeta>,
623 /// Whether the self-name prologue (`special_object 2` then the store) has been
624 /// emitted for this function.
625 ///
626 /// A *nested* function's lookup declares the binding early (see
627 /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
628 /// prologue is still needed — the binding existing is not the same as it being
629 /// initialised.
630 self_name_initialized: bool,
631 /// Whether the code emitted so far leaves the program's result on the stack.
632 /// The reference tracks this for the hidden `<ret>` local of an eval script.
633 leaves_value: bool,
634 /// Statement nesting depth, used to tell top-level statements apart.
635 stmt_depth: u32,
636 /// Function declarations waiting to be instantiated at scope entry, as
637 /// (target slot, constant pool index). The reference emits these from
638 /// `instantiate_hoisted_definitions` rather than at the statement, because a
639 /// declaration is visible before it is reached.
640 hoisted: Vec<(u64, HoistTarget, u32)>,
641 /// Function declarations whose bodies are compiled only once the enclosing scope
642 /// has finished hoisting, as (owning block, declaration).
643 ///
644 /// Compiling a body at the declaration makes the result depend on source order: in
645 /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
646 /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
647 /// names first and the bodies second is what removes that dependence.
648 deferred_funcs: Vec<(u64, Box<ast::Function>)>,
649 /// The source position of the node being compiled. Every instruction emitted
650 /// takes it, which is how the position table that feeds stack traces is built.
651 cur_pos: Option<Position>,
652 /// One position per entry in `insns`, index-aligned.
653 insn_pos: Vec<Option<Position>>,
654}
655
656/// Where a hoisted function declaration is stored.
657#[derive(Debug, Clone)]
658enum HoistTarget {
659 Arg(u32),
660 Loc(u32),
661 /// A global, which the resolver looks up by name.
662 Global(String),
663}
664
665impl FnState {
666 /// Whether this function suspends: a generator or an async function.
667 ///
668 /// A suspending function's `return` is a `return_async` and its body starts with an
669 /// `initial_yield`, so almost every statement that touches control flow asks this.
670 fn is_suspending(&self) -> bool {
671 self.kind.is_generator() || self.kind.is_async()
672 }
673
674 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
675 FnState {
676 name: name.into(),
677 kind,
678 strict: false,
679 args: Vec::new(),
680 vars: Vec::new(),
681 closure_vars: Vec::new(),
682 cpool: Vec::new(),
683 atoms: Vec::new(),
684 blocks: Vec::new(),
685 current_block: 0,
686 created_in_block: NO_PARENT,
687 var_block: Vec::new(),
688 no_value: false,
689 label_since_insn: false,
690 discard_value: false,
691 body_block: 0,
692 block_heads: Vec::new(),
693 jump_targets: Vec::new(),
694 insns: Vec::new(),
695 labels: Vec::new(),
696 var_ref_count: 0,
697 line: 1,
698 column: 1,
699 is_script: false,
700 is_module: false,
701 is_arrow: false,
702 defined_args: 0,
703 param_prologue: Vec::new(),
704 ctor_kind: CtorKind::None,
705 class_ctor_pending: None,
706 needs_this_local: false,
707 needs_arguments_local: false,
708 needs_new_target_local: false,
709 has_this_prologue: false,
710 needs_home_object_local: false,
711 needs_active_func_local: false,
712 with_names: Vec::new(),
713 emitting_with_guard: false,
714 self_name: None,
715 has_direct_eval: false,
716 body_start: (0, 0),
717 has_parameter_expressions: false,
718 in_params: false,
719 needs_param_arguments: false,
720 created_in_params: false,
721 eval_sites: Vec::new(),
722 pending_eval_sites: Vec::new(),
723 has_await: false,
724 module: None,
725 self_name_initialized: false,
726 leaves_value: false,
727 stmt_depth: 0,
728 hoisted: Vec::new(),
729 deferred_funcs: Vec::new(),
730 cur_pos: None,
731 insn_pos: Vec::new(),
732 }
733 }
734
735 /// The scope a declaration lands in: a script's top-level declarations are
736 /// globals, everything else gets a slot.
737 /// Whether a binding declared *now* becomes a property of the global object.
738 ///
739 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
740 /// The `var` case is decided by the keyword rather than by the cursor position:
741 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
742 /// binding as a `var i` in the body, even though the head has its own block.
743 fn declares_globally(&self, def: &VarDef) -> bool {
744 // A module's top-level declarations are *module*-scoped: they live in the module
745 // record, never on the global object. Two modules can both declare `var x`
746 // without seeing each other, which is the whole point.
747 if self.is_module {
748 return false;
749 }
750 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
751 }
752}
753
754/// The compiler's entry point.
755pub struct Compiler {
756 module: bool,
757 /// Whether the program itself is the body of an `async` function.
758 ///
759 /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
760 /// completion value is wrapped so a returned promise is not adopted.
761 async_body: bool,
762 /// Enclosing functions, outermost first. The last entry is the current one.
763 stack: Vec<FnState>,
764 /// The private names visible at this point, innermost class body last.
765 ///
766 /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
767 /// to the class body: a method, an arrow inside it and a class nested inside that arrow
768 /// all resolve against the same entries, and the parser accepts exactly that set
769 /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
770 /// class's names the moment a method started.
771 private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
772}
773
774/// How a use site of a private name compiles.
775///
776/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
777/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
778/// of a setter-only accessor pair.
779#[derive(Clone, Copy, PartialEq, Eq)]
780enum PrivateKind {
781 /// `#x = 1`: an own property keyed by the symbol in the binding.
782 Field,
783 /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
784 Method,
785 /// `get #a() {}`: the binding holds the getter, and a read calls it.
786 Getter,
787 /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
788 /// the same `TypeError` as reading an uninitialised `const`.
789 Setter,
790}
791
792/// What the compiler knows about one `#name` where it is used.
793#[derive(Clone)]
794struct PrivateUse {
795 kind: PrivateKind,
796 /// `#a<set>` when the class defines a setter for this name.
797 ///
798 /// A second binding, not a second field of the first: the reference stores the setter
799 /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
800 setter: Option<String>,
801}
802
803/// The class-scope bindings one class body needs, in declaration order.
804#[derive(Default)]
805struct ClassPlan {
806 /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
807 /// at class entry, in member order.
808 bindings: Vec<String>,
809 /// The private names, for the use sites inside the body.
810 uses: std::collections::HashMap<String, PrivateUse>,
811 /// Computed field keys, by element index, so the emission pass does not have to redo the
812 /// per-half counter that names them.
813 computed: std::collections::HashMap<usize, String>,
814 /// Whether the instance initialiser has to add the brand to `this`.
815 instance_brand: bool,
816 /// Whether the constructor itself has to carry the brand.
817 static_brand: bool,
818}
819
820impl ClassPlan {
821 /// Walk a class body once and decide every class-scope binding it needs.
822 ///
823 /// Order is the reference's: a member's binding is created when the member is parsed, so
824 /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
825 /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
826 /// the disassembly stops matching even when every instruction is right.
827 fn build(class: &Class) -> ClassPlan {
828 let mut plan = ClassPlan::default();
829 let mut instance_keys = 0usize;
830 let mut static_keys = 0usize;
831 for (index, element) in class.elements.iter().enumerate() {
832 match element {
833 ClassElement::Method {
834 key: PropName::Private(ident),
835 kind,
836 is_static,
837 ..
838 } => {
839 let name = format!("#{}", ident.name);
840 let first = !plan.uses.contains_key(&name);
841 if first {
842 plan.bindings.push(name.clone());
843 plan.uses.insert(
844 name.clone(),
845 PrivateUse {
846 kind: match kind {
847 MethodKind::Get => PrivateKind::Getter,
848 MethodKind::Set => PrivateKind::Setter,
849 _ => PrivateKind::Method,
850 },
851 setter: None,
852 },
853 );
854 }
855 match kind {
856 MethodKind::Set => {
857 let binding = format!("{name}<set>");
858 plan.bindings.push(binding.clone());
859 if let Some(use_) = plan.uses.get_mut(&name) {
860 use_.setter = Some(binding);
861 }
862 }
863 // A getter is what makes the name readable, so a pair that started
864 // as a setter becomes readable once the getter arrives.
865 MethodKind::Get => {
866 if let Some(use_) = plan.uses.get_mut(&name) {
867 use_.kind = PrivateKind::Getter;
868 }
869 }
870 _ => {}
871 }
872 if *is_static {
873 plan.static_brand = true;
874 } else {
875 plan.instance_brand = true;
876 }
877 }
878 ClassElement::Method {
879 key: PropName::Computed(_),
880 ..
881 } => {}
882 ClassElement::Method { .. } => {}
883 ClassElement::Field {
884 key: PropName::Private(ident),
885 ..
886 } => {
887 let name = format!("#{}", ident.name);
888 if !plan.uses.contains_key(&name) {
889 plan.bindings.push(name.clone());
890 plan.uses.insert(
891 name,
892 PrivateUse {
893 kind: PrivateKind::Field,
894 setter: None,
895 },
896 );
897 }
898 }
899 ClassElement::Field {
900 key: PropName::Computed(_),
901 is_static,
902 ..
903 } => {
904 let index_in_half = if *is_static {
905 static_keys += 1;
906 static_keys - 1
907 } else {
908 instance_keys += 1;
909 instance_keys - 1
910 };
911 let binding = computed_field_binding(index_in_half, *is_static);
912 plan.bindings.push(binding.clone());
913 plan.computed.insert(index, binding);
914 }
915 ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
916 }
917 }
918 plan
919 }
920
921 /// How a private name used inside the body compiles, or `None` if no enclosing class
922 /// declares it.
923 fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
924 compiler
925 .private_scopes
926 .iter()
927 .rev()
928 .find_map(|scope| scope.get(name))
929 }
930}
931
932/// Compile a script.
933pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
934 Compiler::new(false).compile(program)
935}
936
937/// Compile a script whose top level is the body of an `async` function.
938///
939/// The body is an ordinary script in every other way — it still reports a completion value
940/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
941/// it answers a promise instead of a value. The wrapper is what keeps that promise from
942/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
943/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
944/// documents.
945pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
946 Compiler::for_suspensible_script().compile(program)
947}
948
949/// Compile a module.
950pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
951 Compiler::new(true).compile(program)
952}
953
954impl Compiler {
955 /// Create a compiler.
956 pub fn new(module: bool) -> Compiler {
957 Compiler {
958 module,
959 async_body: false,
960 stack: Vec::new(),
961 private_scopes: Vec::new(),
962 }
963 }
964
965 /// Create a compiler for a script whose top level is an `async` function body.
966 fn for_suspensible_script() -> Compiler {
967 Compiler {
968 module: false,
969 async_body: true,
970 stack: Vec::new(),
971 private_scopes: Vec::new(),
972 }
973 }
974
975 /// Compile a whole program into its top-level function.
976 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
977 let mut state = FnState::new("<eval>", FunctionKind::Normal);
978 // A module body is *not* a script: it has no completion value, so no hidden
979 // `<ret>` local and no `put_loc0` before each statement. What it shares with one
980 // is having no `arguments` of its own and no receiver — see `is_module`.
981 state.is_script = !self.module;
982 state.is_module = self.module;
983 if self.module {
984 state.module = Some(ModuleMeta::default());
985 }
986 state.strict = program.strict || self.module;
987 state.line = program.span.start.line;
988 state.column = program.span.start.column;
989 // Locals are numbered in declaration order; `<ret>` is always slot 0.
990 //
991 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
992 // slot that only appears in one of the two arrays shifts every later
993 // binding's block and silently loses the temporal-dead-zone marking for
994 // the script's own blocks. A function frame has no `<ret>`, which is why
995 // the misalignment only showed up at the top level.
996 if !self.module {
997 state.vars.push(VarDef::var("<ret>"));
998 state.var_block.push(FUNCTION_SCOPE);
999 }
1000 self.stack.push(state);
1001 // The body is its own scope, keyed by the position of the program.
1002 // The script body needs a key no statement can produce. Statement keys are
1003 // source offsets, and the program's own start offset is `0` — which is also
1004 // the offset of the first statement, so a top-level `{ let x }` or
1005 // `for (let i …)` used to share the body's block and lose its scope.
1006 let body_key = SCRIPT_BODY;
1007 self.push_block(body_key, NO_PARENT);
1008 self.state().body_block = body_key;
1009 // A module body opens with a re-entry guard. The host evaluates a module exactly
1010 // once, so the guard never fires in practice — but the reference emits it, and a
1011 // module function called a second time (through `eval` of its own source, say)
1012 // must not run its body again.
1013 let module_guard = self.module.then(|| self.new_label());
1014 if let Some(body) = module_guard {
1015 // The guard wraps the *hoisting* too: a second evaluation of the same module
1016 // body must not even re-create its function declarations.
1017 self.emit(Opcode::PushThis, &[]);
1018 self.emit_jump(Opcode::IfFalse, body, &[]);
1019 }
1020 self.hoist(&program.body, body_key)?;
1021 // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1022 // come before the guard's `return_undef`: the reference's jump target sits past
1023 // both, and a second evaluation therefore re-creates nothing.
1024 self.emit_scope_enter(body_key);
1025 if let Some(body) = module_guard {
1026 self.emit(Opcode::ReturnUndef, &[]);
1027 self.place_label(body);
1028 }
1029 // Through `stmts` rather than the loop, so a `using` region at the top level of an
1030 // eval'd body or a module gets its disposal epilogue like any other block.
1031 self.stmts(&program.body)?;
1032 if self.module {
1033 // A module has no completion value; its body simply ends.
1034 self.emit(Opcode::Undefined, &[]);
1035 self.emit(Opcode::ReturnAsync, &[]);
1036 // Top-level `await` makes the body an async function, so the host runs it as
1037 // a coroutine and waits. Without this the `await` opcode would suspend in a
1038 // body that nothing knows how to resume — which is what "a generator body ran
1039 // as an ordinary call" was reporting.
1040 if self.cur().has_await {
1041 self.state().kind = FunctionKind::Async;
1042 }
1043 } else if self.async_body {
1044 // An async body reports its completion value the same way, but through an
1045 // object: the function answers a promise, and resolving that promise *with*
1046 // the completion value would adopt a promise completion instead of reporting
1047 // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1048 // resolve to `{value: <promise>}` rather than to `7`.
1049 //
1050 // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1051 // value in an object so that promises can be safely returned").
1052 self.emit(Opcode::Object, &[]);
1053 self.emit(Opcode::Dup, &[]);
1054 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1055 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1056 self.emit(Opcode::Return, &[]);
1057 self.state().kind = FunctionKind::Async;
1058 } else {
1059 // The program's value is whatever the last expression statement stored in
1060 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1061 // case into a single `set_loc0`.
1062 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1063 self.emit(Opcode::Return, &[]);
1064 }
1065 Ok(self.finish_current())
1066 }
1067
1068 // -- emitting ----------------------------------------------------------
1069
1070 fn state(&mut self) -> &mut FnState {
1071 self.stack.last_mut().expect("a function is being compiled")
1072 }
1073
1074 fn cur(&self) -> &FnState {
1075 self.stack.last().expect("a function is being compiled")
1076 }
1077
1078 fn emit(&mut self, op: Opcode, operands: &[Op]) {
1079 self.state().label_since_insn = false;
1080 let pos = self.cur().cur_pos;
1081 self.state().insns.push(Insn::Fixed {
1082 op,
1083 operands: operands.to_vec(),
1084 });
1085 self.state().insn_pos.push(pos);
1086 }
1087
1088 /// Reset the script's hidden return value to `undefined`.
1089 ///
1090 /// Called at the start of every statement that does not itself produce the
1091 /// program's value, which is how the reference keeps `if`/loop results from
1092 /// leaking into an eval result.
1093 fn reset_value(&mut self) {
1094 if !self.cur().is_script {
1095 return;
1096 }
1097 self.emit(Opcode::Undefined, &[]);
1098 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1099 self.state().leaves_value = false;
1100 }
1101
1102 /// Whether `name` is a local or argument slot rather than a global.
1103 fn is_slot(&self, name: &str) -> bool {
1104 self.cur().vars.iter().any(|v| v.name == name)
1105 || self.cur().args.iter().any(|a| a.name == name)
1106 }
1107
1108 /// `with (object) body`
1109 ///
1110 /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1111 /// what makes the object reachable from a closure created inside the block, and it
1112 /// is also what lets an `eval` find it: the runtime collects the active `With`
1113 /// locals of every frame and resolves names against them before the realm.
1114 ///
1115 /// Inside the block every name reference is spelled as "look in the with objects
1116 /// first", innermost outwards, and falls through to the ordinary access. The test is
1117 /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1118 /// Record asks.
1119 fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1120 let name = self.next_with_name();
1121 // The object expression is evaluated *outside* the scope it introduces, so no
1122 // wrapper may be emitted for the names it mentions.
1123 let saved = std::mem::take(&mut self.state().with_names);
1124 self.expr(object)?;
1125 self.state().with_names = saved;
1126 self.emit(Opcode::ToObject, &[]);
1127 self.declare_hidden_local(&name, VarKind::With);
1128 // Pushed before the store so the store itself is not guarded by an *outer*
1129 // `with` — the object being stored is the new one, not something to look up.
1130 self.state().with_names.push(name.clone());
1131 self.emit_var(VarAction::Put, &name);
1132 let result = self.stmt(body);
1133 self.state().with_names.pop();
1134 result
1135 }
1136
1137 /// A hidden-local name for one `with` block, distinct from every enclosing one.
1138 fn next_with_name(&self) -> String {
1139 let depth = self.cur().with_names.len();
1140 if depth == 0 {
1141 "<with>".to_string()
1142 } else {
1143 format!("<with{depth}>")
1144 }
1145 }
1146
1147 /// Declare a hidden local that must stay a *local* even in a script.
1148 ///
1149 /// A script's `var` is a property of the global object, but the `with` object is not
1150 /// part of the source program's name space at all — it only exists for the compiler
1151 /// and the runtime — so it goes straight into the frame's slot list.
1152 fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1153 let state = self.state();
1154 if state.vars.iter().any(|v| v.name == name) {
1155 return;
1156 }
1157 state.var_block.push(FUNCTION_SCOPE);
1158 state.vars.push(VarDef {
1159 kind,
1160 ..VarDef::var(name)
1161 });
1162 }
1163
1164 /// Emit a name access, guarded by every active `with` object.
1165 ///
1166 /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1167 /// the read itself; the outer guards and the plain access are what the `if_false`
1168 /// jumps to, so the innermost object wins.
1169 fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1170 let names = self.cur().with_names.clone();
1171 let done = self.new_label();
1172 let mut starts = Vec::new();
1173 // Innermost object first: the last `with` opened is the one that shadows the
1174 // others, so its guard has to be the first chance to satisfy the name.
1175 for with_name in names.iter().rev() {
1176 let next = self.new_label();
1177 // `in` takes the key then the object.
1178 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1179 self.emit_var(VarAction::Get, with_name);
1180 self.emit(Opcode::In, &[]);
1181 self.emit_jump(Opcode::IfFalse, next, &[]);
1182 starts.push(next);
1183 match action {
1184 // A store keeps the value under the receiver, which is where
1185 // `put_field` expects it.
1186 VarAction::Put | VarAction::PutInit => {
1187 self.emit_var(VarAction::Get, with_name);
1188 self.emit(Opcode::Swap, &[]);
1189 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
1190 }
1191 _ => {
1192 self.emit_var(VarAction::Get, with_name);
1193 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1194 self.emit(Opcode::GetArrayEl, &[]);
1195 }
1196 }
1197 self.emit_jump(Opcode::Goto, done, &[]);
1198 self.place_label(next);
1199 }
1200 self.emit_var(action, name);
1201 self.place_label(done);
1202 }
1203
1204 fn emit_var(&mut self, action: VarAction, name: &str) {
1205 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1206 // stores and keeps the value in one instruction. The reference does this
1207 // in a post-pass; folding it at emit time keeps instruction indices
1208 // stable, which matters because labels are recorded as indices.
1209 //
1210 // Only slots have a `set_` form: a global is stored with `put_var` and
1211 // read with `get_var`, and the reference does not fold those.
1212 //
1213 // A label between the two cancels the fold. `set_x v` leaves the value on
1214 // the stack, which is only equivalent when the read immediately follows the
1215 // store; when a jump target sits in between, the store must *consume* the
1216 // value and the read must fetch it afresh. A loop head is exactly that
1217 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1218 // condition re-reads it — and folding across the label would make the
1219 // condition compare whatever the previous iteration left on the stack.
1220 if action == VarAction::Get {
1221 let is_slot = self.is_slot(name);
1222 let at_label = std::mem::take(&mut self.state().label_since_insn);
1223 //
1224 // `arguments` is excluded because the reference treats it as a special
1225 // binding: it is initialised once and read many times, and folding its
1226 // initialisation into a `set_` would leave the object on the stack where
1227 // the reference leaves nothing.
1228 if is_slot
1229 && name != "arguments"
1230 && !at_label
1231 && let Some(Insn::Var {
1232 action: previous,
1233 name: previous_name,
1234 ..
1235 }) = self.state().insns.last_mut()
1236 && *previous == VarAction::Put
1237 && previous_name == name
1238 {
1239 *previous = VarAction::Set;
1240 return;
1241 }
1242 }
1243 // Inside a `with`, every name lookup consults the with objects first. The
1244 // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
1245 let guarded = !self.cur().with_names.is_empty()
1246 && !self.cur().with_names.iter().any(|hidden| hidden == name)
1247 && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1248 && !self.state().emitting_with_guard;
1249 if guarded {
1250 self.state().emitting_with_guard = true;
1251 self.emit_with_guarded(action, name);
1252 self.state().emitting_with_guard = false;
1253 return;
1254 }
1255 let block = self.cur().current_block;
1256 self.state().label_since_insn = false;
1257 let pos = self.cur().cur_pos;
1258 let in_params = self.cur().in_params;
1259 self.state().insns.push(Insn::Var {
1260 action,
1261 name: name.to_string(),
1262 block,
1263 in_params,
1264 });
1265 self.state().insn_pos.push(pos);
1266 }
1267
1268 fn new_label(&mut self) -> Label {
1269 let state = self.state();
1270 state.labels.push(None);
1271 Label(state.labels.len() as u32 - 1)
1272 }
1273
1274 fn place_label(&mut self, label: Label) {
1275 let index = self.cur().insns.len();
1276 self.state().label_since_insn = true;
1277 self.state().labels[label.0 as usize] = Some(index);
1278 }
1279
1280 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1281 let mut operands = vec![Op::Label(label)];
1282 operands.extend_from_slice(extra);
1283 self.emit(op, &operands);
1284 }
1285
1286 // -- scopes ------------------------------------------------------------
1287
1288 /// Start a new lexical scope inside `parent`.
1289 fn push_block(&mut self, key: u64, parent: u64) {
1290 let state = self.state();
1291 if !state.blocks.iter().any(|b| b.key == key) {
1292 state.blocks.push(Block { key, parent });
1293 }
1294 state.current_block = key;
1295 }
1296
1297 /// Emit the code that runs when a lexical scope is entered.
1298 ///
1299 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1300 /// so entering its block marks it uninitialised. Hoisted function
1301 /// declarations are created here instead, which is why a call before the
1302 /// declaration still works.
1303 ///
1304 /// The order is not obvious: bindings are emitted in *reverse* declaration
1305 /// order, because the reference walks its scope chain, which is built by
1306 /// prepending.
1307 fn emit_scope_enter(&mut self, block: u64) {
1308 let hoisted = std::mem::take(&mut self.state().hoisted);
1309 let mut mine: Vec<(HoistTarget, u32)> = hoisted
1310 .into_iter()
1311 .filter(|(owner, _, _)| *owner == block)
1312 .map(|(_, target, pool_index)| (target, pool_index))
1313 .collect();
1314 mine.sort_by_key(|(target, _)| match target {
1315 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1316 HoistTarget::Global(_) => u32::MAX,
1317 });
1318 for (target, pool_index) in mine {
1319 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1320 match target {
1321 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1322 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1323 HoistTarget::Global(name) => {
1324 // A global binding lives in a reference cell, so the store
1325 // goes through `put_var_ref` while reads use `get_var`.
1326 let block = self.cur().current_block;
1327 let pos = self.cur().cur_pos;
1328 let in_params = self.cur().in_params;
1329 self.state().insns.push(Insn::Var {
1330 action: VarAction::PutRef,
1331 name,
1332 block,
1333 in_params,
1334 });
1335 self.state().insn_pos.push(pos);
1336 }
1337 }
1338 }
1339 for index in self.block_vars_reversed(block) {
1340 self.emit(
1341 Opcode::SetLocUninitialized,
1342 &[Op::Slot(Slot::Loc(index as u32))],
1343 );
1344 }
1345 }
1346
1347 /// Emit the code that runs when a lexical scope is exited.
1348 ///
1349 /// A captured binding has to be closed: detaching its reference cell freezes
1350 /// the value the binding had when the block ended, which is what a closure
1351 /// created inside the block must keep seeing.
1352 fn emit_scope_leave(&mut self, block: u64) {
1353 for index in self.block_vars_reversed(block) {
1354 if self.cur().vars[index].is_captured {
1355 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1356 }
1357 }
1358 }
1359
1360 /// Locals declared in `block`, in reverse declaration order.
1361 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1362 let state = self.cur();
1363 let mut out: Vec<usize> = (0..state.vars.len())
1364 .filter(|index| {
1365 state.var_block.get(*index).copied() == Some(block)
1366 && state.vars[*index].is_lexical
1367 // A derived constructor's `this` is lexical but is not initialised by
1368 // entering the scope: `check_ctor` proves it, so its dead-zone marker
1369 // was emitted with the constructor's own prologue.
1370 && state.vars[*index].name != "this"
1371 })
1372 .collect();
1373 out.reverse();
1374 out
1375 }
1376
1377 /// Declare a local, even at the top level of a script.
1378 ///
1379 /// A `catch` parameter is always a local: the reference puts it in the
1380 /// function's own variable list (`1: catch e`), never in the global object,
1381 /// because it only exists while the handler runs.
1382 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1383 let state = self.state();
1384 let index = state.vars.len() as u32;
1385 // A `catch` parameter belongs to a scope even though it is not lexical: the
1386 // runtime instantiates it per handler entry, but it never sits in the
1387 // temporal dead zone.
1388 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1389 state.current_block
1390 } else {
1391 0
1392 };
1393 state.var_block.push(block);
1394 state.vars.push(def);
1395 index
1396 }
1397
1398 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1399 if self.cur().is_module
1400 && self.cur().current_block == self.cur().body_block
1401 && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1402 {
1403 // Only the body's own block: a `let` inside a module-level `{}` is still an
1404 // ordinary local of that block, not a module variable.
1405 //
1406 // A `using` binding is excluded on purpose, and the reference excludes it in
1407 // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1408 // "'using' variables are currently not exported in modules"): a module-level
1409 // `using` is an ordinary *local* of the module body function, not a module
1410 // cell. Two things follow, and both are what the reference does — `export {a}`
1411 // of a `using` binding is "exported variable 'a' does not exist", and
1412 // disposal works, because the disposal epilogue addresses locals by slot.
1413 //
1414 // The hidden dispose-method variable is excluded for a stronger reason: it is
1415 // *always* a local (`add_scope_var` in the reference), and it must sit
1416 // immediately after its value so `using_dispose` can find it at `slot + 1`.
1417 return self.declare_module(name, &def);
1418 }
1419 if self.cur().declares_globally(&def) {
1420 self.declare_global(name, &def);
1421 return 0;
1422 }
1423 let state = self.state();
1424 let index = state.vars.len() as u32;
1425 let block = if def.is_lexical {
1426 state.current_block
1427 } else {
1428 0
1429 };
1430 state.var_block.push(block);
1431 state.vars.push(def);
1432 index
1433 }
1434
1435 /// Declare a `using` binding and its cached dispose method, returning both slots.
1436 ///
1437 /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1438 /// `(value, value + 1)` — the reference does the same and documents the constraint.
1439 fn declare_using(&mut self, name: &str) -> (u32, u32) {
1440 let mut def = VarDef::lexical(name);
1441 def.kind = VarKind::Using;
1442 let value = self.declare(name, def);
1443 let mut method = VarDef::lexical(using_method_name(name));
1444 method.kind = VarKind::UsingMethod;
1445 let method_slot = self.declare(&using_method_name(name), method);
1446 (value, method_slot)
1447 }
1448
1449 /// The slot a `using` binding's dispose method lives in.
1450 fn using_method_slot(&self, name: &str) -> Option<u32> {
1451 let hidden = using_method_name(name);
1452 self.cur()
1453 .vars
1454 .iter()
1455 .position(|var| var.name == hidden)
1456 .map(|index| index as u32)
1457 }
1458
1459 // -- statements --------------------------------------------------------
1460
1461 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1462 self.stmt_labelled(stmt, &[])
1463 }
1464
1465 /// Compile a statement that a chain of labels names.
1466 ///
1467 /// Only a loop consumes `labels`; every other statement ignores them (the
1468 /// parser has already rejected a label on a statement that cannot use it).
1469 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1470 // Only a *top-level* expression statement supplies the program's value.
1471 let saved = self.cur().leaves_value;
1472 self.state().leaves_value =
1473 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1474 self.state().stmt_depth += 1;
1475 let result = self.stmt_inner(stmt, labels);
1476 self.state().stmt_depth -= 1;
1477 // A nested statement never contributes the program's value, so the flag
1478 // the wrapper set above is what survives.
1479 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1480 self.state().leaves_value = produced;
1481 let _ = saved;
1482 result
1483 }
1484
1485 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1486 match &stmt.kind {
1487 StmtKind::Empty | StmtKind::Debugger => {}
1488 StmtKind::Expr(expr) => {
1489 // The statement's first token is a position the reference records: an
1490 // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1491 // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1492 // is why an error from a construct with no position of its own (`[...it]`
1493 // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1494 let saved = self.cur().cur_pos;
1495 self.state().cur_pos = Some(expr.span.start);
1496 // An expression statement's value is thrown away — except in a
1497 // script, where it becomes the program's result. `assign` reads this
1498 // and clears it, so a nested assignment still produces a value.
1499 self.state().discard_value = !self.cur().is_script;
1500 let result = self.expr(expr);
1501 self.state().discard_value = false;
1502 result?;
1503 if std::mem::take(&mut self.state().no_value) {
1504 // A store whose value was discarded left nothing to drop.
1505 } else if self.cur().is_script {
1506 // The program's value lands in the hidden `<ret>` local.
1507 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1508 } else {
1509 self.emit(Opcode::Drop, &[]);
1510 }
1511 // Restored last: the trailing `drop` is part of the statement, and in the
1512 // reference it simply inherits whatever the expression last recorded.
1513 self.state().cur_pos = saved;
1514 }
1515 StmtKind::Block(body) => {
1516 // The block's declarations were hoisted with its enclosing
1517 // statement list, so there is nothing left to declare here.
1518 let key = stmt.span.start.offset as u64;
1519 let parent = self.cur().current_block;
1520 self.push_block(key, parent);
1521 self.emit_scope_enter(key);
1522 // A block is where a `using` region lives, so its statements have to go
1523 // through `stmts`: that is what emits the disposal epilogue.
1524 self.stmts(body)?;
1525 self.emit_scope_leave(key);
1526 self.state().current_block = parent;
1527 }
1528 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1529 // A function declaration was already instantiated when its scope was
1530 // entered, so the statement itself emits nothing.
1531 StmtKind::FuncDecl(_) => {}
1532 StmtKind::If { test, cons, alt } => {
1533 self.reset_value();
1534 let else_label = self.new_label();
1535 let end_label = self.new_label();
1536 self.expr(test)?;
1537 self.emit_jump(Opcode::IfFalse, else_label, &[]);
1538 self.stmt(cons)?;
1539 if alt.is_some() {
1540 self.emit_jump(Opcode::Goto, end_label, &[]);
1541 }
1542 self.place_label(else_label);
1543 if let Some(alt) = alt {
1544 self.stmt(alt)?;
1545 self.place_label(end_label);
1546 }
1547 }
1548 StmtKind::While { test, body } => {
1549 self.reset_value();
1550 let top = self.new_label();
1551 let end = self.new_label();
1552 self.place_label(top);
1553 self.expr(test)?;
1554 // The condition's false branch and `break` share one target,
1555 // which is why a `while` loop needs only one end label.
1556 self.emit_jump(Opcode::IfFalse, end, &[]);
1557 self.loop_body(body, labels, top, end)?;
1558 self.emit_jump(Opcode::Goto, top, &[]);
1559 self.place_label(end);
1560 }
1561 StmtKind::DoWhile { body, test } => {
1562 self.reset_value();
1563 let top = self.new_label();
1564 let cont = self.new_label();
1565 let end = self.new_label();
1566 self.place_label(top);
1567 // `continue` in a `do…while` runs the test, so it lands on `cont`
1568 // rather than on the loop head.
1569 self.loop_body(body, labels, cont, end)?;
1570 self.place_label(cont);
1571 self.expr(test)?;
1572 self.emit_jump(Opcode::IfTrue, top, &[]);
1573 self.place_label(end);
1574 }
1575 StmtKind::For {
1576 init,
1577 test,
1578 update,
1579 body,
1580 } => {
1581 self.reset_value();
1582 let for_key = stmt.span.start.offset as u64;
1583 let for_parent = self.cur().current_block;
1584 self.push_block(for_key, for_parent);
1585 self.emit_scope_enter(for_key);
1586 if let Some(init) = init {
1587 match init {
1588 ForInit::VarDecl(decl) => {
1589 self.var_decl(decl)?;
1590 }
1591 ForInit::Expr(expr) => {
1592 // The head's value is discarded. Saying so lets an
1593 // assignment store with `put` instead of `dup`+`put`, which
1594 // is what the reference emits — and the difference matters:
1595 // a `dup`/`drop` pair around the store gives the peephole a
1596 // chance to fold the store into the *condition's* read.
1597 self.state().discard_value = true;
1598 let result = self.expr(expr);
1599 self.state().discard_value = false;
1600 result?;
1601 if !std::mem::take(&mut self.state().no_value) {
1602 self.emit(Opcode::Drop, &[]);
1603 }
1604 }
1605 }
1606 }
1607 // A `let`/`const` in the head gets a *fresh binding per iteration*,
1608 // so a closure made in the body captures that iteration's value
1609 // instead of sharing one. The reference expresses this with
1610 // `close_loc`, which swaps in a new reference cell holding the
1611 // current value; the three points below are the ones it uses — after
1612 // the initialiser, before the update, and after the loop.
1613 let loop_bindings = match init {
1614 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1615 let mut names: Vec<String> = Vec::new();
1616 for declarator in &decl.declarators {
1617 let mut idents = Vec::new();
1618 declarator.target.bound_names(&mut idents);
1619 names.extend(idents.into_iter().map(|ident| ident.name));
1620 }
1621 names
1622 }
1623 _ => Vec::new(),
1624 };
1625 // The reference also closes right after the initialiser, so the first
1626 // iteration's closures get their own cell rather than sharing the one
1627 // the initialiser wrote into.
1628 for name in &loop_bindings {
1629 let pos = self.cur().cur_pos;
1630 self.state().insns.push(Insn::CloseCaptured {
1631 name: name.clone(),
1632 block: for_key,
1633 });
1634 self.state().insn_pos.push(pos);
1635 }
1636 let top = self.new_label();
1637 let cont = self.new_label();
1638 let end = self.new_label();
1639 self.place_label(top);
1640 if let Some(test) = test {
1641 self.expr(test)?;
1642 self.emit_jump(Opcode::IfFalse, end, &[]);
1643 }
1644 // `continue` runs the update expression first, so it lands on
1645 // `cont`, which sits just before the update.
1646 self.loop_body(body, labels, cont, end)?;
1647 self.place_label(cont);
1648 // Each iteration ends with a fresh cell, so the closures the body just
1649 // created keep the cell they captured and the update writes to a new
1650 // one. Without this every closure in the loop shares one binding.
1651 let binding_block = for_key;
1652 for name in &loop_bindings {
1653 let pos = self.cur().cur_pos;
1654 self.state().insns.push(Insn::CloseCaptured {
1655 name: name.clone(),
1656 block: binding_block,
1657 });
1658 self.state().insn_pos.push(pos);
1659 }
1660 if let Some(update) = update {
1661 self.state().discard_value = true;
1662 let result = self.expr(update);
1663 self.state().discard_value = false;
1664 result?;
1665 if !std::mem::take(&mut self.state().no_value) {
1666 self.emit(Opcode::Drop, &[]);
1667 }
1668 }
1669 self.emit_jump(Opcode::Goto, top, &[]);
1670 self.place_label(end);
1671 self.emit_scope_leave(for_key);
1672 self.state().current_block = for_parent;
1673 }
1674 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1675 StmtKind::Throw(expr) => {
1676 self.expr(expr)?;
1677 self.emit(Opcode::Throw, &[]);
1678 }
1679 StmtKind::Break(_) | StmtKind::Continue(_) => {
1680 // Labels and loops are wired up in a later milestone; a bare
1681 // break/continue jumps to the innermost enclosing target, which
1682 // the loop helpers register.
1683 self.control_transfer(stmt)?;
1684 }
1685 StmtKind::Labeled { label, body } => {
1686 self.labeled(label, body, stmt)?;
1687 }
1688 StmtKind::Switch {
1689 discriminant,
1690 cases,
1691 } => {
1692 self.switch(discriminant, cases, stmt)?;
1693 }
1694 StmtKind::Try {
1695 block,
1696 handler,
1697 finalizer,
1698 } => {
1699 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1700 }
1701 StmtKind::ForIn { left, right, body } => {
1702 self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1703 }
1704 StmtKind::ForOf {
1705 left,
1706 right,
1707 body,
1708 is_await,
1709 } => {
1710 let kind = if *is_await {
1711 ForLoopKind::AwaitOf
1712 } else {
1713 ForLoopKind::Of
1714 };
1715 self.for_in_of(stmt, left, right, body, kind, labels)?;
1716 }
1717 StmtKind::With { object, body } => self.with_stmt(object, body)?,
1718 StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1719 // `import` emits nothing: hoisting already bound its names, and the host
1720 // fills their cells before the body runs.
1721 StmtKind::Import(_) => {}
1722 StmtKind::Export(decl) => self.export_stmt(decl)?,
1723 }
1724 Ok(())
1725 }
1726
1727 /// Compile `return`, running every enclosing finalizer on the way out.
1728 ///
1729 /// `nip_catch` is what makes this possible: it discards everything on the stack
1730 /// down to and including the `catch` offset while keeping the return value on
1731 /// top, so the frame the finalizer sees has the same shape as on the normal
1732 /// path.
1733 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1734 let mut has_value = value.is_some();
1735 if let Some(expr) = value {
1736 // `return f(x)` is a tail call *only* when nothing has to happen to the
1737 // value afterwards. A `finally` or an open iterator in scope forces the
1738 // normal path, because the cleanup has to run after the call returns —
1739 // which is exactly what a tail call refuses to do.
1740 let plain = self
1741 .cur()
1742 .jump_targets
1743 .iter()
1744 .all(|target| target.finally_label.is_none() && !target.has_iterator);
1745 if plain && self.expr_if_tail_call(expr)? {
1746 return Ok(());
1747 }
1748 self.expr(expr)?;
1749 }
1750 // `return v` in an *async generator* awaits `v` before anything else happens —
1751 // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
1752 // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
1753 // exactly that reason ("the await must be done before handling the finally in case
1754 // it raises an exception").
1755 if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
1756 self.emit(Opcode::Await, &[]);
1757 self.state().has_await = true;
1758 }
1759 has_value = self.emit_unwind_for_return(has_value);
1760 // A generator or async function does not return to its caller: it either
1761 // finishes, and the value becomes `{value, done: true}`, or it suspends.
1762 // `return_async` is the "finished" half, and it reads the value off the stack
1763 // rather than carrying it, which is what the resume machinery expects.
1764 if self.cur().is_suspending() {
1765 if !has_value {
1766 self.emit(Opcode::Undefined, &[]);
1767 }
1768 self.emit(Opcode::ReturnAsync, &[]);
1769 return Ok(());
1770 }
1771 if has_value {
1772 self.emit(Opcode::Return, &[]);
1773 } else {
1774 self.emit(Opcode::ReturnUndef, &[]);
1775 }
1776 Ok(())
1777 }
1778
1779 /// Close an iterator: the reference's `emit_iterator_close`.
1780 ///
1781 /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
1782 /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
1783 /// sequence, and three details in it are load-bearing:
1784 ///
1785 /// * the iterator object is compared against `undefined` first, because a loop that
1786 /// ran to completion clears that slot rather than closing an exhausted iterator;
1787 /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
1788 /// * `preserve_completion` keeps whatever was underneath (the return value of the
1789 /// function being left), which is why one branch ends on `nip` and the other on `drop`.
1790 fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
1791 if !is_async {
1792 if preserve_completion {
1793 self.emit(Opcode::Rot3r, &[]);
1794 self.emit(Opcode::Undefined, &[]);
1795 }
1796 self.emit(Opcode::IteratorClose, &[]);
1797 return;
1798 }
1799 if preserve_completion {
1800 // `iter next completion -> completion iter`
1801 self.emit(Opcode::Nip, &[]);
1802 self.emit(Opcode::Swap, &[]);
1803 } else {
1804 // `iter next catch_offset -> iter`
1805 self.emit(Opcode::Drop, &[]);
1806 self.emit(Opcode::Drop, &[]);
1807 }
1808 let done = self.new_label();
1809 let no_return = self.new_label();
1810 self.emit(Opcode::Dup, &[]);
1811 self.emit(Opcode::IsUndefined, &[]);
1812 self.emit_jump(Opcode::IfTrue, done, &[]);
1813 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
1814 self.emit(Opcode::Dup, &[]);
1815 self.emit(Opcode::IsUndefinedOrNull, &[]);
1816 self.emit_jump(Opcode::IfTrue, no_return, &[]);
1817 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
1818 self.emit(Opcode::Await, &[]);
1819 self.state().has_await = true;
1820 self.emit_jump(Opcode::Goto, done, &[]);
1821 self.place_label(no_return);
1822 self.emit(Opcode::Drop, &[]);
1823 self.place_label(done);
1824 self.emit(Opcode::Drop, &[]);
1825 }
1826
1827 /// Emit the finalizer/iterator cleanup for leaving the current position with a
1828 /// return, and report whether a value is now on the stack for it to carry.
1829 ///
1830 /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
1831 /// enclosing `finally` at once, and the two used to be separate — the `yield` path
1832 /// simply emitted `return_async`, so `it.return()` ended the generator without ever
1833 /// running `finally` blocks the body was sitting inside.
1834 fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
1835 let targets = self.cur().jump_targets.clone();
1836 for target in targets.iter().rev() {
1837 if target.finally_label.is_none() && !target.has_iterator {
1838 continue;
1839 }
1840 if !has_value {
1841 // The cleanup expects a value to pass through; with nothing to
1842 // return, `undefined` stands in.
1843 self.emit(Opcode::Undefined, &[]);
1844 has_value = true;
1845 }
1846 self.emit(Opcode::NipCatch, &[]);
1847 if target.has_iterator {
1848 // Rewind to the loop's own slots and hand the close a dummy catch offset:
1849 // the loop is being abandoned, so there is nothing left to catch.
1850 self.emit_iterator_close(target.is_async_iterator, true);
1851 } else if let Some(finally) = target.finally_label {
1852 self.emit_jump(Opcode::Gosub, finally, &[]);
1853 }
1854 }
1855 has_value
1856 }
1857
1858 /// Compile a statement list, stopping at the first statement that cannot
1859 /// fall through.
1860 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1861 for (index, stmt) in body.iter().enumerate() {
1862 // A `using` declaration is not just a binding: everything after it, to the end
1863 // of the list, runs inside its disposal region. Compiling the rest of the list
1864 // recursively is what gives nested regions their innermost-first order.
1865 if Self::using_declaration(stmt).is_some() {
1866 return self.using_region(stmt, &body[index + 1..]);
1867 }
1868 self.stmt(stmt)?;
1869 if Self::terminates(stmt) {
1870 break;
1871 }
1872 }
1873 Ok(())
1874 }
1875
1876 /// The declaration a `using` statement carries, if it is one.
1877 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
1878 match &stmt.kind {
1879 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
1880 _ => None,
1881 }
1882 }
1883
1884 /// Compile `decl` and then the rest of its block, disposing when the block ends.
1885 ///
1886 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
1887 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
1888 /// exception — and this engine already funnels all of those through `catch` plus
1889 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
1890 /// `return` and `break` dispose without knowing anything about `using`.
1891 ///
1892 /// ```text
1893 /// <declaration> value -> x, method -> x+1
1894 /// catch CATCH <- an exception in the rest lands here
1895 /// REST:
1896 /// <the rest of the block>
1897 /// drop <- the catch offset, on the fall-through path
1898 /// undefined; gosub DISPOSE; drop
1899 /// goto END
1900 /// CATCH:
1901 /// using_dispose x <- merges the failure into the pending exception
1902 /// throw
1903 /// DISPOSE:
1904 /// using_dispose_init
1905 /// using_dispose x
1906 /// using_dispose_end <- rethrows if a dispose failed
1907 /// ret
1908 /// END:
1909 /// ```
1910 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
1911 let Some(decl) = Self::using_declaration(stmt) else {
1912 unreachable!("using_region is only called for a using declaration");
1913 };
1914 // `using` binds exactly one name and has no pattern form, which the parser
1915 // enforces; the region still has to know *which* slot to dispose.
1916 let name = decl
1917 .declarators
1918 .first()
1919 .and_then(|declarator| match &declarator.target.kind {
1920 PatternKind::Ident(ident) => Some(ident.name.clone()),
1921 _ => None,
1922 });
1923 self.stmt(stmt)?;
1924 let Some(name) = name else {
1925 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
1926 // must not make the compiler panic.
1927 return self.stmts(rest);
1928 };
1929 let Some(value_slot) = self.using_value_slot(&name) else {
1930 // Declared globally, which the parser rules out for a script; a module's
1931 // top level is a scope, and there the disposal stays a known gap.
1932 return self.stmts(rest);
1933 };
1934 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
1935 // exit path already disposed.
1936 let live = !rest.last().is_some_and(Self::terminates);
1937 self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
1938 }
1939
1940 /// The slot a `using` binding's value lives in.
1941 fn using_value_slot(&self, name: &str) -> Option<u32> {
1942 self.cur()
1943 .vars
1944 .iter()
1945 .position(|var| var.name == name && var.kind == VarKind::Using)
1946 .map(|index| index as u32)
1947 }
1948
1949 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
1950 ///
1951 /// Shared between a `using` statement — which owns the rest of its block — and a
1952 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
1953 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
1954 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
1955 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
1956 /// target with a `finally_label` is what makes `return` and `break` dispose without
1957 /// knowing anything about `using`.
1958 ///
1959 /// ```text
1960 /// catch CATCH <- an exception inside lands here
1961 /// <inside>
1962 /// drop <- the catch offset, on the fall-through path
1963 /// undefined; gosub DISPOSE; drop
1964 /// goto END
1965 /// CATCH:
1966 /// using_dispose slot <- merges the failure into the pending exception
1967 /// throw
1968 /// DISPOSE:
1969 /// using_dispose_init
1970 /// using_dispose slot
1971 /// using_dispose_end <- rethrows if a dispose failed
1972 /// ret
1973 /// END:
1974 /// ```
1975 fn using_region_around(
1976 &mut self,
1977 value_slot: u32,
1978 live: bool,
1979 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
1980 ) -> Result<(), SyntaxError> {
1981 let catch_label = self.new_label();
1982 let end_label = self.new_label();
1983 let dispose_label = self.new_label();
1984
1985 self.emit_jump(Opcode::Catch, catch_label, &[]);
1986 self.push_jump_target(JumpTarget {
1987 names: Vec::new(),
1988 break_label: None,
1989 continue_label: None,
1990 // The catch offset is the one thing on the stack that leaving has to remove.
1991 drop_count: 1,
1992 finally_label: Some(dispose_label),
1993 is_regular_stmt: false,
1994 has_iterator: false,
1995 is_async_iterator: false,
1996 });
1997 inside(self)?;
1998 self.pop_jump_target();
1999
2000 if live {
2001 self.emit(Opcode::Drop, &[]);
2002 self.emit(Opcode::Undefined, &[]);
2003 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2004 self.emit(Opcode::Drop, &[]);
2005 self.emit_jump(Opcode::Goto, end_label, &[]);
2006 }
2007
2008 // An exception unwinds to here with the thrown value on the stack, which is exactly
2009 // the shape `using_dispose` expects as its error state.
2010 self.place_label(catch_label);
2011 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2012 self.emit(Opcode::Throw, &[]);
2013
2014 self.place_label(dispose_label);
2015 // Inside the subroutine the return value and the `gosub` return address are both
2016 // live, and neither an outer finalizer nor another region may run before this one
2017 // has finished.
2018 self.push_jump_target(JumpTarget {
2019 names: Vec::new(),
2020 break_label: None,
2021 continue_label: None,
2022 drop_count: 2,
2023 finally_label: None,
2024 is_regular_stmt: false,
2025 has_iterator: false,
2026 is_async_iterator: false,
2027 });
2028 self.emit(Opcode::UsingDisposeInit, &[]);
2029 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2030 self.emit(Opcode::UsingDisposeEnd, &[]);
2031 self.pop_jump_target();
2032 self.emit(Opcode::Ret, &[]);
2033 self.place_label(end_label);
2034 Ok(())
2035 }
2036
2037 /// Declare every name a statement list introduces, before compiling any of
2038 /// it, so a reference that appears textually before a declaration still
2039 /// resolves.
2040 ///
2041 /// Declarations are walked in source order because that is the order the
2042 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2043 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2044 /// declarations hoist out to the function scope; lexical names belong to the
2045 /// block they were written in, which `block` records.
2046 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2047 let saved = self.cur().current_block;
2048 self.state().current_block = block;
2049 let result = self.hoist_list(body);
2050 // Only now is every binding of this scope known, so the deferred function
2051 // bodies can be compiled against the finished list. Compiled at its own
2052 // declaration instead, a body that names a `var` written further down would
2053 // have resolved that name as a global.
2054 if result.is_ok() {
2055 let deferred = std::mem::take(&mut self.state().deferred_funcs);
2056 let mut outcome = Ok(());
2057 for (owner, func) in deferred {
2058 let previous = self.cur().current_block;
2059 self.state().current_block = owner;
2060 outcome = self.func_decl(&func);
2061 self.state().current_block = previous;
2062 if outcome.is_err() {
2063 break;
2064 }
2065 }
2066 self.state().current_block = saved;
2067 return outcome;
2068 }
2069 // `current_block` is restored by the caller for a block statement, since
2070 // it needs it set while compiling; only clean up on the hoist path.
2071 self.state().current_block = saved;
2072 result
2073 }
2074
2075 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2076 for stmt in body {
2077 self.hoist_stmt(stmt)?;
2078 }
2079 Ok(())
2080 }
2081
2082 /// Whether a statement always transfers control away, making everything after
2083 /// it in the same list unreachable.
2084 ///
2085 /// The reference drops such statements in `skip_dead_code`, so `return 1;
2086 /// let x = 2;` compiles to the same bytecode as `return 1;`.
2087 fn terminates(stmt: &Stmt) -> bool {
2088 matches!(
2089 stmt.kind,
2090 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2091 )
2092 }
2093
2094 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2095 match &stmt.kind {
2096 StmtKind::VarDecl(decl) => {
2097 for declarator in &decl.declarators {
2098 let mut names = Vec::new();
2099 declarator.target.bound_names(&mut names);
2100 for name in names {
2101 let text = name.name.clone();
2102 if decl.kind == VarDeclKind::Var {
2103 let def = VarDef::var(text.clone());
2104 self.declare_var(&text, def);
2105 } else if decl.kind.is_using() {
2106 // Two adjacent slots: the resource, then the dispose method
2107 // snapshotted at declaration. `using_dispose` reads them as a
2108 // pair `(slot, slot + 1)`, so nothing may be declared between
2109 // them — which is why both are declared here, in one step,
2110 // rather than the method being added at emission time.
2111 self.declare_using(&text);
2112 } else {
2113 let def = if decl.kind == VarDeclKind::Const {
2114 VarDef::constant(text.clone())
2115 } else {
2116 VarDef::lexical(text.clone())
2117 };
2118 self.declare(&text, def);
2119 }
2120 }
2121 }
2122 }
2123 StmtKind::FuncDecl(func) => {
2124 if let Some(name) = &func.name {
2125 // A function declaration is a `var` binding that happens to
2126 // hold a function, not a lexical one.
2127 let def = VarDef::var(name.name.clone());
2128 self.declare_var(&name.name.clone(), def);
2129 }
2130 // The function object is created when the scope is entered, so it
2131 // exists before the declaration is reached. Its body is compiled
2132 // *after* this scope's hoisting finishes, so a name it uses resolves
2133 // even when the `var` that declares it comes later in the source.
2134 let owner = self.cur().current_block;
2135 self.state().deferred_funcs.push((owner, func.clone()));
2136 }
2137 StmtKind::ClassDecl(class) => {
2138 if let Some(name) = &class.name {
2139 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2140 }
2141 }
2142 // A module's imports are bound before any of its code runs, and its exports
2143 // declare the very bindings they export — so both hoist the declarations
2144 // their `StmtKind` arm will later emit code for.
2145 StmtKind::Import(decl) => self.hoist_import(decl)?,
2146 StmtKind::Export(decl) => self.hoist_export(decl)?,
2147 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2148 StmtKind::If { cons, alt, .. } => {
2149 self.hoist_stmt(cons)?;
2150 if let Some(alt) = alt {
2151 self.hoist_stmt(alt)?;
2152 }
2153 }
2154 StmtKind::While { body, .. }
2155 | StmtKind::DoWhile { body, .. }
2156 | StmtKind::Labeled { body, .. }
2157 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2158 StmtKind::For { init, body, .. } => {
2159 // A `for` head gets its own scope even when it declares nothing,
2160 // because `let` in the head is scoped to the loop.
2161 let key = stmt.span.start.offset as u64;
2162 let parent = self.cur().current_block;
2163 self.push_block(key, parent);
2164 if let Some(init) = init
2165 && let ForInit::VarDecl(decl) = init
2166 {
2167 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2168 }
2169 self.hoist_stmt(body)?;
2170 self.state().current_block = parent;
2171 }
2172 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2173 let key = stmt.span.start.offset as u64;
2174 let parent = self.cur().current_block;
2175 self.push_block(key, parent);
2176 if let ForHead::VarDecl(decl) = left {
2177 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2178 }
2179 self.hoist_stmt(body)?;
2180 self.state().current_block = parent;
2181 }
2182 StmtKind::Try {
2183 block,
2184 handler,
2185 finalizer,
2186 } => {
2187 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2188 let try_parent = self.cur().current_block;
2189 if let Some(handler) = handler {
2190 // The catch parameter belongs to the function scope, not to a
2191 // block: it is a `catch` binding rather than a `let`, so it is
2192 // never in the temporal dead zone and `emit_scope_enter` must
2193 // not mark it uninitialised. It still has to be declared before
2194 // the handler body is hoisted, so it takes the slot the
2195 // reference gives it (bindings are numbered in source order).
2196 if let Some(pattern) = &handler.param {
2197 // The parameter gets its own scope, so entering the handler
2198 // does not have to re-declare it. It is not lexical, so it
2199 // is never marked uninitialised.
2200 let key = Self::try_block_key(stmt, TryPart::Param);
2201 let parent = self.cur().current_block;
2202 self.push_block(key, parent);
2203 // A destructuring parameter binds several names, one slot each,
2204 // in the order they are written. The reference declares those as
2205 // `let`s rather than as one `catch` binding — its dump prints
2206 // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2207 // so the kind follows the shape of the parameter.
2208 //
2209 // Neither form is in the dead zone: the stores run as the handler
2210 // is entered, so both use the unchecked `put_loc`.
2211 let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2212 let mut names = Vec::new();
2213 pattern.bound_names(&mut names);
2214 for name in names {
2215 let def = VarDef {
2216 name: name.name.clone(),
2217 is_const: false,
2218 is_lexical: destructures,
2219 kind: if destructures {
2220 crate::bytecode::VarKind::LexicalCatch
2221 } else {
2222 crate::bytecode::VarKind::Catch
2223 },
2224 is_captured: false,
2225 scope_level: 0,
2226 scope_next: None,
2227 };
2228 self.declare_local(&name.name.clone(), def);
2229 }
2230 // The handler body nests inside the parameter's scope, so the
2231 // body's bindings chain on to the parameter (the reference
2232 // prints `let y [next:1]`, pointing at `e`).
2233 self.state().current_block = key;
2234 }
2235 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2236 // Back to the block the `try` itself lives in, so the finalizer
2237 // is a sibling of the handler rather than nested in it.
2238 self.state().current_block = try_parent;
2239 }
2240 if let Some(finalizer) = finalizer {
2241 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2242 }
2243 }
2244 StmtKind::Switch { cases, .. } => {
2245 let key = stmt.span.start.offset as u64;
2246 let parent = self.cur().current_block;
2247 self.push_block(key, parent);
2248 for case in cases {
2249 self.hoist_list(&case.body)?;
2250 }
2251 self.state().current_block = parent;
2252 }
2253 _ => {}
2254 }
2255 Ok(())
2256 }
2257
2258 /// Hoist a nested statement list, which is its own lexical scope.
2259 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2260 let parent = self.cur().current_block;
2261 self.push_block(key, parent);
2262 self.hoist_list(body)?;
2263 self.state().current_block = parent;
2264 Ok(())
2265 }
2266
2267 /// A block key for one part of a `try` statement.
2268 ///
2269 /// The three parts are three separate scopes, so they cannot share the key a
2270 /// statement's own offset would give them: the try block, the handler body and
2271 /// the finalizer would then look like one scope, and their `let` bindings would
2272 /// be marked uninitialised only on entering the first of them.
2273 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2274 (stmt.span.start.offset as u64) * 4 + part as u64
2275 }
2276
2277 /// Declare a `var`: it lives in the function's own scope, not the block's.
2278 fn declare_var(&mut self, name: &str, def: VarDef) {
2279 if self.cur().is_module {
2280 self.declare_module(name, &def);
2281 return;
2282 }
2283 if self.cur().declares_globally(&def) {
2284 self.declare_global(name, &def);
2285 return;
2286 }
2287 let state = self.state();
2288 // A binding of the *parameter* scope does not count: the body's `var` of the
2289 // same name is a different binding and needs a slot of its own.
2290 if state.vars.iter().enumerate().any(|(index, v)| {
2291 v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2292 }) {
2293 return;
2294 }
2295 // A `var` belongs to the function scope, never to the enclosing block.
2296 state.var_block.push(FUNCTION_SCOPE);
2297 state.vars.push(def);
2298 }
2299
2300 /// Declare `name` as a binding of the parameter scope, returning its slot.
2301 fn declare_param_var(&mut self, name: &str) -> u32 {
2302 declare_param_var_at(self.state(), name)
2303 }
2304
2305 /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2306 ///
2307 /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2308 /// so each points at the one declared before it and the oldest ends the chain with
2309 /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2310 /// runtime walks when it instantiates them.
2311 fn declare_param_binding(&mut self, name: &str) -> u32 {
2312 let state = self.state();
2313 let previous = state
2314 .vars
2315 .iter()
2316 .enumerate()
2317 .rev()
2318 .find(|(index, var)| {
2319 state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2320 })
2321 .map(|(index, _)| index as i32);
2322 let index = state.vars.len() as u32;
2323 state.var_block.push(PARAM_SCOPE);
2324 let mut def = VarDef::lexical(name);
2325 // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2326 // the function's, and its bindings are initialised one by one rather than all at
2327 // once — which is exactly what the dead zone needs.
2328 def.scope_level = 1;
2329 def.scope_next = Some(previous.unwrap_or(-2));
2330 state.vars.push(def);
2331 index
2332 }
2333
2334 /// The slot of a parameter-list binding, if the list has one by that name.
2335 fn param_binding_slot(&self, name: &str) -> Option<u32> {
2336 let state = self.cur();
2337 state
2338 .vars
2339 .iter()
2340 .enumerate()
2341 .position(|(index, var)| {
2342 var.name == name
2343 && var.is_lexical
2344 && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2345 })
2346 .map(|index| index as u32)
2347 }
2348
2349 /// Every parameter-list binding, in declaration order.
2350 fn param_binding_names(&self) -> Vec<String> {
2351 let state = self.cur();
2352 state
2353 .vars
2354 .iter()
2355 .enumerate()
2356 .filter(|(index, var)| {
2357 var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2358 })
2359 .map(|(_, var)| var.name.clone())
2360 .collect()
2361 }
2362
2363 /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2364 fn body_var_slot(&self, name: &str) -> Option<u32> {
2365 let state = self.cur();
2366 state
2367 .vars
2368 .iter()
2369 .enumerate()
2370 .find(|(index, var)| {
2371 var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2372 })
2373 .map(|(index, _)| index as u32)
2374 }
2375
2376 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2377 /// one.
2378 ///
2379 /// With parameter expressions the reference creates two: an unmapped one in the
2380 /// argument scope, for the defaults and anything they close over, and the body's own.
2381 /// They are separate bindings, which is what makes
2382 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2383 /// report 1 from `p` and 2 from the body.
2384 fn provide_param_arguments(&mut self) {
2385 if !self.cur().has_parameter_expressions {
2386 return;
2387 }
2388 let mentioned = self.cur().needs_param_arguments
2389 || self
2390 .cur()
2391 .insns
2392 .iter()
2393 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2394 if !mentioned {
2395 return;
2396 }
2397 let slot = self.declare_param_var("arguments");
2398 let magic = if self.cur().strict { 0 } else { 1 };
2399 self.prepend_initialiser_to(
2400 slot,
2401 Insn::Fixed {
2402 op: Opcode::SpecialObject,
2403 operands: vec![Op::Int(magic)],
2404 },
2405 );
2406 }
2407
2408 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2409 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2410 let current = self.stack.len() - 1;
2411 let init = [
2412 producer,
2413 Insn::Fixed {
2414 op: Opcode::PutLoc,
2415 operands: vec![Op::Slot(Slot::Loc(slot))],
2416 },
2417 ];
2418 let inserted = init.len();
2419 for (index, instruction) in init.into_iter().enumerate() {
2420 self.stack[current].insns.insert(index, instruction);
2421 }
2422 for placed in self.stack[current].labels.iter_mut().flatten() {
2423 *placed += inserted;
2424 }
2425 self.state().label_since_insn = false;
2426 }
2427
2428 /// Give the function an `arguments` binding if its body mentions one.
2429 ///
2430 /// The check runs on the *instruction* stream rather than the AST: by this point
2431 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2432 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2433 /// would renumber every later local slot and stop the bytecode matching the
2434 /// reference, which only adds the binding when the body uses it.
2435 ///
2436 /// `arguments` is a local, initialised at the top of the body by
2437 /// `special_object`; that is the reference's shape, so the disassembly agrees.
2438 fn provide_arguments(&mut self) {
2439 let current = self.stack.len() - 1;
2440 if self.stack[current].is_script || self.stack[current].is_module {
2441 // A module has no `arguments` binding; referring to it is a ReferenceError,
2442 // which is exactly what an unbound name produces.
2443 return;
2444 }
2445 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2446 // function, which is why `() => arguments` sees the caller's arguments.
2447 if self.stack[current].is_arrow {
2448 if self.mentions("arguments") {
2449 self.ensure_enclosing_arguments();
2450 }
2451 return;
2452 }
2453 // Only a *body* mention needs the body's binding: the parameter list has one of
2454 // its own (see [`Compiler::provide_param_arguments`]).
2455 let mentioned = self.cur().insns.iter().any(|insn| {
2456 matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params)
2457 });
2458 if !mentioned && !self.cur().needs_arguments_local {
2459 return;
2460 }
2461 // The request may have come only from a parameter-list arrow, in which case the
2462 // parameter scope's binding already answers for it and the body needs none.
2463 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2464 return;
2465 }
2466 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`. The mapping itself is
2467 // not implemented, so the two behave alike for now.
2468 //
2469 // With parameter expressions the list and the body are separate environments, so
2470 // an assignment to a parameter cannot be reflected into `arguments` at all — the
2471 // arguments object is unmapped whatever the mode, which is why the reference emits
2472 // `special_object 0` here even in sloppy code.
2473 let magic = if self.stack[current].strict || self.stack[current].has_parameter_expressions {
2474 0
2475 } else {
2476 1
2477 };
2478 self.prepend_binding("arguments", magic);
2479 }
2480
2481 /// Whether a *body* instruction refers to `arguments`.
2482 fn body_mentions_arguments(&self) -> bool {
2483 self.cur()
2484 .insns
2485 .iter()
2486 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2487 }
2488
2489 /// Whether the function body's instruction stream refers to `name`.
2490 fn mentions(&self, name: &str) -> bool {
2491 let current = self.stack.len() - 1;
2492 // A binding of the parameter scope does not answer for the body: the body's own
2493 // `arguments` (or self-name) still has to be provided for it.
2494 if self.stack[current]
2495 .vars
2496 .iter()
2497 .enumerate()
2498 .any(|(index, v)| {
2499 v.name == name
2500 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2501 })
2502 {
2503 return false;
2504 }
2505 self.stack[current]
2506 .insns
2507 .iter()
2508 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2509 }
2510
2511 /// Bind the name a named function expression uses to refer to itself.
2512 ///
2513 /// The value is `special_object 2`, the function currently running, so the binding
2514 /// is the closure itself and not a copy. It is a local of this function, which is
2515 /// what keeps `g` out of the enclosing scope.
2516 /// Give the function a local `this`, for an arrow inside it to capture.
2517 fn provide_this_local(&mut self) {
2518 let current = self.stack.len() - 1;
2519 if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2520 return;
2521 }
2522 if !self.stack[current]
2523 .vars
2524 .iter()
2525 .any(|var| var.name == "this")
2526 {
2527 self.declare_hidden_local("this", VarKind::Normal);
2528 }
2529 self.prepend_initialiser(
2530 "this",
2531 Insn::Fixed {
2532 op: Opcode::PushThis,
2533 operands: vec![],
2534 },
2535 );
2536 }
2537
2538 /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2539 /// to read through `super`.
2540 fn provide_home_object_local(&mut self) {
2541 let current = self.stack.len() - 1;
2542 if !self.stack[current].needs_home_object_local {
2543 return;
2544 }
2545 if !self.stack[current]
2546 .vars
2547 .iter()
2548 .any(|var| var.name == HOME_OBJECT)
2549 {
2550 self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2551 }
2552 self.prepend_initialiser(
2553 HOME_OBJECT,
2554 Insn::Fixed {
2555 op: Opcode::SpecialObject,
2556 operands: vec![Op::Int(4)],
2557 },
2558 );
2559 }
2560
2561 fn provide_self_name(&mut self) {
2562 let current = self.stack.len() - 1;
2563 let Some(name) = self.stack[current].self_name.clone() else {
2564 return;
2565 };
2566 if self.stack[current].self_name_initialized {
2567 return;
2568 }
2569 // Either the body refers to the name, or a nested function already forced the
2570 // binding into existence while being resolved. A direct `eval` can name it
2571 // without mentioning it, so its presence is a third reason: in strict mode
2572 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2573 // that only happens if the binding exists.
2574 let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2575 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2576 return;
2577 }
2578 self.stack[current].self_name_initialized = true;
2579 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2580 }
2581
2582 /// Insert `special_object magic` plus the store to `name` at the top of the body.
2583 ///
2584 /// Prepending shifts every label that has been placed, so they are all moved by
2585 /// the number of instructions inserted.
2586 fn prepend_binding(&mut self, name: &str, magic: i32) {
2587 self.prepend_binding_with(name, magic, VarKind::Normal);
2588 }
2589
2590 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2591 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2592 let current = self.stack.len() - 1;
2593 // A function-expression's own name is immutable in strict mode, which is what
2594 // makes `f = 1` inside a strict body throw instead of being dropped.
2595 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2596 self.declare_var(
2597 name,
2598 VarDef {
2599 kind,
2600 is_const,
2601 ..VarDef::var(name)
2602 },
2603 );
2604 let init = [
2605 Insn::Fixed {
2606 op: Opcode::SpecialObject,
2607 operands: vec![Op::Int(magic)],
2608 },
2609 Insn::Var {
2610 // An initialisation, not an assignment: sloppy mode drops stores to a
2611 // function-expression's own name, and the prologue is what puts the
2612 // value there in the first place.
2613 action: if kind == VarKind::FunctionName {
2614 VarAction::PutInit
2615 } else {
2616 VarAction::Put
2617 },
2618 name: name.to_string(),
2619 block: 0,
2620 in_params: false,
2621 },
2622 ];
2623 let inserted = init.len();
2624 for (index, instruction) in init.into_iter().enumerate() {
2625 self.stack[current].insns.insert(index, instruction);
2626 }
2627 for placed in self.stack[current].labels.iter_mut().flatten() {
2628 *placed += inserted;
2629 }
2630 // A store sits at the insertion point now, so the `put`/`get` fold must not
2631 // reach across it.
2632 self.stack[current].label_since_insn = true;
2633 }
2634
2635 /// Record a top-level script declaration as a global.
2636 ///
2637 /// A script's top-level `var`/`let`/`function` create properties of the
2638 /// global object, not slots in the script's frame, so they show up as closure
2639 /// variables instead.
2640 fn declare_global(&mut self, name: &str, def: &VarDef) {
2641 let state = self.state();
2642 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2643 // The name was already referenced, from a function compiled before this
2644 // declaration was reached — `function a(){ b() } function b(){}` resolves
2645 // `b` while `b` is still unknown, and that guess has to be corrected here.
2646 // Leaving it as a plain global meant the declaration was never registered,
2647 // so the binding did not exist at run time and `a()` threw
2648 // `b is not defined`.
2649 if matches!(existing.closure_type, ClosureType::Global) {
2650 existing.closure_type = ClosureType::GlobalDecl;
2651 existing.is_const = def.is_const;
2652 existing.is_lexical = def.is_lexical;
2653 }
2654 return;
2655 }
2656 state.closure_vars.push(ClosureVar {
2657 name: name.to_string(),
2658 is_const: def.is_const,
2659 is_lexical: def.is_lexical,
2660 closure_type: ClosureType::GlobalDecl,
2661 var_idx: 0,
2662 });
2663 }
2664
2665 /// Record a module-level declaration as a module variable.
2666 ///
2667 /// The binding is a closure variable of the module body, so reads and writes are
2668 /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
2669 /// *who fills the cell*: the module record does, before the body runs, and an import
2670 /// points its cell at the exporting module's, which is what makes bindings live and
2671 /// cycles work.
2672 fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
2673 let state = self.state();
2674 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2675 // The name may have been referenced before this declaration was hoisted,
2676 // which resolved it as a plain global. Correct that here, the way
2677 // `declare_global` does.
2678 if matches!(existing.closure_type, ClosureType::Global) {
2679 existing.closure_type = ClosureType::ModuleDecl;
2680 existing.is_const = def.is_const;
2681 existing.is_lexical = def.is_lexical;
2682 }
2683 return 0;
2684 }
2685 state.closure_vars.push(ClosureVar {
2686 name: name.to_string(),
2687 is_const: def.is_const,
2688 is_lexical: def.is_lexical,
2689 closure_type: ClosureType::ModuleDecl,
2690 var_idx: 0,
2691 });
2692 0
2693 }
2694
2695 /// Declare a module variable and answer its closure-variable index.
2696 ///
2697 /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
2698 /// module variable is not one. The import table needs the real index instead, because
2699 /// that is the position the host writes the cell into.
2700 fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
2701 self.declare_module(name, def);
2702 self.cur()
2703 .closure_vars
2704 .iter()
2705 .position(|c| c.name == name)
2706 .map(|index| index as u32)
2707 .unwrap_or(0)
2708 }
2709
2710 /// Declare one imported binding as a module variable.
2711 ///
2712 /// Returns the closure-variable index, which is what the import table records: the
2713 /// host writes the exporter's cell into that slot before the body runs.
2714 fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
2715 let state = self.state();
2716 if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
2717 // Keep the slot, fix the kind: the name may already have been referenced.
2718 state.closure_vars[index].closure_type = ClosureType::ModuleImport;
2719 state.closure_vars[index].is_const = is_const;
2720 return index as u32;
2721 }
2722 state.closure_vars.push(ClosureVar {
2723 name: name.to_string(),
2724 // An imported binding cannot be assigned: `x = 1` on an import is a
2725 // `TypeError` at run time, which the const flag is what produces.
2726 is_const: true,
2727 // Lexical, so reads go through `get_var_ref_check`: before linking has filled
2728 // the cell an import is in its dead zone, and reading it there must say so
2729 // rather than answer `undefined`.
2730 is_lexical: true,
2731 closure_type: ClosureType::ModuleImport,
2732 var_idx: 0,
2733 });
2734 state.closure_vars.len() as u32 - 1
2735 }
2736
2737 /// Emit the code an `export` needs.
2738 ///
2739 /// Only `export default <expr>` has any: everything else is a table entry whose
2740 /// binding is declared elsewhere. The expression is stored into the hidden
2741 /// `*default*` variable rather than returned, because the module body has no value
2742 /// to speak of.
2743 fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2744 match &decl.kind {
2745 ExportKind::Declaration(stmt) => self.stmt(stmt),
2746 ExportKind::Default(expr) => {
2747 // A named default function/class is already a module binding; the export
2748 // points at it and there is nothing to evaluate.
2749 if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some())
2750 || matches!(&expr.kind, ExprKind::Class(class) if class.name.is_some())
2751 {
2752 return Ok(());
2753 }
2754 self.expr(expr)?;
2755 let index = self.declare_export_default();
2756 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2757 Ok(())
2758 }
2759 ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
2760 }
2761 }
2762
2763 /// A module name as the string it denotes.
2764 fn module_name_text(name: &ModuleName) -> &str {
2765 match name {
2766 ModuleName::Ident(ident) => &ident.name,
2767 ModuleName::Str(text) => text,
2768 }
2769 }
2770
2771 /// Bind `import`'s local names and record where each one comes from.
2772 ///
2773 /// Nothing is emitted: an import is not an instruction, it is a promise that the
2774 /// binding's cell will be filled before the body runs. The cell lands in the module's
2775 /// environment at a fixed index, and the host fills it from the exporter's cell —
2776 /// which is why a cyclic import can bind before the other module has evaluated.
2777 fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
2778 let request = self.module_request(&decl.source, &decl.attributes);
2779 for specifier in &decl.specifiers {
2780 let (local, name, is_star) = match specifier {
2781 ImportSpecifier::Default(ident) => {
2782 (ident.name.clone(), "default".to_string(), false)
2783 }
2784 ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
2785 ImportSpecifier::Named { imported, local } => (
2786 local.name.clone(),
2787 Self::module_name_text(imported).to_string(),
2788 false,
2789 ),
2790 };
2791 // `import * as ns` is *not* a live binding of another module's variable —
2792 // it is a value of its own, which is why the reference declares it like a
2793 // module variable and the host stores the namespace object in that cell.
2794 let var_idx = if is_star {
2795 // `const`: a namespace object is a value, and the binding is immutable.
2796 self.declare_module_var(&local, &VarDef::constant(local.clone()))
2797 } else {
2798 self.declare_import(&local, true)
2799 };
2800 self.module_meta().imports.push(ImportEntry {
2801 module: request,
2802 name,
2803 var_idx,
2804 is_star,
2805 });
2806 }
2807 Ok(())
2808 }
2809
2810 /// Record what an `export` offers, declaring the binding it exports.
2811 ///
2812 /// `export var x = 1` is a declaration like any other; only the table entry is extra.
2813 fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2814 match &decl.kind {
2815 ExportKind::Declaration(stmt) => {
2816 // The inner declaration keeps its own hoisting, then every name it binds
2817 // becomes an export of the same name.
2818 self.hoist_stmt(stmt)?;
2819 let mut names = Vec::new();
2820 Self::declared_names(stmt, &mut names);
2821 for name in names {
2822 let var_idx = self.module_binding_index(&name);
2823 self.exports_local(&name, var_idx);
2824 }
2825 }
2826 ExportKind::Default(expr) => {
2827 // The reference puts a default export in a hidden `*default*` variable,
2828 // so `export default function f(){}` can export a *value* while `f` stays
2829 // a binding of the module.
2830 if let ExprKind::Function(func) = &expr.kind
2831 && let Some(name) = &func.name
2832 {
2833 let text = name.name.clone();
2834 self.hoist_stmt(&Stmt {
2835 kind: StmtKind::FuncDecl(func.clone()),
2836 span: expr.span,
2837 })?;
2838 let var_idx = self.module_binding_index(&text);
2839 self.module_meta().exports.push(ExportEntry::Local {
2840 export_name: "default".to_string(),
2841 var_idx,
2842 });
2843 return Ok(());
2844 }
2845 if let ExprKind::Class(class) = &expr.kind
2846 && let Some(name) = &class.name
2847 {
2848 let text = name.name.clone();
2849 self.hoist_stmt(&Stmt {
2850 kind: StmtKind::ClassDecl(class.clone()),
2851 span: expr.span,
2852 })?;
2853 let var_idx = self.module_binding_index(&text);
2854 let _ = var_idx;
2855 }
2856 let var_idx = self.declare_export_default();
2857 self.module_meta().exports.push(ExportEntry::Local {
2858 export_name: "default".to_string(),
2859 var_idx,
2860 });
2861 }
2862 ExportKind::Named {
2863 specifiers,
2864 source,
2865 attributes,
2866 } => match source {
2867 Some(source) => {
2868 let request = self.module_request(source, attributes);
2869 for specifier in specifiers {
2870 self.module_meta().exports.push(ExportEntry::Indirect {
2871 export_name: Self::module_name_text(&specifier.exported).to_string(),
2872 module: request,
2873 import_name: Self::module_name_text(&specifier.local).to_string(),
2874 });
2875 }
2876 }
2877 None => {
2878 for specifier in specifiers {
2879 let local = Self::module_name_text(&specifier.local).to_string();
2880 let var_idx = self.module_binding_index(&local);
2881 let export_name = Self::module_name_text(&specifier.exported).to_string();
2882 self.module_meta().exports.push(ExportEntry::Local {
2883 export_name,
2884 var_idx,
2885 });
2886 }
2887 }
2888 },
2889 ExportKind::All {
2890 source,
2891 exported,
2892 attributes,
2893 } => {
2894 let request = self.module_request(source, attributes);
2895 match exported {
2896 Some(name) => {
2897 self.module_meta().exports.push(ExportEntry::StarAs {
2898 export_name: Self::module_name_text(name).to_string(),
2899 module: request,
2900 });
2901 }
2902 None => {
2903 self.module_meta()
2904 .exports
2905 .push(ExportEntry::Star { module: request });
2906 }
2907 }
2908 }
2909 }
2910 Ok(())
2911 }
2912
2913 /// The names a declaration binds, which is what `export <decl>` exports.
2914 fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
2915 match &stmt.kind {
2916 StmtKind::VarDecl(decl) => {
2917 for declarator in &decl.declarators {
2918 let mut names = Vec::new();
2919 declarator.target.bound_names(&mut names);
2920 out.extend(names.into_iter().map(|name| name.name));
2921 }
2922 }
2923 StmtKind::FuncDecl(func) => {
2924 if let Some(name) = &func.name {
2925 out.push(name.name.clone());
2926 }
2927 }
2928 StmtKind::ClassDecl(class) => {
2929 if let Some(name) = &class.name {
2930 out.push(name.name.clone());
2931 }
2932 }
2933 _ => {}
2934 }
2935 }
2936
2937 /// The closure-variable index of a module binding, declaring it if the name was
2938 /// exported without being declared here.
2939 ///
2940 /// `export { x }` where `x` is not declared in the module is a link-time
2941 /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
2942 fn module_binding_index(&mut self, name: &str) -> u32 {
2943 if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
2944 return index as u32;
2945 }
2946 self.declare_module_var(name, &VarDef::lexical(name.to_string()))
2947 }
2948
2949 fn exports_local(&mut self, export_name: &str, var_idx: u32) {
2950 self.module_meta().exports.push(ExportEntry::Local {
2951 export_name: export_name.to_string(),
2952 var_idx,
2953 });
2954 }
2955
2956 /// The hidden `*default*` binding `export default <expr>` stores into.
2957 fn declare_export_default(&mut self) -> u32 {
2958 const DEFAULT: &str = "*default*";
2959 if let Some(index) = self
2960 .cur()
2961 .closure_vars
2962 .iter()
2963 .position(|c| c.name == DEFAULT)
2964 {
2965 return index as u32;
2966 }
2967 self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
2968 }
2969
2970 /// The module tables, which only the top-level state has.
2971 fn module_meta(&mut self) -> &mut ModuleMeta {
2972 self.state()
2973 .module
2974 .as_mut()
2975 .expect("module tables are only touched while compiling a module")
2976 }
2977
2978 /// The index of `specifier`'s request, adding it if it is new.
2979 ///
2980 /// Deduplicated on the specifier *and* its attributes: the same file imported once as
2981 /// JSON and once as text is two modules with two different contents, which is exactly
2982 /// what `hello_module.js` does.
2983 fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
2984 let attributes: Vec<(String, String)> = attributes
2985 .iter()
2986 .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
2987 .collect();
2988 let meta = self.module_meta();
2989 if let Some(index) = meta
2990 .requests
2991 .iter()
2992 .position(|request| request.specifier == specifier && request.attributes == attributes)
2993 {
2994 return index as u32;
2995 }
2996 meta.requests.push(ModuleRequest {
2997 specifier: specifier.to_string(),
2998 attributes,
2999 });
3000 meta.requests.len() as u32 - 1
3001 }
3002
3003 /// Compile a loop body with a `break`/`continue` target pushed for it.
3004 fn loop_body(
3005 &mut self,
3006 body: &Stmt,
3007 labels: &[String],
3008 continue_label: Label,
3009 break_label: Label,
3010 ) -> Result<(), SyntaxError> {
3011 self.push_jump_target(JumpTarget {
3012 names: labels.to_vec(),
3013 break_label: Some(break_label),
3014 continue_label: Some(continue_label),
3015 // A loop leaves nothing of its own on the value stack.
3016 drop_count: 0,
3017 finally_label: None,
3018 is_regular_stmt: false,
3019 has_iterator: false,
3020 is_async_iterator: false,
3021 });
3022 let result = self.stmt(body);
3023 self.pop_jump_target();
3024 result
3025 }
3026
3027 fn push_jump_target(&mut self, target: JumpTarget) {
3028 self.state().jump_targets.push(target);
3029 }
3030
3031 fn pop_jump_target(&mut self) {
3032 self.state().jump_targets.pop();
3033 }
3034
3035 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3036 let (label, is_break) = match &stmt.kind {
3037 StmtKind::Break(label) => (label.as_ref(), true),
3038 StmtKind::Continue(label) => (label.as_ref(), false),
3039 _ => unreachable!("control_transfer is only called for break and continue"),
3040 };
3041
3042 // Walk outward from the innermost construct. Everything considered before
3043 // the match is a construct control is leaving, and leaving it has a cost:
3044 // its stack slots go, and its finalizer runs.
3045 let targets = self.cur().jump_targets.clone();
3046 for target in targets.iter().rev() {
3047 let destination = match (label, is_break) {
3048 // An unlabelled `break` skips a labelled non-loop statement: `break`
3049 // may name one, but the bare form only means "leave the loop".
3050 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3051 (None, false) => target.continue_label,
3052 (Some(name), true) => target
3053 .break_label
3054 .filter(|_| target.names.contains(&name.name)),
3055 (Some(name), false) => target
3056 .continue_label
3057 .filter(|_| target.names.contains(&name.name)),
3058 };
3059
3060 if let Some(destination) = destination {
3061 self.emit_jump(Opcode::Goto, destination, &[]);
3062 return Ok(());
3063 }
3064
3065 // Closing the iterator consumes the three slots the loop keeps on the
3066 // stack (iterator, next method, catch offset), so those are not dropped
3067 // again below.
3068 let mut remaining = target.drop_count;
3069 if target.has_iterator {
3070 self.emit_iterator_close(target.is_async_iterator, false);
3071 remaining = remaining.saturating_sub(3);
3072 }
3073 for _ in 0..remaining {
3074 self.emit(Opcode::Drop, &[]);
3075 }
3076 if let Some(finally) = target.finally_label {
3077 // The finalizer runs as a subroutine and is handed a dummy return
3078 // value, which is dropped afterwards to keep the stack the depth it
3079 // had before.
3080 self.emit(Opcode::Undefined, &[]);
3081 self.emit_jump(Opcode::Gosub, finally, &[]);
3082 self.emit(Opcode::Drop, &[]);
3083 }
3084 }
3085
3086 // The parser rejects a break/continue with no target, so reaching here
3087 // means the compiler's own bookkeeping is wrong.
3088 Err(SyntaxError::new(
3089 if is_break {
3090 "break has no enclosing loop or switch"
3091 } else {
3092 "continue has no enclosing loop"
3093 },
3094 stmt.span,
3095 ))
3096 }
3097
3098 /// Compile a labelled statement.
3099 ///
3100 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3101 /// that loop's targets, so the chain is collected and handed to the loop. A
3102 /// label on a non-loop statement only provides a `break` target, because
3103 /// `continue` may not target it.
3104 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3105 let mut names = vec![label.name.clone()];
3106 let mut inner = body;
3107 while let StmtKind::Labeled {
3108 label: next,
3109 body: deeper,
3110 } = &inner.kind
3111 {
3112 names.push(next.name.clone());
3113 inner = deeper;
3114 }
3115 if Self::is_loop(inner) {
3116 return self.stmt_labelled(inner, &names);
3117 }
3118 let end = self.new_label();
3119 self.push_jump_target(JumpTarget {
3120 names,
3121 break_label: Some(end),
3122 continue_label: None,
3123 drop_count: 0,
3124 finally_label: None,
3125 is_regular_stmt: true,
3126 has_iterator: false,
3127 is_async_iterator: false,
3128 });
3129 let result = self.stmt(inner);
3130 self.pop_jump_target();
3131 result?;
3132 self.place_label(end);
3133 let _ = stmt;
3134 Ok(())
3135 }
3136
3137 /// Whether a statement is a loop, i.e. a valid target for `continue`.
3138 fn is_loop(stmt: &Stmt) -> bool {
3139 matches!(
3140 stmt.kind,
3141 StmtKind::While { .. }
3142 | StmtKind::DoWhile { .. }
3143 | StmtKind::For { .. }
3144 | StmtKind::ForIn { .. }
3145 | StmtKind::ForOf { .. }
3146 )
3147 }
3148
3149 /// Compile `switch`.
3150 ///
3151 /// The discriminant is evaluated once and stays on the value stack while the
3152 /// clauses compare against copies of it, so it is dropped at the end — which is
3153 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3154 /// clause's body jumps over the *next* clause's tests straight into its body.
3155 ///
3156 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3157 /// the next run's tests. Only the last run's miss reaches the `default` body, or
3158 /// the end of the switch when there is no `default`. That failure path can point
3159 /// backwards (`default` written first), so the runs and their labels are worked
3160 /// out before any code is emitted.
3161 fn switch(
3162 &mut self,
3163 discriminant: &Expr,
3164 cases: &[SwitchCase],
3165 stmt: &Stmt,
3166 ) -> Result<(), SyntaxError> {
3167 self.reset_value();
3168 // The discriminant is evaluated outside the switch's block scope, before
3169 // any `case` clause exists.
3170 self.expr(discriminant)?;
3171
3172 let switch_key = stmt.span.start.offset as u64;
3173 let switch_parent = self.cur().current_block;
3174 self.push_block(switch_key, switch_parent);
3175 self.emit_scope_enter(switch_key);
3176
3177 let break_label = self.new_label();
3178 self.push_jump_target(JumpTarget {
3179 names: Vec::new(),
3180 break_label: Some(break_label),
3181 // `switch` is a valid `break` target but not a `continue` target.
3182 continue_label: None,
3183 // The discriminant stays on the value stack for the whole statement, so
3184 // a `break` aimed further out has to discard it.
3185 drop_count: 1,
3186 finally_label: None,
3187 is_regular_stmt: false,
3188 has_iterator: false,
3189 is_async_iterator: false,
3190 });
3191
3192 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3193 // its label to the clause after it, so both tests reach the same body.
3194 let mut runs: Vec<(usize, usize)> = Vec::new();
3195 let mut scan = 0;
3196 while scan < cases.len() {
3197 if cases[scan].test.is_some() {
3198 let mut last = scan;
3199 while last + 1 < cases.len()
3200 && cases[last].test.is_some()
3201 && cases[last].body.is_empty()
3202 && cases[last + 1].test.is_some()
3203 {
3204 last += 1;
3205 }
3206 runs.push((scan, last));
3207 scan = last + 1;
3208 } else {
3209 scan += 1;
3210 }
3211 }
3212
3213 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3214 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3215 let default_at = cases.iter().position(|case| case.test.is_none());
3216 // Where the last run sends control when nothing matched.
3217 let miss_target = match default_at {
3218 Some(index) => body_labels[index],
3219 None => break_label,
3220 };
3221
3222 // When `default` comes first, control has to jump over it to reach the
3223 // tests. It only needs to when some clause actually has a test; otherwise
3224 // the default body is the entry point.
3225 let mut entry = None;
3226 if default_at == Some(0) && !runs.is_empty() {
3227 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3228 entry = Some(run_labels[0]);
3229 }
3230
3231 let mut index = 0;
3232 let mut run = 0;
3233 let result = (|| -> Result<(), SyntaxError> {
3234 while index < cases.len() {
3235 if cases[index].test.is_some() {
3236 let (first, last) = runs[run];
3237 // Reaching these tests from the preceding body is a
3238 // fallthrough, which continues inside the body and skips them.
3239 if index > 0 {
3240 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3241 }
3242 if let Some(label) = entry.take() {
3243 self.place_label(label);
3244 }
3245 self.place_label(run_labels[run]);
3246
3247 for (offset, case) in cases[first..=last].iter().enumerate() {
3248 let test = case.test.as_ref().unwrap();
3249 self.emit(Opcode::Dup, &[]);
3250 self.expr(test)?;
3251 self.emit(Opcode::StrictEq, &[]);
3252 if first + offset < last {
3253 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3254 } else {
3255 // Hand over to the next run's tests, or give up.
3256 let next = match runs.get(run + 1) {
3257 Some(_) => run_labels[run + 1],
3258 None => miss_target,
3259 };
3260 self.emit_jump(Opcode::IfFalse, next, &[]);
3261 }
3262 }
3263
3264 self.place_label(body_labels[index]);
3265 for case in &cases[first..=last] {
3266 self.stmts(&case.body)?;
3267 }
3268 index = last + 1;
3269 run += 1;
3270 } else {
3271 // `default`: control arrives here either by falling through or
3272 // because every test missed.
3273 self.place_label(body_labels[index]);
3274 self.stmts(&cases[index].body)?;
3275 index += 1;
3276 }
3277 }
3278 Ok(())
3279 })();
3280
3281 if result.is_ok() {
3282 self.place_label(break_label);
3283 // Discard the discriminant now that no test needs it.
3284 self.emit(Opcode::Drop, &[]);
3285 }
3286
3287 self.pop_jump_target();
3288 self.emit_scope_leave(switch_key);
3289 self.state().current_block = switch_parent;
3290 result
3291 }
3292
3293 /// Compile `try`/`catch`/`finally`.
3294 ///
3295 /// The shape is an exception table built out of `catch` instructions, each of
3296 /// which records where control goes if the instructions that follow raise:
3297 ///
3298 /// ```text
3299 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
3300 /// <guarded block>
3301 /// drop <- discard the catch offset
3302 /// undefined; gosub FINALLY; drop
3303 /// goto END
3304 /// HANDLER:
3305 /// <bind the catch parameter>
3306 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
3307 /// <handler body>
3308 /// drop; undefined; gosub FINALLY; drop; goto END
3309 /// CATCH2:
3310 /// gosub FINALLY; throw <- run the finalizer, then let the error out
3311 /// FINALLY:
3312 /// <finalizer>
3313 /// ret <- return to the `gosub`
3314 /// END:
3315 /// ```
3316 ///
3317 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3318 /// of the finalizer serves the normal path, the handler path and the
3319 /// propagating-exception path.
3320 ///
3321 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3322 /// runs with `ret_value` on the stack, and the normal path has no value to
3323 /// keep, so it pushes one to keep the stack depth identical on every path.
3324 fn try_stmt(
3325 &mut self,
3326 stmt: &Stmt,
3327 block: &[Stmt],
3328 handler: &Option<CatchClause>,
3329 finalizer: Option<&[Stmt]>,
3330 ) -> Result<(), SyntaxError> {
3331 self.reset_value();
3332
3333 let catch_label = self.new_label();
3334 let catch2_label = self.new_label();
3335 let finally_label = self.new_label();
3336 let end_label = self.new_label();
3337
3338 self.emit_jump(Opcode::Catch, catch_label, &[]);
3339
3340 // The guarded block. `break` may not target it, so its entry exists purely
3341 // to unwind: a jump out has to discard the catch offset and run the
3342 // finalizer.
3343 self.push_jump_target(JumpTarget {
3344 names: Vec::new(),
3345 break_label: None,
3346 continue_label: None,
3347 drop_count: 1,
3348 finally_label: Some(finally_label),
3349 is_regular_stmt: false,
3350 has_iterator: false,
3351 is_async_iterator: false,
3352 });
3353
3354 let block_key = Self::try_block_key(stmt, TryPart::Block);
3355 let block_parent = self.cur().current_block;
3356 self.push_block(block_key, block_parent);
3357 self.emit_scope_enter(block_key);
3358 self.stmts(block)?;
3359 self.emit_scope_leave(block_key);
3360 self.state().current_block = block_parent;
3361 // A guarded block that ends in a `return`/`throw` never reaches the
3362 // epilogue, so the reference does not emit one.
3363 self.pop_jump_target();
3364 let block_live = !block.last().is_some_and(Self::terminates);
3365
3366 if block_live {
3367 self.emit(Opcode::Drop, &[]);
3368 self.emit(Opcode::Undefined, &[]);
3369 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3370 self.emit(Opcode::Drop, &[]);
3371 self.emit_jump(Opcode::Goto, end_label, &[]);
3372 }
3373
3374 if let Some(handler) = handler {
3375 self.place_label(catch_label);
3376 // The thrown value is on top of the stack: bind it, or discard it for
3377 // `catch { }`.
3378 match &handler.param {
3379 Some(pattern) => {
3380 // The stores resolve the names, so they have to run inside the
3381 // parameter's own scope; otherwise a same-named `catch` further out
3382 // could win. A `catch` binding is never in the dead zone, so the store
3383 // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3384 let param_key = Self::try_block_key(stmt, TryPart::Param);
3385 let param_parent = self.cur().current_block;
3386 self.push_block(param_key, param_parent);
3387 self.destructure(pattern, Some(VarDeclKind::Var))?;
3388 self.state().current_block = param_parent;
3389 }
3390 None => self.emit(Opcode::Drop, &[]),
3391 }
3392 self.emit_jump(Opcode::Catch, catch2_label, &[]);
3393
3394 self.push_jump_target(JumpTarget {
3395 names: Vec::new(),
3396 break_label: None,
3397 continue_label: None,
3398 drop_count: 1,
3399 finally_label: Some(finally_label),
3400 is_regular_stmt: false,
3401 has_iterator: false,
3402 is_async_iterator: false,
3403 });
3404 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3405 let catch_parent = self.cur().current_block;
3406 self.push_block(catch_key, catch_parent);
3407 self.emit_scope_enter(catch_key);
3408 self.stmts(&handler.body)?;
3409 self.emit_scope_leave(catch_key);
3410 self.state().current_block = catch_parent;
3411 self.pop_jump_target();
3412 let handler_live = !handler.body.last().is_some_and(Self::terminates);
3413
3414 if handler_live {
3415 self.emit(Opcode::Drop, &[]);
3416 self.emit(Opcode::Undefined, &[]);
3417 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3418 self.emit(Opcode::Drop, &[]);
3419 self.emit_jump(Opcode::Goto, end_label, &[]);
3420 }
3421
3422 // An error raised inside the handler still has to run the finalizer.
3423 self.place_label(catch2_label);
3424 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3425 self.emit(Opcode::Throw, &[]);
3426 } else {
3427 // `try`/`finally` with no handler: the finalizer runs, then the error
3428 // keeps propagating.
3429 self.place_label(catch_label);
3430 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3431 self.emit(Opcode::Throw, &[]);
3432 }
3433
3434 self.place_label(finally_label);
3435 // Inside the finalizer, leaving has a different cost: the return value and
3436 // the `gosub` return address are both on the stack, and neither finalizer nor
3437 // any outer one may run before the block has finished.
3438 self.push_jump_target(JumpTarget {
3439 names: Vec::new(),
3440 break_label: None,
3441 continue_label: None,
3442 drop_count: 2,
3443 finally_label: None,
3444 is_regular_stmt: false,
3445 has_iterator: false,
3446 is_async_iterator: false,
3447 });
3448 if let Some(finalizer) = finalizer {
3449 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3450 let finally_parent = self.cur().current_block;
3451 self.push_block(finally_key, finally_parent);
3452 self.emit_scope_enter(finally_key);
3453 self.stmts(finalizer)?;
3454 self.emit_scope_leave(finally_key);
3455 self.state().current_block = finally_parent;
3456 }
3457 self.pop_jump_target();
3458 self.emit(Opcode::Ret, &[]);
3459 self.place_label(end_label);
3460 Ok(())
3461 }
3462
3463 /// Compile `for`/`in` and `for`/`of`.
3464 ///
3465 /// Both keep an enumeration record on the value stack for the whole loop, which
3466 /// is what makes leaving early expensive: the record has to be dropped, or the
3467 /// iterator closed. The layout is
3468 ///
3469 /// ```text
3470 /// <iterated expression>
3471 /// for_in_start | for_of_start <- pushes the record
3472 /// goto TEST
3473 /// NEXT:
3474 /// <bind the loop variable>
3475 /// <body>
3476 /// TEST:
3477 /// for_in_next | for_of_next 0
3478 /// if_false NEXT <- not finished: next iteration
3479 /// drop <- finished: discard the leftover value
3480 /// BREAK:
3481 /// drop | iterator_close <- the one cleanup `break` also uses
3482 /// ```
3483 ///
3484 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3485 /// normal exit share one copy — which is why `break` inside the loop emits nothing
3486 /// of its own, and only a jump that passes *through* the loop pays for its record.
3487 fn for_in_of(
3488 &mut self,
3489 stmt: &Stmt,
3490 left: &ForHead,
3491 right: &Expr,
3492 body: &Stmt,
3493 kind: ForLoopKind,
3494 labels: &[String],
3495 ) -> Result<(), SyntaxError> {
3496 self.reset_value();
3497
3498 let loop_key = stmt.span.start.offset as u64;
3499 let loop_parent = self.cur().current_block;
3500 self.push_block(loop_key, loop_parent);
3501 self.emit_scope_enter(loop_key);
3502
3503 // The iterated expression is evaluated inside the loop's scope, after the
3504 // bindings exist in the temporal dead zone.
3505 self.expr(right)?;
3506
3507 let next = self.new_label();
3508 let test = self.new_label();
3509 let break_target = self.new_label();
3510
3511 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3512 match kind {
3513 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3514 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3515 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3516 }
3517 self.emit_jump(Opcode::Goto, test, &[]);
3518
3519 self.push_jump_target(JumpTarget {
3520 // `outer: for (x of xs) … break outer` needs the name here. Without it the
3521 // loop had no label to break to, and the compiler reported "break has no
3522 // enclosing loop" for a loop that was plainly enclosing it.
3523 names: labels.to_vec(),
3524 break_label: Some(break_target),
3525 continue_label: Some(test),
3526 // Passing through the loop has to dispose of its record. A `for`/`of`
3527 // record is three slots, and closing the iterator consumes all of them.
3528 drop_count: if has_iterator { 3 } else { 1 },
3529 finally_label: None,
3530 is_regular_stmt: false,
3531 has_iterator,
3532 is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3533 });
3534
3535 self.place_label(next);
3536 self.bind_loop_variable(left)?;
3537 // The reference marks the body with its own label here. Nothing jumps to it
3538 // once the loop is laid out, but it is not decoration: a label between the
3539 // store and the body is why `put_loc v; get_loc v` does *not* fold into
3540 // `set_loc v` when the body starts by reading the loop variable.
3541 let body_label = self.new_label();
3542 self.place_label(body_label);
3543 // `for (using x of …)` disposes once per iteration, so the body is a disposal
3544 // region rather than the whole loop: the resource is the element that this
3545 // iteration produced.
3546 let using_slot = match left {
3547 ForHead::VarDecl(decl) if decl.kind.is_using() => {
3548 decl.declarators
3549 .first()
3550 .and_then(|declarator| match &declarator.target.kind {
3551 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3552 _ => None,
3553 })
3554 }
3555 _ => None,
3556 };
3557 match using_slot {
3558 Some(slot) => {
3559 let live = !Self::terminates(body);
3560 self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3561 }
3562 None => self.stmt(body)?,
3563 }
3564
3565 self.place_label(test);
3566 match kind {
3567 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3568 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3569 ForLoopKind::AwaitOf => {
3570 // The reference's shape: step, `await` the result, then unpack it.
3571 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3572 self.emit(Opcode::Await, &[]);
3573 self.state().has_await = true;
3574 self.emit(Opcode::IteratorGetValueDone, &[]);
3575 }
3576 }
3577 self.emit_jump(Opcode::IfFalse, next, &[]);
3578 // The loop is finished; `for_xx_next` left an `undefined` behind.
3579 self.emit(Opcode::Drop, &[]);
3580
3581 self.pop_jump_target();
3582 self.place_label(break_target);
3583 if has_iterator {
3584 // A loop that ran to completion finds its iterator slot already cleared (see
3585 // `iterator_get_value_done`), so this closes only an iterator abandoned by a
3586 // `break` that jumped here.
3587 self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
3588 } else {
3589 self.emit(Opcode::Drop, &[]);
3590 }
3591
3592 self.emit_scope_leave(loop_key);
3593 self.state().current_block = loop_parent;
3594 Ok(())
3595 }
3596
3597 /// Store the value `for_xx_next` left on the stack into the loop variable.
3598 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3599 // A declaration *initialises* the binding, which is what takes a `let` out of
3600 // the temporal dead zone, so the store is the unchecked form. Assigning to a
3601 // binding declared elsewhere is an ordinary write and keeps its check.
3602 let (pattern, action) = match left {
3603 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3604 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3605 };
3606 match &pattern.kind {
3607 PatternKind::Ident(name) => {
3608 // `for (using x of …)` validates and snapshots each iteration's value
3609 // before the body runs, which is what makes a non-disposable element fail
3610 // on the iteration that produced it rather than at the end of the loop.
3611 if let ForHead::VarDecl(decl) = left
3612 && decl.kind.is_using()
3613 {
3614 let method_slot = self
3615 .using_method_slot(&name.name)
3616 .expect("a using binding was declared during hoisting");
3617 self.emit(
3618 Opcode::UsingCheck,
3619 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3620 );
3621 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3622 }
3623 self.emit_var(action, &name.name);
3624 Ok(())
3625 }
3626 // Every other target stores through the same path an assignment pattern
3627 // uses, which is what makes `for (a[0] in obj)` write each key into the
3628 // property instead of refusing the loop outright.
3629 _ => self.destructure(
3630 pattern,
3631 match left {
3632 ForHead::VarDecl(decl) => Some(decl.kind),
3633 ForHead::Assign(_) => None,
3634 },
3635 ),
3636 }
3637 }
3638
3639 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3640 for declarator in &decl.declarators {
3641 let Some(init) = &declarator.init else {
3642 // `var x;` stays `undefined`. A lexical binding is different: it
3643 // has to be *initialised* to leave the temporal dead zone, so the
3644 // compiler supplies an explicit `undefined`.
3645 if decl.kind.is_lexical() {
3646 // A lexical binding has to be *initialised* to leave the temporal
3647 // dead zone, and a destructuring one is no different — `let {a}`
3648 // with no initialiser is a syntax error, but `let [a] = []` still
3649 // needs `a` to be initialised from an empty source, which the
3650 // pattern does on its own.
3651 self.emit(Opcode::Undefined, &[]);
3652 self.destructure(&declarator.target, Some(decl.kind))?;
3653 }
3654 continue;
3655 };
3656 match &declarator.target.kind {
3657 PatternKind::Ident(name) => {
3658 self.expr(init)?;
3659 self.set_name_if_anonymous(init, &name.name);
3660 if decl.kind.is_using() {
3661 // `using_check` validates the value and snapshots its dispose
3662 // method: `value -> value, method`. The snapshot is what makes a
3663 // later change to `Symbol.dispose` irrelevant, and validating here
3664 // is what keeps the body from running at all when the value is not
3665 // disposable.
3666 let method_slot = self
3667 .using_method_slot(&name.name)
3668 .expect("a using binding was declared during hoisting");
3669 self.emit(
3670 Opcode::UsingCheck,
3671 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3672 );
3673 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3674 self.emit_var(VarAction::PutInit, &name.name);
3675 continue;
3676 }
3677 // A declaration statement produces no value, so nothing is
3678 // duplicated onto the stack.
3679 match decl.kind {
3680 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3681 _ => self.emit_var(VarAction::PutInit, &name.name),
3682 }
3683 }
3684 _ => {
3685 // A destructuring declaration keeps nothing on the stack: the
3686 // pattern consumes the initialiser.
3687 self.expr(init)?;
3688 self.destructure(&declarator.target, Some(decl.kind))?;
3689 }
3690 }
3691 }
3692 Ok(())
3693 }
3694
3695 /// Bind a destructuring pattern from the value on top of the stack.
3696 ///
3697 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
3698 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
3699 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
3700 /// *assignment*, where a member expression is a legal target and the store is an
3701 /// ordinary property write.
3702 ///
3703 /// The value is consumed. An assignment expression's own result is the right-hand
3704 /// side, which the caller keeps separately — the spec does not make the pattern's
3705 /// last store produce it.
3706 fn destructure(
3707 &mut self,
3708 pattern: &Pattern,
3709 decl: Option<VarDeclKind>,
3710 ) -> Result<(), SyntaxError> {
3711 match &pattern.kind {
3712 PatternKind::Ident(name) => {
3713 match decl {
3714 Some(VarDeclKind::Var) | None => {
3715 self.emit_var(VarAction::Put, &name.name);
3716 }
3717 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
3718 }
3719 Ok(())
3720 }
3721 PatternKind::Assign { target, default } => {
3722 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
3723 // keeps `null`.
3724 //
3725 // The shape is the reference's: test for `undefined`, and when the value is
3726 // present fall **through** to a single store both paths share. The
3727 // alternatives — branching to the store on each side — need a second store
3728 // and a jump between them, which is what the dump used to show.
3729 let has_value = self.new_label();
3730 self.emit(Opcode::Dup, &[]);
3731 self.emit(Opcode::IsUndefined, &[]);
3732 self.emit_jump(Opcode::IfFalse, has_value, &[]);
3733 self.emit(Opcode::Drop, &[]);
3734 self.expr(default)?;
3735 // `var {f = function(){}} = {}` names the function `f`, like a plain
3736 // `var f = function(){}` does. Both pattern forms do it:
3737 // `BindingInitialization` names the value for a *binding* target, and since
3738 // ES2018 `DestructuringAssignmentEvaluation` does the same, so
3739 // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
3740 // no name to give, which is why only an identifier qualifies.
3741 if let PatternKind::Ident(name) = &target.kind {
3742 self.set_name_if_anonymous(default, &name.name);
3743 }
3744 self.place_label(has_value);
3745 self.destructure(target, decl)
3746 }
3747 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
3748 PatternKind::Object { properties, rest } => {
3749 self.destructure_object(properties, rest, decl, pattern)
3750 }
3751 PatternKind::Member(member) if decl.is_none() => {
3752 // An assignment pattern may store into a property. The value is on the
3753 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
3754 // put the three in the order `put_array_el`/`put_field` expect.
3755 self.expr(&member.object)?;
3756 match &member.property {
3757 MemberProp::Ident(name) => {
3758 // `value obj` -> `obj value`, the order `put_field` takes.
3759 // Nothing needs to be left behind: a pattern element's value is
3760 // consumed by its own store.
3761 self.emit(Opcode::Swap, &[]);
3762 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
3763 }
3764 MemberProp::Computed(index) => {
3765 self.expr(index)?;
3766 // `value obj key` -> `obj key value`.
3767 self.emit(Opcode::Rot3l, &[]);
3768 self.emit(Opcode::PutArrayEl, &[]);
3769 }
3770 MemberProp::Private(name) => {
3771 // `value obj` -> `obj value`, and the store half of the assignment is
3772 // the same one `obj.#x = value` uses — only without `insert2`,
3773 // because a pattern element's value is not wanted back.
3774 let binding = format!("#{}", name.name);
3775 let (kind, setter) = self.private_use(&binding, member.span)?;
3776 self.emit(Opcode::Swap, &[]);
3777 self.private_store(&binding, kind, setter.as_deref())?;
3778 }
3779 }
3780 Ok(())
3781 }
3782 PatternKind::Rest(inner) => self.destructure(inner, decl),
3783 PatternKind::Invalid(expr) => {
3784 Err(SyntaxError::new("invalid assignment target", expr.span))
3785 }
3786 _ => Err(SyntaxError::new(
3787 "this destructuring target is not supported by the compiler yet",
3788 pattern.span,
3789 )),
3790 }
3791 }
3792
3793 /// `[…]` on the left: drain an iterator, binding one target per element.
3794 fn destructure_array(
3795 &mut self,
3796 elements: &[Option<PatternElement>],
3797 rest: &Option<Box<RestElement>>,
3798 decl: Option<VarDeclKind>,
3799 ) -> Result<(), SyntaxError> {
3800 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
3801 // pattern accepts any iterable and closes the iterator when the pattern ends
3802 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
3803 // first because it is on top.
3804 self.emit(Opcode::ForOfStart, &[]);
3805 for element in elements {
3806 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
3807 self.emit(Opcode::Drop, &[]);
3808 match element {
3809 Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
3810 Some(PatternElement::Property { span, .. }) => {
3811 return Err(SyntaxError::new(
3812 "a property pattern is not a valid array element",
3813 *span,
3814 ));
3815 }
3816 // An elision skips the value, which is already on the stack.
3817 None => self.emit(Opcode::Drop, &[]),
3818 }
3819 }
3820 if let Some(rest) = rest {
3821 // The remaining values go into a fresh array. The target and its running
3822 // index stay on the stack above the iterator, which is what the operand of
3823 // `for_of_next` accounts for: two values sit above the iterator triple.
3824 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
3825 self.emit(Opcode::Push0, &[]);
3826 let top = self.new_label();
3827 self.place_label(top);
3828 self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
3829 let done = self.new_label();
3830 self.emit_jump(Opcode::IfTrue, done, &[]);
3831 self.emit(Opcode::DefineArrayEl, &[]);
3832 self.emit(Opcode::Inc, &[]);
3833 self.emit_jump(Opcode::Goto, top, &[]);
3834 self.place_label(done);
3835 self.emit(Opcode::Drop, &[]);
3836 self.emit(Opcode::Drop, &[]);
3837 self.destructure_rest(rest, decl)?;
3838 }
3839 self.emit(Opcode::IteratorClose, &[]);
3840 Ok(())
3841 }
3842
3843 /// `{…}` on the left: read properties off one boxed source object.
3844 fn destructure_object(
3845 &mut self,
3846 properties: &[Option<PatternElement>],
3847 rest: &Option<Box<RestElement>>,
3848 decl: Option<VarDeclKind>,
3849 pattern: &Pattern,
3850 ) -> Result<(), SyntaxError> {
3851 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
3852 // aside for the rest element below.
3853 self.emit(Opcode::ToObject, &[]);
3854 let mut taken: Vec<String> = Vec::new();
3855 // Whether any key was computed, which a rest element cannot exclude.
3856 let mut computed = false;
3857 for property in properties {
3858 let Some(PatternElement::Property {
3859 key, value, span, ..
3860 }) = property
3861 else {
3862 return Err(SyntaxError::new(
3863 "a bare pattern is not a valid object property",
3864 properties
3865 .iter()
3866 .flatten()
3867 .map(|element| match element {
3868 PatternElement::Pattern(pattern) => pattern.span,
3869 PatternElement::Property { span, .. } => *span,
3870 })
3871 .next()
3872 .unwrap_or(pattern.span),
3873 ));
3874 };
3875 // Every read needs the source twice: to read from, and to keep for the next
3876 // property. `get_field2` is that duplicate-and-read in one instruction, but it
3877 // leaves the copy *under* the value, so it is only usable when whatever
3878 // consumes the value tolerates that. See [`reads_with_get_field2`].
3879 let nested = reads_with_get_field2(decl, value);
3880 if !nested {
3881 self.emit(Opcode::Dup, &[]);
3882 }
3883 match key {
3884 PropName::Literal(literal) => {
3885 let name = self.property_key_text(literal, *span)?;
3886 taken.push(name.clone());
3887 self.emit(
3888 if nested {
3889 Opcode::GetField2
3890 } else {
3891 Opcode::GetField
3892 },
3893 &[Op::Atom(Atom::from_text(&name))],
3894 );
3895 }
3896 PropName::Computed(index) => {
3897 // A computed key has no name to exclude ahead of time, so a rest
3898 // element that has to skip it is refused below rather than silently
3899 // copying the property into the rest object.
3900 computed = true;
3901 self.expr(index)?;
3902 self.emit(Opcode::GetArrayEl, &[]);
3903 }
3904 PropName::Private(_) => {
3905 return Err(SyntaxError::new(
3906 "private fields are not supported by the compiler yet",
3907 value.span,
3908 ));
3909 }
3910 }
3911 self.destructure(value, decl)?;
3912 }
3913 match rest {
3914 Some(rest) => {
3915 if computed {
3916 return Err(SyntaxError::new(
3917 "a computed key with a rest element is not supported by the compiler yet",
3918 Self::rest_span(rest),
3919 ));
3920 }
3921 // `target src exclude`: the exclusion list is an array of the keys the
3922 // literal part already took, so the rest object gets only the others.
3923 self.emit(Opcode::Object, &[]);
3924 self.emit(Opcode::Swap, &[]);
3925 for name in &taken {
3926 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
3927 }
3928 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
3929 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
3930 self.emit(Opcode::Drop, &[]);
3931 self.emit(Opcode::Drop, &[]);
3932 self.destructure_rest(rest, decl)?;
3933 }
3934 // The source was only kept for a rest element.
3935 None => self.emit(Opcode::Drop, &[]),
3936 }
3937 Ok(())
3938 }
3939
3940 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
3941 fn destructure_rest(
3942 &mut self,
3943 rest: &RestElement,
3944 decl: Option<VarDeclKind>,
3945 ) -> Result<(), SyntaxError> {
3946 match rest {
3947 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
3948 // `[...a.b] = c` stores into a property.
3949 RestElement::Member(member) => {
3950 let pattern = Pattern {
3951 kind: PatternKind::Member(member.clone()),
3952 span: member.span,
3953 };
3954 self.destructure(&pattern, decl)
3955 }
3956 }
3957 }
3958
3959 /// The source range of a rest element, for error messages.
3960 fn rest_span(rest: &RestElement) -> Span {
3961 match rest {
3962 RestElement::Pattern(pattern) => pattern.span,
3963 RestElement::Member(member) => member.span,
3964 }
3965 }
3966
3967 /// Compile a function declaration and queue it for instantiation at scope
3968 /// entry.
3969 ///
3970 /// A declaration is visible before the statement that declares it, so the
3971 /// code that creates the function object belongs at the top of the enclosing
3972 /// scope, not at the declaration.
3973 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
3974 let name = func.name.as_ref().expect("a declaration has a name");
3975 let function = self.compile_function(func)?;
3976 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
3977 let target = self.hoist_target(&name.name);
3978 let block = self.cur().current_block;
3979 self.state().hoisted.push((block, target, pool_index));
3980 Ok(())
3981 }
3982
3983 /// Where a name lives, for a hoisted declaration.
3984 fn hoist_target(&self, name: &str) -> HoistTarget {
3985 let state = self.cur();
3986 if let Some(index) = state.args.iter().position(|a| a.name == name) {
3987 return HoistTarget::Arg(index as u32);
3988 }
3989 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
3990 return HoistTarget::Loc(index as u32);
3991 }
3992 // A global function declaration is not a slot at all.
3993 HoistTarget::Global(name.to_string())
3994 }
3995
3996 // -- expressions -------------------------------------------------------
3997
3998 /// Compile one expression, recording where its instructions sit.
3999 ///
4000 /// The position is the node's operator when it has one and its first token
4001 /// otherwise, and it is restored on the way out so a parent's own instructions —
4002 /// which are emitted *after* its children — are blamed on the parent. Without the
4003 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4004 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4005 let saved = self.cur().cur_pos;
4006 // Only the node kinds the reference calls `emit_source_pos` for record a position:
4007 // the operator a node exists for, and a variable *read*, which the reference
4008 // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4009 // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4010 // start, a parenthesised group, an anonymous function expression — leaves the
4011 // previous position in place, because a table entry the reference never writes is
4012 // one we must not write either: the instruction that inherits a position (the
4013 // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4014 // report a more recent token than the reference does.
4015 let pos = expr.op_pos.or(match &expr.kind {
4016 ExprKind::Ident(ident) => Some(ident.span.start),
4017 _ => None,
4018 });
4019 match pos {
4020 Some(pos) => self.state().cur_pos = Some(pos),
4021 // A node the reference records nothing for: its own instructions stay
4022 // unpositioned, so they inherit whatever was written last — which is what an
4023 // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4024 // enclosing position instead would blame them on a token the reference has not
4025 // reached yet: a spread's `iterator_open` reports the expression it follows, and
4026 // a template's `to_propkey` the interpolation.
4027 None => self.state().cur_pos = None,
4028 }
4029 // Note a direct `eval` call before compiling it, because the *whole* function
4030 // is affected: an eval can name any binding the function declares, so every one
4031 // of them has to live in a cell for a closure it creates to capture it.
4032 if Self::is_direct_eval(expr) {
4033 // Every enclosing function is affected too: the eval sees the whole scope
4034 // chain, and a closure it creates can capture a binding of any of them.
4035 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
4036 // cell, because the closure the eval builds outlives the loop iteration.
4037 for state in &mut self.stack {
4038 state.has_direct_eval = true;
4039 }
4040 let block = self.cur().current_block;
4041 let in_params = self.cur().in_params;
4042 self.state()
4043 .pending_eval_sites
4044 .push((expr.span, block, in_params));
4045 }
4046 let result = self.expr_inner(expr);
4047 self.state().cur_pos = saved;
4048 result
4049 }
4050
4051 /// Record which bindings are in scope at a direct `eval` call.
4052 ///
4053 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4054 /// resolves names from a string at run time, so the only chance to pin down *which*
4055 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4056 /// its block is the current block, an enclosing one, or the function scope.
4057 fn materialize_eval_sites(&mut self) {
4058 let pending = std::mem::take(&mut self.state().pending_eval_sites);
4059 for (span, site_block, in_params) in pending {
4060 self.resolve_eval_site(span, site_block, in_params);
4061 }
4062 }
4063
4064 /// Resolve the bindings visible at one `eval` call.
4065 fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
4066 /// How near a binding is: function distance first, then block depth, then the
4067 /// later declaration (which shadows the earlier one in the same block).
4068 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4069
4070 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4071 // walked, innermost function first: a direct `eval` sees every enclosing
4072 // function's bindings, and none of them can be resolved at run time because the
4073 // runtime only has names to go on.
4074 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4075 let deepest = self.stack.len() - 1;
4076 for (level, state) in self.stack.iter().enumerate().rev() {
4077 let owner = (deepest - level) as u32;
4078 // The innermost function's block is the one the call sat in, which is not
4079 // the block the compiler is in now; the enclosing functions are still at
4080 // the point where this one was created.
4081 let here = if level == deepest {
4082 site_block
4083 } else {
4084 state.current_block
4085 };
4086 // The chain of live blocks, innermost first, with a depth for each. The walk
4087 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4088 // block can start at source offset zero.
4089 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4090 let mut block = here;
4091 while let Some(parent) = state
4092 .blocks
4093 .iter()
4094 .find(|candidate| candidate.key == block)
4095 .map(|candidate| candidate.parent)
4096 .filter(|parent| *parent != NO_PARENT)
4097 .filter(|parent| parent != &block)
4098 {
4099 live.push((parent, live.len()));
4100 block = parent;
4101 }
4102 let depth_of = |key: u64| {
4103 live.iter()
4104 .find(|(candidate, _)| *candidate == key)
4105 .map(|(_, depth)| *depth)
4106 // The function scope is the outermost depth there is. A binding of a
4107 // block this site is not inside lands here too, which pushes it
4108 // behind every live one — the right answer: it is out of scope.
4109 .unwrap_or(live.len())
4110 };
4111 for (index, arg) in state.args.iter().enumerate() {
4112 bindings.push((
4113 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4114 EvalVisible {
4115 name: arg.name.clone(),
4116 is_arg: true,
4117 index: index as u32,
4118 owner,
4119 },
4120 ));
4121 }
4122 // A parameter list cannot see the body, so a body `var` is not a binding the
4123 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4124 // not let that eval write the body's `c`.
4125 let hides_body = if level == deepest {
4126 site_in_params
4127 } else {
4128 state.created_in_params
4129 };
4130 for (index, var) in state.vars.iter().enumerate() {
4131 let block = state
4132 .var_block
4133 .get(index)
4134 .copied()
4135 .unwrap_or(FUNCTION_SCOPE);
4136 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4137 continue;
4138 }
4139 bindings.push((
4140 (
4141 owner as usize,
4142 depth_of(block),
4143 std::cmp::Reverse(index as u32),
4144 ),
4145 EvalVisible {
4146 name: var.name.clone(),
4147 is_arg: false,
4148 index: index as u32,
4149 owner,
4150 },
4151 ));
4152 }
4153 }
4154 // Innermost function first, then innermost block, then the later declaration
4155 // (which shadows the earlier one within a block).
4156 bindings.sort_by_key(|(priority, _)| *priority);
4157 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4158 self.state().eval_sites.push(EvalSite {
4159 line: span.start.line,
4160 column: span.start.column,
4161 bindings,
4162 });
4163 }
4164
4165 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4166 ///
4167 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4168 /// a bare identifier callee counts.
4169 fn is_direct_eval(expr: &Expr) -> bool {
4170 matches!(
4171 &expr.kind,
4172 ExprKind::Call { callee, .. }
4173 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4174 )
4175 }
4176
4177 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4178 match &expr.kind {
4179 ExprKind::Number(value) => self.push_number(*value),
4180 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4181 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4182 ExprKind::Null => self.emit(Opcode::Null, &[]),
4183 ExprKind::String(text) => self.push_string(text),
4184 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4185 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4186 ExprKind::This => self.this_expression(),
4187 ExprKind::NewTarget => self.new_target_expression(),
4188 ExprKind::Paren(inner) => self.expr(inner)?,
4189 ExprKind::Binary { op, left, right } => {
4190 self.expr(left)?;
4191 self.expr(right)?;
4192 self.emit(binary_opcode(*op), &[]);
4193 }
4194 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4195 ExprKind::Unary {
4196 op: UnaryOp::Minus,
4197 argument,
4198 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4199 let ExprKind::Number(value) = argument.unparen().kind else {
4200 unreachable!("matched above")
4201 };
4202 // The reference folds a negative literal only when the negation is
4203 // exact in the integer range: `-1` becomes `push_minus1` and
4204 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4205 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4206 // `-Infinity`, not `Infinity` — and folding a fraction would change
4207 // which instruction the reference emits.
4208 let negated = -value;
4209 // `-2147483648` is deliberately excluded: its magnitude is one past
4210 // `i32::MAX`, so the reference sends it through the constant pool and
4211 // negates at run time instead.
4212 if value > 0.0
4213 && negated == negated.trunc()
4214 && negated >= -(i32::MAX as f64)
4215 && negated < 0.0
4216 {
4217 self.push_number(negated);
4218 } else {
4219 self.push_number(value);
4220 self.emit(Opcode::Neg, &[]);
4221 }
4222 }
4223 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4224 ExprKind::Conditional { test, cons, alt } => {
4225 let else_label = self.new_label();
4226 let end_label = self.new_label();
4227 self.expr(test)?;
4228 self.emit_jump(Opcode::IfFalse, else_label, &[]);
4229 self.expr(cons)?;
4230 self.emit_jump(Opcode::Goto, end_label, &[]);
4231 self.place_label(else_label);
4232 self.expr(alt)?;
4233 self.place_label(end_label);
4234 }
4235 ExprKind::Assign { op, target, value } => self.assign(*op, target, value)?,
4236 ExprKind::Update {
4237 op,
4238 argument,
4239 prefix,
4240 } => self.update(*op, argument, *prefix)?,
4241 ExprKind::Sequence(items) => {
4242 for (index, item) in items.iter().enumerate() {
4243 self.expr(item)?;
4244 if index + 1 != items.len() {
4245 self.emit(Opcode::Drop, &[]);
4246 }
4247 }
4248 }
4249 ExprKind::Call { .. } => self.chain_link_top(expr)?,
4250 ExprKind::Member { .. } => self.chain_link_top(expr)?,
4251 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4252 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4253 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4254 ExprKind::Template(template) => self.template_literal(template)?,
4255 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4256 ExprKind::New { callee, arguments } => {
4257 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4258 // The `dup` is not redundant: `call_constructor` takes the
4259 // constructor twice, once as the target and once as `new.target`,
4260 // which is what makes `new.target === C` inside the body.
4261 self.expr(callee)?;
4262 self.emit(Opcode::Dup, &[]);
4263 let args = arguments.as_deref().unwrap_or(&[]);
4264 if Self::has_spread(args) {
4265 // `C C array`: the duplicated callee is already both the target
4266 // and `new.target`, so no reordering is needed before `apply 1`.
4267 self.argument_array(args)?;
4268 self.emit(Opcode::Apply, &[Op::Int(1)]);
4269 return Ok(());
4270 }
4271 for argument in args {
4272 self.expr(argument)?;
4273 }
4274 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4275 }
4276 ExprKind::Class(class) => self.class_definition(class, true)?,
4277 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4278 ExprKind::Yield { argument, delegate } => {
4279 self.yield_expression(argument.as_deref(), *delegate)?
4280 }
4281 ExprKind::Await(argument) => self.await_expression(argument)?,
4282 ExprKind::RegExp { pattern, flags } => {
4283 // A literal is compiled *here*, at parse time, not when the line runs. The
4284 // spec is explicit that an invalid pattern is an early error (§12.9.4:
4285 // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
4286 // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
4287 // also validates `\p{…}` names: 163 conformance cases are patterns that have
4288 // to be rejected before any code runs.
4289 //
4290 // This is the whole reason the engine lives in its own crate rather than
4291 // inside `quickjs-pure`: the compiler could not depend on the interpreter
4292 // (`pure` depends on `compile`), but both need this.
4293 // The lexer already rejected an unknown or repeated flag, so an unparsable
4294 // flag string here would be a bug in the lexer rather than in the script;
4295 // fall back to the default flags instead of inventing a second message.
4296 let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
4297 let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
4298 SyntaxError::new(
4299 format!("invalid regular expression: {}", error.message),
4300 expr.span,
4301 )
4302 })?;
4303 // The tree is thrown away and rebuilt when the literal first runs: keeping it
4304 // would mean serialising the syntax tree into the function's constant pool,
4305 // and a literal is created once per evaluation of its expression anyway.
4306 let _ = parsed;
4307 // The pattern and its flags travel as two string constants; `regexp` builds
4308 // the object. A dedicated opcode (rather than a call to the constructor) is
4309 // what the reference does too, so that a literal never goes through the
4310 // public `RegExp` function and its string-coercion rules.
4311 self.push_string(pattern);
4312 self.push_string(flags);
4313 self.emit(Opcode::Regexp, &[]);
4314 }
4315 ExprKind::Arrow(func) => {
4316 let function = self.compile_function(func)?;
4317 let index = self.push_constant(Constant::Function(Box::new(function)));
4318 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4319 }
4320 ExprKind::Function(func) => {
4321 let function = self.compile_function_with_name(func, true)?;
4322 let index = self.push_constant(Constant::Function(Box::new(function)));
4323 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4324 }
4325 // `import.meta`: the host fills a per-module object at link time.
4326 ExprKind::ImportMeta => {
4327 self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
4328 }
4329 // `import("x")` compiles to a two-slot push followed by one opcode: the
4330 // specifier, then the options object (`undefined` here, since this compiler
4331 // does not accept the second argument yet).
4332 ExprKind::ImportCall(specifier) => {
4333 self.expr(specifier)?;
4334 self.emit(Opcode::Undefined, &[]);
4335 self.emit(Opcode::Import, &[]);
4336 }
4337 ExprKind::PrivateIn { name, object } => {
4338 // `#x in o`: the object, then the binding, then one opcode which decides what
4339 // to do with the second operand. A field's binding holds a symbol and the
4340 // answer is an own-property test; a method's holds a function and the answer
4341 // is a brand check — both live in `private_in`, so the compiler emits the
4342 // same instruction for either.
4343 self.expr(object)?;
4344 self.emit_var(VarAction::Get, &format!("#{}", name.name));
4345 self.emit(Opcode::PrivateIn, &[]);
4346 }
4347 _ => {
4348 return Err(SyntaxError::new(
4349 "this expression form is not supported by the compiler yet",
4350 expr.span,
4351 ));
4352 }
4353 }
4354 Ok(())
4355 }
4356
4357 /// Build one array holding the evaluated call arguments, which is how a call
4358 /// containing a spread is compiled: the reference does the same, building the
4359 /// list on the stack and handing it to `apply`.
4360 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4361 let elements: Vec<Option<ArrayElement>> = arguments
4362 .iter()
4363 .map(|argument| match &argument.unparen().kind {
4364 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
4365 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
4366 })
4367 .collect();
4368 self.array_literal(&elements, Span::default())
4369 }
4370
4371 /// Whether any argument is a spread, which is what selects the `apply` form.
4372 fn has_spread(arguments: &[Expr]) -> bool {
4373 arguments
4374 .iter()
4375 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
4376 }
4377
4378 /// Compile `a${x}b`.
4379 ///
4380 /// A template is a `+` chain built left to right: the leading chunk (or an empty
4381 /// string when the template starts with a substitution), then for each
4382 /// substitution its value, `to_propkey` and `add`, then the following chunk when
4383 /// it is not empty. `to_propkey` is what makes a number or object substitute the
4384 /// way `ToString` would while leaving the result a string for `add` to
4385 /// concatenate.
4386 ///
4387 /// The chunk is an atom rather than a constant-pool string, because a non-empty
4388 /// chunk always lands where a value is pushed and `push_atom_value` is the
4389 /// instruction the reference uses for it; the empty first chunk has its own
4390 /// zero-byte form.
4391 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
4392 let first = template.quasis.first();
4393 match first.and_then(|quasi| quasi.cooked.clone()) {
4394 Some(text) if !text.is_empty() => {
4395 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(&text))]);
4396 }
4397 // Either the template begins with a substitution, or the chunk is
4398 // empty — in both cases the chain needs a string to start from.
4399 _ => self.emit(Opcode::PushEmptyString, &[]),
4400 }
4401 for (index, expression) in template.expressions.iter().enumerate() {
4402 self.expr(expression)?;
4403 self.emit(Opcode::ToPropkey, &[]);
4404 self.emit(Opcode::Add, &[]);
4405 if let Some(text) = template
4406 .quasis
4407 .get(index + 1)
4408 .and_then(|quasi| quasi.cooked.clone())
4409 && !text.is_empty()
4410 {
4411 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(&text))]);
4412 self.emit(Opcode::Add, &[]);
4413 }
4414 }
4415 Ok(())
4416 }
4417
4418 /// Compile an object literal.
4419 ///
4420 /// The object is built in place: `object` pushes it, and each property leaves it
4421 /// on the stack with one field more, so no temporary is needed and later
4422 /// properties can overwrite earlier ones.
4423 ///
4424 /// The instruction depends on *how* the property was written, not on what kind
4425 /// of value it holds:
4426 ///
4427 /// | source | instruction |
4428 /// |---|---|
4429 /// | `{ a: v }` | `define_field a` |
4430 /// | `{ __proto__: v }` | `set_proto` |
4431 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4432 /// | `{ m() {} }` | `define_method m,4` |
4433 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4434 /// | `{ [k]() {} }` | `define_method_computed 4` |
4435 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4436 ///
4437 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
4438 /// key itself, which is why the trailing `drop` is absent there too.
4439 /// `tag`…``: a call whose first argument is the call site's template object.
4440 ///
4441 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
4442 /// array beside it, so `String.raw` can read the source text back. It is a constant
4443 /// because its contents never change; the reference builds one per call site and
4444 /// reuses it, while this builds one per evaluation, which only `tag` code that
4445 /// compares template objects across calls could tell apart.
4446 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
4447 let cooked = quasi
4448 .quasis
4449 .iter()
4450 .map(|chunk| chunk.cooked.clone())
4451 .collect();
4452 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
4453 let index = self.push_constant(Constant::Template { cooked, raw });
4454 let count = quasi.expressions.len() + 1;
4455 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
4456 if let ExprKind::Member {
4457 object, property, ..
4458 } = &tag.unparen().kind
4459 {
4460 self.expr(object)?;
4461 match property {
4462 MemberProp::Ident(name) => {
4463 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
4464 }
4465 MemberProp::Computed(key) => {
4466 self.expr(key)?;
4467 self.emit(Opcode::GetArrayEl2, &[]);
4468 }
4469 MemberProp::Private(name) => {
4470 let binding = format!("#{}", name.name);
4471 let (kind, _) = self.private_use(&binding, tag.span)?;
4472 self.private_callee(&binding, kind)?;
4473 }
4474 }
4475 self.emit(Opcode::PushConst, &[Op::Const(index)]);
4476 for expression in &quasi.expressions {
4477 self.expr(expression)?;
4478 }
4479 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
4480 return Ok(());
4481 }
4482 self.expr(tag)?;
4483 self.emit(Opcode::PushConst, &[Op::Const(index)]);
4484 for expression in &quasi.expressions {
4485 self.expr(expression)?;
4486 }
4487 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
4488 Ok(())
4489 }
4490
4491 fn object_literal(
4492 &mut self,
4493 properties: &[ObjectProperty],
4494 span: Span,
4495 ) -> Result<(), SyntaxError> {
4496 self.emit(Opcode::Object, &[]);
4497 for property in properties {
4498 match property {
4499 ObjectProperty::Spread(value) => {
4500 // `copy_data_properties` takes the target, the source and an
4501 // exclusion list; a literal `null` means "exclude nothing".
4502 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
4503 // exclusion list by stack offset.
4504 self.expr(spread_argument(value))?;
4505 self.emit(Opcode::Null, &[]);
4506 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4507 self.emit(Opcode::Drop, &[]);
4508 self.emit(Opcode::Drop, &[]);
4509 }
4510 ObjectProperty::Property {
4511 key,
4512 value,
4513 kind,
4514 shorthand,
4515 span: property_span,
4516 } => match key {
4517 PropName::Computed(key_expr) => {
4518 self.expr(key_expr)?;
4519 match kind {
4520 PropertyKind::Value => {
4521 self.emit(Opcode::ToPropkey, &[]);
4522 self.expr(value)?;
4523 self.set_name_if_anonymous_computed(value);
4524 self.emit(Opcode::DefineArrayEl, &[]);
4525 // `define_array_el` leaves the object and the key;
4526 // the key is no longer needed.
4527 self.emit(Opcode::Drop, &[]);
4528 }
4529 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4530 self.emit_method_function(value)?;
4531 self.emit(
4532 Opcode::DefineMethodComputed,
4533 &[Op::Int(define_method_flags(*kind))],
4534 );
4535 }
4536 }
4537 }
4538 PropName::Literal(key) => {
4539 let name = self.property_key_text(key, *property_span)?;
4540 match kind {
4541 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4542 self.emit_method_function(value)?;
4543 self.emit(
4544 Opcode::DefineMethod,
4545 &[
4546 Op::Atom(Atom::from_text(&name)),
4547 Op::Int(define_method_flags(*kind)),
4548 ],
4549 );
4550 }
4551 PropertyKind::Value => {
4552 self.expr(value)?;
4553 // `{__proto__: x}` sets the prototype instead of
4554 // creating a property; the shorthand `{__proto__}`
4555 // is an ordinary property and does not.
4556 if name == "__proto__" && !shorthand {
4557 self.emit(Opcode::SetProto, &[]);
4558 } else {
4559 self.set_name_if_anonymous(value, &name);
4560 self.emit(
4561 Opcode::DefineField,
4562 &[Op::Atom(Atom::from_text(&name))],
4563 );
4564 }
4565 }
4566 }
4567 }
4568 PropName::Private(_) => {
4569 return Err(SyntaxError::new(
4570 "private names are not valid in object literals",
4571 *property_span,
4572 ));
4573 }
4574 },
4575 }
4576 }
4577 let _ = span;
4578 Ok(())
4579 }
4580
4581 /// Emit the function a method/accessor property defines.
4582 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
4583 self.expr(value)
4584 }
4585
4586 /// The name a literal property key contributes.
4587 ///
4588 /// String keys are used as written. A numeric key is converted the way
4589 /// `ToString` would convert it, because the atom is made from that spelling:
4590 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
4591 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<String, SyntaxError> {
4592 match key {
4593 PropKey::Str(text) => Ok(text.clone()),
4594 PropKey::Num(value) => numeric_key_text(*value, span),
4595 }
4596 }
4597
4598 /// Compile an optional chain.
4599 ///
4600 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
4601 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
4602 /// `undefined`. So the chain is compiled with one end label and every guard
4603 /// jumps to it. The parser hands us the extent of that spine as an
4604 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
4605 /// exactly the scope the label has to cover.
4606 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
4607 let end = self.new_label();
4608 self.chain_link(inner, end)?;
4609 self.place_label(end);
4610 Ok(())
4611 }
4612
4613 /// A member access or call reached from outside any optional chain.
4614 ///
4615 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
4616 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
4617 /// still created because [`Self::chain_link`] takes it, and placing it at the
4618 /// end is a no-op that keeps a single code path.
4619 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4620 let end = self.new_label();
4621 self.chain_link(expr, end)?;
4622 self.place_label(end);
4623 Ok(())
4624 }
4625
4626 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
4627 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
4628 match &expr.kind {
4629 ExprKind::Member {
4630 object,
4631 property,
4632 optional,
4633 } => {
4634 // `super.x` is not a lookup on a value: it starts at the home object's
4635 // prototype and keeps `this` as the receiver, so it cannot go through
4636 // `chain_link` and the ordinary field read.
4637 if matches!(object.unparen().kind, ExprKind::SuperProp) {
4638 self.super_base();
4639 match property {
4640 MemberProp::Ident(name) => self.emit(
4641 Opcode::PushAtomValue,
4642 &[Op::Atom(Atom::from_text(&name.name))],
4643 ),
4644 MemberProp::Computed(index) => self.expr(index)?,
4645 MemberProp::Private(_) => {
4646 return Err(SyntaxError::new(
4647 "private fields are not supported by the compiler yet",
4648 expr.span,
4649 ));
4650 }
4651 }
4652 self.emit(Opcode::GetSuperValue, &[]);
4653 return Ok(());
4654 }
4655 self.chain_link(object, end)?;
4656 if *optional {
4657 self.optional_guard(end);
4658 }
4659 match property {
4660 // `.length` has its own opcode. The reference emits it for every
4661 // object, not just arrays, so a name-based rule is right and
4662 // cheaper than the generic field read.
4663 MemberProp::Ident(name) if name.name == "length" => {
4664 self.emit(Opcode::GetLength, &[]);
4665 }
4666 MemberProp::Ident(name) => {
4667 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
4668 }
4669 MemberProp::Computed(index) => {
4670 self.expr(index)?;
4671 self.emit(Opcode::GetArrayEl, &[]);
4672 }
4673 MemberProp::Private(name) => {
4674 // The binding comes from the class scope, so a read from outside the
4675 // class cannot name it at all. `?.` checks the object, not the field:
4676 // `o?.#x` guards on `o` being nullish.
4677 let binding = format!("#{}", name.name);
4678 let (kind, _) = self.private_use(&binding, expr.span)?;
4679 self.private_load(&binding, kind, expr.span)?;
4680 }
4681 }
4682 Ok(())
4683 }
4684 ExprKind::Call {
4685 callee,
4686 arguments,
4687 optional,
4688 } => {
4689 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
4690 // cannot: it reads the function and then calls it with no
4691 // receiver at all. The reference's answer is to keep the object
4692 // under the function value — `get_field2` reads a field and leaves
4693 // its base in place — and to use `call_method`, which takes the
4694 // receiver from the stack. Missing this does not just cost an
4695 // instruction, it loses the `this` binding.
4696 if let ExprKind::Member {
4697 object,
4698 property,
4699 optional: member_optional,
4700 } = &callee.unparen().kind
4701 {
4702 // `super.m()` reads the method off the home object's prototype but
4703 // calls it with `this`, so the receiver goes under the read instead of
4704 // being replaced by it.
4705 if matches!(object.unparen().kind, ExprKind::SuperProp) {
4706 self.super_base();
4707 match property {
4708 MemberProp::Ident(name) => self.emit(
4709 Opcode::PushAtomValue,
4710 &[Op::Atom(Atom::from_text(&name.name))],
4711 ),
4712 MemberProp::Computed(index) => self.expr(index)?,
4713 MemberProp::Private(_) => {
4714 return Err(SyntaxError::new(
4715 "private fields are not supported by the compiler yet",
4716 expr.span,
4717 ));
4718 }
4719 }
4720 // The two-output form would drop the receiver; this one replaces
4721 // the prototype and the key, leaving `this` underneath.
4722 self.emit(Opcode::GetArrayEl, &[]);
4723 if Self::has_spread(arguments) {
4724 self.argument_array(arguments)?;
4725 self.emit(Opcode::Perm3, &[]);
4726 self.emit(Opcode::Apply, &[Op::Int(0)]);
4727 return Ok(());
4728 }
4729 for argument in arguments {
4730 self.expr(argument)?;
4731 }
4732 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4733 return Ok(());
4734 }
4735 self.chain_link(object, end)?;
4736 if *member_optional {
4737 self.optional_guard(end);
4738 }
4739 match property {
4740 MemberProp::Ident(name) => {
4741 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4742 }
4743 MemberProp::Computed(index) => {
4744 self.expr(index)?;
4745 // The key is not needed after the read, so this is the
4746 // two-output form: object, value.
4747 self.emit(Opcode::GetArrayEl2, &[]);
4748 }
4749 MemberProp::Private(name) => {
4750 // The receiver is already under the callee, which is exactly the
4751 // shape `call_method` and `apply` want — so nothing is dropped.
4752 let binding = format!("#{}", name.name);
4753 let (kind, _) = self.private_use(&binding, expr.span)?;
4754 self.private_callee(&binding, kind)?;
4755 }
4756 }
4757 if Self::has_spread(arguments) {
4758 // Stack is `obj func`; the array goes on top, then `perm3`
4759 // reorders to the `func this array` that `apply` wants.
4760 self.argument_array(arguments)?;
4761 self.emit(Opcode::Perm3, &[]);
4762 self.emit(Opcode::Apply, &[Op::Int(0)]);
4763 return Ok(());
4764 }
4765 for argument in arguments {
4766 self.expr(argument)?;
4767 }
4768 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4769 return Ok(());
4770 }
4771 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
4772 // with `get_field2` so the base stays under it, and on the short-circuit
4773 // path pushes an extra `undefined` as a placeholder receiver — the call
4774 // then throws, which is what calling a missing optional chain should do.
4775 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
4776 && let ExprKind::Member {
4777 object,
4778 property,
4779 optional: member_optional,
4780 } = &inner.unparen().kind
4781 {
4782 let call = self.new_label();
4783 // A guard target of its own: the outer `end` skips the whole
4784 // expression, and a short-circuited receiver still has to reach the
4785 // call so that calling it throws.
4786 let short = self.new_label();
4787 self.chain_link(object, end)?;
4788 if *member_optional {
4789 self.optional_guard(short);
4790 }
4791 match property {
4792 MemberProp::Ident(name) => {
4793 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4794 }
4795 MemberProp::Computed(index) => {
4796 self.expr(index)?;
4797 self.emit(Opcode::GetArrayEl2, &[]);
4798 }
4799 MemberProp::Private(name) => {
4800 let binding = format!("#{}", name.name);
4801 let (kind, _) = self.private_use(&binding, expr.span)?;
4802 self.private_callee(&binding, kind)?;
4803 }
4804 }
4805 self.emit_jump(Opcode::Goto, call, &[]);
4806 self.place_label(short);
4807 self.emit(Opcode::Undefined, &[]);
4808 self.place_label(call);
4809 if Self::has_spread(arguments) {
4810 self.argument_array(arguments)?;
4811 self.emit(Opcode::Perm3, &[]);
4812 self.emit(Opcode::Apply, &[Op::Int(0)]);
4813 return Ok(());
4814 }
4815 for argument in arguments {
4816 self.expr(argument)?;
4817 }
4818 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4819 return Ok(());
4820 }
4821 self.chain_link(callee, end)?;
4822 if *optional {
4823 self.optional_guard(end);
4824 }
4825 if Self::has_spread(arguments) {
4826 // `func array -> func undefined array`, which is the plain-call
4827 // form of `apply`: the receiver is `undefined`.
4828 self.argument_array(arguments)?;
4829 self.emit(Opcode::Undefined, &[]);
4830 self.emit(Opcode::Swap, &[]);
4831 self.emit(Opcode::Apply, &[Op::Int(0)]);
4832 return Ok(());
4833 }
4834 for argument in arguments {
4835 self.expr(argument)?;
4836 }
4837 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
4838 Ok(())
4839 }
4840 _ => self.expr(expr),
4841 }
4842 }
4843
4844 /// Compile `expr` as a tail call when it is one, reporting whether it was.
4845 ///
4846 /// `tail_call` reuses the current frame instead of pushing a new one, so a
4847 /// tail-recursive function runs in constant stack space. It also has to be the
4848 /// *last* thing the function does, which is why only a `return` reaches here.
4849 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
4850 let ExprKind::Call {
4851 callee,
4852 arguments,
4853 optional: false,
4854 } = &expr.unparen().kind
4855 else {
4856 return Ok(false);
4857 };
4858 let end = self.new_label();
4859 if let ExprKind::Member {
4860 object,
4861 property,
4862 optional: false,
4863 } = &callee.unparen().kind
4864 {
4865 // `super.m()` in tail position is still an ordinary method call with `this`
4866 // as the receiver; only the read of the method differs.
4867 if matches!(object.unparen().kind, ExprKind::SuperProp) {
4868 self.super_base();
4869 match property {
4870 MemberProp::Ident(name) => self.emit(
4871 Opcode::PushAtomValue,
4872 &[Op::Atom(Atom::from_text(&name.name))],
4873 ),
4874 MemberProp::Computed(index) => self.expr(index)?,
4875 MemberProp::Private(_) => return Ok(false),
4876 }
4877 self.emit(Opcode::GetArrayEl, &[]);
4878 for argument in arguments {
4879 self.expr(argument)?;
4880 }
4881 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
4882 self.place_label(end);
4883 return Ok(true);
4884 }
4885 self.chain_link(object, end)?;
4886 match property {
4887 MemberProp::Ident(name) => {
4888 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4889 }
4890 MemberProp::Computed(index) => {
4891 self.expr(index)?;
4892 self.emit(Opcode::GetArrayEl2, &[]);
4893 }
4894 MemberProp::Private(_) => return Ok(false),
4895 }
4896 for argument in arguments {
4897 self.expr(argument)?;
4898 }
4899 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
4900 self.place_label(end);
4901 return Ok(true);
4902 }
4903 self.chain_link(callee, end)?;
4904 for argument in arguments {
4905 self.expr(argument)?;
4906 }
4907 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
4908 self.place_label(end);
4909 Ok(true)
4910 }
4911
4912 /// The `?.` guard: keep the value if it is neither null nor undefined,
4913 /// otherwise replace it with `undefined` and leave the whole chain.
4914 fn optional_guard(&mut self, end: Label) {
4915 let cont = self.new_label();
4916 self.emit(Opcode::Dup, &[]);
4917 self.emit(Opcode::IsUndefinedOrNull, &[]);
4918 self.emit_jump(Opcode::IfFalse, cont, &[]);
4919 self.emit(Opcode::Drop, &[]);
4920 self.emit(Opcode::Undefined, &[]);
4921 self.emit_jump(Opcode::Goto, end, &[]);
4922 self.place_label(cont);
4923 }
4924
4925 fn push_number(&mut self, value: f64) {
4926 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
4927 // goes into the constant pool.
4928 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
4929 let int = value as i32;
4930 if (-1..=7).contains(&int) {
4931 self.emit(Opcode::PushI32, &[Op::Int(int)]);
4932 return;
4933 }
4934 if (-128..=127).contains(&int) {
4935 self.emit(Opcode::PushI8, &[Op::Int(int)]);
4936 return;
4937 }
4938 if (-32768..=32767).contains(&int) {
4939 self.emit(Opcode::PushI16, &[Op::Int(int)]);
4940 return;
4941 }
4942 self.emit(Opcode::PushI32, &[Op::Int(int)]);
4943 return;
4944 }
4945 let index = self.push_constant(Constant::Number(value));
4946 self.emit(Opcode::PushConst, &[Op::Const(index)]);
4947 }
4948
4949 /// Push a `BigInt` literal.
4950 ///
4951 /// A value that fits an `i32` uses the immediate form, which is what the reference
4952 /// emits too; anything larger goes into the constant pool, because the operand of
4953 /// `push_bigint` is only four bytes wide.
4954 fn push_bigint(&mut self, digits: &str, radix: u32) {
4955 if radix == 10
4956 && let Ok(value) = digits.parse::<i64>()
4957 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
4958 {
4959 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
4960 return;
4961 }
4962 let index = self.push_constant(Constant::BigInt {
4963 digits: digits.to_string(),
4964 radix,
4965 });
4966 self.emit(Opcode::PushConst, &[Op::Const(index)]);
4967 }
4968
4969 fn push_string(&mut self, text: &str) {
4970 if text.is_empty() {
4971 self.emit(Opcode::PushEmptyString, &[]);
4972 return;
4973 }
4974 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(text))]);
4975 }
4976
4977 /// Name an anonymous function from the binding it is assigned to.
4978 ///
4979 /// `var f = function(){}` produces a function whose `name` is `f`, which the
4980 /// runtime cannot know without being told: the function object is created
4981 /// before the store. `set_name` carries the name across.
4982 fn set_name_if_anonymous(&mut self, value: &Expr, name: &str) {
4983 if value.is_anonymous_function_definition() {
4984 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(name))]);
4985 }
4986 }
4987
4988 /// The same, for a computed key: the name comes from the value on the stack
4989 /// rather than from an atom, so a different instruction carries it.
4990 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
4991 if value.is_anonymous_function_definition() {
4992 self.emit(Opcode::SetNameComputed, &[]);
4993 }
4994 }
4995
4996 /// Compile a function body that exists only in the compiler's head — a class's
4997 /// implicit constructor or its field initialiser.
4998 ///
4999 /// Everything structural is the same as a written function: a fresh `FnState`, its
5000 /// own body block, and resolution while the frame is still on the stack. Only the
5001 /// statements differ.
5002 fn compile_synthetic_function(
5003 &mut self,
5004 name: &str,
5005 strict: bool,
5006 span: Span,
5007 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5008 ) -> Result<CompiledFunction, SyntaxError> {
5009 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5010 state.strict = strict;
5011 state.created_in_block = self.cur().current_block;
5012 state.with_names = self.cur().with_names.clone();
5013 state.line = span.start.line;
5014 state.column = span.start.column;
5015 let depth = self.stack.len();
5016 self.stack.push(state);
5017 let body_key = span.start.offset as u64;
5018 self.push_block(body_key, NO_PARENT);
5019 self.state().body_block = body_key;
5020 let result = (|| {
5021 self.emit_scope_enter(body_key);
5022 body(self)?;
5023 if self.end_is_reachable() {
5024 self.emit(Opcode::ReturnUndef, &[]);
5025 }
5026 Ok(())
5027 })();
5028 if result.is_err() {
5029 self.stack.truncate(depth);
5030 return result.map(|()| unreachable!());
5031 }
5032 Ok(self.finish_current())
5033 }
5034
5035 /// The implicit return of a class constructor.
5036 ///
5037 /// A constructor that falls off the end initialises its instance fields first, and a
5038 /// derived one returns `this` — which is what makes `new D()` the object `super()`
5039 /// built rather than `undefined`.
5040 fn emit_class_constructor_tail(&mut self) {
5041 match self.cur().ctor_kind {
5042 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5043 // Nothing to install: a base constructor did it in its prologue and a derived
5044 // one at each `super()` site, which is where `this` first exists.
5045 CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5046 CtorKind::Derived => {
5047 // `get_loc_check` rather than `get_loc`: reaching the end without ever
5048 // running `super()` is a ReferenceError, not `undefined`.
5049 self.emit_var(VarAction::Get, "this");
5050 self.emit(Opcode::Return, &[]);
5051 }
5052 }
5053 }
5054
5055 /// `yield expr` / `yield* expr`.
5056 ///
5057 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5058 /// it to the caller and parks the frame. On resume the stack holds the value the
5059 /// caller passed *and* a "magic" number saying which method resumed it — `next`
5060 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5061 /// `if_false <continue>` asks whether this was an ordinary `next`:
5062 ///
5063 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5064 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5065 /// and uses the value sitting under the magic number.
5066 ///
5067 /// A `throw` never reaches here: the interpreter unwinds instead (see
5068 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5069 fn yield_expression(
5070 &mut self,
5071 argument: Option<&Expr>,
5072 delegate: bool,
5073 ) -> Result<(), SyntaxError> {
5074 if delegate {
5075 return self.yield_star(argument);
5076 }
5077 // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5078 // does the same for the `return(v)` that can resume it — which is why an async
5079 // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5080 // generator's is just `yield`.
5081 let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5082 match argument {
5083 Some(value) => self.expr(value)?,
5084 None => self.emit(Opcode::Undefined, &[]),
5085 }
5086 if is_async {
5087 self.emit(Opcode::Await, &[]);
5088 self.state().has_await = true;
5089 }
5090 self.emit(Opcode::Yield, &[]);
5091 let resume = self.new_label();
5092 self.emit_jump(Opcode::IfFalse, resume, &[]);
5093 // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5094 // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5095 // finished the generator and never ran the `finally`.
5096 if is_async {
5097 self.emit(Opcode::Await, &[]);
5098 }
5099 self.emit_unwind_for_return(true);
5100 self.emit(Opcode::ReturnAsync, &[]);
5101 self.place_label(resume);
5102 // Nothing is emitted here: the value the caller passed to `next` *is* the value
5103 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5104 // it through the ordinary expression-statement discard.
5105 Ok(())
5106 }
5107
5108 /// `yield* iterable`.
5109 ///
5110 /// The shape is the reference's, and it is a fall-through chain rather than a
5111 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5112 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5113 /// the inner iterator and finishes, `throw` forwards the exception into it and
5114 /// continues only if it has a `throw` method.
5115 ///
5116 /// The stack is `iter next catch value` throughout, `catch` being the offset
5117 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5118 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5119 match argument {
5120 Some(value) => self.expr(value)?,
5121 // The parser rejects a bare `yield*`, so this is unreachable in practice.
5122 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5123 }
5124 // `for await of` is the same protocol as `for of` with two differences that matter
5125 // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5126 // every `next()` result is a promise the delegate has to await.
5127 let is_async = self.cur().kind.is_async();
5128 self.emit(
5129 if is_async {
5130 Opcode::ForAwaitOfStart
5131 } else {
5132 Opcode::ForOfStart
5133 },
5134 &[],
5135 );
5136 self.emit(Opcode::Drop, &[]);
5137 self.emit(Opcode::Undefined, &[]);
5138 self.emit(Opcode::Undefined, &[]);
5139 let next = self.new_label();
5140 let resume = self.new_label();
5141 let finished = self.new_label();
5142 let rethrow = self.new_label();
5143 let throw_no_method = self.new_label();
5144 let done = self.new_label();
5145 self.place_label(next);
5146 self.emit(Opcode::IteratorNext, &[]);
5147 if is_async {
5148 self.emit(Opcode::Await, &[]);
5149 self.state().has_await = true;
5150 }
5151 self.emit(Opcode::IteratorCheckObject, &[]);
5152 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5153 self.emit_jump(Opcode::IfTrue, done, &[]);
5154 // The suspension. `resume` is both the label the return path jumps back to in order
5155 // to yield one more value and where the caller's answer arrives, as the value
5156 // followed by the magic number.
5157 //
5158 // The two forms differ in what they hand the suspension: `yield_star` takes the
5159 // result object itself, `async_yield_star` takes `.value`, because an async
5160 // generator awaits and re-wraps whatever it yields.
5161 self.place_label(resume);
5162 if is_async {
5163 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5164 self.emit(Opcode::AsyncYieldStar, &[]);
5165 } else {
5166 self.emit(Opcode::YieldStar, &[]);
5167 }
5168 self.emit(Opcode::Dup, &[]);
5169 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5170 self.emit(Opcode::Drop, &[]);
5171 self.emit_jump(Opcode::Goto, next, &[]);
5172
5173 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5174 self.place_label(rethrow);
5175 self.emit(Opcode::PushI32, &[Op::Int(2)]);
5176 self.emit(Opcode::StrictEq, &[]);
5177 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5178 // A `return` closes the inner iterator; if it had none, the delegate simply
5179 // finishes with the requested value. In an async generator both the call and its
5180 // result are awaited, because the inner `return` may itself be async.
5181 if is_async {
5182 self.emit(Opcode::Await, &[]);
5183 }
5184 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5185 self.emit_jump(Opcode::IfTrue, finished, &[]);
5186 if is_async {
5187 self.emit(Opcode::Await, &[]);
5188 }
5189 self.emit(Opcode::IteratorCheckObject, &[]);
5190 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5191 self.emit_jump(Opcode::IfFalse, resume, &[]);
5192 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5193 self.place_label(finished);
5194 self.emit(Opcode::Nip, &[]);
5195 self.emit(Opcode::Nip, &[]);
5196 self.emit(Opcode::Nip, &[]);
5197 // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5198 // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5199 // awaits the value in an async generator and then runs the same `finally`/iterator
5200 // unwinding a written `return` would. Skipping the unwinding made
5201 // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5202 if is_async {
5203 self.emit(Opcode::Await, &[]);
5204 }
5205 self.emit_unwind_for_return(true);
5206 self.emit(Opcode::ReturnAsync, &[]);
5207
5208 // `throw(e)`: forward it into the inner iterator.
5209 self.place_label(throw_no_method);
5210 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5211 let no_throw = self.new_label();
5212 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5213 if is_async {
5214 self.emit(Opcode::Await, &[]);
5215 }
5216 self.emit(Opcode::IteratorCheckObject, &[]);
5217 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5218 self.emit_jump(Opcode::IfFalse, resume, &[]);
5219 self.emit_jump(Opcode::Goto, done, &[]);
5220 // No `throw` method: close the iterator, then report the spec's TypeError. The
5221 // `if_true` before the `await` is the reference's shape — the flag it consumes is
5222 // what `iterator_call` leaves behind, and a close that *did* find no `return`
5223 // method has nothing to await.
5224 self.place_label(no_throw);
5225 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5226 let no_close = self.new_label();
5227 self.emit_jump(Opcode::IfTrue, no_close, &[]);
5228 if is_async {
5229 self.emit(Opcode::Await, &[]);
5230 }
5231 self.place_label(no_close);
5232 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5233
5234 // The inner iterator finished: the delegate's value is the `yield*` expression's
5235 // value, so it is left on the stack for whatever consumes it.
5236 self.place_label(done);
5237 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5238 self.emit(Opcode::Nip, &[]);
5239 self.emit(Opcode::Nip, &[]);
5240 self.emit(Opcode::Nip, &[]);
5241 Ok(())
5242 }
5243
5244 /// `await expr`: exactly one instruction.
5245 ///
5246 /// No resume-magic branch follows it. The reference's `await` leaves a single value
5247 /// on the stack and completion is signalled by the `return_async` at the end of the
5248 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5249 /// reference never emits, and a `for await` loop — which reaches `await` through the
5250 /// same opcode — would then spill a value the loop's unpacking does not expect.
5251 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5252 self.expr(argument)?;
5253 self.emit(Opcode::Await, &[]);
5254 self.state().has_await = true;
5255 Ok(())
5256 }
5257
5258 /// The `super` base: the receiver followed by the home object's prototype.
5259 ///
5260 /// Everything `super` does needs both. A *read* starts at the prototype but reports
5261 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5262 /// prototype but calls it with the receiver.
5263 fn super_base(&mut self) {
5264 self.this_expression();
5265 self.home_object();
5266 self.emit(Opcode::GetSuper, &[]);
5267 }
5268
5269 /// `[[HomeObject]]` as `super` sees it.
5270 ///
5271 /// A method, a constructor and a field initialiser each carry one — `set_home_object`
5272 /// put it there — so for them the special object *is* the answer. An arrow and a
5273 /// static block have none: they read the enclosing function's, which has to be
5274 /// materialised into a local, exactly as `this` is for an arrow.
5275 ///
5276 /// The name matches what the reference stores, so the disassembly agrees; it is not a
5277 /// name any program can write.
5278 fn home_object(&mut self) {
5279 if !self.cur().is_arrow {
5280 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
5281 return;
5282 }
5283 if let Some(target) = self.enclosing_function() {
5284 self.state_at(target).needs_home_object_local = true;
5285 self.declare_at(target, HOME_OBJECT);
5286 }
5287 self.emit_var(VarAction::Get, HOME_OBJECT);
5288 }
5289
5290 /// `super(args)`: construct the parent class and adopt the result as `this`.
5291 ///
5292 /// The parent is the prototype of the constructor that is running, which is exactly
5293 /// what `extends` set up. `new.target` is passed through unchanged so that
5294 /// `new.target` inside the parent is the class actually being constructed.
5295 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5296 self.active_func_expression();
5297 self.emit(Opcode::GetSuper, &[]);
5298 self.new_target_expression();
5299 if Self::has_spread(arguments) {
5300 self.argument_array(arguments)?;
5301 self.emit(Opcode::Apply, &[Op::Int(1)]);
5302 } else {
5303 for argument in arguments {
5304 self.expr(argument)?;
5305 }
5306 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
5307 }
5308 // The value stays on the stack: `super()` is an expression, and a derived
5309 // constructor's `this` may only be initialised once.
5310 self.emit(Opcode::Dup, &[]);
5311 self.emit_var(VarAction::PutInitChecked, "this");
5312 // Instance fields are installed here, not at the top of the body: a derived
5313 // constructor has no `this` to install them on until `super()` returns. The
5314 // reference emits the same call at every `super()` site.
5315 self.call_field_initialiser();
5316 Ok(())
5317 }
5318
5319 /// `this` as a local, which every class constructor and field initialiser needs.
5320 ///
5321 /// The reference materialises the receiver into a local rather than reading
5322 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
5323 /// and a field initialiser has to see the final value.
5324 fn begin_this_local(&mut self) {
5325 self.declare_hidden_local("this", VarKind::Normal);
5326 self.emit(Opcode::PushThis, &[]);
5327 self.emit_var(VarAction::Put, "this");
5328 // The store is already at the top of the body, so `provide_this_local` has
5329 // nothing left to prepend. Without this the initialiser ended up with
5330 // `push_this; put_loc0 this` twice whenever the class also held a field
5331 // initialiser whose body read `this` through an arrow.
5332 self.state().has_this_prologue = true;
5333 }
5334
5335 /// Compile a constructor the class wrote.
5336 ///
5337 /// The flags have to be in place before the body is compiled, but
5338 /// `compile_function_with_name` creates its own state — so the caller's state is
5339 /// marked instead and the new one inherits it. That is the same trick the parameter
5340 /// prologue uses, and it keeps one code path for both.
5341 fn compile_class_constructor(
5342 &mut self,
5343 func: &ast::Function,
5344 has_heritage: bool,
5345 ) -> Result<CompiledFunction, SyntaxError> {
5346 let saved = self.cur().ctor_kind;
5347 self.state().class_ctor_pending = Some(if has_heritage {
5348 CtorKind::Derived
5349 } else {
5350 CtorKind::Base
5351 });
5352 let result = self.compile_function_with_name(func, false);
5353 self.state().ctor_kind = saved;
5354 self.state().class_ctor_pending = None;
5355 result
5356 }
5357
5358 /// The constructor a class gets when it does not declare one.
5359 ///
5360 /// A base class's is empty; a derived class's forwards every argument to the parent
5361 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
5362 /// instance field initialiser afterwards when the class has fields, which is why the
5363 /// initialiser is captured rather than inlined.
5364 fn compile_implicit_constructor(
5365 &mut self,
5366 class: &Class,
5367 has_heritage: bool,
5368 ) -> Result<CompiledFunction, SyntaxError> {
5369 self.compile_synthetic_function(
5370 "",
5371 true,
5372 Span::new(class.body_end, class.body_end),
5373 |compiler| {
5374 if has_heritage {
5375 // A derived constructor's `this` does not exist until `super()` returns,
5376 // so it starts in the dead zone and `init_ctor` fills it.
5377 compiler.declare("this", VarDef::lexical("this"));
5378 compiler.emit(
5379 Opcode::SetLocUninitialized,
5380 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5381 );
5382 compiler.emit(Opcode::InitCtor, &[]);
5383 compiler.emit(
5384 Opcode::PutLocCheckInit,
5385 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5386 );
5387 } else {
5388 compiler.begin_this_local();
5389 compiler.emit(Opcode::CheckCtor, &[]);
5390 }
5391 compiler.call_field_initialiser();
5392 // A derived constructor returns `this`, the object `super()` built. Without
5393 // this the implicit constructor fell through to `return_undef`, and `new B()`
5394 // handed back the empty object `construct` had made instead of the one the
5395 // parent constructor initialised.
5396 if has_heritage {
5397 compiler.emit_var(VarAction::Get, "this");
5398 compiler.emit(Opcode::Return, &[]);
5399 }
5400 Ok(())
5401 },
5402 )
5403 }
5404
5405 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
5406 ///
5407 /// A class with no instance fields leaves the binding `undefined`, and calling it
5408 /// would throw; the reference emits the same guard rather than branching at compile
5409 /// time because a class can be extended by a subclass whose fields still have to run.
5410 fn call_field_initialiser(&mut self) {
5411 let skip = self.new_label();
5412 self.emit_var(VarAction::Get, "<class_fields_init>");
5413 self.emit(Opcode::Dup, &[]);
5414 self.emit_jump(Opcode::IfFalse, skip, &[]);
5415 self.emit_var(VarAction::Get, "this");
5416 self.emit(Opcode::Swap, &[]);
5417 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5418 self.place_label(skip);
5419 self.emit(Opcode::Drop, &[]);
5420 }
5421
5422 /// The function that defines one class's fields on `this`, and runs its static blocks.
5423 ///
5424 /// `define_field` rather than `put_field`: a field is an own property created
5425 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
5426 /// `x = 1` field must not call the setter.
5427 ///
5428 /// One function serves the whole class: it is called once per instance (or once, for
5429 /// the static half) and walks the members in source order. Static blocks are compiled
5430 /// into the same function because they *are* part of the same sequence — `static a =
5431 /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
5432 /// different values, so the two kinds cannot be split apart.
5433 fn compile_field_initialiser(
5434 &mut self,
5435 items: &[StaticInitItem<'_>],
5436 span: Span,
5437 instance: bool,
5438 add_brand: bool,
5439 ) -> Result<CompiledFunction, SyntaxError> {
5440 self.compile_synthetic_function("", true, span, |compiler| {
5441 if instance {
5442 // An instance initialiser always carries a `<home_object>` local, because the
5443 // brand block below reads it — even when that block turns out to be dead. The
5444 // reference has the same artefact, and the store is visible in its dump.
5445 let current = compiler.stack.len() - 1;
5446 compiler.stack[current].needs_home_object_local = true;
5447 }
5448 compiler.begin_this_local();
5449 if instance {
5450 // `this` gets the brand the prototype created, before any field is defined —
5451 // which is what makes `#m()` usable from inside a field initialiser.
5452 //
5453 // The reference always emits `push_false; if_false L; this; home; add_brand;
5454 // L:` and patches the `push_false` to `push_true` from the class parse when
5455 // the class has private methods; either way the branch folds, but the *mark*
5456 // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
5457 // `this` local from being fused into a `set_loc`.
5458 let skip = compiler.new_label();
5459 if add_brand {
5460 compiler.emit(Opcode::PushTrue, &[]);
5461 } else {
5462 compiler.emit(Opcode::PushFalse, &[]);
5463 }
5464 compiler.emit_jump(Opcode::IfFalse, skip, &[]);
5465 compiler.emit_var(VarAction::Get, "this");
5466 compiler.emit_var(VarAction::Get, HOME_OBJECT);
5467 compiler.emit(Opcode::AddBrand, &[]);
5468 compiler.place_label(skip);
5469 }
5470 for item in items {
5471 match item {
5472 StaticInitItem::Field(key, value) => {
5473 // A private field is *defined*, not assigned: `define_private_field`
5474 // reads `obj symbol value`, and its point is that it fails on a
5475 // receiver that is not this class's — which `put_field` would not.
5476 //
5477 // The three shapes are the reference's: `define_field <atom>` for a
5478 // static name, `define_array_el` for a key that is only known at run
5479 // time (`obj key value`), `define_private_field` for `#x`, and a
5480 // computed key is read from its binding rather than recomputed.
5481 compiler.emit_var(VarAction::Get, "this");
5482 match key {
5483 FieldKey::Private(binding) | FieldKey::Computed(binding) => {
5484 compiler.emit_var(VarAction::Get, binding);
5485 }
5486 FieldKey::Literal(_) => {}
5487 }
5488 match value {
5489 Some(value) => compiler.expr(value)?,
5490 None => compiler.emit(Opcode::Undefined, &[]),
5491 }
5492 match key {
5493 FieldKey::Literal(literal) => {
5494 let text = compiler.property_key_text(literal, span)?;
5495 compiler
5496 .emit(Opcode::DefineField, &[Op::Atom(Atom::from_text(&text))]);
5497 }
5498 FieldKey::Computed(_) => {
5499 compiler.emit(Opcode::DefineArrayEl, &[]);
5500 // `define_array_el` leaves `obj key`; the key is consumed by
5501 // the copy the pattern machinery wants, so both go.
5502 compiler.emit(Opcode::Drop, &[]);
5503 }
5504 FieldKey::Private(_) => {
5505 compiler.emit(Opcode::DefinePrivateField, &[]);
5506 }
5507 }
5508 compiler.emit(Opcode::Drop, &[]);
5509 }
5510 StaticInitItem::Block { body, body_start } => {
5511 let block = compiler.compile_static_block(body, *body_start)?;
5512 let index = compiler.push_constant(Constant::Function(Box::new(block)));
5513 // `this fclosure`, so `call_method` finds the receiver below the
5514 // callee: the block runs with `this` bound to the class.
5515 compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
5516 compiler.emit_var(VarAction::Get, "this");
5517 compiler.emit(Opcode::Swap, &[]);
5518 compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
5519 // Nothing the block evaluates is wanted; its effects are the point.
5520 compiler.emit(Opcode::Drop, &[]);
5521 }
5522 }
5523 }
5524 Ok(())
5525 })
5526 }
5527
5528 /// Compile a `static { … }` body into the function the class calls for it.
5529 ///
5530 /// Shaped like an arrow, because that is the one function form with no `this`,
5531 /// `new.target` or `arguments` of its own: all three reach the enclosing static
5532 /// initialiser, and through it the class. `arguments` never gets that far — the parser
5533 /// rejects the reference — but `this` and `super` both depend on it.
5534 ///
5535 /// The body is hoisted like a function body's, because the reference parses it as one:
5536 /// `var` inside a block is a local of the block's function, not of whatever encloses
5537 /// the class.
5538 fn compile_static_block(
5539 &mut self,
5540 body: &[Stmt],
5541 body_start: Position,
5542 ) -> Result<CompiledFunction, SyntaxError> {
5543 let mut state = FnState::new(String::new(), FunctionKind::Normal);
5544 // Class bodies are strict, so a static block is too.
5545 state.strict = true;
5546 // The one property that makes this an arrow: nothing of its own to bind `this` to,
5547 // so `this` and `super` come from the initialiser that calls it.
5548 state.is_arrow = true;
5549 state.created_in_block = self.cur().current_block;
5550 state.with_names = self.cur().with_names.clone();
5551 state.line = body_start.line;
5552 state.column = body_start.column;
5553 let depth = self.stack.len();
5554 self.stack.push(state);
5555 let body_key = body_start.offset as u64;
5556 self.push_block(body_key, NO_PARENT);
5557 self.state().body_block = body_key;
5558 let result = (|| {
5559 self.hoist(body, body_key)?;
5560 self.emit_scope_enter(body_key);
5561 for statement in body {
5562 self.stmt(statement)?;
5563 }
5564 if self.end_is_reachable() {
5565 self.emit(Opcode::ReturnUndef, &[]);
5566 }
5567 Ok(())
5568 })();
5569 if result.is_err() {
5570 self.stack.truncate(depth);
5571 return result.map(|()| unreachable!());
5572 }
5573 Ok(self.finish_current())
5574 }
5575
5576 /// Compile a class, leaving the constructor on the stack when `keep`.
5577 ///
5578 /// The shape follows the reference: the class body is its own scope holding the
5579 /// class's *inner* name as a `const` — which is what lets a method refer to the
5580 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
5581 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
5582 /// on the top of the stack: the prototype for instance members, the constructor
5583 /// itself for `static` ones, which is why a static member costs an extra `swap`.
5584 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
5585 let parent_block = self.cur().current_block;
5586 let key = class.span.start.offset as u64;
5587 self.push_block(key, parent_block);
5588 let name = class.name.as_ref().map(|ident| ident.name.clone());
5589 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
5590 // resolves `E` without a global lookup. An *unnamed* class expression has no such
5591 // binding, and `define_class` is handed the empty name.
5592 if let Some(name) = &name {
5593 self.declare(name, VarDef::constant(name.clone()));
5594 }
5595 self.emit_scope_enter(key);
5596
5597 // The heritage clause is evaluated outside the class's own scope: it cannot see
5598 // the class binding it is about to initialise.
5599 let saved_block = self.cur().current_block;
5600 self.state().current_block = parent_block;
5601 match &class.super_class {
5602 Some(parent) => self.expr(parent)?,
5603 None => self.emit(Opcode::Undefined, &[]),
5604 }
5605 self.state().current_block = saved_block;
5606 let has_heritage = class.super_class.is_some();
5607
5608 // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
5609 // lands after the heritage's code — which is where the reference puts it, because it
5610 // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
5611 // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
5612 // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
5613 // came out in the opposite order from the reference's.
5614 //
5615 // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
5616 // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
5617 // a const accepts — so the old comment's worry ("a const would refuse the second
5618 // store") did not apply: there is no second store.
5619 // Every `#name` the class declares gets a `const` binding in the class scope, and so
5620 // does every computed field key. That is how the reference does it
5621 // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
5622 // what makes a private name resolve like any other class-scope variable — including
5623 // through a nested function's closure — while remaining invisible outside.
5624 //
5625 // All of them are declared *before* `<class_fields_init>`, in member order, because
5626 // that is when the reference's parser creates them.
5627 let plan = ClassPlan::build(class);
5628 // The body's private names are visible from here to the end of the class, and shadow
5629 // any outer class's of the same spelling. Pushed *before* the constructor is compiled
5630 // — it is compiled first because `define_class` consumes it, but its body can name
5631 // `#x` like any other member's.
5632 self.private_scopes.push(plan.uses.clone());
5633 let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
5634 for binding in &plan.bindings {
5635 class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
5636 }
5637 let fci = self.declare(
5638 "<class_fields_init>",
5639 VarDef::constant("<class_fields_init>"),
5640 );
5641 // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
5642 // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
5643 // members' bindings follow in reverse.
5644 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
5645 for slot in class_slots.iter().rev() {
5646 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
5647 }
5648
5649 // The constructor is compiled before `define_class` because that instruction
5650 // consumes it; a class without one gets the implicit version.
5651 let constructor = class.elements.iter().find_map(|element| match element {
5652 ClassElement::Method {
5653 kind: MethodKind::Constructor,
5654 func,
5655 ..
5656 } => Some(&**func),
5657 _ => None,
5658 });
5659 // A constructor is compiled differently from a method: it owns `this`. The flags
5660 // go on the *enclosing* state because a constructor is a nested function and
5661 // `compile_function_with_name` starts a fresh one.
5662 let ctor = match constructor {
5663 Some(func) => self.compile_class_constructor(func, has_heritage)?,
5664 None => self.compile_implicit_constructor(class, has_heritage)?,
5665 };
5666 // A closure, not the bare constant: the constructor captures
5667 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
5668 // has to hold the cell rather than a copy of its value.
5669 //
5670 // The pool slot is left unassigned for now, because the reference gives the
5671 // constructor the *last* index of the members' range: `js_parse_class` emits a
5672 // `push_const` whose operand is patched at the end of the class parse, after every
5673 // method has taken a slot. Emitting the members first and the constant second is how
5674 // the numbering comes out the same; the instruction itself stays where it is.
5675 let ctor_insn = self.cur().insns.len();
5676 self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
5677 let flags = if has_heritage { 1 } else { 0 };
5678 self.emit(
5679 Opcode::DefineClass,
5680 &[
5681 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
5682 Op::Int(flags),
5683 ],
5684 );
5685
5686 // Instance fields and static fields are two different functions: the first runs
5687 // per instance from the constructor, the second runs once, here.
5688 let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
5689 let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
5690 for (index, element) in class.elements.iter().enumerate() {
5691 match element {
5692 ClassElement::Method {
5693 key: member_key,
5694 is_static,
5695 kind,
5696 func,
5697 span,
5698 } => {
5699 if *kind == MethodKind::Constructor {
5700 continue;
5701 }
5702 // `static(x)` is a *method* named `static`, not a static method; the
5703 // parser already decided which by putting it in `kind`.
5704 if *is_static {
5705 self.emit(Opcode::Swap, &[]);
5706 }
5707 let function = self.compile_function_with_name(func, true)?;
5708 let index = self.push_constant(Constant::Function(Box::new(function)));
5709 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5710 match member_key {
5711 // A private method is not a property of the prototype: it is a
5712 // closure in the class scope, which is why nothing outside can reach
5713 // it and why a use site has to brand-check. `set_name` gives the
5714 // function its `name` (`#m`), which an accessor does not get — the
5715 // reference leaves that commented out.
5716 PropName::Private(ident) => {
5717 let name = format!("#{}", ident.name);
5718 // `set_home_object` first: the brand check reads the function's
5719 // home object, and for a method that is the prototype.
5720 self.emit(Opcode::SetHomeObject, &[]);
5721 let binding = if *kind == MethodKind::Set {
5722 format!("{name}<set>")
5723 } else {
5724 name.clone()
5725 };
5726 if *kind == MethodKind::Method {
5727 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
5728 }
5729 self.emit_var(VarAction::PutInit, &binding);
5730 }
5731 PropName::Computed(key) => {
5732 self.emit(Opcode::Swap, &[]);
5733 self.expr(key)?;
5734 self.emit(
5735 Opcode::DefineMethodComputed,
5736 &[Op::Int(class_method_flags(*kind))],
5737 );
5738 // `define_method_computed` leaves the key; drop it.
5739 self.emit(Opcode::Drop, &[]);
5740 }
5741 PropName::Literal(literal) => {
5742 let text = self.property_key_text(literal, *span)?;
5743 self.emit(
5744 Opcode::DefineMethod,
5745 &[
5746 Op::Atom(Atom::from_text(&text)),
5747 Op::Int(class_method_flags(*kind)),
5748 ],
5749 );
5750 }
5751 }
5752 if *is_static {
5753 self.emit(Opcode::Swap, &[]);
5754 }
5755 }
5756 ClassElement::Field {
5757 key: field_key,
5758 is_static,
5759 value,
5760 ..
5761 } => {
5762 // A private field's *symbol* is created here, at the member, and stored
5763 // in its binding: the field's property is keyed by it, so it has to exist
5764 // before any initialiser runs, and a fresh one per class body is what
5765 // makes two classes that both write `#x` independent.
5766 //
5767 // A computed key is evaluated once, here, and `to_propkey`'d once — a key
5768 // whose `toString` has a side effect must not run again per instance.
5769 let key = match field_key {
5770 PropName::Private(ident) => {
5771 let binding = format!("#{}", ident.name);
5772 if *is_static {
5773 self.emit(Opcode::Swap, &[]);
5774 }
5775 self.emit(
5776 Opcode::PrivateSymbol,
5777 &[Op::Atom(Atom::from_text(&binding))],
5778 );
5779 self.emit_var(VarAction::PutInit, &binding);
5780 if *is_static {
5781 self.emit(Opcode::Swap, &[]);
5782 }
5783 FieldKey::Private(binding)
5784 }
5785 PropName::Computed(expression) => {
5786 let binding = plan
5787 .computed
5788 .get(&index)
5789 .cloned()
5790 .expect("every computed key got a binding");
5791 if *is_static {
5792 self.emit(Opcode::Swap, &[]);
5793 }
5794 self.expr(expression)?;
5795 self.emit(Opcode::ToPropkey, &[]);
5796 self.emit_var(VarAction::PutInit, &binding);
5797 if *is_static {
5798 self.emit(Opcode::Swap, &[]);
5799 }
5800 FieldKey::Computed(binding)
5801 }
5802 PropName::Literal(literal) => FieldKey::Literal(literal),
5803 };
5804 if *is_static {
5805 static_items.push(StaticInitItem::Field(key, value.as_deref()));
5806 } else {
5807 instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
5808 }
5809 }
5810 ClassElement::StaticBlock {
5811 body, body_start, ..
5812 } => static_items.push(StaticInitItem::Block {
5813 body,
5814 body_start: *body_start,
5815 }),
5816 }
5817 }
5818
5819 // Now that every member has its slot, the constructor can have the next one and the
5820 // `fclosure` above can name it.
5821 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
5822 match self.state().insns.get_mut(ctor_insn) {
5823 Some(Insn::Fixed { operands, .. }) => {
5824 operands[0] = Op::Const(ctor_index);
5825 }
5826 // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
5827 // loudly beats emitting a `fclosure` of slot 4294967295.
5828 _ => {
5829 return Err(SyntaxError::new(
5830 "the class constructor's fclosure went missing",
5831 class.span,
5832 ));
5833 }
5834 }
5835
5836 // The instance brand: a symbol created once on the prototype, which every instance
5837 // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
5838 // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
5839 // copy is created. The prototype is on top of the stack at this point.
5840 if plan.instance_brand {
5841 self.emit(Opcode::Dup, &[]);
5842 self.emit(Opcode::Null, &[]);
5843 self.emit(Opcode::Swap, &[]);
5844 self.emit(Opcode::AddBrand, &[]);
5845 }
5846
5847 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
5848 // class has no instance fields. The constructor calls it only when it is defined.
5849 //
5850 // A class with private *methods* but no fields still needs one, because adding the
5851 // brand to each new instance is the initialiser's job.
5852 if instance_fields.is_empty() && !plan.instance_brand {
5853 self.emit(Opcode::Undefined, &[]);
5854 } else {
5855 let initialiser = self.compile_field_initialiser(
5856 &instance_fields,
5857 class.span,
5858 true,
5859 plan.instance_brand,
5860 )?;
5861 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
5862 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5863 // `set_home_object` reads `obj func`, so the prototype stays where it is.
5864 self.emit(Opcode::SetHomeObject, &[]);
5865 }
5866 self.emit_var(VarAction::PutInit, "<class_fields_init>");
5867 // The prototype has done its job: every instance member is defined on it. What
5868 // is left under it is the constructor.
5869 self.emit(Opcode::Drop, &[]);
5870
5871 // The static brand, for `static #m() {}`: same opcode, but the home object is the
5872 // constructor itself, so the symbol lands on the class and the class carries it.
5873 if plan.static_brand {
5874 self.emit(Opcode::Dup, &[]);
5875 self.emit(Opcode::Dup, &[]);
5876 self.emit(Opcode::AddBrand, &[]);
5877 }
5878
5879 // The class binding is initialised *before* static fields run, so a static field
5880 // can refer to the class by name (`static y = S.x`).
5881 // `set_loc` leaves the constructor on the stack, which is what the static field
5882 // call and the outer store both consume.
5883 //
5884 // Only when there *is* such a binding: an anonymous class expression declares no
5885 // class-scope name, and asking for one by the empty string resolved to nothing —
5886 // which made `var x = class {}` assign `undefined` and put a bogus global store in
5887 // the instruction stream.
5888 if let Some(name) = &name {
5889 self.emit_var(VarAction::SetInit, name);
5890 }
5891 if !static_items.is_empty() {
5892 // The static half has no brand prologue of its own: the constructor got its
5893 // brand above, before this runs.
5894 let initialiser =
5895 self.compile_field_initialiser(&static_items, class.span, false, false)?;
5896 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
5897 self.emit(Opcode::Dup, &[]);
5898 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5899 self.emit(Opcode::SetHomeObject, &[]);
5900 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5901 self.emit(Opcode::Drop, &[]);
5902 }
5903 // The body is over, and with it this class's private names.
5904 let _ = self.private_scopes.pop();
5905 self.emit_scope_leave(key);
5906 self.state().current_block = parent_block;
5907 if keep {
5908 // A class *expression* is its own value; the class-scope binding was only
5909 // ever an alias for it.
5910 return Ok(());
5911 }
5912 // A declaration stores into the binding the enclosing statement declared.
5913 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
5914 Ok(())
5915 }
5916
5917 fn push_this(&mut self) {
5918 self.emit(Opcode::PushThis, &[]);
5919 }
5920
5921 /// `this`, which an arrow does not have of its own.
5922 ///
5923 /// The reference gives the enclosing function a local named `this`, initialised from
5924 /// `push_this` at the top of its body, and the arrow then reads it as a captured
5925 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
5926 /// the arrow is called with none.
5927 fn this_expression(&mut self) {
5928 // In a class constructor `this` is a local: a derived constructor only gets one
5929 // when `super()` returns, and reading the raw receiver would give the *outer*
5930 // one instead.
5931 if self.cur().ctor_kind != CtorKind::None {
5932 self.emit_var(VarAction::Get, "this");
5933 return;
5934 }
5935 if !self.cur().is_arrow {
5936 self.push_this();
5937 return;
5938 }
5939 if let Some(target) = self.enclosing_function() {
5940 self.state_at(target).needs_this_local = true;
5941 self.declare_at(target, "this");
5942 }
5943 self.emit_var(VarAction::Get, "this");
5944 }
5945
5946 /// `new.target`, which an arrow likewise does not own.
5947 fn new_target_expression(&mut self) {
5948 if !self.cur().is_arrow {
5949 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
5950 return;
5951 }
5952 if let Some(target) = self.enclosing_function() {
5953 self.state_at(target).needs_new_target_local = true;
5954 self.declare_at(target, NEW_TARGET);
5955 }
5956 self.emit_var(VarAction::Get, NEW_TARGET);
5957 }
5958
5959 /// `this.active_func`: the function `super()` resolves against.
5960 ///
5961 /// In a constructor or a method that is the function being run, so the special object
5962 /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
5963 /// a closure variable — see [`FnState::needs_active_func_local`].
5964 fn active_func_expression(&mut self) {
5965 if !self.cur().is_arrow {
5966 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
5967 return;
5968 }
5969 if let Some(target) = self.enclosing_function() {
5970 self.state_at(target).needs_active_func_local = true;
5971 self.declare_at(target, ACTIVE_FUNC);
5972 }
5973 self.emit_var(VarAction::Get, ACTIVE_FUNC);
5974 }
5975
5976 /// Give the function a local `<active_func>`, for an arrow inside it to capture.
5977 fn provide_active_func_local(&mut self) {
5978 let current = self.stack.len() - 1;
5979 if !self.stack[current].needs_active_func_local {
5980 return;
5981 }
5982 if !self.stack[current]
5983 .vars
5984 .iter()
5985 .any(|var| var.name == ACTIVE_FUNC)
5986 {
5987 self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
5988 }
5989 self.prepend_initialiser(
5990 ACTIVE_FUNC,
5991 Insn::Fixed {
5992 op: Opcode::SpecialObject,
5993 operands: vec![Op::Int(2)],
5994 },
5995 );
5996 }
5997
5998 /// Give the function a local `new.target`, for an arrow inside it to capture.
5999 fn provide_new_target_local(&mut self) {
6000 let current = self.stack.len() - 1;
6001 if !self.stack[current].needs_new_target_local {
6002 return;
6003 }
6004 if !self.stack[current]
6005 .vars
6006 .iter()
6007 .any(|var| var.name == NEW_TARGET)
6008 {
6009 self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6010 }
6011 self.prepend_initialiser(
6012 NEW_TARGET,
6013 Insn::Fixed {
6014 op: Opcode::SpecialObject,
6015 operands: vec![Op::Int(3)],
6016 },
6017 );
6018 }
6019
6020 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6021 /// function.
6022 fn ensure_enclosing_arguments(&mut self) {
6023 // An arrow created in a parameter list needs the *parameter* scope's
6024 // `arguments`, not the body's: the two are separate bindings and the arrow was
6025 // born before the body existed.
6026 let from_params = self.cur().created_in_params;
6027 if let Some(target) = self.enclosing_function() {
6028 self.state_at(target).needs_arguments_local = true;
6029 if from_params {
6030 self.state_at(target).needs_param_arguments = true;
6031 // Declare it now, not at the enclosing function's `finish_current`: the
6032 // arrow resolves its own `arguments` before that runs, and a binding that
6033 // does not exist yet resolves as a global.
6034 declare_param_var_at(&mut self.stack[target], "arguments");
6035 }
6036 self.declare_at(target, "arguments");
6037 }
6038 }
6039
6040 /// The innermost enclosing frame that is a real function — an arrow inherits from it
6041 /// rather than starting a scope of its own.
6042 fn enclosing_function(&self) -> Option<usize> {
6043 (0..self.stack.len())
6044 .rev()
6045 .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
6046 }
6047
6048 fn state_at(&mut self, index: usize) -> &mut FnState {
6049 &mut self.stack[index]
6050 }
6051
6052 /// Declare a `var` binding directly in a specific frame.
6053 fn declare_at(&mut self, index: usize, name: &str) {
6054 let state = &mut self.stack[index];
6055 if state.vars.iter().any(|var| var.name == name) {
6056 return;
6057 }
6058 state.var_block.push(FUNCTION_SCOPE);
6059 state.vars.push(VarDef::var(name));
6060 }
6061
6062 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6063 /// the reference calls a `special_object` gets initialised on entry.
6064 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6065 let current = self.stack.len() - 1;
6066 let init = [
6067 producer,
6068 Insn::Var {
6069 action: VarAction::Put,
6070 name: name.to_string(),
6071 block: 0,
6072 // A prologue initialiser runs before the body proper, but it is body
6073 // code: `this` and `arguments` are provided for it, not by it.
6074 in_params: false,
6075 },
6076 ];
6077 let inserted = init.len();
6078 for (index, instruction) in init.into_iter().enumerate() {
6079 self.stack[current].insns.insert(index, instruction);
6080 }
6081 for placed in self.stack[current].labels.iter_mut().flatten() {
6082 *placed += inserted;
6083 }
6084 self.stack[current].label_since_insn = true;
6085 }
6086
6087 fn push_constant(&mut self, constant: Constant) -> u32 {
6088 let state = self.state();
6089 let index = state.cpool.len() as u32;
6090 state.cpool.push(constant);
6091 index
6092 }
6093
6094 /// Compile `a && b`, `a || b`, `a ?? b`.
6095 ///
6096 /// A run of the *same* operator shares one end label, so `a || b || c` tests
6097 /// `a` once and jumps past everything when it is truthy, instead of falling
6098 /// into `b`'s test. The parser builds such a run left-associated —
6099 /// `((a || b) || c)` — so the operands are collected off the left spine.
6100 ///
6101 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6102 /// `||`'s label, because the inner chain really does end before `&&` begins.
6103 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6104 let mut operands = Vec::new();
6105 collect_same_operator(op, left, &mut operands);
6106 operands.push(right);
6107
6108 let end = self.new_label();
6109 // Every operand but the last decides whether the chain stops here.
6110 let last = operands.pop().expect("the right operand is always present");
6111 for operand in operands {
6112 self.expr(operand)?;
6113 self.emit(Opcode::Dup, &[]);
6114 match op {
6115 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6116 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6117 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6118 // `0 || b` is `b`. The dedicated test keeps the value unless it is
6119 // null-ish, so the jump is taken on `false`.
6120 LogicalOp::Coalesce => {
6121 self.emit(Opcode::IsUndefinedOrNull, &[]);
6122 self.emit_jump(Opcode::IfFalse, end, &[]);
6123 }
6124 }
6125 self.emit(Opcode::Drop, &[]);
6126 }
6127 self.expr(last)?;
6128 self.place_label(end);
6129 Ok(())
6130 }
6131
6132 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6133 match op {
6134 UnaryOp::Typeof => {
6135 // `typeof x` must not throw on an undeclared name.
6136 if let ExprKind::Ident(name) = &argument.kind {
6137 self.emit_var(VarAction::GetUndef, &name.name);
6138 } else {
6139 self.expr(argument)?;
6140 }
6141 self.emit(Opcode::Typeof, &[]);
6142 }
6143 UnaryOp::Delete => {
6144 // `delete obj.prop` really deletes, and answers whether it could.
6145 // Deleting a *binding* is always `false`: a local, an argument and a
6146 // declared global are all non-configurable, which the reference encodes
6147 // as a constant `push_false` rather than a runtime check. Only a
6148 // property access has anything to do at run time.
6149 // `delete super.x` is not a delete at all: the spec refuses it, and the
6150 // reference encodes the refusal as a `throw_error`. The receiver and the
6151 // key are still evaluated first, which is what keeps the evaluation order
6152 // of the operand intact.
6153 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6154 // nothing to delete, and a failed delete is not the same as a skipped
6155 // one. The reference emits the guards so they land on a `drop; push_true`
6156 // tail, which is what this reproduces.
6157 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6158 && let ExprKind::Member {
6159 object, property, ..
6160 } = &inner.unparen().kind
6161 {
6162 let end = self.new_label();
6163 let done = self.new_label();
6164 self.chain_link(object, end)?;
6165 match property {
6166 MemberProp::Ident(name) => self.emit(
6167 Opcode::PushAtomValue,
6168 &[Op::Atom(Atom::from_text(&name.name))],
6169 ),
6170 MemberProp::Computed(index) => self.expr(index)?,
6171 MemberProp::Private(_) => {
6172 return Err(SyntaxError::new(
6173 "deleting a private field is not allowed",
6174 argument.span,
6175 ));
6176 }
6177 }
6178 self.emit(Opcode::Delete, &[]);
6179 self.emit_jump(Opcode::Goto, done, &[]);
6180 self.place_label(end);
6181 self.emit(Opcode::Drop, &[]);
6182 self.emit(Opcode::PushTrue, &[]);
6183 self.place_label(done);
6184 return Ok(());
6185 }
6186 if let ExprKind::Member { object, .. } = &argument.unparen().kind
6187 && matches!(object.unparen().kind, ExprKind::SuperProp)
6188 {
6189 self.super_base();
6190 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6191 return Ok(());
6192 }
6193 match &argument.kind {
6194 ExprKind::Member {
6195 object, property, ..
6196 } => {
6197 self.expr(object)?;
6198 match property {
6199 MemberProp::Ident(name) => {
6200 self.emit(
6201 Opcode::PushAtomValue,
6202 &[Op::Atom(Atom::from_text(&name.name))],
6203 );
6204 }
6205 MemberProp::Computed(index) => self.expr(index)?,
6206 MemberProp::Private(_) => {
6207 return Err(SyntaxError::new(
6208 "deleting a private field is not allowed",
6209 argument.span,
6210 ));
6211 }
6212 }
6213 self.emit(Opcode::Delete, &[]);
6214 }
6215 ExprKind::Ident(name) => {
6216 // `delete name`: a declared global, a local and an argument all
6217 // answer `false`, but an *implicit* global (`x = 1` with no
6218 // declaration) is a configurable property of the global object
6219 // and really goes away. Which of those a name is only the
6220 // resolver knows, so the decision waits for it.
6221 let pos = self.cur().cur_pos;
6222 self.state().insns.push(Insn::DeleteVar {
6223 name: name.name.clone(),
6224 });
6225 self.state().insn_pos.push(pos);
6226 }
6227 _ => self.emit(Opcode::PushFalse, &[]),
6228 }
6229 }
6230 UnaryOp::Void => {
6231 self.expr(argument)?;
6232 self.emit(Opcode::Drop, &[]);
6233 self.emit(Opcode::Undefined, &[]);
6234 }
6235 UnaryOp::Minus => {
6236 self.expr(argument)?;
6237 self.emit(Opcode::Neg, &[]);
6238 }
6239 UnaryOp::Plus => {
6240 self.expr(argument)?;
6241 self.emit(Opcode::Plus, &[]);
6242 }
6243 UnaryOp::Not => {
6244 self.expr(argument)?;
6245 self.emit(Opcode::Lnot, &[]);
6246 }
6247 UnaryOp::BitNot => {
6248 self.expr(argument)?;
6249 self.emit(Opcode::Not, &[]);
6250 }
6251 }
6252 Ok(())
6253 }
6254
6255 /// Compile an assignment.
6256 ///
6257 /// Three operator families, three shapes:
6258 ///
6259 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
6260 /// the value is kept, because `put_field`/`put_array_el` consume both the
6261 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
6262 /// the pair it wants and leaves a copy on top.
6263 /// * **compound** `+=` … — read the place, apply the operator, store. A member
6264 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
6265 /// index) underneath the value precisely so the store can follow.
6266 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
6267 /// right-hand side. The test *keeps* the current value and skips the store
6268 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
6269 /// `a` is already truthy.
6270 fn assign(&mut self, op: AssignOp, target: &Pattern, value: &Expr) -> Result<(), SyntaxError> {
6271 // Reading the flag clears it: only the outermost assignment of an
6272 // expression statement may drop its value.
6273 let keep = !std::mem::take(&mut self.state().discard_value);
6274 match &target.kind {
6275 PatternKind::Ident(name) => {
6276 // A *simple* store is blamed on the identifier, not on the `=`: a
6277 // strict-mode `not_def = 1` raises when the name is written, which the
6278 // reference reports at the name's column. A compound store is blamed on
6279 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
6280 // which the reference reports at the `+=`), so only the simple case
6281 // moves the position.
6282 let saved = self.cur().cur_pos;
6283 let name_pos = Some(name.span.start);
6284 if matches!(op, AssignOp::Assign) {
6285 self.state().cur_pos = name_pos;
6286 }
6287 // A *compound* store reads the binding before it combines, and that read
6288 // is blamed on the identifier: `not_def += 2` fails while reading
6289 // `not_def`, so the position is the name's, not the `+=`'s. The
6290 // combination that follows is blamed on the operator, which is why
6291 // `cur_pos` is put back to the operator position before it is emitted.
6292 self.state().cur_pos = name_pos;
6293 match op {
6294 AssignOp::Assign => {
6295 self.expr(value)?;
6296 self.set_name_if_anonymous(value, &name.name);
6297 // A discarded store to a *slot* consumes its value, so no copy
6298 // is needed. A global store goes through `put_var`, which the
6299 // reference always pairs with a `dup` — matching it keeps the
6300 // bytecode identical. Getting this wrong is not only an extra
6301 // instruction: a stray copy gives the peephole a chance to fold
6302 // the store into an unrelated later read.
6303 let slot = self.is_slot(&name.name);
6304 if keep || !slot {
6305 self.emit(Opcode::Dup, &[]);
6306 }
6307 self.state().no_value = !keep && slot;
6308 self.emit_var(VarAction::Put, &name.name);
6309 }
6310 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6311 let end = self.new_label();
6312 self.emit_var(VarAction::Get, &name.name);
6313 self.state().cur_pos = saved;
6314 self.emit(Opcode::Dup, &[]);
6315 self.emit_logical_test(op);
6316 self.emit_jump(logical_jump(op), end, &[]);
6317 self.emit(Opcode::Drop, &[]);
6318 self.expr(value)?;
6319 self.emit(Opcode::Dup, &[]);
6320 self.emit_var(VarAction::Put, &name.name);
6321 self.place_label(end);
6322 }
6323 _ => {
6324 self.emit_var(VarAction::Get, &name.name);
6325 self.expr(value)?;
6326 self.state().cur_pos = saved;
6327 self.emit(compound_opcode(op), &[]);
6328 self.emit(Opcode::Dup, &[]);
6329 self.emit_var(VarAction::Put, &name.name);
6330 }
6331 }
6332 self.state().cur_pos = saved;
6333 Ok(())
6334 }
6335 PatternKind::Member(member) => {
6336 // `super.x = v` is not a store through a value: it starts at the home
6337 // object's prototype but writes to `this`, so it goes through
6338 // `put_super_value` rather than `put_field`. The receiver, prototype, key
6339 // and value are handed over together.
6340 if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
6341 return self.assign_super(member, op, value);
6342 }
6343 // A store is blamed on the selector punctuator (`.` or `[`), the same
6344 // token a load is blamed on — the reference records `put_field obj.a`
6345 // at the `.`, so a setter that throws reports that column and not the
6346 // `=` of the assignment it sits in. The inner expressions restore their
6347 // own positions, so the selector's sticks for the store instructions.
6348 let saved = self.cur().cur_pos;
6349 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6350 self.expr(&member.object)?;
6351 match &member.property {
6352 MemberProp::Ident(property) => {
6353 let atom = Atom::from_text(&property.name);
6354 match op {
6355 AssignOp::Assign => {
6356 self.expr(value)?;
6357 // `put_field` consumes the object and the value, so
6358 // without `insert2` nothing is left over for the
6359 // statement to drop.
6360 self.state().no_value = !keep;
6361 if keep {
6362 self.emit(Opcode::Insert2, &[]);
6363 }
6364 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6365 }
6366 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6367 // `get_field2` leaves the object under the value, so
6368 // the keep path has an object to dispose of. The store
6369 // path must jump *over* that cleanup: falling into it
6370 // would `nip` a stack that only holds the value.
6371 let (keep_label, end) = (self.new_label(), self.new_label());
6372 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6373 self.emit(Opcode::Dup, &[]);
6374 self.emit_logical_test(op);
6375 self.emit_jump(logical_jump(op), keep_label, &[]);
6376 self.emit(Opcode::Drop, &[]);
6377 self.expr(value)?;
6378 self.emit(Opcode::Insert2, &[]);
6379 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6380 self.emit_jump(Opcode::Goto, end, &[]);
6381 self.place_label(keep_label);
6382 self.emit(Opcode::Nip, &[]);
6383 self.place_label(end);
6384 }
6385 _ => {
6386 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6387 self.expr(value)?;
6388 self.emit(compound_opcode(op), &[]);
6389 self.state().no_value = !keep;
6390 if keep {
6391 self.emit(Opcode::Insert2, &[]);
6392 }
6393 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6394 }
6395 }
6396 }
6397 MemberProp::Computed(index) => {
6398 self.expr(index)?;
6399 match op {
6400 AssignOp::Assign => {
6401 self.expr(value)?;
6402 self.state().no_value = !keep;
6403 if keep {
6404 self.emit(Opcode::Insert3, &[]);
6405 }
6406 self.emit(Opcode::PutArrayEl, &[]);
6407 }
6408 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6409 let (keep_label, end) = (self.new_label(), self.new_label());
6410 self.emit(Opcode::GetArrayEl3, &[]);
6411 self.emit(Opcode::Dup, &[]);
6412 self.emit_logical_test(op);
6413 self.emit_jump(logical_jump(op), keep_label, &[]);
6414 self.emit(Opcode::Drop, &[]);
6415 self.expr(value)?;
6416 self.emit(Opcode::Insert3, &[]);
6417 self.emit(Opcode::PutArrayEl, &[]);
6418 self.emit_jump(Opcode::Goto, end, &[]);
6419 self.place_label(keep_label);
6420 // Both the object and the index are left over.
6421 self.emit(Opcode::Nip, &[]);
6422 self.emit(Opcode::Nip, &[]);
6423 self.place_label(end);
6424 }
6425 _ => {
6426 self.emit(Opcode::GetArrayEl3, &[]);
6427 self.expr(value)?;
6428 self.emit(compound_opcode(op), &[]);
6429 self.state().no_value = !keep;
6430 if keep {
6431 self.emit(Opcode::Insert3, &[]);
6432 }
6433 self.emit(Opcode::PutArrayEl, &[]);
6434 }
6435 }
6436 }
6437 MemberProp::Private(name) => {
6438 // `obj value` is on the stack, and every private store wants exactly
6439 // that. A top-level private name cannot be assigned (the parser rejects
6440 // `#x = 1`), so the only way here is `this.#x = …` inside the class.
6441 //
6442 // The reference emits `insert2` whether or not the value is wanted,
6443 // so this does too: the copy left behind is the assignment expression's
6444 // value, and a discarded one is simply never read.
6445 let binding = format!("#{}", name.name);
6446 let (kind, setter) = self.private_use(&binding, member.span)?;
6447 match op {
6448 AssignOp::Assign => {
6449 self.expr(value)?;
6450 if keep {
6451 self.emit(Opcode::Insert2, &[]);
6452 }
6453 self.private_store(&binding, kind, setter.as_deref())?;
6454 self.state().no_value = !keep;
6455 }
6456 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6457 let (keep_label, end) = (self.new_label(), self.new_label());
6458 self.emit(Opcode::Dup, &[]);
6459 self.private_load(&binding, kind, member.span)?;
6460 self.emit(Opcode::Dup, &[]);
6461 self.emit_logical_test(op);
6462 self.emit_jump(logical_jump(op), keep_label, &[]);
6463 self.emit(Opcode::Drop, &[]);
6464 self.expr(value)?;
6465 self.emit(Opcode::Insert2, &[]);
6466 self.private_store(&binding, kind, setter.as_deref())?;
6467 self.emit_jump(Opcode::Goto, end, &[]);
6468 self.place_label(keep_label);
6469 self.emit(Opcode::Nip, &[]);
6470 self.place_label(end);
6471 }
6472 _ => {
6473 self.emit(Opcode::Dup, &[]);
6474 self.private_load(&binding, kind, member.span)?;
6475 self.expr(value)?;
6476 self.emit(compound_opcode(op), &[]);
6477 self.emit(Opcode::Insert2, &[]);
6478 self.private_store(&binding, kind, setter.as_deref())?;
6479 }
6480 }
6481 }
6482 }
6483 self.state().cur_pos = saved;
6484 Ok(())
6485 }
6486 // A destructuring assignment: the right-hand side is the expression's own
6487 // value, so it is evaluated once and kept under the pattern's stores.
6488 PatternKind::Array { .. } | PatternKind::Object { .. } => {
6489 self.expr(value)?;
6490 if keep {
6491 self.emit(Opcode::Dup, &[]);
6492 }
6493 self.destructure(target, None)?;
6494 self.state().no_value = !keep;
6495 Ok(())
6496 }
6497 _ => Err(SyntaxError::new(
6498 "this assignment target is not supported by the compiler yet",
6499 target.span,
6500 )),
6501 }
6502 }
6503
6504 /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
6505 ///
6506 /// The stack has to carry four values — receiver, prototype, key, value — because
6507 /// `put_super_value` takes them together; the receiver is what makes a setter found on
6508 /// the prototype run with `this`, and the key has to survive until the store, which is
6509 /// why a compound form converts it to a property key once and `dup3`s rather than
6510 /// evaluating it twice.
6511 fn assign_super(
6512 &mut self,
6513 member: &MemberPattern,
6514 op: AssignOp,
6515 value: &Expr,
6516 ) -> Result<(), SyntaxError> {
6517 let saved = self.cur().cur_pos;
6518 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6519 self.super_base();
6520 match &member.property {
6521 MemberProp::Ident(property) => self.emit(
6522 Opcode::PushAtomValue,
6523 &[Op::Atom(Atom::from_text(&property.name))],
6524 ),
6525 MemberProp::Computed(index) => self.expr(index)?,
6526 MemberProp::Private(_) => {
6527 return Err(SyntaxError::new(
6528 "private fields are not supported by the compiler yet",
6529 member.span,
6530 ));
6531 }
6532 }
6533 match op {
6534 AssignOp::Assign => {
6535 // The key is only converted once, by `put_super_value` itself, so a
6536 // computed key's `toString` runs exactly once.
6537 self.expr(value)?;
6538 self.emit(Opcode::Insert4, &[]);
6539 self.emit(Opcode::PutSuperValue, &[]);
6540 }
6541 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6542 let (keep_label, end) = (self.new_label(), self.new_label());
6543 self.emit(Opcode::ToPropkey, &[]);
6544 self.emit(Opcode::Dup3, &[]);
6545 self.emit(Opcode::GetSuperValue, &[]);
6546 self.emit(Opcode::Dup, &[]);
6547 self.emit_logical_test(op);
6548 self.emit_jump(logical_jump(op), keep_label, &[]);
6549 self.emit(Opcode::Drop, &[]);
6550 self.expr(value)?;
6551 self.emit(Opcode::Insert4, &[]);
6552 self.emit(Opcode::PutSuperValue, &[]);
6553 self.emit_jump(Opcode::Goto, end, &[]);
6554 self.place_label(keep_label);
6555 // The prototype and the key are still under the value that was read.
6556 self.emit(Opcode::Nip, &[]);
6557 self.emit(Opcode::Nip, &[]);
6558 self.emit(Opcode::Nip, &[]);
6559 self.place_label(end);
6560 }
6561 _ => {
6562 self.emit(Opcode::ToPropkey, &[]);
6563 self.emit(Opcode::Dup3, &[]);
6564 self.emit(Opcode::GetSuperValue, &[]);
6565 self.expr(value)?;
6566 self.emit(compound_opcode(op), &[]);
6567 self.emit(Opcode::Insert4, &[]);
6568 self.emit(Opcode::PutSuperValue, &[]);
6569 }
6570 }
6571 // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
6572 // is still on the stack when the store finishes, and the expression statement is
6573 // what disposes of it — the same arrangement as `put_field`, reached from the other
6574 // side: there the store consumes the value (`no_value`), here it leaves it
6575 // (`keep` already false, so nothing tells the statement otherwise).
6576 self.state().cur_pos = saved;
6577 Ok(())
6578 }
6579
6580 /// The test a logical assignment applies to the current value.
6581 ///
6582 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
6583 /// assign, while `0 ||= b` must not.
6584 fn emit_logical_test(&mut self, op: AssignOp) {
6585 if op == AssignOp::Coalesce {
6586 self.emit(Opcode::IsUndefinedOrNull, &[]);
6587 }
6588 }
6589
6590 /// The private name `#name` this use site resolves against.
6591 ///
6592 /// The parser has already rejected a name no enclosing class declares, so a miss here
6593 /// means the compiler lost track of a class scope — which is worth a real error rather
6594 /// than an `unwrap`.
6595 fn private_use(
6596 &self,
6597 binding: &str,
6598 span: Span,
6599 ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
6600 ClassPlan::find(self, binding)
6601 .map(|use_| (use_.kind, use_.setter.clone()))
6602 .ok_or_else(|| {
6603 SyntaxError::new(
6604 format!("the private name '{binding}' is out of scope here"),
6605 span,
6606 )
6607 })
6608 }
6609
6610 /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
6611 ///
6612 /// The three readable kinds take three different instructions, because a private name
6613 /// holds three different things — a symbol, a method function, a getter function — and
6614 /// only the first one is a property read at all.
6615 fn private_load(
6616 &mut self,
6617 binding: &str,
6618 kind: PrivateKind,
6619 span: Span,
6620 ) -> Result<(), SyntaxError> {
6621 match kind {
6622 PrivateKind::Field => {
6623 self.emit_var(VarAction::Get, binding);
6624 self.emit(Opcode::GetPrivateField, &[]);
6625 }
6626 PrivateKind::Method => {
6627 self.emit_var(VarAction::Get, binding);
6628 self.emit(Opcode::CheckBrand, &[]);
6629 // `check_brand` reads `obj func` and leaves both; the method itself is what
6630 // `this.#m` evaluates to.
6631 self.emit(Opcode::Nip, &[]);
6632 }
6633 PrivateKind::Getter => {
6634 self.emit_var(VarAction::Get, binding);
6635 self.emit(Opcode::CheckBrand, &[]);
6636 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6637 }
6638 // `#a` is declared but never filled when only a setter exists, so reading it is
6639 // the same refusal as assigning to a `const`. The reference reports it with the
6640 // generic read-only wording and leaves the better message as a `XXX`.
6641 PrivateKind::Setter => self.emit(
6642 Opcode::ThrowError,
6643 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6644 ),
6645 }
6646 let _ = span;
6647 Ok(())
6648 }
6649
6650 /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
6651 fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
6652 match kind {
6653 // A method *is* the callee, so only the check goes in between.
6654 PrivateKind::Method => {
6655 self.emit_var(VarAction::Get, binding);
6656 self.emit(Opcode::CheckBrand, &[]);
6657 }
6658 _ => self.private_load(binding, kind, Span::default())?,
6659 }
6660 Ok(())
6661 }
6662
6663 /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
6664 /// wanted back.
6665 ///
6666 /// A getter/setter pair is a *method call*, not a property store: the reference reads
6667 /// the setter out of its own binding and calls it with the receiver, which is why the
6668 /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
6669 /// keeps the assignment's value for an expression context.
6670 fn private_store(
6671 &mut self,
6672 binding: &str,
6673 kind: PrivateKind,
6674 setter: Option<&str>,
6675 ) -> Result<(), SyntaxError> {
6676 match kind {
6677 PrivateKind::Field => {
6678 self.emit_var(VarAction::Get, binding);
6679 self.emit(Opcode::PutPrivateField, &[]);
6680 }
6681 PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
6682 Some(setter) => {
6683 self.emit_var(VarAction::Get, setter);
6684 // `obj func value` -> `value obj func` for the check, and back again for
6685 // the call, which wants `obj func arg`.
6686 self.emit(Opcode::Swap, &[]);
6687 self.emit(Opcode::Rot3r, &[]);
6688 self.emit(Opcode::CheckBrand, &[]);
6689 self.emit(Opcode::Rot3l, &[]);
6690 self.emit(Opcode::CallMethod, &[Op::Int(1)]);
6691 // The setter's return value is discarded; the assignment's own value is
6692 // whatever the caller left underneath.
6693 self.emit(Opcode::Drop, &[]);
6694 }
6695 None => self.emit(
6696 Opcode::ThrowError,
6697 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6698 ),
6699 },
6700 }
6701 Ok(())
6702 }
6703
6704 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
6705 let instruction = match (op, prefix) {
6706 (UpdateOp::Increment, true) => Opcode::Inc,
6707 (UpdateOp::Increment, false) => Opcode::PostInc,
6708 (UpdateOp::Decrement, true) => Opcode::Dec,
6709 (UpdateOp::Decrement, false) => Opcode::PostDec,
6710 };
6711 if let ExprKind::Member {
6712 object,
6713 property,
6714 optional: _,
6715 } = &argument.kind
6716 {
6717 // `o.x++` needs the receiver twice, so the last link is read with the
6718 // `get_*2`/`get_*3` form that keeps it, and the update is written back
6719 // with `put_field`/`put_array_el`. The reordering in between is what puts
6720 // the old value below the receiver for a postfix update and the new one
6721 // above it for a prefix one:
6722 //
6723 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
6724 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
6725 //
6726 // This mirrors the reference instruction for instruction.
6727 self.expr(object)?;
6728 match property {
6729 MemberProp::Ident(name) => {
6730 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
6731 self.emit(instruction, &[]);
6732 self.emit(
6733 if prefix {
6734 Opcode::Insert2
6735 } else {
6736 Opcode::Perm3
6737 },
6738 &[],
6739 );
6740 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
6741 }
6742 MemberProp::Computed(index) => {
6743 self.expr(index)?;
6744 self.emit(Opcode::GetArrayEl3, &[]);
6745 self.emit(instruction, &[]);
6746 self.emit(
6747 if prefix {
6748 Opcode::Insert3
6749 } else {
6750 Opcode::Perm4
6751 },
6752 &[],
6753 );
6754 self.emit(Opcode::PutArrayEl, &[]);
6755 }
6756 MemberProp::Private(name) => {
6757 // The receiver is duplicated and the read keeps it, exactly as `get_field2`
6758 // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
6759 // `perm3` -> `old obj new` -> store.
6760 let binding = format!("#{}", name.name);
6761 let (kind, setter) = self.private_use(&binding, argument.span)?;
6762 self.emit(Opcode::Dup, &[]);
6763 self.private_load(&binding, kind, argument.span)?;
6764 self.emit(instruction, &[]);
6765 self.emit(
6766 if prefix {
6767 Opcode::Insert2
6768 } else {
6769 Opcode::Perm3
6770 },
6771 &[],
6772 );
6773 self.private_store(&binding, kind, setter.as_deref())?;
6774 }
6775 }
6776 return Ok(());
6777 }
6778 let ExprKind::Ident(name) = &argument.kind else {
6779 return Err(SyntaxError::new(
6780 "increment of a non-variable is not supported by the compiler yet",
6781 argument.span,
6782 ));
6783 };
6784 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
6785 // reference's `inc_loc` folds those three into one, but it does so only in some
6786 // positions (a `for` update and not a bare statement, and never for a lexical
6787 // binding), so emitting it unconditionally would move *away* from its output.
6788 // The instruction is equivalent either way; matching the reference matters more
6789 // than saving two instructions.
6790 let _ = !std::mem::take(&mut self.state().discard_value);
6791 self.emit_var(VarAction::Get, &name.name);
6792 self.emit(instruction, &[]);
6793 if prefix {
6794 self.emit(Opcode::Dup, &[]);
6795 }
6796 self.emit_var(VarAction::Put, &name.name);
6797 Ok(())
6798 }
6799
6800 /// Compile an array literal.
6801 ///
6802 /// The reference splits this into three phases, and the split is load-bearing
6803 /// rather than an optimisation detail:
6804 ///
6805 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
6806 /// the array in one instruction.
6807 /// 2. **Everything up to the first spread** is appended with explicit indices
6808 /// (`define_field <index>`), because a hole has no element to pass to
6809 /// `array_from`. A hole here is what makes `length` need fixing up: an
6810 /// explicit index does not extend the array the way a pushed element does.
6811 /// 3. **From the first spread on** the index lives on the stack, so `append` and
6812 /// `define_array_el` can consume it and `inc` advances it.
6813 ///
6814 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
6815 /// forces phase 2, and `[...a]` forces phase 3.
6816 fn array_literal(
6817 &mut self,
6818 elements: &[Option<ArrayElement>],
6819 span: Span,
6820 ) -> Result<(), SyntaxError> {
6821 let _ = span;
6822 let mut index: u32 = 0;
6823 let mut cursor = 0usize;
6824
6825 // Phase 1: a leading run of plain elements, at most 32 of them.
6826 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
6827 if index >= 32 {
6828 break;
6829 }
6830 self.expr(element)?;
6831 index += 1;
6832 cursor += 1;
6833 }
6834 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
6835
6836 // Phase 2: explicit indices, up to the first spread.
6837 let mut need_length = false;
6838 while let Some(element) = elements.get(cursor) {
6839 if matches!(element, Some(ArrayElement::Spread(_))) {
6840 break;
6841 }
6842 need_length = true;
6843 if let Some(ArrayElement::Expr(expression)) = element {
6844 self.expr(expression)?;
6845 self.emit_define_index(index);
6846 need_length = false;
6847 }
6848 index += 1;
6849 cursor += 1;
6850 }
6851
6852 if cursor >= elements.len() {
6853 if need_length {
6854 // `define_field` cannot set `length`, which is not configurable.
6855 self.emit(Opcode::Dup, &[]);
6856 self.push_number(index as f64);
6857 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
6858 }
6859 return Ok(());
6860 }
6861
6862 // Phase 3: the index moves onto the stack for the spreading tail.
6863 //
6864 // `need_length` deliberately carries over from phase 2: a hole before the
6865 // first spread still has to be reflected in `length`, and only the final
6866 // check can do it because the array is not finished until the tail is
6867 // appended.
6868 self.push_number(index as f64);
6869 while let Some(element) = elements.get(cursor) {
6870 match element {
6871 Some(ArrayElement::Spread(expression)) => {
6872 // `append` copies an iterable and leaves the next index behind,
6873 // so no `inc` is needed here.
6874 self.expr(spread_argument(expression))?;
6875 self.emit(Opcode::Append, &[]);
6876 }
6877 None | Some(ArrayElement::Expr(_)) => {
6878 need_length = true;
6879 if let Some(ArrayElement::Expr(expression)) = element {
6880 self.expr(expression)?;
6881 self.emit(Opcode::DefineArrayEl, &[]);
6882 need_length = false;
6883 }
6884 self.emit(Opcode::Inc, &[]);
6885 }
6886 }
6887 cursor += 1;
6888 }
6889 if need_length {
6890 self.emit(Opcode::Dup1, &[]);
6891 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
6892 } else {
6893 self.emit(Opcode::Drop, &[]);
6894 }
6895 Ok(())
6896 }
6897
6898 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
6899 fn emit_define_index(&mut self, index: u32) {
6900 self.emit(
6901 Opcode::DefineField,
6902 &[Op::Atom(Atom::from_text(&index.to_string()))],
6903 );
6904 }
6905
6906 // -- functions ---------------------------------------------------------
6907
6908 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
6909 self.compile_function_with_name(func, false)
6910 }
6911
6912 /// Compile a function, recording whether it is a *named function expression*.
6913 ///
6914 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
6915 /// must not leak outside. The reference does that by declaring `g` as a local of
6916 /// the function itself and initialising it with `special_object 2` (the current
6917 /// function), which is why this has to be known at compile time.
6918 fn compile_function_with_name(
6919 &mut self,
6920 func: &ast::Function,
6921 is_expression: bool,
6922 ) -> Result<CompiledFunction, SyntaxError> {
6923 let kind = match (func.is_generator, func.is_async) {
6924 (false, false) => FunctionKind::Normal,
6925 (true, false) => FunctionKind::Generator,
6926 (false, true) => FunctionKind::Async,
6927 (true, true) => FunctionKind::AsyncGenerator,
6928 };
6929 let mut state = FnState::new(
6930 func.name
6931 .as_ref()
6932 .map(|n| n.name.clone())
6933 .unwrap_or_default(),
6934 kind,
6935 );
6936 // The function's own mode, recorded by the parser. Inheriting the enclosing
6937 // function's instead let a nested `"use strict"` directive be ignored, so the
6938 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
6939 state.strict = func.strict;
6940 // A function defined inside a `with` block keeps seeing that object: the guard
6941 // chain names the enclosing `<with>` locals, which resolve outward into closure
6942 // variables exactly like any other captured binding.
6943 state.with_names = self.cur().with_names.clone();
6944 state.is_arrow = func.is_arrow;
6945 state.created_in_block = self.cur().current_block;
6946 // A default anywhere in the parameter list is what gives the function two
6947 // variable environments. The reference decides this the same way: it scans the
6948 // parenthesis for a top-level `=`, so a destructured name without a default
6949 // stays a plain function-scope binding.
6950 state.in_params = false;
6951 // The reference scans the parenthesis for *any* `=`, including one nested inside
6952 // a pattern, so `function f({a = 1})` has parameter expressions even though the
6953 // parameter itself carries no initialiser.
6954 state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
6955 // A function born inside a parameter list inherits the prohibition: it must not
6956 // see the body bindings of the function it was created in.
6957 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
6958 // A class constructor knows what it is only because the class told it.
6959 if let Some(kind) = self.cur().class_ctor_pending {
6960 state.ctor_kind = kind;
6961 }
6962 // A named *expression* binds its own name; a declaration's name is already
6963 // bound in the enclosing scope.
6964 state.self_name = if is_expression && !func.is_arrow {
6965 func.name.as_ref().map(|n| n.name.clone())
6966 } else {
6967 None
6968 };
6969 state.line = func.span.start.line;
6970 state.column = func.span.start.column;
6971 // A function body has no hidden `<ret>` local; the value comes back on
6972 // the stack. Only a script keeps one.
6973 // Parameters are positional, so even a pattern occupies one argument slot. A
6974 // simple name is that slot itself; anything else (a pattern, a default, a rest
6975 // parameter) takes an anonymous slot and is unpicked into locals at the top of
6976 // the body, which is the only way one argument can bind several names.
6977 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
6978 // `.length` stops at the first parameter that can be substituted: a default
6979 // fills a missing argument in, and a rest parameter absorbs the rest.
6980 let mut defined_args = func.params.len() as u32;
6981 for (index, param) in func.params.iter().enumerate() {
6982 match simple_parameter(param) {
6983 Some(name) => state.args.push(VarDef::var(name.name.clone())),
6984 None => {
6985 state.args.push(VarDef::var(ANONYMOUS_BINDING));
6986 prologue.push((index, param.clone()));
6987 }
6988 }
6989 }
6990 // A default anywhere before the end also ends the count, which the loop above
6991 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
6992 for (position, param) in func.params.iter().enumerate() {
6993 if matches!(
6994 param.kind,
6995 PatternKind::Assign { .. } | PatternKind::Rest(_)
6996 ) {
6997 defined_args = position as u32;
6998 break;
6999 }
7000 }
7001 state.defined_args = defined_args;
7002 state.param_prologue = prologue;
7003 let depth = self.stack.len();
7004 self.stack.push(state);
7005 let result = self.compile_function_body(func);
7006 if result.is_err() {
7007 // A failed compile must not leave its `FnState` behind. Every caller
7008 // reads `self.state()` as "the function being compiled", so a leftover
7009 // frame silently retargets all later bookkeeping at a dead function.
7010 self.stack.truncate(depth);
7011 }
7012 result
7013 }
7014
7015 /// The body of a function, with its frame already pushed.
7016 fn compile_function_body(
7017 &mut self,
7018 func: &ast::Function,
7019 ) -> Result<CompiledFunction, SyntaxError> {
7020 let body_key = func.params_span.end.offset as u64;
7021 // Where the body begins, in source order. The runtime needs this to tell a
7022 // closure created by a default expression from one the body creates — the two see
7023 // different variable environments — and a bytecode offset would not survive the
7024 // instruction shuffling that building the frame does. Positions are in source
7025 // order, so a comparison answers it.
7026 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7027 self.push_block(body_key, NO_PARENT);
7028 self.state().body_block = body_key;
7029 // An arrow with an expression body has no statements; the expression is
7030 // its `return`. Building the statement here keeps one code path below, and
7031 // matters for correctness beyond convenience: returning early with the new
7032 // `FnState` still on the stack would leave the compiler looking at the
7033 // wrong function, which surfaces as an unrelated underflow later.
7034 let concise = match &func.body {
7035 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
7036 StmtKind::Return(Some(Box::new((**value).clone()))),
7037 value.span,
7038 )),
7039 js_parse::ast::FunctionBody::Block(_) => None,
7040 };
7041 let body: &[Stmt] = match &concise {
7042 Some(stmt) => std::slice::from_ref(stmt),
7043 None => func
7044 .body
7045 .statements()
7046 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
7047 };
7048 let prologue = std::mem::take(&mut self.state().param_prologue);
7049 let has_param_scope = self.cur().has_parameter_expressions;
7050 // The parameter scope's own bindings, declared in source order.
7051 //
7052 // With parameter expressions the list gets a variable environment of its own, and
7053 // every name it binds is a `let` there. That is what puts the *list* in the
7054 // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
7055 // and `function f(x = y, y){}` does the same, where a single shared environment
7056 // would answer `undefined` to both.
7057 if has_param_scope {
7058 let mut declared: Vec<String> = Vec::new();
7059 for param in &func.params {
7060 let mut names = Vec::new();
7061 param.bound_names(&mut names);
7062 for name in names {
7063 if declared.contains(&name.name) {
7064 continue;
7065 }
7066 declared.push(name.name.clone());
7067 self.declare_param_binding(&name.name);
7068 }
7069 }
7070 }
7071 // A pattern parameter binds its names as function-scope locals, so they have to
7072 // exist — and be unpicked from the argument — before the body runs. With a
7073 // parameter scope these are the *second* environment: the pattern fills the
7074 // parameter's copy, and the body's binding is filled from it afterwards.
7075 for (_, pattern) in &prologue {
7076 let mut names = Vec::new();
7077 pattern.bound_names(&mut names);
7078 for name in names {
7079 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
7080 }
7081 }
7082 self.hoist(body, body_key)?;
7083 // A constructor's prologue is not a parameter unpacking but the `this` binding:
7084 // a base constructor takes the receiver, a derived one starts in the dead zone
7085 // because only `super()` may produce it.
7086 match self.cur().ctor_kind {
7087 CtorKind::None => {}
7088 CtorKind::Base => {
7089 self.begin_this_local();
7090 self.emit(Opcode::CheckCtor, &[]);
7091 // Instance fields are installed at the top of a base constructor's body,
7092 // before any statement — `class C { x = 1; constructor() { this.x } }` sees
7093 // `1`. This used to be emitted at the *tail*, which made every field read
7094 // `undefined` inside the constructor that declared it.
7095 self.call_field_initialiser();
7096 }
7097 CtorKind::Derived => {
7098 self.declare("this", VarDef::lexical("this"));
7099 let slot = self.cur().vars.len() as u32 - 1;
7100 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7101 self.emit(Opcode::CheckCtor, &[]);
7102 }
7103 }
7104 // Entering the parameter list: everything it binds starts in the dead zone.
7105 // The order is the reference's — it walks the scope chain, which is prepended, so
7106 // the bindings come out newest first.
7107 for name in self.param_binding_names().into_iter().rev() {
7108 if let Some(slot) = self.param_binding_slot(&name) {
7109 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7110 }
7111 }
7112 // The whole parameter list is one scope, and nothing in the body exists yet, so
7113 // every name it mentions resolves against the parameter bindings and outward.
7114 self.state().in_params = has_param_scope;
7115 for (index, param) in func.params.iter().enumerate() {
7116 if let Some(pattern) = prologue_pattern(&prologue, index) {
7117 // A destructuring parameter *initialises* its bindings: with a parameter
7118 // scope they are the list's own `let`s, which is why the stores skip the
7119 // dead-zone check, and why the reference reads their properties with
7120 // `get_field2` — a `let` needs no reference.
7121 let kind = if has_param_scope {
7122 VarDeclKind::Let
7123 } else {
7124 VarDeclKind::Var
7125 };
7126 match &pattern.kind {
7127 // `...rest` collects what is left rather than reading one slot.
7128 PatternKind::Rest(inner) => {
7129 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7130 self.destructure(inner, Some(kind))?;
7131 }
7132 _ => {
7133 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7134 self.destructure(pattern, Some(kind))?;
7135 }
7136 }
7137 continue;
7138 }
7139 // A plain name binds straight from its argument slot. With a parameter scope
7140 // the slot is also copied into the parameter binding, which is what a later
7141 // default (or a closure made among the defaults) reads.
7142 let Some(name) = simple_parameter(param) else {
7143 continue;
7144 };
7145 let target = self.param_binding_slot(&name.name);
7146 if matches!(param.kind, PatternKind::Rest(_)) {
7147 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7148 if let Some(slot) = target {
7149 self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
7150 }
7151 // `put_arg` rather than `set_arg`: the array is the last thing on the
7152 // stack and nothing keeps it. Named by hand because a name in the
7153 // parameter list resolves to the parameter binding, and this store has to
7154 // reach the *argument* — that is what the body reads.
7155 self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
7156 continue;
7157 }
7158 if let PatternKind::Assign { default, .. } = ¶m.kind {
7159 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7160 let has_value = self.new_label();
7161 self.emit(Opcode::Dup, &[]);
7162 self.emit(Opcode::IsUndefined, &[]);
7163 self.emit_jump(Opcode::IfFalse, has_value, &[]);
7164 self.emit(Opcode::Drop, &[]);
7165 self.expr(default)?;
7166 self.set_name_if_anonymous(default, &name.name);
7167 // The argument slot keeps the substituted value, because the *body* reads
7168 // the slot rather than the parameter binding — so this store is named
7169 // explicitly, like the rest parameter's.
7170 self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7171 self.place_label(has_value);
7172 if let Some(slot) = target {
7173 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7174 }
7175 continue;
7176 }
7177 if let Some(slot) = target {
7178 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7179 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7180 }
7181 }
7182 // Copy the parameter scope into the body. A plain parameter needs nothing: the
7183 // body reads its argument slot, and the list kept the two in step. A name a
7184 // pattern bound has no argument slot of its own, so the body gets a `var` filled
7185 // from the parameter's copy — and *that* is why an assignment inside a default
7186 // does not reach the body.
7187 if has_param_scope {
7188 for (_, pattern) in &prologue {
7189 let mut names = Vec::new();
7190 pattern.bound_names(&mut names);
7191 for name in names {
7192 let Some(slot) = self.param_binding_slot(&name.name) else {
7193 continue;
7194 };
7195 let Some(body) = self.body_var_slot(&name.name) else {
7196 continue;
7197 };
7198 self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
7199 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
7200 }
7201 }
7202 }
7203 // The parameter list is over; from here on a direct `eval` belongs to the body.
7204 self.state().in_params = false;
7205 // Entering the body's own scope comes *after* the parameter list: the body's
7206 // `let`s are not in existence while the defaults run, and the reference emits
7207 // their `set_loc_uninitialized` only once the parameters are bound.
7208 self.emit_scope_enter(body_key);
7209 // A generator starts suspended: `initial_yield` parks the body so that creating one
7210 // runs no body code until the first `next()`.
7211 //
7212 // It comes *after* the parameter unpacking, not before, because a parameter
7213 // initialiser is not body code — `function* g(a = sideEffect())` must run
7214 // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
7215 // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
7216 // until the first `next()` and 29 test262 cases that check for a synchronous throw
7217 // saw none at all.
7218 //
7219 // An async function does **not** get one. Its body runs synchronously up to the
7220 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
7221 // before its caller's next statement — so an `initial_yield` here would park the
7222 // body before it started, which is not fixable at run time: the suspension looks
7223 // exactly like a real `await`.
7224 if self.cur().kind.is_generator() {
7225 self.emit(Opcode::InitialYield, &[]);
7226 }
7227 // Through `stmts`: the body is a block, and a `using` declaration in it is a
7228 // disposal region.
7229 self.stmts(body)?;
7230 // The implicit return only exists if control can actually get here: an
7231 // infinite loop never falls off the end.
7232 if self.end_is_reachable() {
7233 if self.cur().is_suspending() {
7234 // Falling off the end finishes the generator with `undefined`, and the
7235 // value is what tells the resume machinery "completed" rather than
7236 // "suspended".
7237 self.emit(Opcode::Undefined, &[]);
7238 self.emit(Opcode::ReturnAsync, &[]);
7239 } else {
7240 self.emit_class_constructor_tail();
7241 }
7242 }
7243 // Resolution runs while this function is still on the stack: capturing a
7244 // variable from an enclosing function means reaching into that
7245 // function's state, which requires the whole chain to be present.
7246 Ok(self.finish_current())
7247 }
7248
7249 /// Put every binding of a function that contains a direct `eval` into a cell.
7250 ///
7251 /// A direct eval can name any binding in scope, and any closure it creates has to
7252 /// keep sharing that binding after the function returns — `for (let i …)
7253 /// eval("push(() => i)")` collects one closure per iteration and each must read its
7254 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
7255 /// a cell. Doing this unconditionally for such functions is the cheap, honest
7256 /// answer: the alternative is knowing at compile time which names a string will
7257 /// mention.
7258 fn capture_everything_for_eval(&mut self) {
7259 let current = self.stack.len() - 1;
7260 if !self.stack[current].has_direct_eval {
7261 return;
7262 }
7263 for arg in &mut self.stack[current].args {
7264 arg.is_captured = true;
7265 }
7266 for var in &mut self.stack[current].vars {
7267 var.is_captured = true;
7268 }
7269 }
7270
7271 /// Whether the current position in the instruction stream can be reached.
7272 ///
7273 /// A walk over the control-flow graph, using labels as instruction indices.
7274 /// The reference does the same thing to decide whether an implicit
7275 /// `return_undef` is needed.
7276 fn end_is_reachable(&self) -> bool {
7277 let state = self.cur();
7278 reachable_instructions(state, state.insns.len())[state.insns.len()]
7279 }
7280
7281 /// Resolve and assemble the function on top of the compiler stack, then pop
7282 /// it.
7283 fn finish_current(&mut self) -> CompiledFunction {
7284 self.provide_param_arguments();
7285 self.provide_arguments();
7286 self.provide_this_local();
7287 self.provide_new_target_local();
7288 self.provide_home_object_local();
7289 self.provide_active_func_local();
7290 self.provide_self_name();
7291 self.materialize_eval_sites();
7292 self.capture_everything_for_eval();
7293 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
7294 // Captured bindings need a reference cell; the count goes in the header so
7295 // the runtime knows how many cells to allocate on entry.
7296 let current = self.stack.len() - 1;
7297 let captured = self.stack[current]
7298 .args
7299 .iter()
7300 .filter(|a| a.is_captured)
7301 .count()
7302 + self.stack[current]
7303 .vars
7304 .iter()
7305 .filter(|v| v.is_captured)
7306 .count();
7307 self.stack[current].var_ref_count = captured as u32;
7308 // The scope chain is only final now that every binding is known.
7309 rebuild_scope_chain(&mut self.stack[current]);
7310 let (code, stack_size, positions) =
7311 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
7312 let _ = &mut resolved;
7313 let mut state = self.stack.pop().expect("a function is being compiled");
7314 CompiledFunction {
7315 name: state.name,
7316 kind: state.kind,
7317 strict: state.strict,
7318 is_arrow: state.is_arrow,
7319 has_parameter_expressions: state.has_parameter_expressions,
7320 body_start: state.body_start,
7321 args: state.args,
7322 defined_args: state.defined_args,
7323 vars: state.vars,
7324 closure_vars: state.closure_vars,
7325 cpool: state.cpool,
7326 atoms: state.atoms,
7327 code,
7328 stack_size,
7329 var_ref_count: state.var_ref_count,
7330 positions,
7331 source: None,
7332 line: state.line,
7333 column: state.column,
7334 filename: None,
7335 eval_sites: state.eval_sites,
7336 module: state.module.take().map(Box::new),
7337 }
7338 }
7339}
7340
7341/// Assign each binding a scope level and rebuild the scope chains.
7342///
7343/// Levels are numbered in the order the blocks appear, with 0 reserved for the
7344/// function scope where `var` and hoisted functions live. Every binding outside
7345/// level 0 gets a `scope_next` link to the next binding visible from the same
7346/// point, so walking a block's chain enumerates exactly the bindings live there.
7347///
7348/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
7349/// point at `b`, which is declared later in the source but earlier in the chain.
7350fn rebuild_scope_chain(state: &mut FnState) {
7351 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
7352 // real block that happens to start at offset zero keeps its own level instead of
7353 // being merged into the function scope.
7354 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
7355 for block in &state.blocks {
7356 if !levels.contains(&block.key) {
7357 levels.push(block.key);
7358 }
7359 }
7360 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
7361 let parent_level = |level: usize| -> usize {
7362 if level == 0 {
7363 return 0;
7364 }
7365 let key = levels[level];
7366 let parent = state
7367 .blocks
7368 .iter()
7369 .find(|b| b.key == key)
7370 .map(|b| b.parent)
7371 .unwrap_or(FUNCTION_SCOPE);
7372 level_of(parent)
7373 };
7374
7375 // Own bindings per level, in declaration order.
7376 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
7377 let keys: Vec<u64> = (0..state.vars.len())
7378 .map(|index| {
7379 state
7380 .var_block
7381 .get(index)
7382 .copied()
7383 .unwrap_or(FUNCTION_SCOPE)
7384 })
7385 .collect();
7386 for (index, key) in keys.into_iter().enumerate() {
7387 // The parameter scope is not a block: it is a level of its own with no parent,
7388 // assigned below. Letting it land in level 0 would chain the body's bindings onto
7389 // it, which the reference does not do — the two environments are siblings.
7390 if key == PARAM_SCOPE {
7391 continue;
7392 }
7393 let level = level_of(key);
7394 state.vars[index].scope_level = level as u32;
7395 // A `catch` parameter is part of the runtime scope chain even though it is
7396 // not lexical: the handler's own bindings chain on to it, which is why the
7397 // reference prints `let y [next:1]` with `e` at 1.
7398 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
7399 {
7400 own[level].push(index);
7401 }
7402 }
7403
7404 // A scope's chain is its own bindings in reverse declaration order followed
7405 // by the enclosing scope's chain.
7406 let mut head = vec![-1i32; levels.len()];
7407 for level in 0..levels.len() {
7408 let inherited = if level == 0 {
7409 -1
7410 } else {
7411 head[parent_level(level)]
7412 };
7413 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
7414 head[level] = chain.first().map_or(inherited, |first| *first as i32);
7415 for (position, &index) in chain.iter().enumerate() {
7416 let next = chain
7417 .get(position + 1)
7418 .map_or(inherited, |next| *next as i32);
7419 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
7420 }
7421 }
7422 state.block_heads = head;
7423
7424 // The parameter list is a scope of its own, and it has no parent: the reference pops
7425 // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
7426 // the `-1` a block uses. A level past every real block keeps it out of the walk above
7427 // — nothing but the dump reads it — and the links run newest-to-oldest through the
7428 // bindings themselves, which is the order `set_loc_uninitialized` walks.
7429 let param_level = levels.len() as u32;
7430 let mut previous: Option<usize> = None;
7431 for index in 0..state.vars.len() {
7432 if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
7433 {
7434 continue;
7435 }
7436 state.vars[index].scope_level = param_level;
7437 state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
7438 previous = Some(index);
7439 }
7440}
7441
7442/// This is where names become slots and where the temporal dead zone shows up in
7443/// the instruction stream: a read of a `let`/`const` binding compiles to
7444/// `get_loc_check`, which throws if the binding is still uninitialised.
7445///
7446/// The peephole pass from the reference implementation is applied at the end,
7447/// for the same reason it is applied to resolved bytecode there: the patterns are
7448/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
7449/// resolution. Deleted instructions stay in the list as `None` so that label
7450/// indices remain valid; [`Assembler`] maps them to byte offsets.
7451/// A resolved instruction and the source position it came from.
7452type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
7453
7454/// A resolved instruction paired with its position, which is what `assemble` consumes.
7455type PositionedInsn = (Opcode, Vec<Op>);
7456
7457fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
7458 let current = stack.len() - 1;
7459 // Dead-code elimination, on the symbolic form where labels are still
7460 // instruction indices. A `break` inside a loop leaves the trailing `goto`
7461 // unreachable, and a `return` leaves everything after it unreachable; the
7462 // reference drops both. Doing it here means the emitter never has to think
7463 // about reachability.
7464 strip_empty_gosubs(stack, current);
7465 eliminate_dead_code(stack, current);
7466 let insns = std::mem::take(&mut stack[current].insns);
7467 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
7468 // `insns`, and every arm below pushes exactly one instruction, so the positions
7469 // stay aligned with `out`.
7470 let positions = std::mem::take(&mut stack[current].insn_pos);
7471 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
7472 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
7473 for (index, insn) in insns.iter().enumerate() {
7474 let pos = positions.get(index).copied().flatten();
7475 out_pos.push(pos);
7476 match insn {
7477 Insn::Fixed { op, operands } => {
7478 let operands = operands
7479 .iter()
7480 .map(|operand| match operand {
7481 Op::Atom(atom) => {
7482 Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
7483 }
7484 other => other.clone(),
7485 })
7486 .collect();
7487 out.push(Some((*op, operands)));
7488 }
7489 Insn::Var {
7490 action,
7491 name,
7492 block,
7493 in_params,
7494 } => {
7495 // Both reads and writes in the parameter list address the parameter
7496 // scope. That is what puts the list in the temporal dead zone — a read of
7497 // a later parameter is `get_loc_check` on an uninitialised slot — and it
7498 // is also what keeps an assignment made inside a default away from the
7499 // body, which sees a separate environment.
7500 let slot = resolve_slot(stack, current, name, *block, *in_params);
7501 // A store to the name of a named function expression is special: the
7502 // reference drops it in sloppy mode and throws in strict mode, because
7503 // the binding is immutable but only *checked* when the body is strict.
7504 // The same rule applies when the name is reached through a closure:
7505 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
7506 // the store in the arrow too, not just in the function that owns the
7507 // binding. Reaching the owner means walking the chain of closure
7508 // entries, which is what `self_name_binding` does.
7509 let self_name = matches!(action, VarAction::Put | VarAction::Set)
7510 .then(|| {
7511 // A local of this function is the common case and needs no
7512 // chain walk; only an access that resolves elsewhere can be
7513 // pointing at an enclosing function's name binding.
7514 if let Slot::Loc(index) = slot {
7515 stack[current]
7516 .vars
7517 .get(index as usize)
7518 .filter(|var| var.kind == VarKind::FunctionName)
7519 .map(|var| var.is_const)
7520 } else {
7521 self_name_binding(stack, current, name, *block)
7522 }
7523 })
7524 .flatten();
7525 if let Some(is_const) = self_name {
7526 out.push(Some(if is_const {
7527 (
7528 Opcode::ThrowError,
7529 vec![
7530 Op::AtomId(intern_atom(&mut stack[current], name)),
7531 Op::Int(0),
7532 ],
7533 )
7534 } else {
7535 (Opcode::Drop, Vec::new())
7536 }));
7537 continue;
7538 }
7539 out.push(Some(variable_instruction(stack, current, *action, slot)));
7540 }
7541 Insn::CloseCaptured { name, block } => {
7542 // The block matters: a loop variable is scoped to the `for` head's own
7543 // block, so resolving it against block 0 would miss it entirely and
7544 // silently emit nothing.
7545 let slot = resolve_slot(stack, current, name, *block, false);
7546 // Only a local with a reference cell has anything to close. A global
7547 // or a never-captured local resolves to no instruction at all, which
7548 // keeps the bytecode identical to the reference's.
7549 if let Slot::Loc(index) = slot
7550 && stack[current]
7551 .vars
7552 .get(index as usize)
7553 .is_some_and(|v| v.is_captured)
7554 {
7555 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
7556 } else {
7557 out.push(None);
7558 }
7559 }
7560 Insn::DeleteVar { name } => {
7561 // A binding — a local, an argument, or a declared global — cannot be
7562 // deleted, and the reference encodes that as a constant `push_false`.
7563 // Only an implicit global needs the runtime lookup.
7564 if matches!(
7565 resolve_slot(stack, current, name, 0, false),
7566 Slot::Global(_)
7567 ) {
7568 let atom = intern_atom(&mut stack[current], name);
7569 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
7570 } else {
7571 out.push(Some((Opcode::PushFalse, Vec::new())));
7572 }
7573 }
7574 Insn::Dead => out.push(None),
7575 }
7576 }
7577 // Which label (if any) sits on each instruction, so the jump patterns can
7578 // tell whether they would cross a jump target.
7579 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
7580 for (id, placed) in stack[current].labels.iter().enumerate() {
7581 if let Some(index) = *placed
7582 && index < label_at.len()
7583 && label_at[index].is_none()
7584 {
7585 label_at[index] = Some(id as u32);
7586 }
7587 }
7588 if std::env::var_os("QJS_DEBUG").is_some() {
7589 eprintln!("--- peephole entry ---");
7590 for (i, e) in out.iter().enumerate() {
7591 eprintln!("{i}: {e:?}");
7592 }
7593 eprintln!("label_at: {label_at:?}");
7594 }
7595 peephole(&mut out, &label_at, &stack[current].labels);
7596 (out, out_pos)
7597}
7598
7599/// Find where `name` lives, capturing it in an enclosing function when needed.
7600///
7601/// The search runs outward through the enclosing functions' states, which are
7602/// still on the compiler stack while a nested function is resolved. Finding the
7603/// name in an enclosing function is what creates a closure reference, and every
7604/// function in between has to forward it — a function can only reach its own
7605/// parent's frame.
7606///
7607/// A name declared nowhere is a global. The reference does *not* look it up by
7608/// name from the inner function: the top-level function gets one `[global]`
7609/// entry and every nested function gets a `[global_ref<n>]` pointing at its
7610/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
7611/// rather than `[global]`.
7612/// The lexical blocks enclosing `block`, innermost first.
7613fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
7614 let mut chain = Vec::new();
7615 let mut current = Some(block);
7616 while let Some(key) = current {
7617 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
7618 // explicitly (rather than on "no block with this key") is what keeps a block
7619 // that happens to sit at offset zero from being mistaken for the terminator.
7620 if key == NO_PARENT || chain.contains(&key) {
7621 break;
7622 }
7623 chain.push(key);
7624 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
7625 }
7626 chain
7627}
7628
7629/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
7630///
7631/// The binding may be several functions away: an arrow nested in `function myfunc`
7632/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
7633/// means following `Ref` entries down and then reading the owning function's var table.
7634fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
7635 let state = stack.get(current)?;
7636 // A parameter shadows everything and is never a function-expression name.
7637 if state.args.iter().any(|arg| arg.name == name) {
7638 return None;
7639 }
7640 // A local of this very function: the answer is in its var table.
7641 if let Some(index) = local_slot_index(state, name, block) {
7642 let var = state.vars.get(index)?;
7643 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7644 }
7645 // Otherwise the name lives further out, and the closure entry says how to get
7646 // there. `Local` names the owner's slot directly; `Ref` names the next level's
7647 // closure entry, so the walk continues downwards.
7648 let mut level = current;
7649 let mut index = state
7650 .closure_vars
7651 .iter()
7652 .position(|closure| closure.name == name)?;
7653 loop {
7654 let state = stack.get(level)?;
7655 let closure = state.closure_vars.get(index)?;
7656 match closure.closure_type {
7657 ClosureType::Local => {
7658 let owner = stack.get(level.checked_sub(1)?)?;
7659 let var = owner.vars.get(closure.var_idx as usize)?;
7660 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7661 }
7662 ClosureType::Arg => return None,
7663 ClosureType::Ref => {
7664 level -= 1;
7665 index = closure.var_idx as usize;
7666 }
7667 // A global is never a function-expression name.
7668 ClosureType::Global
7669 | ClosureType::GlobalDecl
7670 | ClosureType::GlobalRef
7671 | ClosureType::ModuleDecl
7672 | ClosureType::ModuleImport => return None,
7673 }
7674 }
7675}
7676
7677/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
7678fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
7679 block_chain(state, block).into_iter().find_map(|scope| {
7680 state.vars.iter().enumerate().find_map(|(index, var)| {
7681 (var.name == name && state.var_block.get(index).copied() == Some(scope))
7682 .then_some(index)
7683 })
7684 })
7685}
7686
7687/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
7688fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
7689 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
7690 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
7691 }) {
7692 return index as u32;
7693 }
7694 state.var_block.push(PARAM_SCOPE);
7695 state.vars.push(VarDef::var(name));
7696 state.vars.len() as u32 - 1
7697}
7698
7699/// The name a parameter binds straight from its argument slot, if it has one.
7700///
7701/// A plain name does — with or without a default, and with or without `...`. Everything
7702/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
7703/// reference names the argument in the first case and leaves it `<null>` in the second,
7704/// so both the dump and the closures that capture the argument depend on this.
7705fn simple_parameter(param: &Pattern) -> Option<&Ident> {
7706 match ¶m.kind {
7707 PatternKind::Ident(name) => Some(name),
7708 PatternKind::Assign { target, .. } => match &target.kind {
7709 PatternKind::Ident(name) => Some(name),
7710 _ => None,
7711 },
7712 PatternKind::Rest(inner) => match &inner.kind {
7713 PatternKind::Ident(name) => Some(name),
7714 _ => None,
7715 },
7716 _ => None,
7717 }
7718}
7719
7720/// The pattern a parameter list has to unpick, if `index` is one of them.
7721fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
7722 prologue
7723 .iter()
7724 .find(|(at, _)| *at == index)
7725 .map(|(_, pattern)| pattern)
7726}
7727
7728/// Whether a parameter pattern contains a default anywhere, at any depth.
7729///
7730/// The reference decides "this function has parameter expressions" by scanning the
7731/// parenthesis for a top-level `=`, which a default buried in a pattern still counts as —
7732/// `function f({a = 1})` has a parameter scope just like `function f(a = 1)`.
7733fn pattern_has_default(pattern: &Pattern) -> bool {
7734 match &pattern.kind {
7735 PatternKind::Assign { .. } => true,
7736 PatternKind::Rest(inner) => pattern_has_default(inner),
7737 PatternKind::Array { elements, rest } => {
7738 elements.iter().flatten().any(element_has_default)
7739 || rest.as_deref().is_some_and(rest_has_default)
7740 }
7741 PatternKind::Object { properties, rest } => {
7742 properties.iter().flatten().any(element_has_default)
7743 || rest.as_deref().is_some_and(rest_has_default)
7744 }
7745 _ => false,
7746 }
7747}
7748
7749fn element_has_default(element: &PatternElement) -> bool {
7750 match element {
7751 PatternElement::Pattern(pattern) => pattern_has_default(pattern),
7752 PatternElement::Property { value, .. } => pattern_has_default(value),
7753 }
7754}
7755
7756fn rest_has_default(rest: &RestElement) -> bool {
7757 match rest {
7758 RestElement::Pattern(pattern) => pattern_has_default(pattern),
7759 RestElement::Member(_) => false,
7760 }
7761}
7762
7763/// Whether a function-scope binding is visible to the parameter list.
7764///
7765/// The parameter list runs before the body, so the body's `var`s and function
7766/// declarations do not exist yet — a name that only the body declares has to resolve
7767/// outward instead. What *does* exist by then is the compiler's own prologue: the
7768/// self-name of a named function expression (bound by `special_object 2` before anything
7769/// else), `this` and `new.target`. Those stay visible, which is what makes
7770/// `function f(a = this)` and `var f = function f(a = f)` work.
7771///
7772/// `arguments` is handled separately, as a binding of the parameter scope itself: with
7773/// parameter expressions the reference creates two of them, and the one the parameter
7774/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
7775fn visible_in_params(var: &VarDef) -> bool {
7776 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
7777}
7778
7779fn resolve_slot(
7780 stack: &mut [FnState],
7781 current: usize,
7782 name: &str,
7783 block: u64,
7784 in_params: bool,
7785) -> Slot {
7786 // The parameter list's own bindings. They are consulted first because they shadow
7787 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
7788 // `a` in the parameter scope, so a closure made there reads the parameter even after
7789 // the body assigns to its own `a`.
7790 if in_params
7791 && let Some(index) = stack[current]
7792 .vars
7793 .iter()
7794 .enumerate()
7795 .position(|(index, var)| {
7796 var.name == name
7797 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
7798 })
7799 {
7800 return Slot::Loc(index as u32);
7801 }
7802 // A name can be bound more than once: two `catch` parameters in nested
7803 // handlers are two slots. The binding that wins is the one whose scope encloses
7804 // the access, and among those the innermost — so the blocks are walked outward
7805 // and the first binding found on the way is the one that counts. A binding in
7806 // no block (`var`) is reachable from anywhere, which is why the function scope
7807 // is the end of the walk.
7808 //
7809 // The block walk comes *before* the argument slots, because a block may shadow a
7810 // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
7811 // slot is only the answer once nothing nearer claims the name.
7812 let chain = block_chain(&stack[current], block);
7813 for scope in &chain {
7814 let found = stack[current]
7815 .vars
7816 .iter()
7817 .enumerate()
7818 .find(|(index, var)| {
7819 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
7820 })
7821 .map(|(index, _)| index);
7822 if let Some(index) = found {
7823 return Slot::Loc(index as u32);
7824 }
7825 }
7826 // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
7827 // its own slot, and `var` of the same name in the body is the same binding.
7828 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
7829 return Slot::Arg(index as u32);
7830 }
7831 // Function-scope bindings — `var` and function declarations — are recorded with
7832 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
7833 // them. They are reachable from anywhere in the function, which is exactly what
7834 // the sentinel means.
7835 //
7836 // This pass is *only* for those. A lexical binding has to be found through the
7837 // chain or not at all, and looking a name up without its block is precisely how
7838 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
7839 // block leaked out of it.
7840 let function_scoped = stack[current]
7841 .vars
7842 .iter()
7843 .enumerate()
7844 .find(|(index, var)| {
7845 var.name == name
7846 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
7847 && (!in_params || visible_in_params(var))
7848 })
7849 .map(|(index, _)| index);
7850 if let Some(index) = function_scoped {
7851 return Slot::Loc(index as u32);
7852 }
7853 if let Some(index) = stack[current]
7854 .closure_vars
7855 .iter()
7856 .position(|c| c.name == name)
7857 {
7858 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
7859 }
7860
7861 for owner in (0..current).rev() {
7862 // The nested function was created inside one of this frame's blocks, and the
7863 // outermost visible binding is the innermost block on that chain — not whatever
7864 // comes first in the variable table. `function f(){ class S{} }` has two `S`
7865 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
7866 // the class body is the one a method may see.
7867 let entry = stack
7868 .get(owner + 1)
7869 .map(|s| s.created_in_block)
7870 .unwrap_or(0);
7871 let lexical = block_chain(&stack[owner], entry)
7872 .into_iter()
7873 .find_map(|scope| {
7874 stack[owner]
7875 .vars
7876 .iter()
7877 .enumerate()
7878 .find(|(index, var)| {
7879 var.name == name
7880 && stack[owner].var_block.get(*index).copied() == Some(scope)
7881 })
7882 .map(|(index, _)| index)
7883 });
7884 // A function born in a parameter list sees that list's bindings, not the body's:
7885 // the parameter scope is the environment it was created in.
7886 let in_param_scope = stack
7887 .get(owner + 1)
7888 .is_some_and(|child| child.created_in_params)
7889 .then(|| {
7890 stack[owner]
7891 .vars
7892 .iter()
7893 .enumerate()
7894 .position(|(index, var)| {
7895 var.name == name
7896 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
7897 })
7898 })
7899 .flatten();
7900 let found = if let Some(index) = in_param_scope {
7901 let var = &stack[owner].vars[index];
7902 Some(Found::Local(
7903 ClosureType::Local,
7904 index as u32,
7905 var.is_const,
7906 var.needs_check(),
7907 ))
7908 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
7909 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
7910 } else if let Some(index) = lexical {
7911 let var = &stack[owner].vars[index];
7912 Some(Found::Local(
7913 ClosureType::Local,
7914 index as u32,
7915 var.is_const,
7916 var.needs_check(),
7917 ))
7918 } else if let Some(index) = stack[owner]
7919 .vars
7920 .iter()
7921 .enumerate()
7922 .find_map(|(index, var)| {
7923 // A function created inside a parameter list must not see the body of the
7924 // function it was born in; see [`FnState::created_in_params`].
7925 let hidden = stack
7926 .get(owner + 1)
7927 .is_some_and(|child| child.created_in_params);
7928 (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
7929 })
7930 {
7931 let var = &stack[owner].vars[index];
7932 Some(Found::Local(
7933 ClosureType::Local,
7934 index as u32,
7935 var.is_const,
7936 var.needs_check(),
7937 ))
7938 } else if stack[owner].self_name.as_deref() == Some(name) {
7939 // A named function expression's own name. The reference declares it here,
7940 // on the first lookup that fails, rather than up front — and that is what
7941 // makes it reachable from a *nested* function: the nested lookup is what
7942 // walks out and creates the binding. A direct reference in the body is
7943 // caught the same way, which is why `provide_self_name` only has to add
7944 // the prologue.
7945 let strict = stack[owner].strict;
7946 stack[owner].var_block.push(FUNCTION_SCOPE);
7947 stack[owner].vars.push(VarDef {
7948 kind: VarKind::FunctionName,
7949 // In strict mode the name is immutable, so a store raises; sloppy
7950 // mode drops the store instead (see `variable_instruction`).
7951 is_const: strict,
7952 ..VarDef::var(name)
7953 });
7954 let index = stack[owner].vars.len() as u32 - 1;
7955 Some(Found::Local(ClosureType::Local, index, strict, false))
7956 } else if let Some(index) = stack[owner]
7957 .closure_vars
7958 .iter()
7959 .position(|c| c.name == name)
7960 {
7961 let closure = &stack[owner].closure_vars[index];
7962 Some(match closure.closure_type {
7963 // `GlobalRef` belongs here too: it is a *global* reached through this
7964 // frame's reference table, so treating it as a `Ref` to a local cell makes
7965 // the reader look for a cell no frame ever fills. That is how a second
7966 // function using `eval` in its parameter list read `undefined` after a
7967 // sibling had already made `eval` a closure entry.
7968 ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
7969 Found::Global(index as u32)
7970 }
7971 // A module variable is a cell in the *module's* environment, which is
7972 // the module body's parent as far as a nested function is concerned — so
7973 // it is captured as a plain reference, not looked up as a global.
7974 ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
7975 ClosureType::Ref,
7976 index as u32,
7977 closure.is_const,
7978 closure.is_lexical,
7979 ),
7980 _ => Found::Local(
7981 ClosureType::Ref,
7982 index as u32,
7983 closure.is_const,
7984 closure.is_lexical,
7985 ),
7986 })
7987 } else {
7988 None
7989 };
7990 let Some(found) = found else { continue };
7991
7992 let (is_const, is_lexical) = match found {
7993 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
7994 Found::Global(_) => (false, false),
7995 };
7996 // Mark the owner's binding as captured so it moves into a reference cell.
7997 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
7998 let slot = match found {
7999 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8000 _ => &mut stack[owner].vars[index as usize],
8001 };
8002 slot.is_captured = true;
8003 }
8004 // Forward the reference through every function in between.
8005 let mut previous = match found {
8006 Found::Local(kind, index, _, _) => (kind, index),
8007 Found::Global(index) => (ClosureType::Global, index),
8008 };
8009 for level in owner + 1..=current {
8010 let kind = match (previous.0, level) {
8011 // A global stays a global at *every* level. Without `GlobalRef` in
8012 // this arm the second nested function over the same global got a
8013 // `Ref` to a cell no frame ever held, so the innermost closure read
8014 // `undefined` — which is how a two-deep getter lost its outer
8015 // variable.
8016 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8017 ClosureType::GlobalRef
8018 }
8019 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8020 _ => ClosureType::Ref,
8021 };
8022 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8023 previous = (kind, index);
8024 }
8025 let index = previous.1;
8026 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8027 }
8028
8029 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8030 // creating a property. The top-level function holds the entry.
8031 let mut previous = (
8032 ClosureType::Global,
8033 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8034 );
8035 for level in 1..=current {
8036 let index = ensure_closure(
8037 stack,
8038 level,
8039 name,
8040 false,
8041 false,
8042 ClosureType::GlobalRef,
8043 previous.1,
8044 );
8045 previous = (ClosureType::GlobalRef, index);
8046 }
8047 Slot::Global(previous.1)
8048}
8049
8050/// What an outward search turned up.
8051#[derive(Debug, Clone, Copy)]
8052enum Found {
8053 /// A binding in an enclosing function, reachable through a closure of this
8054 /// type, with its const/lexical flags.
8055 Local(ClosureType, u32, bool, bool),
8056 /// A global, reached through the enclosing function's closure entry.
8057 Global(u32),
8058}
8059
8060/// Add a closure entry to `level` if it is not there yet.
8061fn ensure_closure(
8062 stack: &mut [FnState],
8063 level: usize,
8064 name: &str,
8065 is_const: bool,
8066 is_lexical: bool,
8067 closure_type: ClosureType,
8068 var_idx: u32,
8069) -> u32 {
8070 if let Some(index) = stack[level]
8071 .closure_vars
8072 .iter()
8073 .position(|c| c.name == name)
8074 {
8075 return index as u32;
8076 }
8077 stack[level].closure_vars.push(ClosureVar {
8078 name: name.to_string(),
8079 is_const,
8080 is_lexical,
8081 closure_type,
8082 var_idx: var_idx as u16,
8083 });
8084 stack[level].closure_vars.len() as u32 - 1
8085}
8086
8087fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
8088 match closure.closure_type {
8089 // A `global_ref` only says *how* the binding is found (through the
8090 // parent's closure table); the access itself is an ordinary global one.
8091 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
8092 ClosureType::GlobalDecl => Slot::GlobalDecl(index),
8093 // A module variable is a real cell in the module's environment, so it is reached
8094 // exactly like a captured local — the host, not the global object, is what fills
8095 // the slot.
8096 ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
8097 _ => Slot::VarRef(index),
8098 }
8099}
8100
8101/// Pick the opcode for one variable access.
8102///
8103/// The `_check` variants are what enforce the temporal dead zone. They are used
8104/// for every access to a `let`/`const` binding except its own initialisation —
8105/// which is exactly the operation that takes the binding out of the dead zone.
8106fn variable_instruction(
8107 stack: &[FnState],
8108 current: usize,
8109 action: VarAction,
8110 slot: Slot,
8111) -> (Opcode, Vec<Op>) {
8112 let lexical = match slot {
8113 Slot::Loc(index) => stack[current]
8114 .vars
8115 .get(index as usize)
8116 .is_some_and(|v| v.needs_check()),
8117 Slot::VarRef(index) => stack[current]
8118 .closure_vars
8119 .get(index as usize)
8120 .is_some_and(|c| c.is_lexical),
8121 _ => false,
8122 };
8123 let operand = vec![Op::Slot(slot)];
8124 match (action, slot) {
8125 (VarAction::Get, Slot::Loc(index)) => (
8126 if lexical {
8127 Opcode::GetLocCheck
8128 } else {
8129 Opcode::GetLoc
8130 },
8131 vec![Op::Slot(Slot::Loc(index))],
8132 ),
8133 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
8134 (VarAction::Get, Slot::VarRef(index)) => (
8135 if lexical {
8136 Opcode::GetVarRefCheck
8137 } else {
8138 Opcode::GetVarRef
8139 },
8140 vec![Op::Slot(Slot::VarRef(index))],
8141 ),
8142 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
8143 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
8144 (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
8145 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
8146 (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
8147 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8148 (Opcode::GetVarUndef, operand)
8149 }
8150
8151 (VarAction::Put, Slot::Loc(_)) => (
8152 if lexical {
8153 Opcode::PutLocCheck
8154 } else {
8155 Opcode::PutLoc
8156 },
8157 operand,
8158 ),
8159 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
8160 (VarAction::Put, Slot::VarRef(_)) => (
8161 if lexical {
8162 Opcode::PutVarRefCheck
8163 } else {
8164 Opcode::PutVarRef
8165 },
8166 operand,
8167 ),
8168 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
8169 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8170 // Initialisation is what ends the dead zone, so it never checks.
8171 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8172 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
8173 // `this` in a derived constructor is always a local, so these cannot happen;
8174 // routing them to the ordinary forms keeps the match total without inventing
8175 // opcodes the reference does not have.
8176 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
8177 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8178 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8179 (Opcode::PutVarInit, operand)
8180 }
8181 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
8182 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8183 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8184 (Opcode::PutVarInit, operand)
8185 }
8186 (VarAction::Set, Slot::Loc(_)) => (
8187 if lexical {
8188 Opcode::SetLocCheck
8189 } else {
8190 Opcode::SetLoc
8191 },
8192 operand,
8193 ),
8194 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
8195 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
8196 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8197 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8198 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
8199 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8200 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
8201 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
8202 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8203 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
8204 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8205 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
8206 }
8207}
8208
8209/// The instruction-rewriting pass.
8210///
8211/// These are the reference implementation's patterns, restricted to the ones the
8212/// constructs this compiler supports can produce. Each entry is a comment on the
8213/// bytecode it removes, because the whole point is that the result is one
8214/// instruction shorter than the literal translation of the AST.
8215fn peephole(
8216 insns: &mut [Option<(Opcode, Vec<Op>)>],
8217 label_at: &[Option<u32>],
8218 placed: &[Option<usize>],
8219) {
8220 fold_dup_patterns(insns, label_at);
8221
8222 // `drop` before `return_undef` is dead: the return discards the whole frame
8223 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
8224 // consumes its own `drop`; removing the drop first would leave the `dup` and
8225 // produce a `set_` where the reference has a `put_`.
8226 for index in 0..insns.len() {
8227 if opcode_at(insns, index) != Some(Opcode::Drop) {
8228 continue;
8229 }
8230 // Skip over a run of drops, but stop at a jump target: removing code on
8231 // one side of a label would silently retarget the jump.
8232 let mut next = index + 1;
8233 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
8234 next += 1;
8235 }
8236 if is_label_at(label_at, next) {
8237 continue;
8238 }
8239 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
8240 for entry in &mut insns[index..next] {
8241 *entry = None;
8242 }
8243 }
8244 }
8245
8246 // The rewrites below all decide against one fixed snapshot, which is what the
8247 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
8248 // the pass, so a rule never observes what an earlier rule removed. Gathering
8249 // every deletion first and applying them together reproduces that.
8250 let snapshot: Vec<Option<Opcode>> = insns
8251 .iter()
8252 .map(|entry| entry.as_ref().map(|(op, _)| *op))
8253 .collect();
8254 // The next instruction that is still there. Holes left by dead-code
8255 // elimination are not instructions, so a rule looks past them.
8256 let next_op = |index: usize| -> Option<usize> {
8257 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
8258 };
8259
8260 let mut doomed = vec![false; insns.len()];
8261 for index in 0..insns.len() {
8262 // A constant pushed only to be dropped does nothing at all. This is what a
8263 // comma expression with a literal left operand compiles to — `(0, f)()` — and
8264 // the reference removes the pair rather than making the reader step over it.
8265 let constant = matches!(
8266 snapshot[index],
8267 Some(
8268 Opcode::Undefined
8269 | Opcode::Null
8270 | Opcode::PushMinus1
8271 | Opcode::Push0
8272 | Opcode::Push1
8273 | Opcode::Push2
8274 | Opcode::Push3
8275 | Opcode::Push4
8276 | Opcode::Push5
8277 | Opcode::Push6
8278 | Opcode::Push7
8279 | Opcode::PushTrue
8280 | Opcode::PushFalse
8281 | Opcode::PushI32
8282 )
8283 );
8284 if constant
8285 && let Some(next) = next_op(index)
8286 && snapshot[next] == Some(Opcode::Drop)
8287 {
8288 doomed[index] = true;
8289 doomed[next] = true;
8290 }
8291 }
8292 for (index, entry) in insns.iter_mut().enumerate() {
8293 if doomed[index] {
8294 *entry = None;
8295 }
8296 }
8297
8298 // A conditional whose destination is the very next instruction just pops its
8299 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
8300 // compiles to.
8301 //
8302 // Order matters, and it is the reference's order: this runs *before* the
8303 // folding below, on the instruction the conditional originally had. Folding
8304 // moves a conditional's destination, and the reference never re-examines it
8305 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
8306 // a conditional even though folding leaves it pointing at the next
8307 // instruction.
8308 for (index, entry) in insns.iter_mut().enumerate() {
8309 let Some((op, operands)) = entry.clone() else {
8310 continue;
8311 };
8312 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
8313 continue;
8314 }
8315 let Some(id) = label_id(&operands) else {
8316 continue;
8317 };
8318 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
8319 *entry = Some((Opcode::Drop, Vec::new()));
8320 }
8321 }
8322
8323 // A constant condition is decided here rather than at run time.
8324 fold_constant_conditions(insns);
8325 // The conditional folding below is about pairs of *real* branches, so it runs
8326 // before a jump to the next instruction is dropped: `do { … if (c) continue }
8327 // while (t)` puts `continue` exactly on the condition, and the reference inverts
8328 // the branch first and only then notices the jump goes nowhere.
8329 fold_conditional_jumps(insns, label_at, placed);
8330
8331 // A jump whose destination is the very next instruction does nothing, which is
8332 // what constant folding leaves behind for `while (1) { … }`.
8333 remove_jump_to_next(insns, placed);
8334
8335 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
8336 // a use of the same variable boils down to.
8337 for index in 0..insns.len() {
8338 let Some((put_op, _)) = insns[index].clone() else {
8339 continue;
8340 };
8341 if !is_foldable_put(put_op) {
8342 continue;
8343 }
8344 if is_label_at(label_at, index + 1) {
8345 continue;
8346 }
8347 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
8348 continue;
8349 };
8350 if get_op != get_form_of(put_op) {
8351 continue;
8352 }
8353 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
8354 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
8355 continue;
8356 }
8357 insns[index] = Some((set_form_of(put_op), get_operands));
8358 insns[index + 1] = None;
8359 }
8360}
8361
8362/// Drop `gosub`s that call an empty subroutine.
8363///
8364/// A `gosub` whose target starts with `ret` returns immediately, so the reference
8365/// drops the call. This is how `try`/`catch` without a `finally` loses its
8366/// finalizer plumbing: the finalizer block is empty, its first instruction is
8367/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
8368/// [`eliminate_dead_code`] then removes.
8369fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
8370 let state = &stack[current];
8371 let mut targets = Vec::new();
8372 for insn in &state.insns {
8373 if let Insn::Fixed { op, operands } = insn
8374 && *op == Opcode::Gosub
8375 && let Some(id) = label_id(operands)
8376 && let Some(target) = state.labels.get(id as usize).copied().flatten()
8377 {
8378 targets.push(target);
8379 }
8380 }
8381 let empty: Vec<usize> = targets
8382 .into_iter()
8383 .filter(|target| {
8384 stack[current]
8385 .insns
8386 .get(*target)
8387 .map(|insn| {
8388 matches!(
8389 insn,
8390 Insn::Fixed {
8391 op: Opcode::Ret,
8392 ..
8393 }
8394 )
8395 })
8396 .unwrap_or(false)
8397 })
8398 .collect();
8399 if empty.is_empty() {
8400 return;
8401 }
8402 for insn in stack[current].insns.iter_mut() {
8403 if let Insn::Fixed { op, operands } = insn
8404 && *op == Opcode::Gosub
8405 && let Some(id) = label_id(operands)
8406 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
8407 && empty.contains(&target)
8408 {
8409 *insn = Insn::Dead;
8410 }
8411 }
8412}
8413
8414/// Replace unreachable instructions with [`Insn::Dead`].
8415fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
8416 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
8417 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
8418 if !reachable[index] {
8419 *insn = Insn::Dead;
8420 }
8421 }
8422}
8423
8424/// Mark every instruction index reachable from the entry, plus the index one past
8425/// the last instruction.
8426///
8427/// `seen[len]` answers "can control reach the end of this function", and the
8428/// entries before it identify dead code. Both DCE and the implicit-return decision
8429/// read the same result, which keeps them from disagreeing.
8430fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
8431 let mut seen = vec![false; count + 1];
8432 let mut worklist = vec![0usize];
8433 while let Some(index) = worklist.pop() {
8434 if index > count || seen[index] {
8435 continue;
8436 }
8437 seen[index] = true;
8438 if index == count {
8439 continue;
8440 }
8441 let (op, operands) = match &state.insns[index] {
8442 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
8443 // A variable access never transfers control, and a removed
8444 // instruction is only reachable if it is already marked.
8445 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
8446 worklist.push(index + 1);
8447 continue;
8448 }
8449 };
8450 match op {
8451 // A return, a throw and a `ret` all leave this instruction stream: the
8452 // first two give control to the caller or the handler, and `ret`
8453 // returns to a `gosub` elsewhere.
8454 // A tail call leaves the function too: the callee's result becomes this
8455 // function's result, so nothing after it runs.
8456 Opcode::Return
8457 | Opcode::ReturnUndef
8458 | Opcode::ReturnAsync
8459 | Opcode::TailCall
8460 | Opcode::TailCallMethod
8461 | Opcode::Throw
8462 | Opcode::ThrowError
8463 | Opcode::Ret => {}
8464 // A `catch` records where exceptions from the code that follows go.
8465 // That code is not reachable through normal control flow, but it is
8466 // reachable — through the exception edge — so the walk has to follow
8467 // it, or dead-code elimination would delete every handler.
8468 Opcode::Catch => {
8469 if let Some(target) = placed_label(state, operands) {
8470 worklist.push(target);
8471 }
8472 worklist.push(index + 1);
8473 }
8474 // A `gosub` calls a subroutine and then continues, so both edges count.
8475 Opcode::Gosub => {
8476 if let Some(target) = placed_label(state, operands) {
8477 worklist.push(target);
8478 }
8479 worklist.push(index + 1);
8480 }
8481 Opcode::Goto => {
8482 if let Some(target) = placed_label(state, operands) {
8483 worklist.push(target);
8484 }
8485 }
8486 Opcode::IfTrue | Opcode::IfFalse => {
8487 if let Some(target) = placed_label(state, operands) {
8488 worklist.push(target);
8489 }
8490 worklist.push(index + 1);
8491 }
8492 _ => worklist.push(index + 1),
8493 }
8494 }
8495 seen
8496}
8497
8498/// The instruction index a jump operand points at, resolved through the label
8499/// placement table.
8500fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
8501 let id = label_id(operands)?;
8502 state.labels.get(id as usize).copied().flatten()
8503}
8504
8505/// The label an instruction refers to.
8506fn label_id(operands: &[Op]) -> Option<u32> {
8507 operands.iter().find_map(|operand| match operand {
8508 Op::Label(label) => Some(label.0),
8509 _ => None,
8510 })
8511}
8512
8513/// Turn `if_false L; goto M; L:` into `if_true M`.
8514///
8515/// A conditional whose alternate branch is an unconditional jump needs one jump,
8516/// not two. This is the shape `if (c) break;` produces, so folding it removes an
8517/// instruction and a label from every conditional `break`.
8518/// The boolean a constant-push instruction produces, or `None` if it is not one.
8519///
8520/// Only the operators whose truthiness is decided by the opcode are covered; a
8521/// constant that needs the constant pool (a string) is left alone, because reading it
8522/// would mean threading the pool through the peephole for a case the reference also
8523/// skips.
8524fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
8525 match op {
8526 // `push_0` returns -1 for zero, `push_1` 1, and so on.
8527 Opcode::PushMinus1 => Some(true),
8528 Opcode::Push0 => Some(false),
8529 Opcode::Push1
8530 | Opcode::Push2
8531 | Opcode::Push3
8532 | Opcode::Push4
8533 | Opcode::Push5
8534 | Opcode::Push6
8535 | Opcode::Push7 => Some(true),
8536 Opcode::PushTrue => Some(true),
8537 Opcode::PushFalse => Some(false),
8538 Opcode::Undefined | Opcode::Null => Some(false),
8539 Opcode::PushI32 => match operands.first() {
8540 Some(Op::Int(value)) => Some(*value != 0),
8541 _ => None,
8542 },
8543 _ => None,
8544 }
8545}
8546
8547/// Fold a branch on a constant condition.
8548///
8549/// `if (0) a() else b()` must not test anything at run time, and the reference
8550/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
8551/// which is why the bytecode for a `while (1)` loop has no condition at all.
8552///
8553/// Two instructions become one, so the slot the test occupied is left empty rather
8554/// than shifting everything after it: labels have already been resolved to indices.
8555fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
8556 for index in 0..insns.len() {
8557 let Some((push_op, push_operands)) = insns[index].clone() else {
8558 continue;
8559 };
8560 let Some(truth) = constant_truth(push_op, &push_operands) else {
8561 continue;
8562 };
8563 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
8564 continue;
8565 };
8566 let (destination, taken) = match branch_op {
8567 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
8568 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
8569 _ => continue,
8570 };
8571 let Some(destination) = destination else {
8572 continue;
8573 };
8574 insns[index] = if taken {
8575 // The branch is always taken, so it becomes an unconditional jump.
8576 Some((Opcode::Goto, vec![destination]))
8577 } else {
8578 // The branch never runs: both instructions disappear and control falls
8579 // through to what came after.
8580 None
8581 };
8582 insns[index + 1] = None;
8583 }
8584}
8585
8586/// Remove a jump whose destination is the instruction right after it.
8587///
8588/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
8589/// its test into nothing, and the loop-end jump then points at the following
8590/// instruction. The reference drops them, so `stack_size` and the listing agree.
8591fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
8592 for index in 0..insns.len() {
8593 let Some((op, operands)) = insns[index].clone() else {
8594 continue;
8595 };
8596 if !is_goto(op) {
8597 continue;
8598 }
8599 let Some(id) = label_id(&operands) else {
8600 continue;
8601 };
8602 // The next instruction that still exists, which is what "the instruction
8603 // after this jump" means once earlier folds have punched holes.
8604 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
8605 if placed.get(id as usize).copied().flatten() == next {
8606 insns[index] = None;
8607 }
8608 }
8609}
8610
8611fn fold_conditional_jumps(
8612 insns: &mut [Option<(Opcode, Vec<Op>)>],
8613 label_at: &[Option<u32>],
8614 placed: &[Option<usize>],
8615) {
8616 for index in 0..insns.len() {
8617 let Some((op, operands)) = insns[index].clone() else {
8618 continue;
8619 };
8620 let inverted = match op {
8621 Opcode::IfFalse => Opcode::IfTrue,
8622 Opcode::IfTrue => Opcode::IfFalse,
8623 _ => continue,
8624 };
8625 // Next must be an unconditional jump that is not itself a target, and the
8626 // instruction after it must be exactly where the conditional goes.
8627 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
8628 continue;
8629 };
8630 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
8631 continue;
8632 }
8633 // The conditional must land on the instruction *after* the jump. Several
8634 // labels can share a position, so this asks where *this* label was put
8635 // rather than what label happens to sit there.
8636 let Some(taken) = label_id(&operands) else {
8637 continue;
8638 };
8639 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
8640 continue;
8641 }
8642 let Some(destination) = next_operands.first().cloned() else {
8643 continue;
8644 };
8645 insns[index] = Some((inverted, vec![destination]));
8646 insns[index + 1] = None;
8647 }
8648}
8649
8650/// Whether a jump target is placed at this instruction index.
8651fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
8652 label_at.get(index).copied().flatten().is_some()
8653}
8654
8655fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
8656 // `dup put_x(n)` -> `set_x(n)`
8657 // `dup put_x(n) drop` -> `put_x(n)`
8658 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
8659 for index in 0..insns.len() {
8660 if opcode_at(insns, index) != Some(Opcode::Dup) {
8661 continue;
8662 }
8663 if is_label_at(label_at, index + 1) {
8664 continue;
8665 }
8666 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
8667 continue;
8668 };
8669 if !is_foldable_put(put_op) {
8670 continue;
8671 }
8672 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
8673 continue;
8674 };
8675 let mut new_op = set_form_of(put_op);
8676 let mut end = index + 2;
8677 if is_label_at(label_at, end) {
8678 // The `put` has to stay as it is; only the `dup` can be folded.
8679 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
8680 insns[index + 1] = None;
8681 continue;
8682 }
8683 // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
8684 // Deleting it moves the label's target onto whatever follows, and the code that
8685 // jumps there arrives with a different stack than the fall-through path: that is
8686 // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
8687 // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
8688 // an empty stack. The store had already consumed the value it was supposed to
8689 // leave behind.
8690 if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
8691 new_op = put_op;
8692 end += 1;
8693 if opcode_at(insns, end) == Some(get_form_of(put_op))
8694 && !is_label_at(label_at, end)
8695 && insns[end]
8696 .as_ref()
8697 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
8698 {
8699 new_op = set_form_of(put_op);
8700 end += 1;
8701 }
8702 }
8703 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
8704 for entry in &mut insns[index + 1..end] {
8705 *entry = None;
8706 }
8707 }
8708}
8709
8710fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
8711 insns
8712 .get(index)
8713 .and_then(|entry| entry.as_ref())
8714 .map(|(op, _)| *op)
8715}
8716
8717/// The four `put_` families that have a `set_` twin. Deliberately not including
8718/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
8719/// these, and folding the others would produce instructions that do not exist.
8720fn is_foldable_put(op: Opcode) -> bool {
8721 matches!(
8722 op,
8723 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
8724 )
8725}
8726
8727fn set_form_of(op: Opcode) -> Opcode {
8728 match op {
8729 Opcode::PutLoc => Opcode::SetLoc,
8730 Opcode::PutLocCheck => Opcode::SetLocCheck,
8731 Opcode::PutArg => Opcode::SetArg,
8732 Opcode::PutVarRef => Opcode::SetVarRef,
8733 other => other,
8734 }
8735}
8736
8737fn get_form_of(op: Opcode) -> Opcode {
8738 match op {
8739 Opcode::PutLoc => Opcode::GetLoc,
8740 Opcode::PutLocCheck => Opcode::GetLocCheck,
8741 Opcode::PutArg => Opcode::GetArg,
8742 Opcode::PutVarRef => Opcode::GetVarRef,
8743 other => other,
8744 }
8745}
8746
8747/// Atom interning, per function.
8748///
8749/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
8750/// identifiers, so the array-index rule applies here rather than at the handful of
8751/// call sites that build property keys.
8752fn intern_atom(state: &mut FnState, name: &str) -> u32 {
8753 intern_atom_value(state, Atom::from_text(name))
8754}
8755
8756/// [`intern_atom`] for an operand that is already an [`Atom`].
8757///
8758/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
8759/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
8760/// would have looked up.
8761fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
8762 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
8763 return index as u32;
8764 }
8765 state.atoms.push(atom);
8766 state.atoms.len() as u32 - 1
8767}
8768
8769fn binary_opcode(op: BinaryOp) -> Opcode {
8770 match op {
8771 BinaryOp::Add => Opcode::Add,
8772 BinaryOp::Sub => Opcode::Sub,
8773 BinaryOp::Mul => Opcode::Mul,
8774 BinaryOp::Div => Opcode::Div,
8775 BinaryOp::Mod => Opcode::Mod,
8776 BinaryOp::Pow => Opcode::Pow,
8777 BinaryOp::BitOr => Opcode::Or,
8778 BinaryOp::BitXor => Opcode::Xor,
8779 BinaryOp::BitAnd => Opcode::And,
8780 BinaryOp::Shl => Opcode::Shl,
8781 BinaryOp::Shr => Opcode::Sar,
8782 BinaryOp::UShr => Opcode::Shr,
8783 BinaryOp::Lt => Opcode::Lt,
8784 BinaryOp::LtEq => Opcode::Lte,
8785 BinaryOp::Gt => Opcode::Gt,
8786 BinaryOp::GtEq => Opcode::Gte,
8787 BinaryOp::Eq => Opcode::Eq,
8788 BinaryOp::NotEq => Opcode::Neq,
8789 BinaryOp::StrictEq => Opcode::StrictEq,
8790 BinaryOp::StrictNotEq => Opcode::StrictNeq,
8791 BinaryOp::In => Opcode::In,
8792 BinaryOp::Instanceof => Opcode::Instanceof,
8793 }
8794}
8795
8796fn compound_opcode(op: AssignOp) -> Opcode {
8797 match op {
8798 AssignOp::Add => Opcode::Add,
8799 AssignOp::Sub => Opcode::Sub,
8800 AssignOp::Mul => Opcode::Mul,
8801 AssignOp::Div => Opcode::Div,
8802 AssignOp::Mod => Opcode::Mod,
8803 AssignOp::Pow => Opcode::Pow,
8804 AssignOp::Shl => Opcode::Shl,
8805 AssignOp::Shr => Opcode::Sar,
8806 AssignOp::UShr => Opcode::Shr,
8807 AssignOp::BitOr => Opcode::Or,
8808 AssignOp::BitXor => Opcode::Xor,
8809 AssignOp::BitAnd => Opcode::And,
8810 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
8811 }
8812}
8813
8814/// Encode the resolved instruction stream, choosing short forms where possible.
8815///
8816/// The peephole pass leaves holes in the instruction list so that label indices
8817/// stay valid. A label names an *instruction index*, and an index that was
8818/// deleted has to resolve to the next surviving instruction, which is what
8819/// [`resolve_label`] does before the byte offsets are known.
8820fn assemble(
8821 insns: &mut [Option<(Opcode, Vec<Op>)>],
8822 insn_pos: &[Option<Position>],
8823 state: &mut FnState,
8824) -> (Vec<u8>, u32, Vec<LineCol>) {
8825 // Compaction: surviving instructions in order, plus the index mapping.
8826 //
8827 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
8828 // point below where instructions are removed — otherwise a stack trace would point
8829 // at the wrong source line as soon as dead-code elimination kicked in.
8830 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
8831 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8832 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
8833 for (original, entry) in insns.iter_mut().enumerate() {
8834 if let Some((op, operands)) = entry.take() {
8835 original_to_kept[original] = Some(kept.len());
8836 kept.push((op, operands));
8837 spans.push(insn_pos.get(original).copied().flatten());
8838 }
8839 }
8840
8841 if std::env::var_os("QJS_DEBUG").is_some() {
8842 eprintln!("--- assemble entry --- {kept:?}");
8843 }
8844 // How many labels are real, as opposed to the per-instruction ones allocated
8845 // just below. Only a real label marks a spot in the source program.
8846 let real_labels = state.labels.len();
8847
8848 // Give every surviving instruction a label of its own. Jump cleanup below
8849 // redirects jumps to arbitrary instructions, and a jump target has to be a
8850 // label; pre-allocating one per index means a redirect never has to invent
8851 // anything.
8852 let existing = state.labels.len();
8853 let base = kept.len();
8854 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
8855 for offset in 0..=kept.len() {
8856 state.labels.push(Some(0));
8857 index_label.push(Label((existing + offset) as u32));
8858 }
8859 // Point each pre-allocated label at its instruction, reusing the count from
8860 // `original_to_kept` so the mapping survives compaction.
8861 let place_index_labels = |state: &mut FnState,
8862 original_to_kept: &[Option<usize>],
8863 kept_len: usize,
8864 index_label: &[Label]| {
8865 for (original, mapped) in original_to_kept.iter().enumerate() {
8866 if let Some(kept_index) = mapped {
8867 let label = index_label[*kept_index].0 as usize;
8868 state.labels[label] = Some(original);
8869 }
8870 }
8871 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
8872 };
8873 place_index_labels(state, &original_to_kept, base, &index_label);
8874
8875 // Resolve every label to a kept index once; the placement table maps labels
8876 // to original indices, so a second hop lands in kept space.
8877 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
8878 for (id, placed) in state.labels.iter().enumerate() {
8879 let Some(original) = placed else { continue };
8880 label_kept[id] = if *original == usize::MAX {
8881 Some(base)
8882 } else {
8883 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
8884 };
8885 }
8886
8887 // Code after an unconditional transfer is unreachable, and the reference drops it
8888 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
8889 // scans forward until it finds a label something still jumps to, so a run of
8890 // dead instructions between a `throw` and the next live target disappears.
8891 //
8892 // The scan repeats because dropping a jump lowers the reference count of the
8893 // label it pointed at, which can strand what follows. Only a real label keeps an
8894 // instruction alive here; the per-instruction labels allocated above belong to
8895 // this pass, not to the program.
8896 loop {
8897 let mut references = vec![false; kept.len() + 1];
8898 for (_, operands) in &kept {
8899 if let Some(target) = target_kept_index(operands, &label_kept)
8900 && target < references.len()
8901 {
8902 references[target] = true;
8903 }
8904 }
8905 let mut doomed = vec![false; kept.len()];
8906 let mut any = false;
8907 for (index, (op, _)) in kept.iter().enumerate() {
8908 if !is_transfer(*op) {
8909 continue;
8910 }
8911 for next in index + 1..kept.len() {
8912 if references[next] {
8913 break;
8914 }
8915 doomed[next] = true;
8916 any = true;
8917 }
8918 }
8919 if !any {
8920 break;
8921 }
8922 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
8923 }
8924
8925 // A label that lands on an unconditional jump stands for wherever that jump
8926 // goes, so retarget it once and every jump to the label follows for free.
8927 // This is what makes `continue` in a `for` head reach the loop top instead of
8928 // stopping at the update's trailing jump.
8929 let folded: Vec<Option<usize>> = label_kept
8930 .iter()
8931 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
8932 .collect();
8933 label_kept = folded;
8934
8935 // Jump cleanup, in compacted index space. Two rewrites the reference also
8936 // applies while it resolves labels:
8937 // * a jump whose destination is the very next instruction does nothing;
8938 // * a jump to a jump is redirected to its final destination.
8939 // The second can expose the first, so this repeats until it settles.
8940 loop {
8941 let mut delete = vec![false; kept.len()];
8942 let mut changed = false;
8943 for index in 0..kept.len() {
8944 let (op, operands) = &kept[index];
8945 if !is_goto(*op) {
8946 continue;
8947 }
8948 let Some(immediate) = target_kept_index(operands, &label_kept) else {
8949 continue;
8950 };
8951 let target = follow_jump_chain(&kept, &label_kept, immediate);
8952 if target == index + 1 {
8953 delete[index] = true;
8954 changed = true;
8955 } else if matches!(
8956 kept.get(target).map(|(op, _)| *op),
8957 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
8958 ) {
8959 // Jumping straight to a return or throw is the same as doing it
8960 // here, so the jump becomes that instruction.
8961 kept[index] = (kept[target].0, Vec::new());
8962 changed = true;
8963 } else if target != immediate {
8964 // Redirect to the end of the chain.
8965 let label = index_label[target];
8966 kept[index].1 = vec![Op::Label(label)];
8967 changed = true;
8968 }
8969 }
8970 if !changed {
8971 break;
8972 }
8973 if !delete.iter().any(|deleted| *deleted) {
8974 break;
8975 }
8976 // Drop the deleted instructions and renumber everything.
8977 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
8978 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
8979 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
8980 for (old, entry) in kept.into_iter().enumerate() {
8981 if delete[old] {
8982 continue;
8983 }
8984 moved[old] = Some(next.len());
8985 next.push(entry);
8986 next_spans.push(spans[old]);
8987 }
8988 for (id, slot) in label_kept.iter_mut().enumerate() {
8989 let Some(old) = *slot else { continue };
8990 *slot = match moved.get(old).copied().flatten() {
8991 Some(new) => Some(new),
8992 // The target was deleted: the jump now lands on whatever follows.
8993 None => (old..moved.len())
8994 .find_map(|i| moved[i])
8995 .or(Some(next.len())),
8996 };
8997 let _ = id;
8998 }
8999 kept = next;
9000 spans = next_spans;
9001 }
9002
9003 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9004 // jump to the next instruction and is deleted, leaving the label at the end with
9005 // nothing pointing at it. If that also strands the last instruction, it goes
9006 // too — which is how a `try` whose body always returns ends on its `ret` rather
9007 // than an implicit `return_undef`.
9008 // Which instructions something still jumps to. Reading the surviving jumps is
9009 // what the reference's reference counts amount to: once a jump has been folded
9010 // away the label it named is unreferenced, even though the program still has a
9011 // label there.
9012 let mut references = vec![false; kept.len() + 1];
9013 let _ = real_labels;
9014 for (_, operands) in &kept {
9015 if let Some(target) = target_kept_index(operands, &label_kept)
9016 && target < references.len()
9017 {
9018 references[target] = true;
9019 }
9020 }
9021 let mut end = kept.len();
9022 while end > 0 {
9023 let last = end - 1;
9024 let reachable = references[last] || end < kept.len();
9025 if reachable {
9026 break;
9027 }
9028 let after_transfer = last
9029 .checked_sub(1)
9030 .map(|previous| {
9031 matches!(
9032 kept[previous].0,
9033 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
9034 )
9035 })
9036 .unwrap_or(false);
9037 if !after_transfer {
9038 break;
9039 }
9040 end = last;
9041 }
9042 kept.truncate(end);
9043 spans.truncate(end);
9044
9045 // Choose an opcode for each instruction and its size, so label offsets can be
9046 // computed.
9047 let chosen = choose_opcodes(&kept, &label_kept);
9048 let offsets = instruction_offsets(&chosen);
9049 let offset = *offsets.last().unwrap_or(&0);
9050
9051 let mut code = Vec::with_capacity(offset);
9052 for (position, (_, operands)) in kept.iter().enumerate() {
9053 let op = chosen[position];
9054 code.push(op as u8);
9055 let operands = retarget_labels(operands, &label_kept, kept.len());
9056 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
9057 }
9058 let stack_size = compute_stack_size(&code);
9059 // Keep only the offsets where the position actually changes: a run of
9060 // instructions on one line is one table entry, and the runtime binary searches
9061 // the table for the frame's pc.
9062 //
9063 // The table always starts at pc 0 with the *function's own* position, because the
9064 // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
9065 // last_line_num)` from `fd->source_pos`, the token the function definition starts at
9066 // (`function`, `async`, a method's property name). An instruction before the first
9067 // recorded operator therefore reports the function's own start, which is what makes a
9068 // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
9069 let mut positions: Vec<LineCol> = vec![LineCol {
9070 pc: 0,
9071 line: state.line,
9072 column: state.column,
9073 }];
9074 let mut last: Option<Position> = None;
9075 for (index, span) in spans.iter().enumerate() {
9076 let Some(pos) = *span else { continue };
9077 if last == Some(pos) {
9078 continue;
9079 }
9080 last = Some(pos);
9081 if pos.line == state.line && pos.column == state.column {
9082 // Already the seed entry above.
9083 continue;
9084 }
9085 positions.push(LineCol {
9086 pc: offsets[index] as u32,
9087 line: pos.line,
9088 column: pos.column,
9089 });
9090 }
9091 (code, stack_size, positions)
9092}
9093
9094/// Whether an instruction always transfers control away, so anything after it in the
9095/// same stream is unreachable.
9096fn is_transfer(op: Opcode) -> bool {
9097 matches!(
9098 op,
9099 Opcode::Goto
9100 | Opcode::Goto8
9101 | Opcode::Goto16
9102 | Opcode::Return
9103 | Opcode::ReturnUndef
9104 | Opcode::Throw
9105 | Opcode::ThrowError
9106 | Opcode::Ret
9107 )
9108}
9109
9110/// Remove the marked instructions and renumber the label table so it keeps pointing
9111/// at the same instructions. A label whose instruction went away moves to whatever
9112/// follows it, since a jump is never left with nowhere to land.
9113fn drop_instructions(
9114 kept: Vec<(Opcode, Vec<Op>)>,
9115 spans: Vec<Option<Position>>,
9116 label_kept: &mut [Option<usize>],
9117 doomed: &[bool],
9118) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
9119 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9120 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9121 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9122 for (old, entry) in kept.into_iter().enumerate() {
9123 if doomed.get(old).copied().unwrap_or(false) {
9124 continue;
9125 }
9126 moved[old] = Some(result.len());
9127 result.push(entry);
9128 result_spans.push(spans[old]);
9129 }
9130 for slot in label_kept.iter_mut() {
9131 let Some(old) = *slot else { continue };
9132 *slot = match moved.get(old).copied().flatten() {
9133 Some(new) => Some(new),
9134 None => (old..moved.len())
9135 .find_map(|i| moved[i])
9136 .or(Some(result.len())),
9137 };
9138 }
9139 (result, result_spans)
9140}
9141
9142fn is_goto(op: Opcode) -> bool {
9143 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
9144}
9145
9146/// The kept index a jump operand points at.
9147fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
9148 let id = label_id(operands)?;
9149 label_kept.get(id as usize).copied().flatten()
9150}
9151
9152/// Follow a chain of unconditional jumps to its first real destination.
9153fn follow_jump_chain(
9154 kept: &[(Opcode, Vec<Op>)],
9155 label_kept: &[Option<usize>],
9156 start: usize,
9157) -> usize {
9158 let mut current = start;
9159 // `for(;;)` jumps to itself, so the walk has to be bounded.
9160 for _ in 0..kept.len() {
9161 let Some((op, operands)) = kept.get(current) else {
9162 return current;
9163 };
9164 if !is_goto(*op) {
9165 return current;
9166 }
9167 let Some(next) = target_kept_index(operands, label_kept) else {
9168 return current;
9169 };
9170 if next == current {
9171 return current;
9172 }
9173 current = next;
9174 }
9175 current
9176}
9177
9178/// Rewrite label operands from label ids to kept instruction indices.
9179fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
9180 operands
9181 .iter()
9182 .map(|operand| match operand {
9183 Op::Label(label) => {
9184 let target = label_kept
9185 .get(label.0 as usize)
9186 .copied()
9187 .flatten()
9188 .unwrap_or(kept_len);
9189 Op::Label(Label(target as u32))
9190 }
9191 other => other.clone(),
9192 })
9193 .collect()
9194}
9195
9196/// Encode the resolved instruction stream, choosing short forms where possible.
9197///
9198/// Compute the maximum value-stack depth by exploring the control-flow graph.
9199///
9200/// This is a breadth-first walk from the first instruction, tracking the stack
9201/// depth on entry to each instruction. Every instruction has at most two
9202/// successors (fall through, and a jump target), so a worklist over byte offsets
9203/// is enough. The reference does the same thing in `compute_stack_size`, which is
9204/// why the resulting numbers match exactly.
9205///
9206/// Instructions that pop a variable number of values (`call`, `array_from`, …)
9207/// encode that count in their operand, which is added to the static `n_pop`.
9208fn compute_stack_size(code: &[u8]) -> u32 {
9209 let mut depth_at = vec![u16::MAX; code.len()];
9210 // Each entry carries the enclosing `catch` levels, innermost last, because
9211 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
9212 // offset and forgets that level.
9213 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
9214 let mut max_depth = 0u32;
9215
9216 while let Some((pc, depth, catch_levels)) = worklist.pop() {
9217 if pc >= code.len() {
9218 continue;
9219 }
9220 if depth_at[pc] != u16::MAX {
9221 continue;
9222 }
9223 force_depth(&mut depth_at, pc, depth);
9224
9225 let Some(op) = Opcode::from_u8(code[pc]) else {
9226 break;
9227 };
9228 let info = op.info();
9229 let next = pc + info.size as usize;
9230 if next > code.len() {
9231 break;
9232 }
9233 let mut n_pop = info.n_pop as u32;
9234 let mut n_push = info.n_push as u32;
9235 // Variable-length forms carry their count in the operand.
9236 match info.format {
9237 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
9238 n_pop += read_u16(code, pc + 1) as u32;
9239 }
9240 crate::opcode::OpFormat::Npopx => {
9241 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
9242 }
9243 _ => {}
9244 }
9245 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
9246 // are the `set_` variant; the table already records that, so nothing to
9247 // adjust here.
9248 let _ = &mut n_push;
9249
9250 // The depth before this instruction's own push, which is what a `catch`
9251 // records as its level.
9252 let depth_before = depth;
9253 let mut depth = depth.saturating_sub(n_pop) + n_push;
9254 let mut catch_levels = catch_levels;
9255 if op == Opcode::NipCatch {
9256 // Discard everything above the innermost catch offset, keeping the value
9257 // on top: the frame the code after this sees is the same shape it would
9258 // have had if the `try` were not there.
9259 if let Some(base) = catch_levels.pop() {
9260 depth = base + 1;
9261 }
9262 }
9263 max_depth = max_depth.max(depth);
9264
9265 // Successors.
9266 let target = jump_target_of(code, pc, op);
9267 match op {
9268 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9269 if let Some(target) = target {
9270 worklist.push((target, depth, catch_levels));
9271 }
9272 }
9273 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
9274 if let Some(target) = target {
9275 worklist.push((target, depth, catch_levels.clone()));
9276 }
9277 worklist.push((next, depth, catch_levels));
9278 }
9279 // A `catch` records an exception edge to the handler. The handler is
9280 // entered with the thrown value on top of the stack, in the slot the
9281 // catch offset occupies on the normal path — which is why the handler's
9282 // first instruction can `put_loc` the exception away, and why the depth
9283 // is the same on both paths.
9284 Opcode::Catch => {
9285 if let Some(target) = target {
9286 // The handler is protected by the *enclosing* catch, not by this
9287 // one: an error raised inside it is what the handler's own
9288 // `catch` catches.
9289 worklist.push((target, depth, catch_levels.clone()));
9290 }
9291 catch_levels.push(depth_before);
9292 worklist.push((next, depth, catch_levels));
9293 }
9294 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
9295 // rewind past it too. Its level sits one slot higher than a `catch`'s:
9296 // the iterator and next-method slots occupy the offset's place.
9297 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
9298 if let Some(target) = target {
9299 worklist.push((target, depth, catch_levels.clone()));
9300 }
9301 catch_levels.push(depth_before + 1);
9302 worklist.push((next, depth, catch_levels));
9303 }
9304 // `gosub` calls a subroutine with the return address on top. The opcode
9305 // table records no push for it — `ret` is what pops the slot — so the
9306 // extra one is added here, where the depth of the subroutine's first
9307 // instruction is being computed.
9308 Opcode::Gosub => {
9309 if let Some(target) = target {
9310 worklist.push((target, depth + 1, catch_levels.clone()));
9311 }
9312 worklist.push((next, depth, catch_levels));
9313 }
9314 // `ret` goes back to a `gosub`; nothing here follows it.
9315 Opcode::Ret
9316 | Opcode::Return
9317 | Opcode::ReturnUndef
9318 | Opcode::Throw
9319 | Opcode::ThrowError => {}
9320 _ => worklist.push((next, depth, catch_levels)),
9321 }
9322 }
9323 max_depth
9324}
9325
9326/// Record the stack depth on entry to `pc`, keeping the deeper value if the
9327/// instruction is reachable more than once.
9328fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
9329 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
9330 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
9331 depth_at[pc] = clamped;
9332 }
9333}
9334
9335fn read_u16(code: &[u8], at: usize) -> u16 {
9336 let mut value = 0u16;
9337 for i in 0..2 {
9338 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
9339 }
9340 value
9341}
9342
9343/// The absolute target of a jump instruction, if it has one.
9344fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
9345 let info = op.info();
9346 let position = pc + 1;
9347 match info.format {
9348 crate::opcode::OpFormat::Label8 => {
9349 let offset = *code.get(position)? as i8 as i64;
9350 Some((position as i64 + offset) as usize)
9351 }
9352 crate::opcode::OpFormat::Label16 => {
9353 let offset = read_u16(code, position) as i16 as i64;
9354 Some((position as i64 + offset) as usize)
9355 }
9356 crate::opcode::OpFormat::Label => {
9357 let mut offset = 0i32;
9358 for i in 0..4 {
9359 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
9360 }
9361 Some((position as i64 + offset as i64) as usize)
9362 }
9363 _ => None,
9364 }
9365}
9366
9367fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
9368 use Opcode::*;
9369 match (op, operands.first()) {
9370 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
9371 op.short_form(*value as u32).unwrap_or(op)
9372 }
9373 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
9374 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
9375 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
9376 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
9377 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
9378 // A declared global is reached through its reference cell, so it shares
9379 // the `var_ref` encodings, short forms included.
9380 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
9381 op.short_form(*index).unwrap_or(op)
9382 }
9383 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
9384 op.short_form(*count as u32).unwrap_or(op)
9385 }
9386 _ => op,
9387 }
9388}
9389
9390/// The byte offset each instruction will start at, plus the total code size.
9391fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
9392 let mut offsets = Vec::with_capacity(chosen.len() + 1);
9393 let mut offset = 0usize;
9394 for op in chosen {
9395 offsets.push(offset);
9396 offset += op.size() as usize;
9397 }
9398 offsets.push(offset);
9399 offsets
9400}
9401
9402/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
9403/// the offset actually fits.
9404///
9405/// The choice is circular: an instruction's size decides the offsets of everything after
9406/// it, and the offsets decide whether a jump may be short. So this starts with every jump
9407/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
9408/// Shrinking only ever *shortens* distances, so the loop converges.
9409///
9410/// Doing it in one pass instead — which is what this used to do — silently truncated any
9411/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
9412/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
9413/// with four closures in its body simply stopped, with no error and no output past the
9414/// first iteration.
9415fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
9416 let mut chosen: Vec<Opcode> = kept
9417 .iter()
9418 .map(|(op, operands)| choose_short_form(*op, operands))
9419 .collect();
9420 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
9421 let candidates = |op: Opcode| match op {
9422 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
9423 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
9424 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
9425 _ => None,
9426 };
9427 loop {
9428 let offsets = instruction_offsets(&chosen);
9429 let mut changed = false;
9430 for index in 0..kept.len() {
9431 let (op, operands) = &kept[index];
9432 let Some((short, medium, has_medium)) = candidates(*op) else {
9433 continue;
9434 };
9435 if chosen[index] == short {
9436 continue;
9437 }
9438 let Some(target) = target_kept_index(operands, label_kept) else {
9439 continue;
9440 };
9441 let Some(&target_offset) = offsets.get(target) else {
9442 continue;
9443 };
9444 // A jump is relative to the byte after its opcode, which is the convention
9445 // `jump_target_of` decodes with.
9446 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
9447 if (-128..=127).contains(&relative) {
9448 chosen[index] = short;
9449 changed = true;
9450 } else if has_medium
9451 && chosen[index] == Opcode::Goto
9452 && (-32_768..=32_767).contains(&relative)
9453 {
9454 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
9455 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
9456 // the reference encodes them.
9457 chosen[index] = medium;
9458 changed = true;
9459 }
9460 }
9461 if !changed {
9462 return chosen;
9463 }
9464 }
9465}
9466
9467fn encode_operands(
9468 code: &mut Vec<u8>,
9469 op: Opcode,
9470 operands: &[Op],
9471 position: usize,
9472 offsets: &[usize],
9473) {
9474 use crate::opcode::OpFormat::*;
9475 let info = op.info();
9476 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
9477 let index = match slot {
9478 Slot::Arg(i)
9479 | Slot::Loc(i)
9480 | Slot::VarRef(i)
9481 | Slot::Global(i)
9482 | Slot::GlobalDecl(i) => i,
9483 };
9484 code.extend_from_slice(&(index as u16).to_be_bytes());
9485 };
9486 match info.format {
9487 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
9488 U8 | Const8 => {
9489 if let Some(value) = operands.first().and_then(operand_uint) {
9490 code.push(value as u8);
9491 }
9492 }
9493 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
9494 // like their wide counterparts, only one byte wide.
9495 Loc8 => {
9496 if let Some(Op::Slot(slot)) = operands.first() {
9497 let index = match slot {
9498 Slot::Arg(i)
9499 | Slot::Loc(i)
9500 | Slot::VarRef(i)
9501 | Slot::Global(i)
9502 | Slot::GlobalDecl(i) => *i,
9503 };
9504 code.push(index as u8);
9505 }
9506 }
9507 I8 => {
9508 if let Some(value) = operands.first().and_then(operand_int) {
9509 code.push(value as i8 as u8);
9510 }
9511 }
9512 U16 | Npop => {
9513 if let Some(value) = operands.first().and_then(operand_int) {
9514 code.extend_from_slice(&(value as u16).to_be_bytes());
9515 }
9516 }
9517 I16 => {
9518 if let Some(value) = operands.first().and_then(operand_int) {
9519 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
9520 }
9521 }
9522 I32 => {
9523 if let Some(value) = operands.first().and_then(operand_int) {
9524 code.extend_from_slice(&value.to_be_bytes());
9525 }
9526 }
9527 U32 | Const => {
9528 if let Some(value) = operands.first().and_then(operand_uint) {
9529 code.extend_from_slice(&value.to_be_bytes());
9530 }
9531 }
9532 Loc | Arg | VarRef => {
9533 if let Some(Op::Slot(slot)) = operands.first() {
9534 write_slot(code, *slot);
9535 }
9536 }
9537 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
9538 if let Some(Op::AtomId(index)) = operands.first() {
9539 code.extend_from_slice(&index.to_be_bytes());
9540 }
9541 // The trailing immediate means different things per format, and the
9542 // atom forms that carry a *label* have to resolve it like any other
9543 // jump, so they cannot share the `U8`/`U16` arms above.
9544 match info.format {
9545 AtomU8 | AtomLabelU8 => {
9546 if let Some(value) = operands.get(1).and_then(operand_uint) {
9547 code.push(value as u8);
9548 }
9549 }
9550 AtomU16 | AtomLabelU16 => {
9551 if let Some(value) = operands.get(1).and_then(operand_uint) {
9552 code.extend_from_slice(&(value as u16).to_be_bytes());
9553 }
9554 }
9555 _ => {}
9556 }
9557 }
9558 NpopU16 => {
9559 for operand in operands.iter().take(2) {
9560 if let Some(value) = operand_uint(operand) {
9561 code.extend_from_slice(&(value as u16).to_be_bytes());
9562 }
9563 }
9564 }
9565 Label | Label8 | Label16 | LabelU16 => {
9566 if let Some(Op::Label(label)) = operands.first() {
9567 // Labels were already remapped to kept-instruction indices.
9568 let Some(&target) = offsets.get(label.0 as usize) else {
9569 debug_assert!(false, "label {} is past the end", label.0);
9570 return;
9571 };
9572 let relative = target as i64 - (position as i64 + 1);
9573 match info.format {
9574 Label8 => code.push(relative as i8 as u8),
9575 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
9576 // `label_u16` stores the target followed by an unrelated u16.
9577 LabelU16 => {
9578 code.extend_from_slice(&(relative as i32).to_be_bytes());
9579 if let Some(value) = operands.get(1).and_then(operand_uint) {
9580 code.extend_from_slice(&(value as u16).to_be_bytes());
9581 }
9582 }
9583 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
9584 }
9585 }
9586 }
9587 }
9588}
9589
9590fn operand_int(op: &Op) -> Option<i32> {
9591 match op {
9592 Op::Int(value) => Some(*value),
9593 _ => None,
9594 }
9595}
9596
9597fn operand_uint(op: &Op) -> Option<u32> {
9598 match op {
9599 Op::Const(value) | Op::AtomId(value) => Some(*value),
9600 Op::Int(value) => Some(*value as u32),
9601 _ => None,
9602 }
9603}
9604
9605/// Disassemble a compiled function.
9606pub fn disassemble(function: &CompiledFunction) -> String {
9607 disasm::disassemble_program(function)
9608}