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, EvalPrivate, EvalPrivateKind,
27 EvalSite, EvalVisible, ExportEntry, Function as CompiledFunction, FunctionKind, ImportEntry,
28 ModuleMeta, ModuleRequest, VarDef, VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::Wtf8;
36use js_parse::ast::{self, *};
37
38/// A label id, local to the function being compiled.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Label(u32);
41
42/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
43///
44/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
45/// is why the brackets are part of the name; nothing a program writes can collide with it.
46const HOME_OBJECT: &str = "<home_object>";
47
48/// The local holding the function `super()` constructs from.
49///
50/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
51/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
52const ACTIVE_FUNC: &str = "this.active_func";
53
54/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
55const NEW_TARGET: &str = "new.target";
56
57/// Stand-in for a constant-pool index that is only known later in the instruction stream.
58///
59/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
60/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
61/// billion members is not a thing — and the compiler patches it before resolution runs, so a
62/// missed patch is a panic-free compiler error rather than a wrong jump.
63const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
64
65/// One step of a class's initialisation, in source order.
66///
67/// A static block is not a member the class keeps — it is a run of statements that executes
68/// at the point the class definition reaches it — so it belongs *inside* the initialiser
69/// function rather than alongside the fields as a separate pass. Merging the two is what
70/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
71/// same way the reference is.
72enum StaticInitItem<'a> {
73 /// `static x = value`, or `x = value` for the instance half.
74 Field(FieldKey<'a>, Option<&'a Expr>),
75 /// `static { … }`
76 Block {
77 body: &'a [Stmt],
78 /// Position of the `{`, which is where the reference puts the function.
79 body_start: Position,
80 },
81}
82
83/// How one field names its property.
84///
85/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
86/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
87/// is fixed when the class is created. Keeping the expression here instead made
88/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
89/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
90/// `{1: "a"}`.
91enum FieldKey<'a> {
92 /// `x`, `"x"`, `0` — the property name is static text.
93 Literal(&'a PropKey),
94 /// `#x`: the class-scope binding that holds the private symbol.
95 Private(String),
96 /// `[expr]`: the class-scope binding that holds the evaluated key.
97 Computed(String),
98}
99
100/// The `var_block` sentinel for a binding that lives at function scope.
101///
102/// It has to be a value a *real* block key can never take. Block keys are source
103/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
104/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
105/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
106/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
107/// sentinel takes the slot below it.
108const FUNCTION_SCOPE: u64 = u64::MAX - 3;
109
110/// The `var_block` sentinel for a binding of the parameter list.
111///
112/// A function whose parameter list contains a default expression gets *two* variable
113/// environments: one for the parameters and one for the body, so a `var` in the body
114/// that shares a name with a parameter is a different binding. The parameter bindings
115/// therefore need a scope key of their own: reachable while the defaults are
116/// evaluated, invisible to the body, and never merged with a body `var` of the same
117/// name.
118///
119/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
120/// the closure and the body shared one slot, when only the parameters were in scope
121/// when it was created.
122const PARAM_SCOPE: u64 = u64::MAX - 4;
123
124/// The name of the hidden local a `using` declaration caches its dispose method in.
125///
126/// It has to be a name no source can produce, because a script may declare anything: the
127/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
128fn using_method_name(name: &str) -> String {
129 format!("<using.method {name}>")
130}
131
132/// The `blocks` parent sentinel for "this block has no enclosing block".
133///
134/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
135/// also the terminator the chain walk from the script body reached the file's
136/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
137/// leaked into the body scope.
138const NO_PARENT: u64 = u64::MAX - 2;
139
140/// The block key for a script body. Distinct from both sentinels and unreachable from
141/// any source offset.
142const SCRIPT_BODY: u64 = u64::MAX - 1;
143
144/// An operand of a symbolic instruction.
145#[derive(Debug, Clone, PartialEq)]
146enum Op {
147 /// An immediate integer.
148 Int(i32),
149 /// A jump target.
150 Label(Label),
151 /// A constant pool index.
152 Const(u32),
153 /// An atom, before interning.
154 Atom(Atom),
155 /// An interned atom, as an index into [`Function::atoms`].
156 AtomId(u32),
157 /// A resolved slot.
158 Slot(Slot),
159}
160
161/// Where a resolved variable lives.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163enum Slot {
164 Arg(u32),
165 Loc(u32),
166 VarRef(u32),
167 /// A global, by closure-var index.
168 Global(u32),
169 /// A global *declared* in this script. The reference keeps these bindings in
170 /// reference cells so that the script and any closure share one variable, so
171 /// a store goes through `put_var_ref` while a read uses `get_var`.
172 GlobalDecl(u32),
173}
174
175/// What a symbolic variable access does, which decides the final opcode.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177enum VarAction {
178 /// Read the value.
179 Get,
180 /// Read the value, yielding `undefined` for an undeclared global.
181 GetUndef,
182 /// Write, leaving nothing on the stack.
183 Put,
184 /// Write and initialise, leaving the value on the stack.
185 PutInit,
186 /// Write, leaving the value on the stack.
187 Set,
188 /// Initialise a binding that may only be initialised once, such as a derived
189 /// constructor's `this`.
190 PutInitChecked,
191 /// Initialise, leaving the value on the stack and without the `const` check.
192 ///
193 /// A class's own scope binding is a `const` that has to be initialised in the middle
194 /// of the definition — after the constructor exists but before the static fields run
195 /// — and the value has to survive for the outer store to use.
196 SetInit,
197 /// Write a binding that lives in a reference cell.
198 PutRef,
199}
200
201#[derive(Debug, Clone)]
202enum Insn {
203 /// A fully determined instruction.
204 Fixed { op: Opcode, operands: Vec<Op> },
205 /// A variable access, resolved in the second pass.
206 ///
207 /// `block` is the lexical block the access appears in, which is what makes
208 /// shadowing work: two bindings can share a name, and the one that wins is
209 /// whichever scope encloses the access.
210 Var {
211 action: VarAction,
212 name: String,
213 block: u64,
214 /// Whether the access was written in the parameter list; see
215 /// [`FnState::in_params`].
216 in_params: bool,
217 },
218 /// Close a binding *if* it turned out to be captured.
219 ///
220 /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
221 /// only known once the body has been compiled — a closure created there is the
222 /// thing that makes it necessary. The reference emits `close_loc` exactly in that
223 /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
224 /// of emitted blind.
225 CloseCaptured { name: String, block: u64 },
226 /// `delete name`, which can only answer `false` once the binding is known.
227 ///
228 /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
229 /// looks the name up on the global object, which is what distinguishes an implicit
230 /// global (configurable, deletable) from a declared one (a binding, always `false`).
231 DeleteVar { name: String },
232 /// An instruction that dead-code elimination removed. It keeps its slot so
233 /// that label indices stay valid, and resolves to no bytecode.
234 Dead,
235}
236
237/// Where `break` and `continue` jump to.
238///
239/// Targets are stacked as the compiler enters loops and labelled statements, so a
240/// bare `break` needs no analysis: it is simply the innermost target. A labelled
241/// one searches outward by name.
242#[derive(Debug, Clone)]
243struct JumpTarget {
244 /// The labels attached to this target. `l: for(;;)` gives one name; a bare
245 /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
246 /// same statement and `break a` must reach the same place as `break b`.
247 names: Vec<String>,
248 /// Where `break` lands. `None` for a construct `break` may only leave, not
249 /// target — a `try`, whose entry exists purely to unwind.
250 break_label: Option<Label>,
251 /// Where `continue` lands. `None` for anything that is not a loop.
252 continue_label: Option<Label>,
253 /// Stack slots to discard when control leaves this construct by a jump.
254 ///
255 /// Both `switch` and `try` leave something on the value stack for the duration
256 /// of the construct — the discriminant, or the `catch` offset — and a jump out
257 /// has to take it with it. A loop leaves nothing.
258 drop_count: u32,
259 /// The finalizer to run when control leaves this construct.
260 ///
261 /// Set on a `try` even when it has no `finally`: the label is always emitted and
262 /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
263 /// does not have to know whether a finalizer exists.
264 finally_label: Option<Label>,
265 /// Whether this is a labelled non-loop statement, which an unlabelled `break`
266 /// does not reach.
267 is_regular_stmt: bool,
268 /// Whether leaving this construct has to close an iterator.
269 ///
270 /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
271 /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
272 /// is dropped rather than closed.
273 has_iterator: bool,
274 /// Whether that iterator speaks the *async* protocol.
275 ///
276 /// An async close has to `await` the inner `return`, so it is an inline instruction
277 /// sequence rather than one opcode — the reference's `emit_iterator_close`.
278 is_async_iterator: bool,
279}
280
281/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
282///
283/// Both leave `source value` on the stack, so this is purely which spelling the reference
284/// picked, and it picked it by whether it had to build a *reference* for the target:
285///
286/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
287/// consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
288/// destructures);
289/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
290/// * a `var`, and any assignment target, go through `dup; get_field`, because the
291/// reference builds a reference for them — which is what `with` needs.
292fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
293 nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
294}
295
296/// Whether binding this pattern starts by boxing the value it was handed.
297fn nests_a_pattern(pattern: &Pattern) -> bool {
298 match &pattern.kind {
299 PatternKind::Array { .. } | PatternKind::Object { .. } => true,
300 PatternKind::Assign { target, .. } => nests_a_pattern(target),
301 _ => false,
302 }
303}
304
305/// `copy_data_properties` flags for an object-literal spread.
306///
307/// The byte packs three fields: the low bits are the stack offset of the source,
308/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
309/// as well as string keys. A spread passes a literal `null` exclusion list right
310/// below the source, so that field stays zero and only the source offset and the
311/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
312const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
313
314/// The expression a `...` introduces.
315///
316/// The parser marks the spread in two places — the element/property variant and an
317/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
318/// stepped through before the argument can be compiled.
319fn spread_argument(spread: &Expr) -> &Expr {
320 match &spread.kind {
321 ExprKind::Spread(inner) => inner,
322 _ => spread,
323 }
324}
325
326/// The flag byte `define_method` takes.
327///
328/// The low two bits pick value/getter/setter; bit 2 marks the property
329/// enumerable, which every object-literal method is.
330/// What kind of class constructor a function is being compiled as.
331///
332/// A constructor is not an ordinary method: a base one materialises `this` and refuses
333/// to run without `new`, and a derived one starts with `this` in the dead zone until
334/// `super()` produces it.
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336enum CtorKind {
337 /// Not a class constructor.
338 None,
339 /// A constructor of a class without `extends`.
340 Base,
341 /// A constructor of a class with `extends`.
342 Derived,
343}
344
345/// The flag byte `define_method` takes for a class member.
346///
347/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
348/// a class method is *not* — that is the whole difference from an object-literal method,
349/// and the reason `Object.keys(C.prototype)` stays empty.
350fn class_method_flags(kind: MethodKind) -> i32 {
351 match kind {
352 MethodKind::Constructor | MethodKind::Method => 0,
353 MethodKind::Get => 1,
354 MethodKind::Set => 2,
355 }
356}
357
358fn define_method_flags(kind: PropertyKind) -> i32 {
359 let base = match kind {
360 PropertyKind::Value | PropertyKind::Method => 0,
361 PropertyKind::Get => 1,
362 PropertyKind::Set => 2,
363 };
364 base | 4
365}
366
367/// Convert a numeric property key to the text an atom would be made from.
368///
369/// `PropertyKey` of a number is `ToString(number)`, the same conversion every other place
370/// uses — so this goes through [`crate::number::number_to_string`] rather than formatting
371/// the value here. It used to accept only `[1e-6, 1e21)` and reject the rest, on the
372/// theory that Rust's `{}` and JavaScript's spelling diverge at the extremes; they do, and
373/// that is exactly why the spec's own algorithm is the thing to call. `get 0.0000001() {}`
374/// binds the key `"1e-7"`, and the rejection made it a `SyntaxError` instead.
375///
376/// The `Result` is kept because the call sites are in a `?` chain, and a key conversion
377/// that could still fail (a non-finite value from a source literal, which the lexer does
378/// not produce) belongs on the same path as the rest of a property name's errors.
379fn numeric_key_text(value: f64, _span: Span) -> Result<String, SyntaxError> {
380 Ok(crate::number::number_to_string(value))
381}
382
383/// Collect the operands of a same-operator logical run, in source order.
384///
385/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
386/// the caller appends `c`. A node with a different operator is one operand.
387fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
388 if let ExprKind::Logical {
389 op: inner_op,
390 left,
391 right,
392 } = &expr.kind
393 && *inner_op == op
394 {
395 collect_same_operator(op, left, out);
396 out.push(right);
397 return;
398 }
399 out.push(expr);
400}
401
402/// The jump a logical assignment or `??` takes when the value is kept.
403///
404/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
405/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
406/// the value when it is *not* null-ish, so it is the `if_false` side.
407fn logical_jump(op: AssignOp) -> Opcode {
408 match op {
409 AssignOp::Or => Opcode::IfTrue,
410 AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
411 _ => Opcode::IfFalse,
412 }
413}
414
415/// Whether a loop enumerates keys or values.
416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
417enum ForLoopKind {
418 /// `for (x in o)` — the keys of an object.
419 In,
420 /// `for (x of o)` — the values of an iterable.
421 Of,
422 /// `for await (x of o)` — the values of an async iterable, or of a sync one.
423 AwaitOf,
424}
425
426/// Which part of a `try` statement a block key refers to.
427#[derive(Debug, Clone, Copy)]
428enum TryPart {
429 /// The guarded block.
430 Block = 0,
431 /// The handler body, excluding the catch parameter.
432 Catch = 1,
433 /// The finalizer block.
434 Finally = 2,
435 /// The catch parameter's own scope.
436 Param = 3,
437}
438
439/// A lexical scope, identified while hoisting and numbered at the end.
440///
441/// Scope identity is needed in two passes that must agree: declarations are
442/// hoisted in source order (so slots come out in source order, as in the
443/// reference), but a binding belongs to the block it was written in, which is only
444/// entered later. Blocks are therefore keyed by the source position of their
445/// opening brace, which is stable across both walks.
446#[derive(Debug, Clone, Copy)]
447struct Block {
448 /// Source position of the block.
449 key: u64,
450 /// The block this one is nested in; `0` for the function scope.
451 parent: u64,
452}
453
454/// One function under construction.
455struct FnState {
456 /// The function's own source range, used to record its text for
457 /// `Function.prototype.toString`.
458 span: Option<(usize, usize)>,
459 name: String,
460 kind: FunctionKind,
461 strict: bool,
462 args: Vec<VarDef>,
463 vars: Vec<VarDef>,
464 closure_vars: Vec<ClosureVar>,
465 cpool: Vec<Constant>,
466 atoms: Vec<Atom>,
467 /// Every lexical scope, in creation order.
468 blocks: Vec<Block>,
469 /// The block currently being parsed or compiled.
470 current_block: u64,
471 /// The block a *nested* function was created in, so a capture made from here can be
472 /// resolved against the enclosing function's lexical scopes rather than against a
473 /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
474 /// function's own `let S` instead of the class body's `const S`.
475 created_in_block: u64,
476 /// The block each local was declared in, parallel to `vars`. `0` means the
477 /// function scope, where `var` bindings live.
478 var_block: Vec<u64>,
479 /// Set when the expression just compiled left no value on the stack.
480 ///
481 /// Only a store can do that: `put_field` consumes the object and the value, so
482 /// an assignment whose result is unused emits nothing extra. The expression
483 /// statement then has nothing to drop.
484 no_value: bool,
485 /// Whether a label was placed since the last instruction was emitted.
486 ///
487 /// The `put`/`get` fold is only valid when the two are adjacent in the final
488 /// stream; a label in between means a jump can land on the read, so the store has
489 /// to keep consuming its value. A flag is enough and avoids having to reason about
490 /// which index a label recorded.
491 label_since_insn: bool,
492 /// Whether the value of the expression being compiled is thrown away.
493 ///
494 /// Only an expression *statement* discards its value, and only the outermost
495 /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
496 /// still has to produce a value. Consumed by [`Compiler::assign`], which is
497 /// the one construct whose bytecode depends on it.
498 discard_value: bool,
499 /// The block that holds the function body.
500 body_block: u64,
501 /// Head of each scope's binding chain, indexed by level. Filled in by
502 /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
503 block_heads: Vec<i32>,
504 /// Enclosing `break`/`continue` targets, innermost last.
505 jump_targets: Vec<JumpTarget>,
506 insns: Vec<Insn>,
507 labels: Vec<Option<usize>>,
508 /// Captured locals, which need a reference cell.
509 var_ref_count: u32,
510 line: u32,
511 column: u32,
512 /// Whether this is a script body. A script's top-level declarations create
513 /// global properties rather than locals, which is why they show up as
514 /// closure variables with `[global_decl]`.
515 is_script: bool,
516 /// Whether this is a module body.
517 ///
518 /// A module body is a script in every respect that matters here — no `arguments`,
519 /// no `this` of its own — but its top-level declarations are *module*-scoped
520 /// instead of global, which is what this flag changes.
521 is_module: bool,
522 /// Whether the function is an arrow, which never gets its own `arguments`.
523 is_arrow: bool,
524 /// The name a *named function expression* binds inside its own body.
525 /// How many parameters count towards `.length`.
526 defined_args: u32,
527 /// Parameters that are not a plain name, with the argument slot each came from.
528 param_prologue: Vec<(usize, Pattern)>,
529 /// What kind of class constructor this function is, if any.
530 ctor_kind: CtorKind,
531 /// Whether the class has instance fields, so the constructor has to run their
532 /// initialiser before it returns.
533 /// What the nested function about to be compiled should be told about its class.
534 class_ctor_pending: Option<CtorKind>,
535 /// Whether this function needs the hidden `this` local, because an arrow inside it
536 /// refers to `this`.
537 ///
538 /// An arrow has no `this` of its own, so the reference materialises the enclosing
539 /// function's receiver into a local and lets the arrow capture it as an ordinary
540 /// closure variable. Declaring the local is not enough on its own: the store that
541 /// fills it has to be prepended to the body, which is what this flag arranges.
542 needs_this_local: bool,
543 /// The same, for `arguments`.
544 needs_arguments_local: bool,
545 /// The same, for `new.target`.
546 needs_new_target_local: bool,
547 /// Whether the body already opens by filling a `this` local, which
548 /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
549 has_this_prologue: bool,
550 /// The same, for `<home_object>`: the object `super` resolves against.
551 ///
552 /// An arrow and a static block have no home object of their own — only the method or
553 /// initialiser they were written in does — so `super.x` inside one is a read of the
554 /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
555 /// by `special_object 4`, the same way `this` is.
556 needs_home_object_local: bool,
557 /// Whether this function has an `arguments` binding of its own.
558 ///
559 /// False for a class field initialiser and a static block: §15.7 puts them outside any
560 /// function, so `arguments` does not exist there and `eval('arguments')` inside one is a
561 /// `SyntaxError` rather than the caller's arguments object. The parser already enforces
562 /// that for written code; this carries the same fact to the `eval` call site, which has
563 /// to compile the eval'd source under the caller's restriction.
564 no_arguments_binding: bool,
565 /// The same, for `this.active_func`: the function `super()` constructs from.
566 ///
567 /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
568 /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
569 /// as a local of the enclosing function; an arrow that escaped the constructor
570 /// (`iter.return = () => super()`) then finds it in its closure even with the
571 /// constructor nowhere on the call stack.
572 needs_active_func_local: bool,
573 /// Hidden locals of the `with` blocks currently open, innermost last.
574 with_names: Vec<String>,
575 /// How many of [`FnState::with_names`] were already open when this function was
576 /// created, i.e. belong to an *enclosing* function.
577 ///
578 /// The distinction decides shadowing, and it is positional rather than lexical. A
579 /// `with` opened **inside** this function's body sits nearer than the function's own
580 /// environment, so it shadows even a `var` of this function:
581 /// `function f(){ with(o){ var v = 1 } }` writes `o.v`. A `with` opened **outside**
582 /// does not: `with(o){ function f(){ var v = 1 } }` writes `f`'s local `v`, because
583 /// `f`'s environment is the inner one. Treating both alike broke one family or the
584 /// other — `S12.10_A1.2` and `S12.10_A1.7` are these two cases.
585 inherited_with_names: usize,
586 /// Set while a with-guard is being emitted, so the guard's own accesses are not
587 /// wrapped in another guard.
588 emitting_with_guard: bool,
589 self_name: Option<String>,
590 /// Where the function body starts, in source order; see [`Function::body_start`].
591 body_start: (u32, u32),
592 /// Whether the body contains a *direct* `eval(...)` call.
593 ///
594 /// A direct eval sees every binding of the function that called it, including ones
595 /// no other code mentions. It also hands those bindings to any closure it creates,
596 /// which can outlive the function. Both need the bindings to live in cells, so this
597 /// flag makes the function treat all of them as captured.
598 has_direct_eval: bool,
599 /// Whether the parameter list contains a default expression, which is what gives
600 /// the function a second variable environment (see [`PARAM_SCOPE`]).
601 has_parameter_expressions: bool,
602 /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
603 simple_parameter_list: bool,
604 /// Whether the instructions being emitted belong to the parameter list.
605 ///
606 /// References made here must not see the body's `var`s: the body has not run yet,
607 /// and the reference's own model keeps the two scopes apart.
608 in_params: bool,
609 /// Whether an arrow created in this function's parameter list needs the parameter
610 /// scope's `arguments` binding.
611 needs_param_arguments: bool,
612 /// Whether this function was *created* inside a parameter list.
613 ///
614 /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
615 /// arrow too. The name reference is the arrow's, but the scope it must not see
616 /// belongs to the function the arrow was born in.
617 created_in_params: bool,
618 /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
619 ///
620 /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
621 /// final while the body is still being compiled: a named function expression declares
622 /// its own name binding *after* the body, and that binding is exactly what
623 /// `eval("myfunc = 1")` has to find.
624 eval_sites: Vec<EvalSite>,
625 /// Direct `eval` call sites seen so far: where, and the block that was current.
626 pending_eval_sites: Vec<(Span, u64, bool, Vec<EvalPrivate>, bool)>,
627 /// Whether this body contains `await`.
628 ///
629 /// For a *module* this decides whether its body is an async function: top-level
630 /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
631 /// to survive to the compiled function rather than being a local of the compiler.
632 has_await: bool,
633 /// The module tables, when this body is a module.
634 ///
635 /// Only the top-level state ever has one: `export` and `import` are top-level
636 /// statements, so nothing nested can add to these tables.
637 module: Option<ModuleMeta>,
638 /// Whether the self-name prologue (`special_object 2` then the store) has been
639 /// emitted for this function.
640 ///
641 /// A *nested* function's lookup declares the binding early (see
642 /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
643 /// prologue is still needed — the binding existing is not the same as it being
644 /// initialised.
645 self_name_initialized: bool,
646 /// Whether the code emitted so far leaves the program's result on the stack.
647 /// The reference tracks this for the hidden `<ret>` local of an eval script.
648 leaves_value: bool,
649 /// Statement nesting depth, used to tell top-level statements apart.
650 stmt_depth: u32,
651 /// Function declarations waiting to be instantiated at scope entry, as
652 /// (target slot, constant pool index). The reference emits these from
653 /// `instantiate_hoisted_definitions` rather than at the statement, because a
654 /// declaration is visible before it is reached.
655 hoisted: Vec<(u64, HoistTarget, u32)>,
656 /// Function declarations whose bodies are compiled only once the enclosing scope
657 /// has finished hoisting, as (owning block, declaration).
658 ///
659 /// Compiling a body at the declaration makes the result depend on source order: in
660 /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
661 /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
662 /// names first and the bodies second is what removes that dependence.
663 deferred_funcs: Vec<(u64, Box<ast::Function>)>,
664 /// The source position of the node being compiled. Every instruction emitted
665 /// takes it, which is how the position table that feeds stack traces is built.
666 cur_pos: Option<Position>,
667 /// One position per entry in `insns`, index-aligned.
668 insn_pos: Vec<Option<Position>>,
669}
670
671/// Where a hoisted function declaration is stored.
672#[derive(Debug, Clone)]
673enum HoistTarget {
674 Arg(u32),
675 Loc(u32),
676 /// A global, which the resolver looks up by name.
677 Global(String),
678}
679
680impl FnState {
681 /// Whether this function suspends: a generator or an async function.
682 ///
683 /// A suspending function's `return` is a `return_async` and its body starts with an
684 /// `initial_yield`, so almost every statement that touches control flow asks this.
685 fn is_suspending(&self) -> bool {
686 self.kind.is_generator() || self.kind.is_async()
687 }
688
689 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
690 FnState {
691 span: None,
692 name: name.into(),
693 kind,
694 strict: false,
695 args: Vec::new(),
696 vars: Vec::new(),
697 closure_vars: Vec::new(),
698 cpool: Vec::new(),
699 atoms: Vec::new(),
700 blocks: Vec::new(),
701 current_block: 0,
702 created_in_block: NO_PARENT,
703 var_block: Vec::new(),
704 no_value: false,
705 label_since_insn: false,
706 discard_value: false,
707 body_block: 0,
708 block_heads: Vec::new(),
709 jump_targets: Vec::new(),
710 insns: Vec::new(),
711 labels: Vec::new(),
712 var_ref_count: 0,
713 line: 1,
714 column: 1,
715 is_script: false,
716 is_module: false,
717 is_arrow: false,
718 defined_args: 0,
719 param_prologue: Vec::new(),
720 ctor_kind: CtorKind::None,
721 class_ctor_pending: None,
722 needs_this_local: false,
723 needs_arguments_local: false,
724 needs_new_target_local: false,
725 has_this_prologue: false,
726 needs_home_object_local: false,
727 no_arguments_binding: false,
728 needs_active_func_local: false,
729 with_names: Vec::new(),
730 inherited_with_names: 0,
731 emitting_with_guard: false,
732 self_name: None,
733 has_direct_eval: false,
734 body_start: (0, 0),
735 has_parameter_expressions: false,
736 simple_parameter_list: true,
737 in_params: false,
738 needs_param_arguments: false,
739 created_in_params: false,
740 eval_sites: Vec::new(),
741 pending_eval_sites: Vec::new(),
742 has_await: false,
743 module: None,
744 self_name_initialized: false,
745 leaves_value: false,
746 stmt_depth: 0,
747 hoisted: Vec::new(),
748 deferred_funcs: Vec::new(),
749 cur_pos: None,
750 insn_pos: Vec::new(),
751 }
752 }
753
754 /// The scope a declaration lands in: a script's top-level declarations are
755 /// globals, everything else gets a slot.
756 /// Whether a binding declared *now* becomes a property of the global object.
757 ///
758 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
759 /// The `var` case is decided by the keyword rather than by the cursor position:
760 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
761 /// binding as a `var i` in the body, even though the head has its own block.
762 fn declares_globally(&self, def: &VarDef) -> bool {
763 // A module's top-level declarations are *module*-scoped: they live in the module
764 // record, never on the global object. Two modules can both declare `var x`
765 // without seeing each other, which is the whole point.
766 if self.is_module {
767 return false;
768 }
769 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
770 }
771}
772
773/// The compiler's entry point.
774pub struct Compiler {
775 /// The text being compiled, kept so each function can record its own slice for
776 /// `Function.prototype.toString`.
777 source: Option<String>,
778 module: bool,
779 /// Whether the program itself is the body of an `async` function.
780 ///
781 /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
782 /// completion value is wrapped so a returned promise is not adopted.
783 async_body: bool,
784 /// Enclosing functions, outermost first. The last entry is the current one.
785 stack: Vec<FnState>,
786 /// The private names visible at this point, innermost class body last.
787 ///
788 /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
789 /// to the class body: a method, an arrow inside it and a class nested inside that arrow
790 /// all resolve against the same entries, and the parser accepts exactly that set
791 /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
792 /// class's names the moment a method started.
793 private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
794 /// Whether the expression [`Compiler::expr`] is about to compile is the one its
795 /// statement asked to discard.
796 ///
797 /// `FnState::discard_value` says "the statement's value is thrown away", which is only
798 /// ever true of the statement's own expression — an assignment nested inside it, as in
799 /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
800 /// keeping the answer here is what tells the two apart; without it the nested store
801 /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
802 /// function threw `undefined is not a function`.
803 discard_root: bool,
804}
805
806/// How a use site of a private name compiles.
807///
808/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
809/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
810/// of a setter-only accessor pair.
811#[derive(Clone, Copy, PartialEq, Eq)]
812enum PrivateKind {
813 /// `#x = 1`: an own property keyed by the symbol in the binding.
814 Field,
815 /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
816 Method,
817 /// `get #a() {}`: the binding holds the getter, and a read calls it.
818 Getter,
819 /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
820 /// the same `TypeError` as reading an uninitialised `const`.
821 Setter,
822}
823
824/// What the compiler knows about one `#name` where it is used.
825#[derive(Clone)]
826struct PrivateUse {
827 kind: PrivateKind,
828 /// `#a<set>` when the class defines a setter for this name.
829 ///
830 /// A second binding, not a second field of the first: the reference stores the setter
831 /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
832 setter: Option<String>,
833}
834
835/// The class-scope bindings one class body needs, in declaration order.
836#[derive(Default)]
837struct ClassPlan {
838 /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
839 /// at class entry, in member order.
840 bindings: Vec<String>,
841 /// The private names, for the use sites inside the body.
842 uses: std::collections::HashMap<String, PrivateUse>,
843 /// Computed field keys, by element index, so the emission pass does not have to redo the
844 /// per-half counter that names them.
845 computed: std::collections::HashMap<usize, String>,
846 /// Whether the instance initialiser has to add the brand to `this`.
847 instance_brand: bool,
848 /// Whether the constructor itself has to carry the brand.
849 static_brand: bool,
850}
851
852impl ClassPlan {
853 /// Walk a class body once and decide every class-scope binding it needs.
854 ///
855 /// Order is the reference's: a member's binding is created when the member is parsed, so
856 /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
857 /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
858 /// the disassembly stops matching even when every instruction is right.
859 fn build(class: &Class) -> ClassPlan {
860 let mut plan = ClassPlan::default();
861 let mut instance_keys = 0usize;
862 let mut static_keys = 0usize;
863 for (index, element) in class.elements.iter().enumerate() {
864 match element {
865 ClassElement::Method {
866 key: PropName::Private(ident),
867 kind,
868 is_static,
869 ..
870 } => {
871 let name = format!("#{}", ident.name);
872 let first = !plan.uses.contains_key(&name);
873 if first {
874 plan.bindings.push(name.clone());
875 plan.uses.insert(
876 name.clone(),
877 PrivateUse {
878 kind: match kind {
879 MethodKind::Get => PrivateKind::Getter,
880 MethodKind::Set => PrivateKind::Setter,
881 _ => PrivateKind::Method,
882 },
883 setter: None,
884 },
885 );
886 }
887 match kind {
888 MethodKind::Set => {
889 let binding = format!("{name}<set>");
890 plan.bindings.push(binding.clone());
891 if let Some(use_) = plan.uses.get_mut(&name) {
892 use_.setter = Some(binding);
893 }
894 }
895 // A getter is what makes the name readable, so a pair that started
896 // as a setter becomes readable once the getter arrives.
897 MethodKind::Get => {
898 if let Some(use_) = plan.uses.get_mut(&name) {
899 use_.kind = PrivateKind::Getter;
900 }
901 }
902 _ => {}
903 }
904 if *is_static {
905 plan.static_brand = true;
906 } else {
907 plan.instance_brand = true;
908 }
909 }
910 ClassElement::Method {
911 key: PropName::Computed(_),
912 ..
913 } => {}
914 ClassElement::Method { .. } => {}
915 ClassElement::Field {
916 key: PropName::Private(ident),
917 ..
918 } => {
919 let name = format!("#{}", ident.name);
920 if !plan.uses.contains_key(&name) {
921 plan.bindings.push(name.clone());
922 plan.uses.insert(
923 name,
924 PrivateUse {
925 kind: PrivateKind::Field,
926 setter: None,
927 },
928 );
929 }
930 }
931 ClassElement::Field {
932 key: PropName::Computed(_),
933 is_static,
934 ..
935 } => {
936 let index_in_half = if *is_static {
937 static_keys += 1;
938 static_keys - 1
939 } else {
940 instance_keys += 1;
941 instance_keys - 1
942 };
943 let binding = computed_field_binding(index_in_half, *is_static);
944 plan.bindings.push(binding.clone());
945 plan.computed.insert(index, binding);
946 }
947 ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
948 }
949 }
950 plan
951 }
952
953 /// How a private name used inside the body compiles, or `None` if no enclosing class
954 /// declares it.
955 fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
956 compiler
957 .private_scopes
958 .iter()
959 .rev()
960 .find_map(|scope| scope.get(name))
961 }
962}
963
964impl Compiler {
965 /// The exact source text of a function, for `Function.prototype.toString`.
966 ///
967 /// §20.2.3.5 requires the *original* text: a function must stringify back to what
968 /// was written, comments and odd spacing included. Slicing the recorded span out of
969 /// the whole source is the only way to get that — rebuilding it from the AST would
970 /// normalise the text, and answering `[native code]` for a script function (which is
971 /// what this engine used to do) makes the result useless for feature detection and
972 /// for libraries that read their own source.
973 ///
974 /// Top-level bodies have no single expression span, so their `source` stays `None`
975 /// and `toString` falls back to the calling convention the spec allows.
976 fn function_source(
977 &self,
978 span: Option<(usize, usize)>,
979 line: u32,
980 column: u32,
981 ) -> Option<String> {
982 let source = self.source.as_ref()?;
983 let span = span?;
984 let bytes = source.as_bytes();
985 let start = span.0;
986 let end = span.1;
987 if start >= bytes.len() || end > bytes.len() || start >= end {
988 let _ = (line, column);
989 return None;
990 }
991 Some(source.get(start..end)?.to_string())
992 }
993}
994
995/// Compile a script.
996pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
997 Compiler::new(false).compile(program)
998}
999
1000/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
1001/// the original source.
1002///
1003/// The separate entry point rather than a parameter on [`compile_script`] because the
1004/// tests and the disassembler compile from an AST they built themselves and have no
1005/// source to give; they keep the `None` behaviour they already relied on.
1006pub fn compile_script_with_source(
1007 program: &Program,
1008 source: &str,
1009) -> Result<CompiledFunction, SyntaxError> {
1010 let mut compiler = Compiler::new(false);
1011 compiler.source = Some(source.to_string());
1012 compiler.compile(program)
1013}
1014
1015/// [`compile_script_with_source`] for a module.
1016pub fn compile_module_with_source(
1017 program: &Program,
1018 source: &str,
1019) -> Result<CompiledFunction, SyntaxError> {
1020 let mut compiler = Compiler::new(true);
1021 compiler.source = Some(source.to_string());
1022 compiler.compile(program)
1023}
1024
1025/// Compile a script whose top level is the body of an `async` function.
1026/// The body is an ordinary script in every other way — it still reports a completion value
1027/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1028/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1029/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1030/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1031/// documents.
1032pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1033 Compiler::for_suspensible_script().compile(program)
1034}
1035
1036/// Compile a module.
1037pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1038 Compiler::new(true).compile(program)
1039}
1040
1041/// Compile a direct `eval` body that inherits private names from its caller.
1042///
1043/// `class C { #m = 44; f() { return eval("this.#m") } }` is legal — private names are
1044/// lexically scoped and the eval runs inside the caller's scope — but the names live in the
1045/// *call site's* compilation unit, so they have to be handed over. Seeding them as the
1046/// outermost private scope is what lets the eval resolve `#m` to the caller's binding: the
1047/// read compiles as an ordinary name lookup of `#m`, which at run time finds the caller's
1048/// slot through the same `eval`-scope machinery every other inherited name uses.
1049///
1050/// `suspensible` selects the `{async: true}` form (`std.evalScript(s, {async: true})`), whose
1051/// body may `await`.
1052pub fn compile_eval_with_private(
1053 program: &Program,
1054 private: &[EvalPrivate],
1055 suspensible: bool,
1056) -> Result<CompiledFunction, SyntaxError> {
1057 let mut compiler = if suspensible {
1058 Compiler::for_suspensible_script()
1059 } else {
1060 Compiler::new(false)
1061 };
1062 if !private.is_empty() {
1063 let scope: std::collections::HashMap<String, PrivateUse> = private
1064 .iter()
1065 .map(|entry| {
1066 (
1067 entry.name.clone(),
1068 PrivateUse {
1069 kind: match entry.kind {
1070 EvalPrivateKind::Field => PrivateKind::Field,
1071 EvalPrivateKind::Method => PrivateKind::Method,
1072 EvalPrivateKind::Getter => PrivateKind::Getter,
1073 EvalPrivateKind::Setter => PrivateKind::Setter,
1074 },
1075 setter: entry.setter.clone(),
1076 },
1077 )
1078 })
1079 .collect();
1080 compiler.private_scopes.push(scope);
1081 }
1082 compiler.compile(program)
1083}
1084
1085impl Compiler {
1086 /// Create a compiler.
1087 pub fn new(module: bool) -> Compiler {
1088 Compiler {
1089 source: None,
1090 module,
1091 async_body: false,
1092 stack: Vec::new(),
1093 private_scopes: Vec::new(),
1094 discard_root: false,
1095 }
1096 }
1097
1098 /// Create a compiler for a script whose top level is an `async` function body.
1099 fn for_suspensible_script() -> Compiler {
1100 Compiler {
1101 source: None,
1102 module: false,
1103 async_body: true,
1104 stack: Vec::new(),
1105 private_scopes: Vec::new(),
1106 discard_root: false,
1107 }
1108 }
1109
1110 /// Compile a whole program into its top-level function.
1111 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1112 let mut state = FnState::new("<eval>", FunctionKind::Normal);
1113 // A module body is *not* a script: it has no completion value, so no hidden
1114 // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1115 // is having no `arguments` of its own and no receiver — see `is_module`.
1116 state.is_script = !self.module;
1117 state.is_module = self.module;
1118 if self.module {
1119 state.module = Some(ModuleMeta::default());
1120 }
1121 state.strict = program.strict || self.module;
1122 state.line = program.span.start.line;
1123 state.column = program.span.start.column;
1124 // Locals are numbered in declaration order; `<ret>` is always slot 0.
1125 //
1126 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1127 // slot that only appears in one of the two arrays shifts every later
1128 // binding's block and silently loses the temporal-dead-zone marking for
1129 // the script's own blocks. A function frame has no `<ret>`, which is why
1130 // the misalignment only showed up at the top level.
1131 if !self.module {
1132 state.vars.push(VarDef::var("<ret>"));
1133 state.var_block.push(FUNCTION_SCOPE);
1134 }
1135 self.stack.push(state);
1136 // The body is its own scope, keyed by the position of the program.
1137 // The script body needs a key no statement can produce. Statement keys are
1138 // source offsets, and the program's own start offset is `0` — which is also
1139 // the offset of the first statement, so a top-level `{ let x }` or
1140 // `for (let i …)` used to share the body's block and lose its scope.
1141 let body_key = SCRIPT_BODY;
1142 self.push_block(body_key, NO_PARENT);
1143 self.state().body_block = body_key;
1144 // A module body opens with a re-entry guard. The host evaluates a module exactly
1145 // once, so the guard never fires in practice — but the reference emits it, and a
1146 // module function called a second time (through `eval` of its own source, say)
1147 // must not run its body again.
1148 let module_guard = self.module.then(|| self.new_label());
1149 if let Some(body) = module_guard {
1150 // The guard wraps the *hoisting* too: a second evaluation of the same module
1151 // body must not even re-create its function declarations.
1152 self.emit(Opcode::PushThis, &[]);
1153 self.emit_jump(Opcode::IfFalse, body, &[]);
1154 }
1155 self.hoist(&program.body, body_key)?;
1156 // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1157 // come before the guard's `return_undef`: the reference's jump target sits past
1158 // both, and a second evaluation therefore re-creates nothing.
1159 self.emit_scope_enter(body_key);
1160 if let Some(body) = module_guard {
1161 self.emit(Opcode::ReturnUndef, &[]);
1162 self.place_label(body);
1163 }
1164 // Through `stmts` rather than the loop, so a `using` region at the top level of an
1165 // eval'd body or a module gets its disposal epilogue like any other block.
1166 self.stmts(&program.body)?;
1167 if self.module {
1168 // A module has no completion value; its body simply ends.
1169 self.emit(Opcode::Undefined, &[]);
1170 self.emit(Opcode::ReturnAsync, &[]);
1171 // Top-level `await` makes the body an async function, so the host runs it as
1172 // a coroutine and waits. Without this the `await` opcode would suspend in a
1173 // body that nothing knows how to resume — which is what "a generator body ran
1174 // as an ordinary call" was reporting.
1175 if self.cur().has_await {
1176 self.state().kind = FunctionKind::Async;
1177 }
1178 } else if self.async_body {
1179 // An async body reports its completion value the same way, but through an
1180 // object: the function answers a promise, and resolving that promise *with*
1181 // the completion value would adopt a promise completion instead of reporting
1182 // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1183 // resolve to `{value: <promise>}` rather than to `7`.
1184 //
1185 // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1186 // value in an object so that promises can be safely returned").
1187 self.emit(Opcode::Object, &[]);
1188 self.emit(Opcode::Dup, &[]);
1189 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1190 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1191 self.emit(Opcode::Return, &[]);
1192 self.state().kind = FunctionKind::Async;
1193 } else {
1194 // The program's value is whatever the last expression statement stored in
1195 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1196 // case into a single `set_loc0`.
1197 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1198 self.emit(Opcode::Return, &[]);
1199 }
1200 Ok(self.finish_current())
1201 }
1202
1203 // -- emitting ----------------------------------------------------------
1204
1205 fn state(&mut self) -> &mut FnState {
1206 self.stack.last_mut().expect("a function is being compiled")
1207 }
1208
1209 fn cur(&self) -> &FnState {
1210 self.stack.last().expect("a function is being compiled")
1211 }
1212
1213 fn emit(&mut self, op: Opcode, operands: &[Op]) {
1214 self.state().label_since_insn = false;
1215 let pos = self.cur().cur_pos;
1216 self.state().insns.push(Insn::Fixed {
1217 op,
1218 operands: operands.to_vec(),
1219 });
1220 self.state().insn_pos.push(pos);
1221 }
1222
1223 /// Reset the script's hidden return value to `undefined`.
1224 ///
1225 /// Called at the start of every statement that does not itself produce the
1226 /// program's value, which is how the reference keeps `if`/loop results from
1227 /// leaking into an eval result.
1228 fn reset_value(&mut self) {
1229 if !self.cur().is_script {
1230 return;
1231 }
1232 self.emit(Opcode::Undefined, &[]);
1233 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1234 self.state().leaves_value = false;
1235 }
1236
1237 /// Whether `name` is a local or argument slot rather than a global.
1238 fn is_slot(&self, name: &str) -> bool {
1239 self.cur().vars.iter().any(|v| v.name == name)
1240 || self.cur().args.iter().any(|a| a.name == name)
1241 }
1242
1243 /// `with (object) body`
1244 ///
1245 /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1246 /// what makes the object reachable from a closure created inside the block, and it
1247 /// is also what lets an `eval` find it: the runtime collects the active `With`
1248 /// locals of every frame and resolves names against them before the realm.
1249 ///
1250 /// Inside the block every name reference is spelled as "look in the with objects
1251 /// first", innermost outwards, and falls through to the ordinary access. The test is
1252 /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1253 /// Record asks.
1254 fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1255 // `with (e) s` completes with `UpdateEmpty(s, undefined)` — an *empty* body still
1256 // produces `undefined`, it does not inherit the previous statement's value. So
1257 // `eval("1; with({}){}")` is `undefined` while `eval("1; with({}){2;}")` is `2`.
1258 // Without this the sticky `<ret>` local leaked the `1` through, the same way it
1259 // would for an `if` or a loop.
1260 self.reset_value();
1261 let name = self.next_with_name();
1262 // The object expression is evaluated *outside* the scope it introduces, so no
1263 // wrapper may be emitted for the names it mentions.
1264 let saved = std::mem::take(&mut self.state().with_names);
1265 self.expr(object)?;
1266 self.state().with_names = saved;
1267 self.emit(Opcode::ToObject, &[]);
1268 self.declare_hidden_local(&name, VarKind::With);
1269 // Pushed before the store so the store itself is not guarded by an *outer*
1270 // `with` — the object being stored is the new one, not something to look up.
1271 self.state().with_names.push(name.clone());
1272 self.emit_var(VarAction::Put, &name);
1273 let result = self.stmt(body);
1274 self.state().with_names.pop();
1275 result
1276 }
1277
1278 /// A hidden-local name for one `with` block, distinct from every enclosing one.
1279 fn next_with_name(&self) -> String {
1280 let depth = self.cur().with_names.len();
1281 if depth == 0 {
1282 "<with>".to_string()
1283 } else {
1284 format!("<with{depth}>")
1285 }
1286 }
1287
1288 /// Declare a hidden local that must stay a *local* even in a script.
1289 ///
1290 /// A script's `var` is a property of the global object, but the `with` object is not
1291 /// part of the source program's name space at all — it only exists for the compiler
1292 /// and the runtime — so it goes straight into the frame's slot list.
1293 fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1294 let state = self.state();
1295 if state.vars.iter().any(|v| v.name == name) {
1296 return;
1297 }
1298 state.var_block.push(FUNCTION_SCOPE);
1299 state.vars.push(VarDef {
1300 kind,
1301 ..VarDef::var(name)
1302 });
1303 }
1304
1305 /// Emit a name access, guarded by every active `with` object.
1306 ///
1307 /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1308 /// the read itself; the outer guards and the plain access are what the `if_false`
1309 /// jumps to, so the innermost object wins.
1310 fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1311 let names = self.visible_with_names(name);
1312 let done = self.new_label();
1313 let mut starts = Vec::new();
1314 // Innermost object first: the last `with` opened is the one that shadows the
1315 // others, so its guard has to be the first chance to satisfy the name.
1316 for with_name in names.iter().rev() {
1317 let next = self.new_label();
1318 // `with_has_var` takes the object and carries the name as an atom. It is not
1319 // `in`: an Object Environment Record also consults `Symbol.unscopables`, so
1320 // `globalThis[Symbol.unscopables] = {v: true}` leaves `v` to the outer scope.
1321 self.emit_var(VarAction::Get, with_name);
1322 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1323 self.emit_jump(Opcode::IfFalse, next, &[]);
1324 starts.push(next);
1325 // The operation is `with_get_var`/`with_put_var`, not a plain property access:
1326 // `GetBindingValue`/`SetMutableBinding` ask `HasProperty` **again** before
1327 // getting or setting. That second question is observable — a proxy's `has`
1328 // trap runs one more time (`get-binding-value-call-with-proxy-env` logs
1329 // `has, get unscopables, has, get`) and an `unscopables` getter that deletes
1330 // the property leaves a binding that has gone, which strict code must report
1331 // as a `ReferenceError` rather than write to.
1332 match action {
1333 // A store already has its value on the stack, and `with_put_var` takes the
1334 // pair in `put_field`'s order: object first, then the value.
1335 VarAction::Put | VarAction::PutInit => {
1336 self.emit_var(VarAction::Get, with_name);
1337 self.emit(Opcode::Swap, &[]);
1338 self.emit(Opcode::WithPutVar, &[Op::Atom(Atom::from_text(name))]);
1339 }
1340 _ => {
1341 self.emit_var(VarAction::Get, with_name);
1342 self.emit(Opcode::WithGetVar, &[Op::Atom(Atom::from_text(name))]);
1343 }
1344 }
1345 self.emit_jump(Opcode::Goto, done, &[]);
1346 self.place_label(next);
1347 }
1348 self.emit_var(action, name);
1349 self.place_label(done);
1350 }
1351
1352 /// The `with` blocks that can shadow `name`, innermost last.
1353 ///
1354 /// A parameter or a local of this function is *inside* every `with` this function
1355 /// opened, so those shadow it; a `with` that was already open when this function was
1356 /// created is outside the function's own environment, so the local wins and that
1357 /// block is skipped. See [`FnState::inherited_with_names`].
1358 fn visible_with_names(&self, name: &str) -> Vec<String> {
1359 let state = self.cur();
1360 // The hidden `<with…>` locals are how the guard reaches its own objects, so they
1361 // must never be guarded themselves — not by their own block (which would recurse)
1362 // and not by an enclosing one (which would ask a `with` object whether it has a
1363 // property called `<with>`, always answer no, and waste the chain). Source can
1364 // never spell these names, so exempting all of them changes nothing else.
1365 if state.with_names.iter().any(|hidden| hidden == name) {
1366 return Vec::new();
1367 }
1368 let start = if self.is_slot(name) {
1369 state.inherited_with_names
1370 } else {
1371 0
1372 };
1373 state.with_names[start..]
1374 .iter()
1375 .filter(|hidden| hidden.as_str() != name)
1376 .cloned()
1377 .collect()
1378 }
1379
1380 /// Compile `x` as a **reference** to the with object's property, resolving the object
1381 /// once for the whole read-modify-write.
1382 ///
1383 /// `x += 1`, `x++` and `x ||= v` read and then write the same name. Two independent
1384 /// guards get that wrong the moment the read changes the answer: with
1385 /// `{ get x(){ delete this.x; return 2 } }`, `with (o) { x++ }` reads through the
1386 /// getter — which removes the property — and then the write's own guard no longer
1387 /// finds it, so the store landed on the *global* `x` and `o.x` stayed `undefined`. The
1388 /// reference resolves the base once (`with_make_ref`) and reuses it for both halves.
1389 ///
1390 /// The same shape comes out of compiling the name as a **member** of the with object:
1391 /// `get_field2`/`put_field` already evaluate their receiver once, and the hidden
1392 /// `<with>` local holds exactly the object the guard just tested. So each candidate
1393 /// object gets `if the name is bound here, compile as `this.name`; otherwise fall
1394 /// through to the next object`, and the last fallback is the ordinary name.
1395 fn with_reference(
1396 &mut self,
1397 name: &str,
1398 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1399 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1400 ) -> Result<(), SyntaxError> {
1401 let targets = self.visible_with_names(name);
1402 if targets.is_empty() {
1403 return plain(self);
1404 }
1405 let done = self.new_label();
1406 let result = self.with_reference_inner(name, &targets, guarded, plain, done);
1407 self.place_label(done);
1408 result
1409 }
1410
1411 fn with_reference_inner(
1412 &mut self,
1413 name: &str,
1414 targets: &[String],
1415 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1416 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1417 done: Label,
1418 ) -> Result<(), SyntaxError> {
1419 let Some((innermost, outer)) = targets.split_last() else {
1420 return plain(self);
1421 };
1422 let next = self.new_label();
1423 self.emit_var(VarAction::Get, innermost);
1424 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1425 self.emit_jump(Opcode::IfFalse, next, &[]);
1426 guarded(self, innermost)?;
1427 self.emit_jump(Opcode::Goto, done, &[]);
1428 self.place_label(next);
1429 self.with_reference_inner(name, outer, guarded, plain, done)
1430 }
1431
1432 /// `delete name`, honouring any enclosing `with`.
1433 ///
1434 /// Inside a `with` the name may be a property of the with object, and then `delete`
1435 /// removes *that* property instead of touching the outer binding —
1436 /// `with (o) { delete p }` answers `true` and leaves `o` without `p` even when a
1437 /// global `p` exists. Left to the resolver it deleted the global instead, so the
1438 /// `statements/with/S12.10_A1.*` family then saw a `ReferenceError` on every later
1439 /// `p`.
1440 ///
1441 /// Emitted as a sequence here rather than during resolution because a resolution slot
1442 /// holds one instruction, and this is a loop over the with objects plus a fallback.
1443 fn delete_ident(&mut self, name: &str) {
1444 let names = self.cur().with_names.clone();
1445 let done = self.new_label();
1446 let mut starts = Vec::new();
1447 if !names.is_empty() {
1448 self.state().emitting_with_guard = true;
1449 // Innermost object first, like the read/write guard: the last `with` opened is
1450 // the one that shadows the others.
1451 for with_name in names.iter().rev() {
1452 let next = self.new_label();
1453 self.emit_var(VarAction::Get, with_name);
1454 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1455 self.emit_jump(Opcode::IfFalse, next, &[]);
1456 // `delete` takes the receiver then the key.
1457 self.emit_var(VarAction::Get, with_name);
1458 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1459 self.emit(Opcode::Delete, &[]);
1460 self.emit_jump(Opcode::Goto, done, &[]);
1461 self.place_label(next);
1462 starts.push(next);
1463 }
1464 self.state().emitting_with_guard = false;
1465 }
1466 // The fallback: not a property of any with object, so the ordinary rule applies.
1467 let pos = self.cur().cur_pos;
1468 self.state().insns.push(Insn::DeleteVar {
1469 name: name.to_string(),
1470 });
1471 self.state().insn_pos.push(pos);
1472 if !names.is_empty() {
1473 self.place_label(done);
1474 }
1475 }
1476
1477 fn emit_var(&mut self, action: VarAction, name: &str) {
1478 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1479 // stores and keeps the value in one instruction. The reference does this
1480 // in a post-pass; folding it at emit time keeps instruction indices
1481 // stable, which matters because labels are recorded as indices.
1482 //
1483 // Only slots have a `set_` form: a global is stored with `put_var` and
1484 // read with `get_var`, and the reference does not fold those.
1485 //
1486 // A label between the two cancels the fold. `set_x v` leaves the value on
1487 // the stack, which is only equivalent when the read immediately follows the
1488 // store; when a jump target sits in between, the store must *consume* the
1489 // value and the read must fetch it afresh. A loop head is exactly that
1490 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1491 // condition re-reads it — and folding across the label would make the
1492 // condition compare whatever the previous iteration left on the stack.
1493 if action == VarAction::Get {
1494 let is_slot = self.is_slot(name);
1495 let at_label = std::mem::take(&mut self.state().label_since_insn);
1496 //
1497 // `arguments` is excluded because the reference treats it as a special
1498 // binding: it is initialised once and read many times, and folding its
1499 // initialisation into a `set_` would leave the object on the stack where
1500 // the reference leaves nothing.
1501 if is_slot
1502 && name != "arguments"
1503 && !at_label
1504 && let Some(Insn::Var {
1505 action: previous,
1506 name: previous_name,
1507 ..
1508 }) = self.state().insns.last_mut()
1509 && *previous == VarAction::Put
1510 && previous_name == name
1511 {
1512 *previous = VarAction::Set;
1513 return;
1514 }
1515 }
1516 // Inside a `with`, every name lookup consults the with objects first. Two names
1517 // are exempt:
1518 //
1519 // * the hidden `<with…>` locals themselves, or the guard would recurse;
1520 // * a name this function **declares** — a parameter, a `var`, or a `let` of the
1521 // current body. `with` sits *outside* the function's own environment, so a
1522 // function declared inside a `with` still resolves its own bindings first:
1523 // `with (o) { function f(){ var value = "x" } }` writes `f`'s local `value`, not
1524 // `o.value`. Guarding it anyway wrote through to the with object whenever it
1525 // happened to have the name, which is why
1526 // `statements/with/S12.10_A1.7` saw `myObj.value` change. The runtime's
1527 // `eval_binding_value` already models the same order.
1528 let guarded = !self.visible_with_names(name).is_empty()
1529 && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1530 && !self.state().emitting_with_guard;
1531 if guarded {
1532 self.state().emitting_with_guard = true;
1533 self.emit_with_guarded(action, name);
1534 self.state().emitting_with_guard = false;
1535 return;
1536 }
1537 let block = self.cur().current_block;
1538 self.state().label_since_insn = false;
1539 let pos = self.cur().cur_pos;
1540 let in_params = self.cur().in_params;
1541 self.state().insns.push(Insn::Var {
1542 action,
1543 name: name.to_string(),
1544 block,
1545 in_params,
1546 });
1547 self.state().insn_pos.push(pos);
1548 }
1549
1550 fn new_label(&mut self) -> Label {
1551 let state = self.state();
1552 state.labels.push(None);
1553 Label(state.labels.len() as u32 - 1)
1554 }
1555
1556 fn place_label(&mut self, label: Label) {
1557 let index = self.cur().insns.len();
1558 self.state().label_since_insn = true;
1559 self.state().labels[label.0 as usize] = Some(index);
1560 }
1561
1562 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1563 let mut operands = vec![Op::Label(label)];
1564 operands.extend_from_slice(extra);
1565 self.emit(op, &operands);
1566 }
1567
1568 // -- scopes ------------------------------------------------------------
1569
1570 /// Start a new lexical scope inside `parent`.
1571 fn push_block(&mut self, key: u64, parent: u64) {
1572 let state = self.state();
1573 if !state.blocks.iter().any(|b| b.key == key) {
1574 state.blocks.push(Block { key, parent });
1575 }
1576 state.current_block = key;
1577 }
1578
1579 /// Emit the code that runs when a lexical scope is entered.
1580 ///
1581 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1582 /// so entering its block marks it uninitialised. Hoisted function
1583 /// declarations are created here instead, which is why a call before the
1584 /// declaration still works.
1585 ///
1586 /// The order is not obvious: bindings are emitted in *reverse* declaration
1587 /// order, because the reference walks its scope chain, which is built by
1588 /// prepending.
1589 fn emit_scope_enter(&mut self, block: u64) {
1590 // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1591 // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1592 // so entering an outer scope threw away every nested block's function
1593 // declarations: `function h(){ { function k(){} } return k; }` answered
1594 // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1595 // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1596 // in a block is also a `var` of the enclosing function), and it is what makes the
1597 // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1598 let mut hoisted = std::mem::take(&mut self.state().hoisted);
1599 let mut rest = Vec::with_capacity(hoisted.len());
1600 let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1601 for (owner, target, pool_index) in hoisted.drain(..) {
1602 if owner == block {
1603 mine.push((target, pool_index));
1604 } else {
1605 rest.push((owner, target, pool_index));
1606 }
1607 }
1608 self.state().hoisted = rest;
1609 mine.sort_by_key(|(target, _)| match target {
1610 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1611 HoistTarget::Global(_) => u32::MAX,
1612 });
1613 for (target, pool_index) in mine {
1614 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1615 match target {
1616 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1617 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1618 HoistTarget::Global(name) => {
1619 // A global binding lives in a reference cell, so the store
1620 // goes through `put_var_ref` while reads use `get_var`.
1621 let block = self.cur().current_block;
1622 let pos = self.cur().cur_pos;
1623 let in_params = self.cur().in_params;
1624 self.state().insns.push(Insn::Var {
1625 action: VarAction::PutRef,
1626 name,
1627 block,
1628 in_params,
1629 });
1630 self.state().insn_pos.push(pos);
1631 }
1632 }
1633 }
1634 for index in self.block_vars_reversed(block) {
1635 self.emit(
1636 Opcode::SetLocUninitialized,
1637 &[Op::Slot(Slot::Loc(index as u32))],
1638 );
1639 }
1640 }
1641
1642 /// Emit the code that runs when a lexical scope is exited.
1643 ///
1644 /// A captured binding has to be closed: detaching its reference cell freezes
1645 /// the value the binding had when the block ended, which is what a closure
1646 /// created inside the block must keep seeing.
1647 fn emit_scope_leave(&mut self, block: u64) {
1648 for index in self.block_vars_reversed(block) {
1649 if self.cur().vars[index].is_captured {
1650 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1651 }
1652 }
1653 }
1654
1655 /// Locals declared in `block`, in reverse declaration order.
1656 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1657 let state = self.cur();
1658 let mut out: Vec<usize> = (0..state.vars.len())
1659 .filter(|index| {
1660 state.var_block.get(*index).copied() == Some(block)
1661 && state.vars[*index].is_lexical
1662 // A derived constructor's `this` is lexical but is not initialised by
1663 // entering the scope: `check_ctor` proves it, so its dead-zone marker
1664 // was emitted with the constructor's own prologue.
1665 && state.vars[*index].name != "this"
1666 })
1667 .collect();
1668 out.reverse();
1669 out
1670 }
1671
1672 /// Declare a local, even at the top level of a script.
1673 ///
1674 /// A `catch` parameter is always a local: the reference puts it in the
1675 /// function's own variable list (`1: catch e`), never in the global object,
1676 /// because it only exists while the handler runs.
1677 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1678 let state = self.state();
1679 let index = state.vars.len() as u32;
1680 // A `catch` parameter belongs to a scope even though it is not lexical: the
1681 // runtime instantiates it per handler entry, but it never sits in the
1682 // temporal dead zone.
1683 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1684 state.current_block
1685 } else {
1686 0
1687 };
1688 state.var_block.push(block);
1689 state.vars.push(def);
1690 index
1691 }
1692
1693 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1694 if self.cur().is_module
1695 && self.cur().current_block == self.cur().body_block
1696 && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1697 {
1698 // Only the body's own block: a `let` inside a module-level `{}` is still an
1699 // ordinary local of that block, not a module variable.
1700 //
1701 // A `using` binding is excluded on purpose, and the reference excludes it in
1702 // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1703 // "'using' variables are currently not exported in modules"): a module-level
1704 // `using` is an ordinary *local* of the module body function, not a module
1705 // cell. Two things follow, and both are what the reference does — `export {a}`
1706 // of a `using` binding is "exported variable 'a' does not exist", and
1707 // disposal works, because the disposal epilogue addresses locals by slot.
1708 //
1709 // The hidden dispose-method variable is excluded for a stronger reason: it is
1710 // *always* a local (`add_scope_var` in the reference), and it must sit
1711 // immediately after its value so `using_dispose` can find it at `slot + 1`.
1712 return self.declare_module(name, &def);
1713 }
1714 if self.cur().declares_globally(&def) {
1715 self.declare_global(name, &def);
1716 return 0;
1717 }
1718 let state = self.state();
1719 let index = state.vars.len() as u32;
1720 let block = if def.is_lexical {
1721 state.current_block
1722 } else {
1723 0
1724 };
1725 state.var_block.push(block);
1726 state.vars.push(def);
1727 index
1728 }
1729
1730 /// Declare a `using` binding and its cached dispose method, returning both slots.
1731 ///
1732 /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1733 /// `(value, value + 1)` — the reference does the same and documents the constraint.
1734 fn declare_using(&mut self, name: &str) -> (u32, u32) {
1735 let mut def = VarDef::lexical(name);
1736 def.kind = VarKind::Using;
1737 let value = self.declare(name, def);
1738 let mut method = VarDef::lexical(using_method_name(name));
1739 method.kind = VarKind::UsingMethod;
1740 let method_slot = self.declare(&using_method_name(name), method);
1741 (value, method_slot)
1742 }
1743
1744 /// The slot a `using` binding's dispose method lives in.
1745 fn using_method_slot(&self, name: &str) -> Option<u32> {
1746 let hidden = using_method_name(name);
1747 self.cur()
1748 .vars
1749 .iter()
1750 .position(|var| var.name == hidden)
1751 .map(|index| index as u32)
1752 }
1753
1754 // -- statements --------------------------------------------------------
1755
1756 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1757 self.stmt_labelled(stmt, &[])
1758 }
1759
1760 /// Compile a statement that a chain of labels names.
1761 ///
1762 /// Only a loop consumes `labels`; every other statement ignores them (the
1763 /// parser has already rejected a label on a statement that cannot use it).
1764 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1765 // Only a *top-level* expression statement supplies the program's value.
1766 let saved = self.cur().leaves_value;
1767 self.state().leaves_value =
1768 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1769 self.state().stmt_depth += 1;
1770 let result = self.stmt_inner(stmt, labels);
1771 self.state().stmt_depth -= 1;
1772 // A nested statement never contributes the program's value, so the flag
1773 // the wrapper set above is what survives.
1774 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1775 self.state().leaves_value = produced;
1776 let _ = saved;
1777 result
1778 }
1779
1780 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1781 match &stmt.kind {
1782 StmtKind::Empty | StmtKind::Debugger => {}
1783 StmtKind::Expr(expr) => {
1784 // The statement's first token is a position the reference records: an
1785 // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1786 // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1787 // is why an error from a construct with no position of its own (`[...it]`
1788 // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1789 let saved = self.cur().cur_pos;
1790 self.state().cur_pos = Some(expr.span.start);
1791 // An expression statement's value is thrown away — except in a
1792 // script, where it becomes the program's result. `assign` reads this
1793 // and clears it, so a nested assignment still produces a value.
1794 self.state().discard_value = !self.cur().is_script;
1795 let result = self.expr(expr);
1796 self.state().discard_value = false;
1797 result?;
1798 if std::mem::take(&mut self.state().no_value) {
1799 // A store whose value was discarded left nothing to drop.
1800 } else if self.cur().is_script {
1801 // The program's value lands in the hidden `<ret>` local.
1802 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1803 } else {
1804 self.emit(Opcode::Drop, &[]);
1805 }
1806 // Restored last: the trailing `drop` is part of the statement, and in the
1807 // reference it simply inherits whatever the expression last recorded.
1808 self.state().cur_pos = saved;
1809 }
1810 StmtKind::Block(body) => {
1811 // The block's declarations were hoisted with its enclosing
1812 // statement list, so there is nothing left to declare here.
1813 let key = stmt.span.start.offset as u64;
1814 let parent = self.cur().current_block;
1815 self.push_block(key, parent);
1816 self.emit_scope_enter(key);
1817 // A block is where a `using` region lives, so its statements have to go
1818 // through `stmts`: that is what emits the disposal epilogue.
1819 self.stmts(body)?;
1820 self.emit_scope_leave(key);
1821 self.state().current_block = parent;
1822 }
1823 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1824 // A function declaration was already instantiated when its scope was
1825 // entered, so the statement itself emits nothing.
1826 StmtKind::FuncDecl(_) => {}
1827 StmtKind::If { test, cons, alt } => {
1828 self.reset_value();
1829 let else_label = self.new_label();
1830 let end_label = self.new_label();
1831 self.expr(test)?;
1832 self.emit_jump(Opcode::IfFalse, else_label, &[]);
1833 self.stmt(cons)?;
1834 if alt.is_some() {
1835 self.emit_jump(Opcode::Goto, end_label, &[]);
1836 }
1837 self.place_label(else_label);
1838 if let Some(alt) = alt {
1839 self.stmt(alt)?;
1840 self.place_label(end_label);
1841 }
1842 }
1843 StmtKind::While { test, body } => {
1844 self.reset_value();
1845 let top = self.new_label();
1846 let end = self.new_label();
1847 self.place_label(top);
1848 self.expr(test)?;
1849 // The condition's false branch and `break` share one target,
1850 // which is why a `while` loop needs only one end label.
1851 self.emit_jump(Opcode::IfFalse, end, &[]);
1852 self.loop_body(body, labels, top, end)?;
1853 self.emit_jump(Opcode::Goto, top, &[]);
1854 self.place_label(end);
1855 }
1856 StmtKind::DoWhile { body, test } => {
1857 self.reset_value();
1858 let top = self.new_label();
1859 let cont = self.new_label();
1860 let end = self.new_label();
1861 self.place_label(top);
1862 // `continue` in a `do…while` runs the test, so it lands on `cont`
1863 // rather than on the loop head.
1864 self.loop_body(body, labels, cont, end)?;
1865 self.place_label(cont);
1866 self.expr(test)?;
1867 self.emit_jump(Opcode::IfTrue, top, &[]);
1868 self.place_label(end);
1869 }
1870 StmtKind::For {
1871 init,
1872 test,
1873 update,
1874 body,
1875 } => {
1876 self.reset_value();
1877 let for_key = stmt.span.start.offset as u64;
1878 let for_parent = self.cur().current_block;
1879 self.push_block(for_key, for_parent);
1880 self.emit_scope_enter(for_key);
1881 if let Some(init) = init {
1882 match init {
1883 ForInit::VarDecl(decl) => {
1884 self.var_decl(decl)?;
1885 }
1886 ForInit::Expr(expr) => {
1887 // The head's value is discarded. Saying so lets an
1888 // assignment store with `put` instead of `dup`+`put`, which
1889 // is what the reference emits — and the difference matters:
1890 // a `dup`/`drop` pair around the store gives the peephole a
1891 // chance to fold the store into the *condition's* read.
1892 self.state().discard_value = true;
1893 let result = self.expr(expr);
1894 self.state().discard_value = false;
1895 result?;
1896 if !std::mem::take(&mut self.state().no_value) {
1897 self.emit(Opcode::Drop, &[]);
1898 }
1899 }
1900 }
1901 }
1902 // A `let`/`const` in the head gets a *fresh binding per iteration*,
1903 // so a closure made in the body captures that iteration's value
1904 // instead of sharing one. The reference expresses this with
1905 // `close_loc`, which swaps in a new reference cell holding the
1906 // current value; the three points below are the ones it uses — after
1907 // the initialiser, before the update, and after the loop.
1908 let loop_bindings = match init {
1909 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1910 let mut names: Vec<String> = Vec::new();
1911 for declarator in &decl.declarators {
1912 let mut idents = Vec::new();
1913 declarator.target.bound_names(&mut idents);
1914 names.extend(idents.into_iter().map(|ident| ident.name));
1915 }
1916 names
1917 }
1918 _ => Vec::new(),
1919 };
1920 // The reference also closes right after the initialiser, so the first
1921 // iteration's closures get their own cell rather than sharing the one
1922 // the initialiser wrote into.
1923 for name in &loop_bindings {
1924 let pos = self.cur().cur_pos;
1925 self.state().insns.push(Insn::CloseCaptured {
1926 name: name.clone(),
1927 block: for_key,
1928 });
1929 self.state().insn_pos.push(pos);
1930 }
1931 let top = self.new_label();
1932 let cont = self.new_label();
1933 let end = self.new_label();
1934 self.place_label(top);
1935 if let Some(test) = test {
1936 self.expr(test)?;
1937 self.emit_jump(Opcode::IfFalse, end, &[]);
1938 }
1939 // `continue` runs the update expression first, so it lands on
1940 // `cont`, which sits just before the update.
1941 self.loop_body(body, labels, cont, end)?;
1942 self.place_label(cont);
1943 // Each iteration ends with a fresh cell, so the closures the body just
1944 // created keep the cell they captured and the update writes to a new
1945 // one. Without this every closure in the loop shares one binding.
1946 let binding_block = for_key;
1947 for name in &loop_bindings {
1948 let pos = self.cur().cur_pos;
1949 self.state().insns.push(Insn::CloseCaptured {
1950 name: name.clone(),
1951 block: binding_block,
1952 });
1953 self.state().insn_pos.push(pos);
1954 }
1955 if let Some(update) = update {
1956 self.state().discard_value = true;
1957 let result = self.expr(update);
1958 self.state().discard_value = false;
1959 result?;
1960 if !std::mem::take(&mut self.state().no_value) {
1961 self.emit(Opcode::Drop, &[]);
1962 }
1963 }
1964 self.emit_jump(Opcode::Goto, top, &[]);
1965 self.place_label(end);
1966 self.emit_scope_leave(for_key);
1967 self.state().current_block = for_parent;
1968 }
1969 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1970 StmtKind::Throw(expr) => {
1971 self.expr(expr)?;
1972 self.emit(Opcode::Throw, &[]);
1973 }
1974 StmtKind::Break(_) | StmtKind::Continue(_) => {
1975 // Labels and loops are wired up in a later milestone; a bare
1976 // break/continue jumps to the innermost enclosing target, which
1977 // the loop helpers register.
1978 self.control_transfer(stmt)?;
1979 }
1980 StmtKind::Labeled { label, body } => {
1981 self.labeled(label, body, stmt)?;
1982 }
1983 StmtKind::Switch {
1984 discriminant,
1985 cases,
1986 } => {
1987 self.switch(discriminant, cases, stmt)?;
1988 }
1989 StmtKind::Try {
1990 block,
1991 handler,
1992 finalizer,
1993 } => {
1994 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1995 }
1996 StmtKind::ForIn { left, right, body } => {
1997 self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1998 }
1999 StmtKind::ForOf {
2000 left,
2001 right,
2002 body,
2003 is_await,
2004 } => {
2005 let kind = if *is_await {
2006 ForLoopKind::AwaitOf
2007 } else {
2008 ForLoopKind::Of
2009 };
2010 self.for_in_of(stmt, left, right, body, kind, labels)?;
2011 }
2012 StmtKind::With { object, body } => self.with_stmt(object, body)?,
2013 StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
2014 // `import` emits nothing: hoisting already bound its names, and the host
2015 // fills their cells before the body runs.
2016 StmtKind::Import(_) => {}
2017 StmtKind::Export(decl) => self.export_stmt(decl)?,
2018 }
2019 Ok(())
2020 }
2021
2022 /// Compile `return`, running every enclosing finalizer on the way out.
2023 ///
2024 /// `nip_catch` is what makes this possible: it discards everything on the stack
2025 /// down to and including the `catch` offset while keeping the return value on
2026 /// top, so the frame the finalizer sees has the same shape as on the normal
2027 /// path.
2028 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
2029 let mut has_value = value.is_some();
2030 if let Some(expr) = value {
2031 // `return f(x)` is a tail call *only* when nothing has to happen to the
2032 // value afterwards. A `finally` or an open iterator in scope forces the
2033 // normal path, because the cleanup has to run after the call returns —
2034 // which is exactly what a tail call refuses to do.
2035 //
2036 // A **generator or async function** never tail-calls either: its `return` is
2037 // not a return to the caller but `return_async`, which reads the value off the
2038 // stack and finishes the coroutine. A tail call replaces the frame and hands
2039 // the callee's result straight to whoever resumed us, so the value vanished and
2040 // `it.next(42)` answered `{done: true, value: undefined}` for
2041 // `function* g(){ return f(yield) }`. The reference emits `call1` plus
2042 // `return_async` there and has no tail form for a suspending body at all.
2043 let plain = !self.cur().is_suspending()
2044 && self
2045 .cur()
2046 .jump_targets
2047 .iter()
2048 .all(|target| target.finally_label.is_none() && !target.has_iterator);
2049 if plain && self.expr_if_tail_call(expr)? {
2050 // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
2051 // happen here as well.
2052 self.note_direct_eval(expr);
2053 return Ok(());
2054 }
2055 self.expr(expr)?;
2056 }
2057 // `return v` in an *async generator* awaits `v` before anything else happens —
2058 // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
2059 // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
2060 // exactly that reason ("the await must be done before handling the finally in case
2061 // it raises an exception").
2062 if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
2063 self.emit(Opcode::Await, &[]);
2064 self.state().has_await = true;
2065 }
2066 has_value = self.emit_unwind_for_return(has_value);
2067 // A generator or async function does not return to its caller: it either
2068 // finishes, and the value becomes `{value, done: true}`, or it suspends.
2069 // `return_async` is the "finished" half, and it reads the value off the stack
2070 // rather than carrying it, which is what the resume machinery expects.
2071 if self.cur().is_suspending() {
2072 if !has_value {
2073 self.emit(Opcode::Undefined, &[]);
2074 }
2075 self.emit(Opcode::ReturnAsync, &[]);
2076 return Ok(());
2077 }
2078 if has_value {
2079 self.emit(Opcode::Return, &[]);
2080 } else {
2081 self.emit(Opcode::ReturnUndef, &[]);
2082 }
2083 Ok(())
2084 }
2085
2086 /// Close an iterator: the reference's `emit_iterator_close`.
2087 ///
2088 /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
2089 /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
2090 /// sequence, and three details in it are load-bearing:
2091 ///
2092 /// * the iterator object is compared against `undefined` first, because a loop that
2093 /// ran to completion clears that slot rather than closing an exhausted iterator;
2094 /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
2095 /// * `preserve_completion` keeps whatever was underneath (the return value of the
2096 /// function being left), which is why one branch ends on `nip` and the other on `drop`.
2097 fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
2098 if !is_async {
2099 if preserve_completion {
2100 self.emit(Opcode::Rot3r, &[]);
2101 self.emit(Opcode::Undefined, &[]);
2102 }
2103 self.emit(Opcode::IteratorClose, &[]);
2104 return;
2105 }
2106 if preserve_completion {
2107 // `iter next completion -> completion iter`
2108 self.emit(Opcode::Nip, &[]);
2109 self.emit(Opcode::Swap, &[]);
2110 } else {
2111 // `iter next catch_offset -> iter`
2112 self.emit(Opcode::Drop, &[]);
2113 self.emit(Opcode::Drop, &[]);
2114 }
2115 let done = self.new_label();
2116 let no_return = self.new_label();
2117 self.emit(Opcode::Dup, &[]);
2118 self.emit(Opcode::IsUndefined, &[]);
2119 self.emit_jump(Opcode::IfTrue, done, &[]);
2120 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
2121 self.emit(Opcode::Dup, &[]);
2122 self.emit(Opcode::IsUndefinedOrNull, &[]);
2123 self.emit_jump(Opcode::IfTrue, no_return, &[]);
2124 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
2125 self.emit(Opcode::Await, &[]);
2126 self.state().has_await = true;
2127 self.emit_jump(Opcode::Goto, done, &[]);
2128 self.place_label(no_return);
2129 self.emit(Opcode::Drop, &[]);
2130 self.place_label(done);
2131 self.emit(Opcode::Drop, &[]);
2132 }
2133
2134 /// Emit the finalizer/iterator cleanup for leaving the current position with a
2135 /// return, and report whether a value is now on the stack for it to carry.
2136 ///
2137 /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
2138 /// enclosing `finally` at once, and the two used to be separate — the `yield` path
2139 /// simply emitted `return_async`, so `it.return()` ended the generator without ever
2140 /// running `finally` blocks the body was sitting inside.
2141 fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
2142 let targets = self.cur().jump_targets.clone();
2143 for target in targets.iter().rev() {
2144 if target.finally_label.is_none() && !target.has_iterator {
2145 continue;
2146 }
2147 if !has_value {
2148 // The cleanup expects a value to pass through; with nothing to
2149 // return, `undefined` stands in.
2150 self.emit(Opcode::Undefined, &[]);
2151 has_value = true;
2152 }
2153 self.emit(Opcode::NipCatch, &[]);
2154 if target.has_iterator {
2155 // Rewind to the loop's own slots and hand the close a dummy catch offset:
2156 // the loop is being abandoned, so there is nothing left to catch.
2157 self.emit_iterator_close(target.is_async_iterator, true);
2158 } else if let Some(finally) = target.finally_label {
2159 self.emit_jump(Opcode::Gosub, finally, &[]);
2160 }
2161 }
2162 has_value
2163 }
2164
2165 /// Compile a statement list, stopping at the first statement that cannot
2166 /// fall through.
2167 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2168 for (index, stmt) in body.iter().enumerate() {
2169 // A `using` declaration is not just a binding: everything after it, to the end
2170 // of the list, runs inside its disposal region. Compiling the rest of the list
2171 // recursively is what gives nested regions their innermost-first order.
2172 if Self::using_declaration(stmt).is_some() {
2173 return self.using_region(stmt, &body[index + 1..]);
2174 }
2175 self.stmt(stmt)?;
2176 if Self::terminates(stmt) {
2177 break;
2178 }
2179 }
2180 Ok(())
2181 }
2182
2183 /// The declaration a `using` statement carries, if it is one.
2184 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2185 match &stmt.kind {
2186 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2187 _ => None,
2188 }
2189 }
2190
2191 /// Compile `decl` and then the rest of its block, disposing when the block ends.
2192 ///
2193 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2194 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2195 /// exception — and this engine already funnels all of those through `catch` plus
2196 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2197 /// `return` and `break` dispose without knowing anything about `using`.
2198 ///
2199 /// ```text
2200 /// <declaration> value -> x, method -> x+1
2201 /// catch CATCH <- an exception in the rest lands here
2202 /// REST:
2203 /// <the rest of the block>
2204 /// drop <- the catch offset, on the fall-through path
2205 /// undefined; gosub DISPOSE; drop
2206 /// goto END
2207 /// CATCH:
2208 /// using_dispose x <- merges the failure into the pending exception
2209 /// throw
2210 /// DISPOSE:
2211 /// using_dispose_init
2212 /// using_dispose x
2213 /// using_dispose_end <- rethrows if a dispose failed
2214 /// ret
2215 /// END:
2216 /// ```
2217 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2218 let Some(decl) = Self::using_declaration(stmt) else {
2219 unreachable!("using_region is only called for a using declaration");
2220 };
2221 // `using` binds exactly one name and has no pattern form, which the parser
2222 // enforces; the region still has to know *which* slot to dispose.
2223 let name = decl
2224 .declarators
2225 .first()
2226 .and_then(|declarator| match &declarator.target.kind {
2227 PatternKind::Ident(ident) => Some(ident.name.clone()),
2228 _ => None,
2229 });
2230 self.stmt(stmt)?;
2231 let Some(name) = name else {
2232 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2233 // must not make the compiler panic.
2234 return self.stmts(rest);
2235 };
2236 let Some(value_slot) = self.using_value_slot(&name) else {
2237 // Declared globally, which the parser rules out for a script; a module's
2238 // top level is a scope, and there the disposal stays a known gap.
2239 return self.stmts(rest);
2240 };
2241 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2242 // exit path already disposed.
2243 let live = !rest.last().is_some_and(Self::terminates);
2244 self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
2245 }
2246
2247 /// The slot a `using` binding's value lives in.
2248 fn using_value_slot(&self, name: &str) -> Option<u32> {
2249 self.cur()
2250 .vars
2251 .iter()
2252 .position(|var| var.name == name && var.kind == VarKind::Using)
2253 .map(|index| index as u32)
2254 }
2255
2256 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2257 ///
2258 /// Shared between a `using` statement — which owns the rest of its block — and a
2259 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2260 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2261 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2262 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2263 /// target with a `finally_label` is what makes `return` and `break` dispose without
2264 /// knowing anything about `using`.
2265 ///
2266 /// ```text
2267 /// catch CATCH <- an exception inside lands here
2268 /// <inside>
2269 /// drop <- the catch offset, on the fall-through path
2270 /// undefined; gosub DISPOSE; drop
2271 /// goto END
2272 /// CATCH:
2273 /// using_dispose slot <- merges the failure into the pending exception
2274 /// throw
2275 /// DISPOSE:
2276 /// using_dispose_init
2277 /// using_dispose slot
2278 /// using_dispose_end <- rethrows if a dispose failed
2279 /// ret
2280 /// END:
2281 /// ```
2282 fn using_region_around(
2283 &mut self,
2284 value_slot: u32,
2285 live: bool,
2286 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2287 ) -> Result<(), SyntaxError> {
2288 let catch_label = self.new_label();
2289 let end_label = self.new_label();
2290 let dispose_label = self.new_label();
2291
2292 self.emit_jump(Opcode::Catch, catch_label, &[]);
2293 self.push_jump_target(JumpTarget {
2294 names: Vec::new(),
2295 break_label: None,
2296 continue_label: None,
2297 // The catch offset is the one thing on the stack that leaving has to remove.
2298 drop_count: 1,
2299 finally_label: Some(dispose_label),
2300 is_regular_stmt: false,
2301 has_iterator: false,
2302 is_async_iterator: false,
2303 });
2304 inside(self)?;
2305 self.pop_jump_target();
2306
2307 if live {
2308 self.emit(Opcode::Drop, &[]);
2309 self.emit(Opcode::Undefined, &[]);
2310 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2311 self.emit(Opcode::Drop, &[]);
2312 self.emit_jump(Opcode::Goto, end_label, &[]);
2313 }
2314
2315 // An exception unwinds to here with the thrown value on the stack, which is exactly
2316 // the shape `using_dispose` expects as its error state.
2317 self.place_label(catch_label);
2318 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2319 self.emit(Opcode::Throw, &[]);
2320
2321 self.place_label(dispose_label);
2322 // Inside the subroutine the return value and the `gosub` return address are both
2323 // live, and neither an outer finalizer nor another region may run before this one
2324 // has finished.
2325 self.push_jump_target(JumpTarget {
2326 names: Vec::new(),
2327 break_label: None,
2328 continue_label: None,
2329 drop_count: 2,
2330 finally_label: None,
2331 is_regular_stmt: false,
2332 has_iterator: false,
2333 is_async_iterator: false,
2334 });
2335 self.emit(Opcode::UsingDisposeInit, &[]);
2336 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2337 self.emit(Opcode::UsingDisposeEnd, &[]);
2338 self.pop_jump_target();
2339 self.emit(Opcode::Ret, &[]);
2340 self.place_label(end_label);
2341 Ok(())
2342 }
2343
2344 /// Declare every name a statement list introduces, before compiling any of
2345 /// it, so a reference that appears textually before a declaration still
2346 /// resolves.
2347 ///
2348 /// Declarations are walked in source order because that is the order the
2349 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2350 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2351 /// declarations hoist out to the function scope; lexical names belong to the
2352 /// block they were written in, which `block` records.
2353 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2354 let saved = self.cur().current_block;
2355 self.state().current_block = block;
2356 let result = self.hoist_list(body);
2357 // Only now is every binding of this scope known, so the deferred function
2358 // bodies can be compiled against the finished list. Compiled at its own
2359 // declaration instead, a body that names a `var` written further down would
2360 // have resolved that name as a global.
2361 if result.is_ok() {
2362 let deferred = std::mem::take(&mut self.state().deferred_funcs);
2363 let mut outcome = Ok(());
2364 for (owner, func) in deferred {
2365 let previous = self.cur().current_block;
2366 self.state().current_block = owner;
2367 outcome = self.func_decl(&func);
2368 self.state().current_block = previous;
2369 if outcome.is_err() {
2370 break;
2371 }
2372 }
2373 self.state().current_block = saved;
2374 return outcome;
2375 }
2376 // `current_block` is restored by the caller for a block statement, since
2377 // it needs it set while compiling; only clean up on the hoist path.
2378 self.state().current_block = saved;
2379 result
2380 }
2381
2382 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2383 for stmt in body {
2384 self.hoist_stmt(stmt)?;
2385 }
2386 Ok(())
2387 }
2388
2389 /// Whether a statement always transfers control away, making everything after
2390 /// it in the same list unreachable.
2391 ///
2392 /// The reference drops such statements in `skip_dead_code`, so `return 1;
2393 /// let x = 2;` compiles to the same bytecode as `return 1;`.
2394 fn terminates(stmt: &Stmt) -> bool {
2395 matches!(
2396 stmt.kind,
2397 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2398 )
2399 }
2400
2401 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2402 match &stmt.kind {
2403 StmtKind::VarDecl(decl) => {
2404 for declarator in &decl.declarators {
2405 let mut names = Vec::new();
2406 declarator.target.bound_names(&mut names);
2407 for name in names {
2408 let text = name.name.clone();
2409 if decl.kind == VarDeclKind::Var {
2410 let def = VarDef::var(text.clone());
2411 self.declare_var(&text, def);
2412 } else if decl.kind.is_using() {
2413 // Two adjacent slots: the resource, then the dispose method
2414 // snapshotted at declaration. `using_dispose` reads them as a
2415 // pair `(slot, slot + 1)`, so nothing may be declared between
2416 // them — which is why both are declared here, in one step,
2417 // rather than the method being added at emission time.
2418 self.declare_using(&text);
2419 } else {
2420 let def = if decl.kind == VarDeclKind::Const {
2421 VarDef::constant(text.clone())
2422 } else {
2423 VarDef::lexical(text.clone())
2424 };
2425 self.declare(&text, def);
2426 }
2427 }
2428 }
2429 }
2430 StmtKind::FuncDecl(func) => {
2431 if let Some(name) = &func.name {
2432 // A function declaration is a `var` binding that happens to
2433 // hold a function, not a lexical one.
2434 let def = VarDef::var(name.name.clone());
2435 self.declare_var(&name.name.clone(), def);
2436 }
2437 // The function object is created when the scope is entered, so it
2438 // exists before the declaration is reached. Its body is compiled
2439 // *after* this scope's hoisting finishes, so a name it uses resolves
2440 // even when the `var` that declares it comes later in the source.
2441 let owner = self.cur().current_block;
2442 self.state().deferred_funcs.push((owner, func.clone()));
2443 }
2444 StmtKind::ClassDecl(class) => {
2445 if let Some(name) = &class.name {
2446 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2447 }
2448 }
2449 // A module's imports are bound before any of its code runs, and its exports
2450 // declare the very bindings they export — so both hoist the declarations
2451 // their `StmtKind` arm will later emit code for.
2452 StmtKind::Import(decl) => self.hoist_import(decl)?,
2453 StmtKind::Export(decl) => self.hoist_export(decl)?,
2454 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2455 StmtKind::If { cons, alt, .. } => {
2456 self.hoist_stmt(cons)?;
2457 if let Some(alt) = alt {
2458 self.hoist_stmt(alt)?;
2459 }
2460 }
2461 StmtKind::While { body, .. }
2462 | StmtKind::DoWhile { body, .. }
2463 | StmtKind::Labeled { body, .. }
2464 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2465 StmtKind::For { init, body, .. } => {
2466 // A `for` head gets its own scope even when it declares nothing,
2467 // because `let` in the head is scoped to the loop.
2468 let key = stmt.span.start.offset as u64;
2469 let parent = self.cur().current_block;
2470 self.push_block(key, parent);
2471 if let Some(init) = init
2472 && let ForInit::VarDecl(decl) = init
2473 {
2474 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2475 }
2476 self.hoist_stmt(body)?;
2477 self.state().current_block = parent;
2478 }
2479 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2480 let key = stmt.span.start.offset as u64;
2481 let parent = self.cur().current_block;
2482 self.push_block(key, parent);
2483 if let ForHead::VarDecl(decl) = left {
2484 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2485 }
2486 self.hoist_stmt(body)?;
2487 self.state().current_block = parent;
2488 }
2489 StmtKind::Try {
2490 block,
2491 handler,
2492 finalizer,
2493 } => {
2494 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2495 let try_parent = self.cur().current_block;
2496 if let Some(handler) = handler {
2497 // The catch parameter belongs to the function scope, not to a
2498 // block: it is a `catch` binding rather than a `let`, so it is
2499 // never in the temporal dead zone and `emit_scope_enter` must
2500 // not mark it uninitialised. It still has to be declared before
2501 // the handler body is hoisted, so it takes the slot the
2502 // reference gives it (bindings are numbered in source order).
2503 if let Some(pattern) = &handler.param {
2504 // The parameter gets its own scope, so entering the handler
2505 // does not have to re-declare it. It is not lexical, so it
2506 // is never marked uninitialised.
2507 let key = Self::try_block_key(stmt, TryPart::Param);
2508 let parent = self.cur().current_block;
2509 self.push_block(key, parent);
2510 // A destructuring parameter binds several names, one slot each,
2511 // in the order they are written. The reference declares those as
2512 // `let`s rather than as one `catch` binding — its dump prints
2513 // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2514 // so the kind follows the shape of the parameter.
2515 //
2516 // Neither form is in the dead zone: the stores run as the handler
2517 // is entered, so both use the unchecked `put_loc`.
2518 let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2519 let mut names = Vec::new();
2520 pattern.bound_names(&mut names);
2521 for name in names {
2522 let def = VarDef {
2523 name: name.name.clone(),
2524 is_const: false,
2525 is_lexical: destructures,
2526 kind: if destructures {
2527 crate::bytecode::VarKind::LexicalCatch
2528 } else {
2529 crate::bytecode::VarKind::Catch
2530 },
2531 is_captured: false,
2532 scope_level: 0,
2533 scope_next: None,
2534 };
2535 self.declare_local(&name.name.clone(), def);
2536 }
2537 // The handler body nests inside the parameter's scope, so the
2538 // body's bindings chain on to the parameter (the reference
2539 // prints `let y [next:1]`, pointing at `e`).
2540 self.state().current_block = key;
2541 }
2542 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2543 // Back to the block the `try` itself lives in, so the finalizer
2544 // is a sibling of the handler rather than nested in it.
2545 self.state().current_block = try_parent;
2546 }
2547 if let Some(finalizer) = finalizer {
2548 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2549 }
2550 }
2551 StmtKind::Switch { cases, .. } => {
2552 let key = stmt.span.start.offset as u64;
2553 let parent = self.cur().current_block;
2554 self.push_block(key, parent);
2555 for case in cases {
2556 self.hoist_list(&case.body)?;
2557 }
2558 self.state().current_block = parent;
2559 }
2560 _ => {}
2561 }
2562 Ok(())
2563 }
2564
2565 /// Hoist a nested statement list, which is its own lexical scope.
2566 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2567 let parent = self.cur().current_block;
2568 self.push_block(key, parent);
2569 self.hoist_list(body)?;
2570 self.state().current_block = parent;
2571 Ok(())
2572 }
2573
2574 /// A block key for one part of a `try` statement.
2575 ///
2576 /// The three parts are three separate scopes, so they cannot share the key a
2577 /// statement's own offset would give them: the try block, the handler body and
2578 /// the finalizer would then look like one scope, and their `let` bindings would
2579 /// be marked uninitialised only on entering the first of them.
2580 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2581 (stmt.span.start.offset as u64) * 4 + part as u64
2582 }
2583
2584 /// Declare a `var`: it lives in the function's own scope, not the block's.
2585 fn declare_var(&mut self, name: &str, def: VarDef) {
2586 if self.cur().is_module {
2587 self.declare_module(name, &def);
2588 return;
2589 }
2590 if self.cur().declares_globally(&def) {
2591 self.declare_global(name, &def);
2592 return;
2593 }
2594 let state = self.state();
2595 // A binding of the *parameter* scope does not count: the body's `var` of the
2596 // same name is a different binding and needs a slot of its own.
2597 if state.vars.iter().enumerate().any(|(index, v)| {
2598 v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2599 }) {
2600 return;
2601 }
2602 // A `var` belongs to the function scope, never to the enclosing block.
2603 state.var_block.push(FUNCTION_SCOPE);
2604 state.vars.push(def);
2605 }
2606
2607 /// Declare `name` as a binding of the parameter scope, returning its slot.
2608 fn declare_param_var(&mut self, name: &str) -> u32 {
2609 declare_param_var_at(self.state(), name)
2610 }
2611
2612 /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2613 ///
2614 /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2615 /// so each points at the one declared before it and the oldest ends the chain with
2616 /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2617 /// runtime walks when it instantiates them.
2618 fn declare_param_binding(&mut self, name: &str) -> u32 {
2619 let state = self.state();
2620 let previous = state
2621 .vars
2622 .iter()
2623 .enumerate()
2624 .rev()
2625 .find(|(index, var)| {
2626 state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2627 })
2628 .map(|(index, _)| index as i32);
2629 let index = state.vars.len() as u32;
2630 state.var_block.push(PARAM_SCOPE);
2631 let mut def = VarDef::lexical(name);
2632 // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2633 // the function's, and its bindings are initialised one by one rather than all at
2634 // once — which is exactly what the dead zone needs.
2635 def.scope_level = 1;
2636 def.scope_next = Some(previous.unwrap_or(-2));
2637 state.vars.push(def);
2638 index
2639 }
2640
2641 /// The slot of a parameter-list binding, if the list has one by that name.
2642 fn param_binding_slot(&self, name: &str) -> Option<u32> {
2643 let state = self.cur();
2644 state
2645 .vars
2646 .iter()
2647 .enumerate()
2648 .position(|(index, var)| {
2649 var.name == name
2650 && var.is_lexical
2651 && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2652 })
2653 .map(|index| index as u32)
2654 }
2655
2656 /// Every parameter-list binding, in declaration order.
2657 fn param_binding_names(&self) -> Vec<String> {
2658 let state = self.cur();
2659 state
2660 .vars
2661 .iter()
2662 .enumerate()
2663 .filter(|(index, var)| {
2664 var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2665 })
2666 .map(|(_, var)| var.name.clone())
2667 .collect()
2668 }
2669
2670 /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2671 fn body_var_slot(&self, name: &str) -> Option<u32> {
2672 let state = self.cur();
2673 state
2674 .vars
2675 .iter()
2676 .enumerate()
2677 .find(|(index, var)| {
2678 var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2679 })
2680 .map(|(index, _)| index as u32)
2681 }
2682
2683 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2684 /// one.
2685 ///
2686 /// With parameter expressions the reference creates two: an unmapped one in the
2687 /// argument scope, for the defaults and anything they close over, and the body's own.
2688 /// They are separate bindings, which is what makes
2689 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2690 /// report 1 from `p` and 2 from the body.
2691 fn provide_param_arguments(&mut self) {
2692 if !self.cur().has_parameter_expressions {
2693 return;
2694 }
2695 let mentioned = self.cur().needs_param_arguments
2696 || self
2697 .cur()
2698 .insns
2699 .iter()
2700 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2701 if !mentioned {
2702 return;
2703 }
2704 let slot = self.declare_param_var("arguments");
2705 let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2706 0
2707 } else {
2708 1
2709 };
2710 self.prepend_initialiser_to(
2711 slot,
2712 Insn::Fixed {
2713 op: Opcode::SpecialObject,
2714 operands: vec![Op::Int(magic)],
2715 },
2716 );
2717 }
2718
2719 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2720 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2721 let current = self.stack.len() - 1;
2722 let init = [
2723 producer,
2724 Insn::Fixed {
2725 op: Opcode::PutLoc,
2726 operands: vec![Op::Slot(Slot::Loc(slot))],
2727 },
2728 ];
2729 let inserted = init.len();
2730 for (index, instruction) in init.into_iter().enumerate() {
2731 self.stack[current].insns.insert(index, instruction);
2732 }
2733 for placed in self.stack[current].labels.iter_mut().flatten() {
2734 *placed += inserted;
2735 }
2736 self.state().label_since_insn = false;
2737 }
2738
2739 /// Give the function an `arguments` binding if its body mentions one.
2740 ///
2741 /// The check runs on the *instruction* stream rather than the AST: by this point
2742 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2743 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2744 /// would renumber every later local slot and stop the bytecode matching the
2745 /// reference, which only adds the binding when the body uses it.
2746 ///
2747 /// `arguments` is a local, initialised at the top of the body by
2748 /// `special_object`; that is the reference's shape, so the disassembly agrees.
2749 fn provide_arguments(&mut self) {
2750 let current = self.stack.len() - 1;
2751 if self.stack[current].is_script || self.stack[current].is_module {
2752 // A module has no `arguments` binding; referring to it is a ReferenceError,
2753 // which is exactly what an unbound name produces.
2754 return;
2755 }
2756 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2757 // function, which is why `() => arguments` sees the caller's arguments.
2758 if self.stack[current].is_arrow {
2759 if self.mentions("arguments") {
2760 self.ensure_enclosing_arguments();
2761 }
2762 return;
2763 }
2764 // Only a *body* mention needs the body's binding: the parameter list has one of
2765 // its own (see [`Compiler::provide_param_arguments`]).
2766 //
2767 // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2768 // `Var`, so without this the body got no binding at all — the name resolved to
2769 // the global object and `delete` answered `true` for a binding that cannot be
2770 // deleted. The reference answers `false`.
2771 let mentioned = self.cur().insns.iter().any(|insn| match insn {
2772 Insn::Var {
2773 name, in_params, ..
2774 } => name == "arguments" && !*in_params,
2775 Insn::DeleteVar { name } => name == "arguments",
2776 _ => false,
2777 });
2778 // A mention that resolves to the body's *own* lexical `arguments` is not a request
2779 // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
2780 // implicit binding is not created at all. Providing it anyway was worse than useless:
2781 // its prologue store resolved past the shadowing `let` and landed on the **global**,
2782 // so `function f(p = eval("var arguments")) { let arguments; }` defined
2783 // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
2784 // test262's `fn-body-cntns-arguments-lex-bind` family).
2785 //
2786 // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
2787 // var *is* the binding, and the implicit arguments object is initialised into it at
2788 // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
2789 // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
2790 // `typeof arguments` `"undefined"`.
2791 if self
2792 .cur()
2793 .vars
2794 .iter()
2795 .any(|var| var.name == "arguments" && var.needs_check())
2796 {
2797 return;
2798 }
2799 if !mentioned && !self.cur().needs_arguments_local {
2800 return;
2801 }
2802 // The request may have come only from a parameter-list arrow, in which case the
2803 // parameter scope's binding already answers for it and the body needs none.
2804 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2805 return;
2806 }
2807 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
2808 //
2809 // With parameter expressions the list and the body are separate environments, so
2810 // an assignment to a parameter cannot be reflected into `arguments` at all — the
2811 // arguments object is unmapped whatever the mode, which is why the reference emits
2812 // `special_object 0` here even in sloppy code.
2813 // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
2814 // object unmapped whatever the mode — §10.4.4 keys the decision on
2815 // `IsSimpleParameterList`, not on strictness alone.
2816 let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
2817 0
2818 } else {
2819 1
2820 };
2821 // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
2822 // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
2823 // The only storage both sides can see is a reference cell, so every parameter the
2824 // object maps gets one — even a parameter no closure captured. Without this the
2825 // slot holds a plain copy and the mapping has nothing to write through.
2826 if magic == 1 {
2827 for arg in &mut self.stack[current].args {
2828 arg.is_captured = true;
2829 }
2830 }
2831 self.prepend_binding("arguments", magic);
2832 }
2833
2834 /// Whether a *body* instruction refers to `arguments`.
2835 fn body_mentions_arguments(&self) -> bool {
2836 self.cur()
2837 .insns
2838 .iter()
2839 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2840 }
2841
2842 /// Whether the function body's instruction stream refers to `name`.
2843 fn mentions(&self, name: &str) -> bool {
2844 let current = self.stack.len() - 1;
2845 // A binding of the parameter scope does not answer for the body: the body's own
2846 // `arguments` (or self-name) still has to be provided for it.
2847 if self.stack[current]
2848 .vars
2849 .iter()
2850 .enumerate()
2851 .any(|(index, v)| {
2852 v.name == name
2853 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2854 })
2855 {
2856 return false;
2857 }
2858 self.stack[current]
2859 .insns
2860 .iter()
2861 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2862 }
2863
2864 /// Bind the name a named function expression uses to refer to itself.
2865 ///
2866 /// The value is `special_object 2`, the function currently running, so the binding
2867 /// is the closure itself and not a copy. It is a local of this function, which is
2868 /// what keeps `g` out of the enclosing scope.
2869 /// Give the function a local `this`, for an arrow inside it to capture.
2870 fn provide_this_local(&mut self) {
2871 let current = self.stack.len() - 1;
2872 if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2873 return;
2874 }
2875 if !self.stack[current]
2876 .vars
2877 .iter()
2878 .any(|var| var.name == "this")
2879 {
2880 self.declare_hidden_local("this", VarKind::Normal);
2881 }
2882 self.prepend_initialiser(
2883 "this",
2884 Insn::Fixed {
2885 op: Opcode::PushThis,
2886 operands: vec![],
2887 },
2888 );
2889 }
2890
2891 /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2892 /// to read through `super`.
2893 fn provide_home_object_local(&mut self) {
2894 let current = self.stack.len() - 1;
2895 if !self.stack[current].needs_home_object_local {
2896 return;
2897 }
2898 if !self.stack[current]
2899 .vars
2900 .iter()
2901 .any(|var| var.name == HOME_OBJECT)
2902 {
2903 self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2904 }
2905 self.prepend_initialiser(
2906 HOME_OBJECT,
2907 Insn::Fixed {
2908 op: Opcode::SpecialObject,
2909 operands: vec![Op::Int(4)],
2910 },
2911 );
2912 }
2913
2914 fn provide_self_name(&mut self) {
2915 let current = self.stack.len() - 1;
2916 let Some(name) = self.stack[current].self_name.clone() else {
2917 return;
2918 };
2919 if self.stack[current].self_name_initialized {
2920 return;
2921 }
2922 // Either the body refers to the name, or a nested function already forced the
2923 // binding into existence while being resolved. A direct `eval` can name it
2924 // without mentioning it, so its presence is a third reason: in strict mode
2925 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2926 // that only happens if the binding exists.
2927 let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2928 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2929 return;
2930 }
2931 self.stack[current].self_name_initialized = true;
2932 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2933 }
2934
2935 /// Insert `special_object magic` plus the store to `name` at the top of the body.
2936 ///
2937 /// Prepending shifts every label that has been placed, so they are all moved by
2938 /// the number of instructions inserted.
2939 fn prepend_binding(&mut self, name: &str, magic: i32) {
2940 self.prepend_binding_with(name, magic, VarKind::Normal);
2941 }
2942
2943 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2944 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2945 let current = self.stack.len() - 1;
2946 // A function-expression's own name is immutable in strict mode, which is what
2947 // makes `f = 1` inside a strict body throw instead of being dropped.
2948 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2949 self.declare_var(
2950 name,
2951 VarDef {
2952 kind,
2953 is_const,
2954 ..VarDef::var(name)
2955 },
2956 );
2957 let init = [
2958 Insn::Fixed {
2959 op: Opcode::SpecialObject,
2960 operands: vec![Op::Int(magic)],
2961 },
2962 Insn::Var {
2963 // An initialisation, not an assignment: sloppy mode drops stores to a
2964 // function-expression's own name, and the prologue is what puts the
2965 // value there in the first place.
2966 action: if kind == VarKind::FunctionName {
2967 VarAction::PutInit
2968 } else {
2969 VarAction::Put
2970 },
2971 name: name.to_string(),
2972 block: 0,
2973 in_params: false,
2974 },
2975 ];
2976 let inserted = init.len();
2977 for (index, instruction) in init.into_iter().enumerate() {
2978 self.stack[current].insns.insert(index, instruction);
2979 }
2980 for placed in self.stack[current].labels.iter_mut().flatten() {
2981 *placed += inserted;
2982 }
2983 // A store sits at the insertion point now, so the `put`/`get` fold must not
2984 // reach across it.
2985 self.stack[current].label_since_insn = true;
2986 }
2987
2988 /// Record a top-level script declaration as a global.
2989 ///
2990 /// A script's top-level `var`/`let`/`function` create properties of the
2991 /// global object, not slots in the script's frame, so they show up as closure
2992 /// variables instead.
2993 fn declare_global(&mut self, name: &str, def: &VarDef) {
2994 let state = self.state();
2995 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2996 // The name was already referenced, from a function compiled before this
2997 // declaration was reached — `function a(){ b() } function b(){}` resolves
2998 // `b` while `b` is still unknown, and that guess has to be corrected here.
2999 // Leaving it as a plain global meant the declaration was never registered,
3000 // so the binding did not exist at run time and `a()` threw
3001 // `b is not defined`.
3002 if matches!(existing.closure_type, ClosureType::Global) {
3003 existing.closure_type = ClosureType::GlobalDecl;
3004 existing.is_const = def.is_const;
3005 existing.is_lexical = def.is_lexical;
3006 }
3007 return;
3008 }
3009 state.closure_vars.push(ClosureVar {
3010 name: name.to_string(),
3011 is_const: def.is_const,
3012 is_lexical: def.is_lexical,
3013 closure_type: ClosureType::GlobalDecl,
3014 var_idx: 0,
3015 });
3016 }
3017
3018 /// Record a module-level declaration as a module variable.
3019 ///
3020 /// The binding is a closure variable of the module body, so reads and writes are
3021 /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
3022 /// *who fills the cell*: the module record does, before the body runs, and an import
3023 /// points its cell at the exporting module's, which is what makes bindings live and
3024 /// cycles work.
3025 fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
3026 let state = self.state();
3027 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3028 // The name may have been referenced before this declaration was hoisted,
3029 // which resolved it as a plain global. Correct that here, the way
3030 // `declare_global` does.
3031 if matches!(existing.closure_type, ClosureType::Global) {
3032 existing.closure_type = ClosureType::ModuleDecl;
3033 existing.is_const = def.is_const;
3034 existing.is_lexical = def.is_lexical;
3035 }
3036 return 0;
3037 }
3038 state.closure_vars.push(ClosureVar {
3039 name: name.to_string(),
3040 is_const: def.is_const,
3041 is_lexical: def.is_lexical,
3042 closure_type: ClosureType::ModuleDecl,
3043 var_idx: 0,
3044 });
3045 0
3046 }
3047
3048 /// Declare a module variable and answer its closure-variable index.
3049 ///
3050 /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
3051 /// module variable is not one. The import table needs the real index instead, because
3052 /// that is the position the host writes the cell into.
3053 fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
3054 self.declare_module(name, def);
3055 self.cur()
3056 .closure_vars
3057 .iter()
3058 .position(|c| c.name == name)
3059 .map(|index| index as u32)
3060 .unwrap_or(0)
3061 }
3062
3063 /// Declare one imported binding as a module variable.
3064 ///
3065 /// Returns the closure-variable index, which is what the import table records: the
3066 /// host writes the exporter's cell into that slot before the body runs.
3067 fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
3068 let state = self.state();
3069 if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
3070 // Keep the slot, fix the kind: the name may already have been referenced.
3071 state.closure_vars[index].closure_type = ClosureType::ModuleImport;
3072 state.closure_vars[index].is_const = is_const;
3073 return index as u32;
3074 }
3075 state.closure_vars.push(ClosureVar {
3076 name: name.to_string(),
3077 // An imported binding cannot be assigned: `x = 1` on an import is a
3078 // `TypeError` at run time, which the const flag is what produces.
3079 is_const: true,
3080 // Lexical, so reads go through `get_var_ref_check`: before linking has filled
3081 // the cell an import is in its dead zone, and reading it there must say so
3082 // rather than answer `undefined`.
3083 is_lexical: true,
3084 closure_type: ClosureType::ModuleImport,
3085 var_idx: 0,
3086 });
3087 state.closure_vars.len() as u32 - 1
3088 }
3089
3090 /// Emit the code an `export` needs.
3091 ///
3092 /// Only `export default <expr>` has any: everything else is a table entry whose
3093 /// binding is declared elsewhere. The expression is stored into the hidden
3094 /// `*default*` variable rather than returned, because the module body has no value
3095 /// to speak of.
3096 fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3097 match &decl.kind {
3098 ExportKind::Declaration(stmt) => self.stmt(stmt),
3099 ExportKind::Default(expr) => {
3100 // `export default class Foo {}`: evaluate the declaration (which binds
3101 // `Foo`), then copy its value into the hidden `*default*` binding, because a
3102 // class declaration is a *statement* and `expr` cannot be compiled as one.
3103 if let ExprKind::Class(class) = &expr.kind
3104 && class.name.is_some()
3105 {
3106 self.stmt(&Stmt {
3107 kind: StmtKind::ClassDecl(class.clone()),
3108 span: expr.span,
3109 })?;
3110 let Some(name) = &class.name else {
3111 return Ok(());
3112 };
3113 self.emit_var(VarAction::Get, &name.name);
3114 let index = self.declare_export_default();
3115 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3116 return Ok(());
3117 }
3118 // A named default function/class is already a module binding; the export
3119 // points at it and there is nothing to evaluate.
3120 if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
3121 return Ok(());
3122 }
3123 self.expr(expr)?;
3124 // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
3125 // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
3126 // name is observable — `imported.default.name` — and without this an
3127 // anonymous `export default class {}` arrived with the empty name.
3128 self.set_name_if_anonymous(expr, &Wtf8::new("default"));
3129 let index = self.declare_export_default();
3130 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3131 Ok(())
3132 }
3133 ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
3134 }
3135 }
3136
3137 /// A module name as the string it denotes.
3138 fn module_name_text(name: &ModuleName) -> &str {
3139 match name {
3140 ModuleName::Ident(ident) => &ident.name,
3141 ModuleName::Str(text) => text,
3142 }
3143 }
3144
3145 /// Bind `import`'s local names and record where each one comes from.
3146 ///
3147 /// Nothing is emitted: an import is not an instruction, it is a promise that the
3148 /// binding's cell will be filled before the body runs. The cell lands in the module's
3149 /// environment at a fixed index, and the host fills it from the exporter's cell —
3150 /// which is why a cyclic import can bind before the other module has evaluated.
3151 fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
3152 let request = self.module_request(&decl.source, &decl.attributes);
3153 for specifier in &decl.specifiers {
3154 let (local, name, is_star) = match specifier {
3155 ImportSpecifier::Default(ident) => {
3156 (ident.name.clone(), "default".to_string(), false)
3157 }
3158 ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3159 ImportSpecifier::Named { imported, local } => (
3160 local.name.clone(),
3161 Self::module_name_text(imported).to_string(),
3162 false,
3163 ),
3164 };
3165 // `import * as ns` is *not* a live binding of another module's variable —
3166 // it is a value of its own, which is why the reference declares it like a
3167 // module variable and the host stores the namespace object in that cell.
3168 let var_idx = if is_star {
3169 // `const`: a namespace object is a value, and the binding is immutable.
3170 self.declare_module_var(&local, &VarDef::constant(local.clone()))
3171 } else {
3172 self.declare_import(&local, true)
3173 };
3174 self.module_meta().imports.push(ImportEntry {
3175 module: request,
3176 name,
3177 var_idx,
3178 is_star,
3179 });
3180 }
3181 Ok(())
3182 }
3183
3184 /// Record what an `export` offers, declaring the binding it exports.
3185 ///
3186 /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3187 fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3188 match &decl.kind {
3189 ExportKind::Declaration(stmt) => {
3190 // The inner declaration keeps its own hoisting, then every name it binds
3191 // becomes an export of the same name.
3192 self.hoist_stmt(stmt)?;
3193 let mut names = Vec::new();
3194 Self::declared_names(stmt, &mut names);
3195 for name in names {
3196 let var_idx = self.module_binding_index(&name);
3197 self.exports_local(&name, var_idx);
3198 }
3199 }
3200 ExportKind::Default(expr) => {
3201 // The reference puts a default export in a hidden `*default*` variable,
3202 // so `export default function f(){}` can export a *value* while `f` stays
3203 // a binding of the module.
3204 if let ExprKind::Function(func) = &expr.kind
3205 && let Some(name) = &func.name
3206 {
3207 let text = name.name.clone();
3208 self.hoist_stmt(&Stmt {
3209 kind: StmtKind::FuncDecl(func.clone()),
3210 span: expr.span,
3211 })?;
3212 let var_idx = self.module_binding_index(&text);
3213 self.module_meta().exports.push(ExportEntry::Local {
3214 export_name: "default".to_string(),
3215 var_idx,
3216 });
3217 return Ok(());
3218 }
3219 if let ExprKind::Class(class) = &expr.kind
3220 && class.name.is_some()
3221 {
3222 // `export default class Foo {}` binds `Foo` in the module scope **and**
3223 // stores the class into the hidden `*default*` binding — it is a
3224 // declaration *and* a value, unlike `export default class {}` which is
3225 // only a value.
3226 //
3227 // Pointing the `default` export straight at `Foo` looked simpler and was
3228 // wrong twice over: `module_binding_index` did not find the lexical
3229 // binding the hoist had just made, so it declared a second one that
3230 // nothing ever wrote, and `export_stmt` then had no code to emit for the
3231 // declaration either. `imported.default` came out `undefined` and `Foo`
3232 // was not in scope inside its own module.
3233 self.hoist_stmt(&Stmt {
3234 kind: StmtKind::ClassDecl(class.clone()),
3235 span: expr.span,
3236 })?;
3237 let var_idx = self.declare_export_default();
3238 self.exports_local("default", var_idx);
3239 return Ok(());
3240 }
3241 let var_idx = self.declare_export_default();
3242 self.module_meta().exports.push(ExportEntry::Local {
3243 export_name: "default".to_string(),
3244 var_idx,
3245 });
3246 }
3247 ExportKind::Named {
3248 specifiers,
3249 source,
3250 attributes,
3251 } => match source {
3252 Some(source) => {
3253 let request = self.module_request(source, attributes);
3254 for specifier in specifiers {
3255 self.module_meta().exports.push(ExportEntry::Indirect {
3256 export_name: Self::module_name_text(&specifier.exported).to_string(),
3257 module: request,
3258 import_name: Self::module_name_text(&specifier.local).to_string(),
3259 });
3260 }
3261 }
3262 None => {
3263 for specifier in specifiers {
3264 let local = Self::module_name_text(&specifier.local).to_string();
3265 let export_name = Self::module_name_text(&specifier.exported).to_string();
3266 // `export { x }` where `x` is itself an **import** re-exports the
3267 // binding the import names, not a binding of this module
3268 // (§16.2.1.6.3: a local export whose local name is imported resolves
3269 // through the imported module). Recording it as a local made two
3270 // modules that both forward one import look like two different
3271 // bindings, and the name was reported ambiguous
3272 // (`import-and-export-propagates-binding`;
3273 // `namespace-unambiguous-if-import-star-as-and-export`).
3274 let closure_names: Vec<String> = self
3275 .cur()
3276 .closure_vars
3277 .iter()
3278 .map(|var| var.name.clone())
3279 .collect();
3280 let forwarded = self
3281 .module_meta()
3282 .imports
3283 .iter()
3284 .filter(|entry| {
3285 closure_names
3286 .get(entry.var_idx as usize)
3287 .is_some_and(|name| *name == local)
3288 })
3289 .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3290 .find(|(_, name, is_star)| !is_star || name.is_empty());
3291 if let Some((request, name, is_star)) = forwarded {
3292 // A namespace import has no export *name* of its own; the
3293 // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3294 // which is what the marker below records.
3295 let import_name = if is_star {
3296 "*namespace*".to_string()
3297 } else {
3298 name
3299 };
3300 self.module_meta().exports.push(ExportEntry::Indirect {
3301 export_name,
3302 module: request,
3303 import_name,
3304 });
3305 continue;
3306 }
3307 let var_idx = self.module_binding_index(&local);
3308 self.module_meta().exports.push(ExportEntry::Local {
3309 export_name,
3310 var_idx,
3311 });
3312 }
3313 }
3314 },
3315 ExportKind::All {
3316 source,
3317 exported,
3318 attributes,
3319 } => {
3320 let request = self.module_request(source, attributes);
3321 match exported {
3322 Some(name) => {
3323 self.module_meta().exports.push(ExportEntry::StarAs {
3324 export_name: Self::module_name_text(name).to_string(),
3325 module: request,
3326 });
3327 }
3328 None => {
3329 self.module_meta()
3330 .exports
3331 .push(ExportEntry::Star { module: request });
3332 }
3333 }
3334 }
3335 }
3336 Ok(())
3337 }
3338
3339 /// The names a declaration binds, which is what `export <decl>` exports.
3340 fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3341 match &stmt.kind {
3342 StmtKind::VarDecl(decl) => {
3343 for declarator in &decl.declarators {
3344 let mut names = Vec::new();
3345 declarator.target.bound_names(&mut names);
3346 out.extend(names.into_iter().map(|name| name.name));
3347 }
3348 }
3349 StmtKind::FuncDecl(func) => {
3350 if let Some(name) = &func.name {
3351 out.push(name.name.clone());
3352 }
3353 }
3354 StmtKind::ClassDecl(class) => {
3355 if let Some(name) = &class.name {
3356 out.push(name.name.clone());
3357 }
3358 }
3359 _ => {}
3360 }
3361 }
3362
3363 /// The closure-variable index of a module binding, declaring it if the name was
3364 /// exported without being declared here.
3365 ///
3366 /// `export { x }` where `x` is not declared in the module is a link-time
3367 /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3368 fn module_binding_index(&mut self, name: &str) -> u32 {
3369 if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3370 return index as u32;
3371 }
3372 self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3373 }
3374
3375 fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3376 self.module_meta().exports.push(ExportEntry::Local {
3377 export_name: export_name.to_string(),
3378 var_idx,
3379 });
3380 }
3381
3382 /// The hidden `*default*` binding `export default <expr>` stores into.
3383 fn declare_export_default(&mut self) -> u32 {
3384 const DEFAULT: &str = "*default*";
3385 if let Some(index) = self
3386 .cur()
3387 .closure_vars
3388 .iter()
3389 .position(|c| c.name == DEFAULT)
3390 {
3391 return index as u32;
3392 }
3393 self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3394 }
3395
3396 /// The module tables, which only the top-level state has.
3397 fn module_meta(&mut self) -> &mut ModuleMeta {
3398 self.state()
3399 .module
3400 .as_mut()
3401 .expect("module tables are only touched while compiling a module")
3402 }
3403
3404 /// The index of `specifier`'s request, adding it if it is new.
3405 ///
3406 /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3407 /// JSON and once as text is two modules with two different contents, which is exactly
3408 /// what `hello_module.js` does.
3409 fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3410 let attributes: Vec<(String, String)> = attributes
3411 .iter()
3412 .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3413 .collect();
3414 let meta = self.module_meta();
3415 if let Some(index) = meta
3416 .requests
3417 .iter()
3418 .position(|request| request.specifier == specifier && request.attributes == attributes)
3419 {
3420 return index as u32;
3421 }
3422 meta.requests.push(ModuleRequest {
3423 specifier: specifier.to_string(),
3424 attributes,
3425 });
3426 meta.requests.len() as u32 - 1
3427 }
3428
3429 /// Compile a loop body with a `break`/`continue` target pushed for it.
3430 fn loop_body(
3431 &mut self,
3432 body: &Stmt,
3433 labels: &[String],
3434 continue_label: Label,
3435 break_label: Label,
3436 ) -> Result<(), SyntaxError> {
3437 self.push_jump_target(JumpTarget {
3438 names: labels.to_vec(),
3439 break_label: Some(break_label),
3440 continue_label: Some(continue_label),
3441 // A loop leaves nothing of its own on the value stack.
3442 drop_count: 0,
3443 finally_label: None,
3444 is_regular_stmt: false,
3445 has_iterator: false,
3446 is_async_iterator: false,
3447 });
3448 let result = self.stmt(body);
3449 self.pop_jump_target();
3450 result
3451 }
3452
3453 fn push_jump_target(&mut self, target: JumpTarget) {
3454 self.state().jump_targets.push(target);
3455 }
3456
3457 fn pop_jump_target(&mut self) {
3458 self.state().jump_targets.pop();
3459 }
3460
3461 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3462 let (label, is_break) = match &stmt.kind {
3463 StmtKind::Break(label) => (label.as_ref(), true),
3464 StmtKind::Continue(label) => (label.as_ref(), false),
3465 _ => unreachable!("control_transfer is only called for break and continue"),
3466 };
3467
3468 // Walk outward from the innermost construct. Everything considered before
3469 // the match is a construct control is leaving, and leaving it has a cost:
3470 // its stack slots go, and its finalizer runs.
3471 let targets = self.cur().jump_targets.clone();
3472 for target in targets.iter().rev() {
3473 let destination = match (label, is_break) {
3474 // An unlabelled `break` skips a labelled non-loop statement: `break`
3475 // may name one, but the bare form only means "leave the loop".
3476 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3477 (None, false) => target.continue_label,
3478 (Some(name), true) => target
3479 .break_label
3480 .filter(|_| target.names.contains(&name.name)),
3481 (Some(name), false) => target
3482 .continue_label
3483 .filter(|_| target.names.contains(&name.name)),
3484 };
3485
3486 if let Some(destination) = destination {
3487 self.emit_jump(Opcode::Goto, destination, &[]);
3488 return Ok(());
3489 }
3490
3491 // Closing the iterator consumes the three slots the loop keeps on the
3492 // stack (iterator, next method, catch offset), so those are not dropped
3493 // again below.
3494 let mut remaining = target.drop_count;
3495 if target.has_iterator {
3496 self.emit_iterator_close(target.is_async_iterator, false);
3497 remaining = remaining.saturating_sub(3);
3498 }
3499 for _ in 0..remaining {
3500 self.emit(Opcode::Drop, &[]);
3501 }
3502 if let Some(finally) = target.finally_label {
3503 // The finalizer runs as a subroutine and is handed a dummy return
3504 // value, which is dropped afterwards to keep the stack the depth it
3505 // had before.
3506 self.emit(Opcode::Undefined, &[]);
3507 self.emit_jump(Opcode::Gosub, finally, &[]);
3508 self.emit(Opcode::Drop, &[]);
3509 }
3510 }
3511
3512 // The parser rejects a break/continue with no target, so reaching here
3513 // means the compiler's own bookkeeping is wrong.
3514 Err(SyntaxError::new(
3515 if is_break {
3516 "break has no enclosing loop or switch"
3517 } else {
3518 "continue has no enclosing loop"
3519 },
3520 stmt.span,
3521 ))
3522 }
3523
3524 /// Compile a labelled statement.
3525 ///
3526 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3527 /// that loop's targets, so the chain is collected and handed to the loop. A
3528 /// label on a non-loop statement only provides a `break` target, because
3529 /// `continue` may not target it.
3530 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3531 let mut names = vec![label.name.clone()];
3532 let mut inner = body;
3533 while let StmtKind::Labeled {
3534 label: next,
3535 body: deeper,
3536 } = &inner.kind
3537 {
3538 names.push(next.name.clone());
3539 inner = deeper;
3540 }
3541 if Self::is_loop(inner) {
3542 return self.stmt_labelled(inner, &names);
3543 }
3544 let end = self.new_label();
3545 self.push_jump_target(JumpTarget {
3546 names,
3547 break_label: Some(end),
3548 continue_label: None,
3549 drop_count: 0,
3550 finally_label: None,
3551 is_regular_stmt: true,
3552 has_iterator: false,
3553 is_async_iterator: false,
3554 });
3555 let result = self.stmt(inner);
3556 self.pop_jump_target();
3557 result?;
3558 self.place_label(end);
3559 let _ = stmt;
3560 Ok(())
3561 }
3562
3563 /// Whether a statement is a loop, i.e. a valid target for `continue`.
3564 fn is_loop(stmt: &Stmt) -> bool {
3565 matches!(
3566 stmt.kind,
3567 StmtKind::While { .. }
3568 | StmtKind::DoWhile { .. }
3569 | StmtKind::For { .. }
3570 | StmtKind::ForIn { .. }
3571 | StmtKind::ForOf { .. }
3572 )
3573 }
3574
3575 /// Compile `switch`.
3576 ///
3577 /// The discriminant is evaluated once and stays on the value stack while the
3578 /// clauses compare against copies of it, so it is dropped at the end — which is
3579 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3580 /// clause's body jumps over the *next* clause's tests straight into its body.
3581 ///
3582 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3583 /// the next run's tests. Only the last run's miss reaches the `default` body, or
3584 /// the end of the switch when there is no `default`. That failure path can point
3585 /// backwards (`default` written first), so the runs and their labels are worked
3586 /// out before any code is emitted.
3587 fn switch(
3588 &mut self,
3589 discriminant: &Expr,
3590 cases: &[SwitchCase],
3591 stmt: &Stmt,
3592 ) -> Result<(), SyntaxError> {
3593 self.reset_value();
3594 // The discriminant is evaluated outside the switch's block scope, before
3595 // any `case` clause exists.
3596 self.expr(discriminant)?;
3597
3598 let switch_key = stmt.span.start.offset as u64;
3599 let switch_parent = self.cur().current_block;
3600 self.push_block(switch_key, switch_parent);
3601 self.emit_scope_enter(switch_key);
3602
3603 let break_label = self.new_label();
3604 self.push_jump_target(JumpTarget {
3605 names: Vec::new(),
3606 break_label: Some(break_label),
3607 // `switch` is a valid `break` target but not a `continue` target.
3608 continue_label: None,
3609 // The discriminant stays on the value stack for the whole statement, so
3610 // a `break` aimed further out has to discard it.
3611 drop_count: 1,
3612 finally_label: None,
3613 is_regular_stmt: false,
3614 has_iterator: false,
3615 is_async_iterator: false,
3616 });
3617
3618 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3619 // its label to the clause after it, so both tests reach the same body.
3620 let mut runs: Vec<(usize, usize)> = Vec::new();
3621 let mut scan = 0;
3622 while scan < cases.len() {
3623 if cases[scan].test.is_some() {
3624 let mut last = scan;
3625 while last + 1 < cases.len()
3626 && cases[last].test.is_some()
3627 && cases[last].body.is_empty()
3628 && cases[last + 1].test.is_some()
3629 {
3630 last += 1;
3631 }
3632 runs.push((scan, last));
3633 scan = last + 1;
3634 } else {
3635 scan += 1;
3636 }
3637 }
3638
3639 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3640 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3641 let default_at = cases.iter().position(|case| case.test.is_none());
3642 // Where the last run sends control when nothing matched.
3643 let miss_target = match default_at {
3644 Some(index) => body_labels[index],
3645 None => break_label,
3646 };
3647
3648 // When `default` comes first, control has to jump over it to reach the
3649 // tests. It only needs to when some clause actually has a test; otherwise
3650 // the default body is the entry point.
3651 let mut entry = None;
3652 if default_at == Some(0) && !runs.is_empty() {
3653 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3654 entry = Some(run_labels[0]);
3655 }
3656
3657 let mut index = 0;
3658 let mut run = 0;
3659 let result = (|| -> Result<(), SyntaxError> {
3660 while index < cases.len() {
3661 if cases[index].test.is_some() {
3662 let (first, last) = runs[run];
3663 // Reaching these tests from the preceding body is a
3664 // fallthrough, which continues inside the body and skips them.
3665 if index > 0 {
3666 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3667 }
3668 if let Some(label) = entry.take() {
3669 self.place_label(label);
3670 }
3671 self.place_label(run_labels[run]);
3672
3673 for (offset, case) in cases[first..=last].iter().enumerate() {
3674 let test = case.test.as_ref().unwrap();
3675 self.emit(Opcode::Dup, &[]);
3676 self.expr(test)?;
3677 self.emit(Opcode::StrictEq, &[]);
3678 if first + offset < last {
3679 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3680 } else {
3681 // Hand over to the next run's tests, or give up.
3682 let next = match runs.get(run + 1) {
3683 Some(_) => run_labels[run + 1],
3684 None => miss_target,
3685 };
3686 self.emit_jump(Opcode::IfFalse, next, &[]);
3687 }
3688 }
3689
3690 self.place_label(body_labels[index]);
3691 for case in &cases[first..=last] {
3692 self.stmts(&case.body)?;
3693 }
3694 index = last + 1;
3695 run += 1;
3696 } else {
3697 // `default`: control arrives here either by falling through or
3698 // because every test missed.
3699 self.place_label(body_labels[index]);
3700 self.stmts(&cases[index].body)?;
3701 index += 1;
3702 }
3703 }
3704 Ok(())
3705 })();
3706
3707 if result.is_ok() {
3708 self.place_label(break_label);
3709 // Discard the discriminant now that no test needs it.
3710 self.emit(Opcode::Drop, &[]);
3711 }
3712
3713 self.pop_jump_target();
3714 self.emit_scope_leave(switch_key);
3715 self.state().current_block = switch_parent;
3716 result
3717 }
3718
3719 /// Compile `try`/`catch`/`finally`.
3720 ///
3721 /// The shape is an exception table built out of `catch` instructions, each of
3722 /// which records where control goes if the instructions that follow raise:
3723 ///
3724 /// ```text
3725 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
3726 /// <guarded block>
3727 /// drop <- discard the catch offset
3728 /// undefined; gosub FINALLY; drop
3729 /// goto END
3730 /// HANDLER:
3731 /// <bind the catch parameter>
3732 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
3733 /// <handler body>
3734 /// drop; undefined; gosub FINALLY; drop; goto END
3735 /// CATCH2:
3736 /// gosub FINALLY; throw <- run the finalizer, then let the error out
3737 /// FINALLY:
3738 /// <finalizer>
3739 /// ret <- return to the `gosub`
3740 /// END:
3741 /// ```
3742 ///
3743 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3744 /// of the finalizer serves the normal path, the handler path and the
3745 /// propagating-exception path.
3746 ///
3747 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3748 /// runs with `ret_value` on the stack, and the normal path has no value to
3749 /// keep, so it pushes one to keep the stack depth identical on every path.
3750 fn try_stmt(
3751 &mut self,
3752 stmt: &Stmt,
3753 block: &[Stmt],
3754 handler: &Option<CatchClause>,
3755 finalizer: Option<&[Stmt]>,
3756 ) -> Result<(), SyntaxError> {
3757 self.reset_value();
3758
3759 let catch_label = self.new_label();
3760 let catch2_label = self.new_label();
3761 let finally_label = self.new_label();
3762 let end_label = self.new_label();
3763
3764 self.emit_jump(Opcode::Catch, catch_label, &[]);
3765
3766 // The guarded block. `break` may not target it, so its entry exists purely
3767 // to unwind: a jump out has to discard the catch offset and run the
3768 // finalizer.
3769 self.push_jump_target(JumpTarget {
3770 names: Vec::new(),
3771 break_label: None,
3772 continue_label: None,
3773 drop_count: 1,
3774 finally_label: Some(finally_label),
3775 is_regular_stmt: false,
3776 has_iterator: false,
3777 is_async_iterator: false,
3778 });
3779
3780 let block_key = Self::try_block_key(stmt, TryPart::Block);
3781 let block_parent = self.cur().current_block;
3782 self.push_block(block_key, block_parent);
3783 self.emit_scope_enter(block_key);
3784 self.stmts(block)?;
3785 self.emit_scope_leave(block_key);
3786 self.state().current_block = block_parent;
3787 // A guarded block that ends in a `return`/`throw` never reaches the
3788 // epilogue, so the reference does not emit one.
3789 self.pop_jump_target();
3790 let block_live = !block.last().is_some_and(Self::terminates);
3791
3792 if block_live {
3793 self.emit(Opcode::Drop, &[]);
3794 self.emit(Opcode::Undefined, &[]);
3795 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3796 self.emit(Opcode::Drop, &[]);
3797 self.emit_jump(Opcode::Goto, end_label, &[]);
3798 }
3799
3800 if let Some(handler) = handler {
3801 self.place_label(catch_label);
3802 // The thrown value is on top of the stack: bind it, or discard it for
3803 // `catch { }`.
3804 match &handler.param {
3805 Some(pattern) => {
3806 // The stores resolve the names, so they have to run inside the
3807 // parameter's own scope; otherwise a same-named `catch` further out
3808 // could win. A `catch` binding is never in the dead zone, so the store
3809 // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3810 let param_key = Self::try_block_key(stmt, TryPart::Param);
3811 let param_parent = self.cur().current_block;
3812 self.push_block(param_key, param_parent);
3813 self.destructure(pattern, Some(VarDeclKind::Var))?;
3814 self.state().current_block = param_parent;
3815 }
3816 None => self.emit(Opcode::Drop, &[]),
3817 }
3818 self.emit_jump(Opcode::Catch, catch2_label, &[]);
3819
3820 self.push_jump_target(JumpTarget {
3821 names: Vec::new(),
3822 break_label: None,
3823 continue_label: None,
3824 drop_count: 1,
3825 finally_label: Some(finally_label),
3826 is_regular_stmt: false,
3827 has_iterator: false,
3828 is_async_iterator: false,
3829 });
3830 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3831 let catch_parent = self.cur().current_block;
3832 self.push_block(catch_key, catch_parent);
3833 self.emit_scope_enter(catch_key);
3834 self.stmts(&handler.body)?;
3835 self.emit_scope_leave(catch_key);
3836 self.state().current_block = catch_parent;
3837 self.pop_jump_target();
3838 let handler_live = !handler.body.last().is_some_and(Self::terminates);
3839
3840 if handler_live {
3841 self.emit(Opcode::Drop, &[]);
3842 self.emit(Opcode::Undefined, &[]);
3843 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3844 self.emit(Opcode::Drop, &[]);
3845 self.emit_jump(Opcode::Goto, end_label, &[]);
3846 }
3847
3848 // An error raised inside the handler still has to run the finalizer.
3849 self.place_label(catch2_label);
3850 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3851 self.emit(Opcode::Throw, &[]);
3852 } else {
3853 // `try`/`finally` with no handler: the finalizer runs, then the error
3854 // keeps propagating.
3855 self.place_label(catch_label);
3856 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3857 self.emit(Opcode::Throw, &[]);
3858 }
3859
3860 self.place_label(finally_label);
3861 // Inside the finalizer, leaving has a different cost: the return value and
3862 // the `gosub` return address are both on the stack, and neither finalizer nor
3863 // any outer one may run before the block has finished.
3864 self.push_jump_target(JumpTarget {
3865 names: Vec::new(),
3866 break_label: None,
3867 continue_label: None,
3868 drop_count: 2,
3869 finally_label: None,
3870 is_regular_stmt: false,
3871 has_iterator: false,
3872 is_async_iterator: false,
3873 });
3874 if let Some(finalizer) = finalizer {
3875 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3876 let finally_parent = self.cur().current_block;
3877 self.push_block(finally_key, finally_parent);
3878 self.emit_scope_enter(finally_key);
3879 self.stmts(finalizer)?;
3880 self.emit_scope_leave(finally_key);
3881 self.state().current_block = finally_parent;
3882 }
3883 self.pop_jump_target();
3884 self.emit(Opcode::Ret, &[]);
3885 self.place_label(end_label);
3886 Ok(())
3887 }
3888
3889 /// Compile `for`/`in` and `for`/`of`.
3890 ///
3891 /// Both keep an enumeration record on the value stack for the whole loop, which
3892 /// is what makes leaving early expensive: the record has to be dropped, or the
3893 /// iterator closed. The layout is
3894 ///
3895 /// ```text
3896 /// <iterated expression>
3897 /// for_in_start | for_of_start <- pushes the record
3898 /// goto TEST
3899 /// NEXT:
3900 /// <bind the loop variable>
3901 /// <body>
3902 /// TEST:
3903 /// for_in_next | for_of_next 0
3904 /// if_false NEXT <- not finished: next iteration
3905 /// drop <- finished: discard the leftover value
3906 /// BREAK:
3907 /// drop | iterator_close <- the one cleanup `break` also uses
3908 /// ```
3909 ///
3910 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3911 /// normal exit share one copy — which is why `break` inside the loop emits nothing
3912 /// of its own, and only a jump that passes *through* the loop pays for its record.
3913 fn for_in_of(
3914 &mut self,
3915 stmt: &Stmt,
3916 left: &ForHead,
3917 right: &Expr,
3918 body: &Stmt,
3919 kind: ForLoopKind,
3920 labels: &[String],
3921 ) -> Result<(), SyntaxError> {
3922 self.reset_value();
3923
3924 let loop_key = stmt.span.start.offset as u64;
3925 let loop_parent = self.cur().current_block;
3926 self.push_block(loop_key, loop_parent);
3927 self.emit_scope_enter(loop_key);
3928
3929 // The iterated expression is evaluated inside the loop's scope, after the
3930 // bindings exist in the temporal dead zone.
3931 self.expr(right)?;
3932
3933 let next = self.new_label();
3934 let test = self.new_label();
3935 let break_target = self.new_label();
3936
3937 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3938 match kind {
3939 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3940 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3941 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3942 }
3943 self.emit_jump(Opcode::Goto, test, &[]);
3944
3945 self.push_jump_target(JumpTarget {
3946 // `outer: for (x of xs) … break outer` needs the name here. Without it the
3947 // loop had no label to break to, and the compiler reported "break has no
3948 // enclosing loop" for a loop that was plainly enclosing it.
3949 names: labels.to_vec(),
3950 break_label: Some(break_target),
3951 continue_label: Some(test),
3952 // Passing through the loop has to dispose of its record. A `for`/`of`
3953 // record is three slots, and closing the iterator consumes all of them.
3954 drop_count: if has_iterator { 3 } else { 1 },
3955 finally_label: None,
3956 is_regular_stmt: false,
3957 has_iterator,
3958 is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3959 });
3960
3961 self.place_label(next);
3962 self.bind_loop_variable(left)?;
3963
3964 // The reference marks the body with its own label here. Nothing jumps to it
3965 // once the loop is laid out, but it is not decoration: a label between the
3966 // store and the body is why `put_loc v; get_loc v` does *not* fold into
3967 // `set_loc v` when the body starts by reading the loop variable.
3968 let body_label = self.new_label();
3969 self.place_label(body_label);
3970 // `for (using x of …)` disposes once per iteration, so the body is a disposal
3971 // region rather than the whole loop: the resource is the element that this
3972 // iteration produced.
3973 let using_slot = match left {
3974 ForHead::VarDecl(decl) if decl.kind.is_using() => {
3975 decl.declarators
3976 .first()
3977 .and_then(|declarator| match &declarator.target.kind {
3978 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3979 _ => None,
3980 })
3981 }
3982 _ => None,
3983 };
3984 match using_slot {
3985 Some(slot) => {
3986 let live = !Self::terminates(body);
3987 self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3988 }
3989 None => self.stmt(body)?,
3990 }
3991
3992 // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
3993 // binding each iteration**, so a closure the body creates keeps that iteration's
3994 // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
3995 // a new reference cell holding the current value.
3996 //
3997 // The position is the *end* of the body, not the start: closing before the body
3998 // would leave the closures pointing at the cell the next `put_loc` overwrites, and
3999 // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
4000 for name in Self::loop_binding_names(left) {
4001 let pos = self.cur().cur_pos;
4002 self.state().insns.push(Insn::CloseCaptured {
4003 name,
4004 block: loop_key,
4005 });
4006 self.state().insn_pos.push(pos);
4007 }
4008 self.place_label(test);
4009 match kind {
4010 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
4011 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
4012 ForLoopKind::AwaitOf => {
4013 // The reference's shape: step, `await` the result, then unpack it.
4014 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
4015 self.emit(Opcode::Await, &[]);
4016 self.state().has_await = true;
4017 self.emit(Opcode::IteratorGetValueDone, &[]);
4018 }
4019 }
4020 self.emit_jump(Opcode::IfFalse, next, &[]);
4021 // The loop is finished; `for_xx_next` left an `undefined` behind.
4022 self.emit(Opcode::Drop, &[]);
4023
4024 self.pop_jump_target();
4025 self.place_label(break_target);
4026 if has_iterator {
4027 // A loop that ran to completion finds its iterator slot already cleared (see
4028 // `iterator_get_value_done`), so this closes only an iterator abandoned by a
4029 // `break` that jumped here.
4030 self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
4031 } else {
4032 self.emit(Opcode::Drop, &[]);
4033 }
4034
4035 self.emit_scope_leave(loop_key);
4036 self.state().current_block = loop_parent;
4037 Ok(())
4038 }
4039
4040 /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
4041 /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
4042 fn loop_binding_names(left: &ForHead) -> Vec<String> {
4043 let ForHead::VarDecl(decl) = left else {
4044 return Vec::new();
4045 };
4046 if decl.kind == VarDeclKind::Var {
4047 return Vec::new();
4048 }
4049 let mut names = Vec::new();
4050 for declarator in &decl.declarators {
4051 let mut idents = Vec::new();
4052 declarator.target.bound_names(&mut idents);
4053 names.extend(idents.into_iter().map(|ident| ident.name));
4054 }
4055 names
4056 }
4057
4058 /// Store the value `for_xx_next` left on the stack into the loop variable.
4059 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
4060 // A declaration *initialises* the binding, which is what takes a `let` out of
4061 // the temporal dead zone, so the store is the unchecked form. Assigning to a
4062 // binding declared elsewhere is an ordinary write and keeps its check.
4063 let (pattern, action) = match left {
4064 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
4065 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
4066 };
4067 match &pattern.kind {
4068 PatternKind::Ident(name) => {
4069 // `for (using x of …)` validates and snapshots each iteration's value
4070 // before the body runs, which is what makes a non-disposable element fail
4071 // on the iteration that produced it rather than at the end of the loop.
4072 if let ForHead::VarDecl(decl) = left
4073 && decl.kind.is_using()
4074 {
4075 let method_slot = self
4076 .using_method_slot(&name.name)
4077 .expect("a using binding was declared during hoisting");
4078 self.emit(
4079 Opcode::UsingCheck,
4080 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4081 );
4082 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4083 }
4084 self.emit_var(action, &name.name);
4085 Ok(())
4086 }
4087 // Every other target stores through the same path an assignment pattern
4088 // uses, which is what makes `for (a[0] in obj)` write each key into the
4089 // property instead of refusing the loop outright.
4090 _ => self.destructure(
4091 pattern,
4092 match left {
4093 ForHead::VarDecl(decl) => Some(decl.kind),
4094 ForHead::Assign(_) => None,
4095 },
4096 ),
4097 }
4098 }
4099
4100 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
4101 for declarator in &decl.declarators {
4102 let Some(init) = &declarator.init else {
4103 // `var x;` stays `undefined`. A lexical binding is different: it
4104 // has to be *initialised* to leave the temporal dead zone, so the
4105 // compiler supplies an explicit `undefined`.
4106 if decl.kind.is_lexical() {
4107 // A lexical binding has to be *initialised* to leave the temporal
4108 // dead zone, and a destructuring one is no different — `let {a}`
4109 // with no initialiser is a syntax error, but `let [a] = []` still
4110 // needs `a` to be initialised from an empty source, which the
4111 // pattern does on its own.
4112 self.emit(Opcode::Undefined, &[]);
4113 self.destructure(&declarator.target, Some(decl.kind))?;
4114 }
4115 continue;
4116 };
4117 match &declarator.target.kind {
4118 PatternKind::Ident(name) => {
4119 self.expr(init)?;
4120 self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
4121 if decl.kind.is_using() {
4122 // `using_check` validates the value and snapshots its dispose
4123 // method: `value -> value, method`. The snapshot is what makes a
4124 // later change to `Symbol.dispose` irrelevant, and validating here
4125 // is what keeps the body from running at all when the value is not
4126 // disposable.
4127 let method_slot = self
4128 .using_method_slot(&name.name)
4129 .expect("a using binding was declared during hoisting");
4130 self.emit(
4131 Opcode::UsingCheck,
4132 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4133 );
4134 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4135 self.emit_var(VarAction::PutInit, &name.name);
4136 continue;
4137 }
4138 // A declaration statement produces no value, so nothing is
4139 // duplicated onto the stack.
4140 match decl.kind {
4141 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
4142 _ => self.emit_var(VarAction::PutInit, &name.name),
4143 }
4144 }
4145 _ => {
4146 // A destructuring declaration keeps nothing on the stack: the
4147 // pattern consumes the initialiser.
4148 self.expr(init)?;
4149 self.destructure(&declarator.target, Some(decl.kind))?;
4150 }
4151 }
4152 }
4153 Ok(())
4154 }
4155
4156 /// Bind a destructuring pattern from the value on top of the stack.
4157 ///
4158 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4159 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4160 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4161 /// *assignment*, where a member expression is a legal target and the store is an
4162 /// ordinary property write.
4163 ///
4164 /// The value is consumed. An assignment expression's own result is the right-hand
4165 /// side, which the caller keeps separately — the spec does not make the pattern's
4166 /// last store produce it.
4167 fn destructure(
4168 &mut self,
4169 pattern: &Pattern,
4170 decl: Option<VarDeclKind>,
4171 ) -> Result<(), SyntaxError> {
4172 match &pattern.kind {
4173 PatternKind::Ident(name) => {
4174 match decl {
4175 Some(VarDeclKind::Var) | None => {
4176 self.emit_var(VarAction::Put, &name.name);
4177 }
4178 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4179 }
4180 Ok(())
4181 }
4182 PatternKind::Assign { target, default } => {
4183 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4184 // keeps `null`.
4185 //
4186 // The shape is the reference's: test for `undefined`, and when the value is
4187 // present fall **through** to a single store both paths share. The
4188 // alternatives — branching to the store on each side — need a second store
4189 // and a jump between them, which is what the dump used to show.
4190 let has_value = self.new_label();
4191 self.emit(Opcode::Dup, &[]);
4192 self.emit(Opcode::IsUndefined, &[]);
4193 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4194 self.emit(Opcode::Drop, &[]);
4195 self.expr(default)?;
4196 // `var {f = function(){}} = {}` names the function `f`, like a plain
4197 // `var f = function(){}` does. Both pattern forms do it:
4198 // `BindingInitialization` names the value for a *binding* target, and since
4199 // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4200 // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4201 // no name to give, which is why only an identifier qualifies.
4202 if let PatternKind::Ident(name) = &target.kind {
4203 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4204 }
4205 self.place_label(has_value);
4206 self.destructure(target, decl)
4207 }
4208 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4209 PatternKind::Object { properties, rest } => {
4210 self.destructure_object(properties, rest, decl, pattern)
4211 }
4212 PatternKind::Member(member) if decl.is_none() => {
4213 // An assignment pattern may store into a property. The value is on the
4214 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4215 // put the three in the order `put_array_el`/`put_field` expect.
4216 self.expr(&member.object)?;
4217 match &member.property {
4218 MemberProp::Ident(name) => {
4219 // `value obj` -> `obj value`, the order `put_field` takes.
4220 // Nothing needs to be left behind: a pattern element's value is
4221 // consumed by its own store.
4222 self.emit(Opcode::Swap, &[]);
4223 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4224 }
4225 MemberProp::Computed(index) => {
4226 self.expr(index)?;
4227 // `value obj key` -> `obj key value`.
4228 self.emit(Opcode::Rot3l, &[]);
4229 self.emit(Opcode::PutArrayEl, &[]);
4230 }
4231 MemberProp::Private(name) => {
4232 // `value obj` -> `obj value`, and the store half of the assignment is
4233 // the same one `obj.#x = value` uses — only without `insert2`,
4234 // because a pattern element's value is not wanted back.
4235 let binding = format!("#{}", name.name);
4236 let (kind, setter) = self.private_use(&binding, member.span)?;
4237 self.emit(Opcode::Swap, &[]);
4238 self.private_store(&binding, kind, setter.as_deref())?;
4239 }
4240 }
4241 Ok(())
4242 }
4243 PatternKind::Rest(inner) => self.destructure(inner, decl),
4244 PatternKind::Invalid(expr) => {
4245 Err(SyntaxError::new("invalid assignment target", expr.span))
4246 }
4247 _ => Err(SyntaxError::new(
4248 "this destructuring target is not supported by the compiler yet",
4249 pattern.span,
4250 )),
4251 }
4252 }
4253
4254 /// `[…]` on the left: drain an iterator, binding one target per element.
4255 ///
4256 /// A target that stores into a **property** — `[o.p] = it` — has its reference worked
4257 /// out *before* the value is pulled. That ordering is observable twice over
4258 /// (`array-elem-iter-thrw-close`):
4259 ///
4260 /// * `next` must not have been called yet when the reference throws, so
4261 /// `[ {}[thrower()] ] = iterable` reports `nextCount === 0`;
4262 /// * the iterator must still be closed, because the throw happens while the record is
4263 /// live — which is `catch_here`'s `catch_offset 0` doing its work.
4264 ///
4265 /// Doing it the other way round — pull the value, then evaluate the reference — got
4266 /// both wrong: an extra `next` call, and, when the reference threw, an iterator that had
4267 /// already been drained past.
4268 fn destructure_array(
4269 &mut self,
4270 elements: &[Option<PatternElement>],
4271 rest: &Option<Box<RestElement>>,
4272 decl: Option<VarDeclKind>,
4273 ) -> Result<(), SyntaxError> {
4274 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4275 // pattern accepts any iterable and closes the iterator when the pattern ends
4276 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4277 // first because it is on top.
4278 //
4279 // It also counts as an open iterator for `return` and `break`: a pattern is not a
4280 // loop, but the record is live across everything the pattern evaluates, so
4281 // `function* g(){ [ {} = yield ] = it }` resumed with `return()` has to close it
4282 // (`array-elem-iter-rtrn-close`). `emit_unwind_for_return` finds it by this entry
4283 // and `nip_catch` uncovers exactly the `iter next` pairs it left behind.
4284 //
4285 // A `break`/`continue` cannot occur inside a pattern, so `names` and both labels
4286 // are empty and `drop_count` — read only by that unreachable path — keeps the
4287 // reference's 2.
4288 self.push_jump_target(JumpTarget {
4289 names: Vec::new(),
4290 break_label: None,
4291 continue_label: None,
4292 drop_count: 2,
4293 finally_label: None,
4294 is_regular_stmt: false,
4295 has_iterator: true,
4296 is_async_iterator: false,
4297 });
4298 self.emit(Opcode::ForOfStart, &[]);
4299 for element in elements {
4300 match element {
4301 Some(PatternElement::Pattern(pattern)) => {
4302 match Self::member_element_target(pattern, decl) {
4303 // A prepared reference sits above the record, so `for_of_next` is
4304 // told how many values are in the way.
4305 Some(member) => {
4306 let extra = self.prepare_member_target(member)?;
4307 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4308 self.emit(Opcode::Drop, &[]);
4309 self.destructure_prepared(pattern, member)?;
4310 }
4311 None => {
4312 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4313 self.emit(Opcode::Drop, &[]);
4314 self.destructure(pattern, decl)?;
4315 }
4316 }
4317 }
4318 Some(PatternElement::Property { span, .. }) => {
4319 return Err(SyntaxError::new(
4320 "a property pattern is not a valid array element",
4321 *span,
4322 ));
4323 }
4324 // An elision skips the value, which is already on the stack.
4325 None => {
4326 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4327 self.emit(Opcode::Drop, &[]);
4328 self.emit(Opcode::Drop, &[]);
4329 }
4330 }
4331 }
4332 if let Some(rest) = rest {
4333 // The remaining values go into a fresh array. The target and its running
4334 // index stay on the stack above the iterator, which is what the operand of
4335 // `for_of_next` accounts for: two values sit above the iterator triple.
4336 let prepared = match decl {
4337 None => Self::member_rest_target(rest),
4338 // A binding pattern cannot store into a property.
4339 Some(_) => None,
4340 };
4341 let extra = match prepared {
4342 Some(member) => 2 + self.prepare_member_target(member)?,
4343 None => 2,
4344 };
4345 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4346 self.emit(Opcode::Push0, &[]);
4347 let top = self.new_label();
4348 self.place_label(top);
4349 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4350 let done = self.new_label();
4351 self.emit_jump(Opcode::IfTrue, done, &[]);
4352 self.emit(Opcode::DefineArrayEl, &[]);
4353 self.emit(Opcode::Inc, &[]);
4354 self.emit_jump(Opcode::Goto, top, &[]);
4355 self.place_label(done);
4356 self.emit(Opcode::Drop, &[]);
4357 self.emit(Opcode::Drop, &[]);
4358 match prepared {
4359 Some(member) => self.store_member_value(member)?,
4360 None => self.destructure_rest(rest, decl)?,
4361 }
4362 }
4363 self.emit(Opcode::IteratorClose, &[]);
4364 self.pop_jump_target();
4365 Ok(())
4366 }
4367
4368 /// The property an array element stores into, when it stores into one at all.
4369 ///
4370 /// `Assign` is peeled because `[o.p = d] = it` evaluates `o.p`'s reference at the same
4371 /// point `[o.p] = it` does; the default value is applied afterwards, on the pulled
4372 /// value. Nothing deeper is: a nested pattern's own targets are reached by recursing
4373 /// into `destructure`, and those never straddle a `for_of_next`.
4374 fn member_element_target(
4375 pattern: &Pattern,
4376 decl: Option<VarDeclKind>,
4377 ) -> Option<&ast::MemberPattern> {
4378 if decl.is_some() {
4379 return None;
4380 }
4381 match &pattern.kind {
4382 PatternKind::Member(member) => Some(member),
4383 PatternKind::Assign { target, .. } => Self::member_element_target(target, decl),
4384 _ => None,
4385 }
4386 }
4387
4388 /// The same, for a rest element.
4389 fn member_rest_target(rest: &RestElement) -> Option<&ast::MemberPattern> {
4390 match rest {
4391 RestElement::Member(member) => Some(member),
4392 RestElement::Pattern(pattern) => match &pattern.kind {
4393 PatternKind::Member(member) => Some(member),
4394 _ => None,
4395 },
4396 }
4397 }
4398
4399 /// Push a member target's reference — the object, and the key when the property is
4400 /// computed — and answer how many values that put above the iterator record.
4401 fn prepare_member_target(&mut self, member: &ast::MemberPattern) -> Result<i32, SyntaxError> {
4402 self.expr(&member.object)?;
4403 match &member.property {
4404 MemberProp::Ident(_) | MemberProp::Private(_) => Ok(1),
4405 MemberProp::Computed(index) => {
4406 self.expr(index)?;
4407 Ok(2)
4408 }
4409 }
4410 }
4411
4412 /// Store the value on top of the stack through a prepared member reference.
4413 ///
4414 /// `obj value` for a named property, `obj key value` for a computed one — the orders
4415 /// `put_field` and `put_array_el` take, so no reordering is needed here. The `swap` and
4416 /// `rot3l` in [`Compiler::destructure`]'s member case exist only because *it* starts
4417 /// with the value already on the stack.
4418 fn store_member_value(&mut self, member: &ast::MemberPattern) -> Result<(), SyntaxError> {
4419 match &member.property {
4420 MemberProp::Ident(name) => {
4421 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4422 }
4423 MemberProp::Computed(_) => self.emit(Opcode::PutArrayEl, &[]),
4424 MemberProp::Private(name) => {
4425 let binding = format!("#{}", name.name);
4426 let (kind, setter) = self.private_use(&binding, member.span)?;
4427 self.private_store(&binding, kind, setter.as_deref())?;
4428 }
4429 }
4430 Ok(())
4431 }
4432
4433 /// The value of an array element whose member reference is already prepared.
4434 ///
4435 /// Only the default-value test differs from [`Compiler::destructure`]: the reference
4436 /// and the value are both on the stack while the test runs, which is why the object is
4437 /// evaluated before the default rather than after it.
4438 fn destructure_prepared(
4439 &mut self,
4440 pattern: &Pattern,
4441 member: &ast::MemberPattern,
4442 ) -> Result<(), SyntaxError> {
4443 if let PatternKind::Assign { default, .. } = &pattern.kind {
4444 let has_value = self.new_label();
4445 self.emit(Opcode::Dup, &[]);
4446 self.emit(Opcode::IsUndefined, &[]);
4447 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4448 self.emit(Opcode::Drop, &[]);
4449 self.expr(default)?;
4450 self.place_label(has_value);
4451 }
4452 self.store_member_value(member)
4453 }
4454
4455 /// `{…}` on the left: read properties off one boxed source object.
4456 fn destructure_object(
4457 &mut self,
4458 properties: &[Option<PatternElement>],
4459 rest: &Option<Box<RestElement>>,
4460 decl: Option<VarDeclKind>,
4461 pattern: &Pattern,
4462 ) -> Result<(), SyntaxError> {
4463 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4464 // aside for the rest element below.
4465 self.emit(Opcode::ToObject, &[]);
4466 let mut taken: Vec<Wtf8> = Vec::new();
4467 // A computed key's *value* is only known at run time, so with a rest element the
4468 // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4469 // local array that every key is written into as the pattern is walked — literal
4470 // keys by name, computed ones by the value the expression produced. Without this,
4471 // `let { [k]: a, ...rest } = o` was refused outright.
4472 let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4473 let key_log = if needs_key_log {
4474 let name = "<rest_exclude>";
4475 self.declare_hidden_local(name, VarKind::Normal);
4476 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4477 self.emit_var(VarAction::Put, name);
4478 Some(name)
4479 } else {
4480 None
4481 };
4482 for property in properties {
4483 let Some(PatternElement::Property {
4484 key, value, span, ..
4485 }) = property
4486 else {
4487 return Err(SyntaxError::new(
4488 "a bare pattern is not a valid object property",
4489 properties
4490 .iter()
4491 .flatten()
4492 .map(|element| match element {
4493 PatternElement::Pattern(pattern) => pattern.span,
4494 PatternElement::Property { span, .. } => *span,
4495 })
4496 .next()
4497 .unwrap_or(pattern.span),
4498 ));
4499 };
4500 // Every read needs the source twice: to read from, and to keep for the next
4501 // property. `get_field2` is that duplicate-and-read in one instruction, but it
4502 // leaves the copy *under* the value, so it is only usable when whatever
4503 // consumes the value tolerates that. See [`reads_with_get_field2`].
4504 let nested = reads_with_get_field2(decl, value);
4505 if !nested {
4506 self.emit(Opcode::Dup, &[]);
4507 }
4508 let slot = taken.len();
4509 match key {
4510 PropName::Literal(literal) => {
4511 let name = self.property_key_text(literal, *span)?;
4512 taken.push(name.clone());
4513 if let Some(log) = &key_log {
4514 // `arr index key -> arr`: the key is written into the log before
4515 // the read, so the order of observable operations is unchanged.
4516 self.emit_var(VarAction::Get, log);
4517 self.push_number(slot as f64);
4518 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4519 self.emit(Opcode::PutArrayEl, &[]);
4520 }
4521 self.emit(
4522 if nested {
4523 Opcode::GetField2
4524 } else {
4525 Opcode::GetField
4526 },
4527 &[Op::Atom(Atom::from_wtf8(&name))],
4528 );
4529 }
4530 PropName::Computed(index) => {
4531 self.expr(index)?;
4532 // `key key`: one stays on the stack for the read, the other goes into
4533 // the exclusion log. The index is a compile-time constant, so no counter
4534 // local is needed.
4535 if let Some(log) = &key_log {
4536 taken.push(Wtf8::default());
4537 self.emit(Opcode::Dup, &[]);
4538 self.emit_var(VarAction::Get, log);
4539 self.emit(Opcode::Swap, &[]);
4540 self.push_number(slot as f64);
4541 self.emit(Opcode::Swap, &[]);
4542 self.emit(Opcode::PutArrayEl, &[]);
4543 }
4544 self.emit(Opcode::GetArrayEl, &[]);
4545 }
4546 PropName::Private(_) => {
4547 return Err(SyntaxError::new(
4548 "private fields are not supported by the compiler yet",
4549 value.span,
4550 ));
4551 }
4552 }
4553 self.destructure(value, decl)?;
4554 }
4555 match rest {
4556 Some(rest) => {
4557 // `target src exclude`: the exclusion list is an array of the keys the
4558 // literal part already took, so the rest object gets only the others.
4559 self.emit(Opcode::Object, &[]);
4560 self.emit(Opcode::Swap, &[]);
4561 match &key_log {
4562 // Built while walking the pattern; see `needs_key_log`.
4563 Some(log) => {
4564 self.emit_var(VarAction::Get, log);
4565 }
4566 None => {
4567 for name in &taken {
4568 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4569 }
4570 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4571 }
4572 }
4573 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4574 self.emit(Opcode::Drop, &[]);
4575 self.emit(Opcode::Drop, &[]);
4576 self.destructure_rest(rest, decl)?;
4577 }
4578 // The source was only kept for a rest element.
4579 None => self.emit(Opcode::Drop, &[]),
4580 }
4581 Ok(())
4582 }
4583
4584 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4585 fn destructure_rest(
4586 &mut self,
4587 rest: &RestElement,
4588 decl: Option<VarDeclKind>,
4589 ) -> Result<(), SyntaxError> {
4590 match rest {
4591 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4592 // `[...a.b] = c` stores into a property.
4593 RestElement::Member(member) => {
4594 let pattern = Pattern {
4595 kind: PatternKind::Member(member.clone()),
4596 span: member.span,
4597 };
4598 self.destructure(&pattern, decl)
4599 }
4600 }
4601 }
4602
4603 /// Compile a function declaration and queue it for instantiation at scope
4604 /// entry.
4605 ///
4606 /// A declaration is visible before the statement that declares it, so the
4607 /// code that creates the function object belongs at the top of the enclosing
4608 /// scope, not at the declaration.
4609 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4610 let name = func.name.as_ref().expect("a declaration has a name");
4611 let function = self.compile_function(func)?;
4612 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4613 let target = self.hoist_target(&name.name);
4614 let block = self.cur().current_block;
4615 self.state().hoisted.push((block, target, pool_index));
4616 Ok(())
4617 }
4618
4619 /// Where a name lives, for a hoisted declaration.
4620 fn hoist_target(&self, name: &str) -> HoistTarget {
4621 let state = self.cur();
4622 if let Some(index) = state.args.iter().position(|a| a.name == name) {
4623 return HoistTarget::Arg(index as u32);
4624 }
4625 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4626 return HoistTarget::Loc(index as u32);
4627 }
4628 // A global function declaration is not a slot at all.
4629 HoistTarget::Global(name.to_string())
4630 }
4631
4632 // -- expressions -------------------------------------------------------
4633
4634 /// Compile one expression, recording where its instructions sit.
4635 ///
4636 /// The position is the node's operator when it has one and its first token
4637 /// otherwise, and it is restored on the way out so a parent's own instructions —
4638 /// which are emitted *after* its children — are blamed on the parent. Without the
4639 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4640 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4641 // `discard_value` belongs to the *statement* that is about to be compiled, so it
4642 // may only be honoured by that statement's own top-level expression. Taking it here
4643 // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4644 // the argument list is a different expression — it must still leave its value on the
4645 // stack. Without this the argument vanished, and `call` then consumed the callee as
4646 // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4647 // function).
4648 self.discard_root = std::mem::take(&mut self.state().discard_value);
4649 let saved = self.cur().cur_pos;
4650 // Only the node kinds the reference calls `emit_source_pos` for record a position:
4651 // the operator a node exists for, and a variable *read*, which the reference
4652 // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4653 // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4654 // start, a parenthesised group, an anonymous function expression — leaves the
4655 // previous position in place, because a table entry the reference never writes is
4656 // one we must not write either: the instruction that inherits a position (the
4657 // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4658 // report a more recent token than the reference does.
4659 let pos = expr.op_pos.or(match &expr.kind {
4660 ExprKind::Ident(ident) => Some(ident.span.start),
4661 _ => None,
4662 });
4663 match pos {
4664 Some(pos) => self.state().cur_pos = Some(pos),
4665 // A node the reference records nothing for: its own instructions stay
4666 // unpositioned, so they inherit whatever was written last — which is what an
4667 // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4668 // enclosing position instead would blame them on a token the reference has not
4669 // reached yet: a spread's `iterator_open` reports the expression it follows, and
4670 // a template's `to_propkey` the interpolation.
4671 None => self.state().cur_pos = None,
4672 }
4673 // Note a direct `eval` call before compiling it, because the *whole* function
4674 // is affected: an eval can name any binding the function declares, so every one
4675 // of them has to live in a cell for a closure it creates to capture it.
4676 self.note_direct_eval(expr);
4677 let result = self.expr_inner(expr);
4678 self.discard_root = false;
4679 self.state().cur_pos = saved;
4680 result
4681 }
4682
4683 /// Record which bindings are in scope at a direct `eval` call.
4684 ///
4685 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4686 /// resolves names from a string at run time, so the only chance to pin down *which*
4687 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4688 /// its block is the current block, an enclosing one, or the function scope.
4689 fn materialize_eval_sites(&mut self) {
4690 let pending = std::mem::take(&mut self.state().pending_eval_sites);
4691 for (span, site_block, in_params, private, arguments_allowed) in pending {
4692 self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
4693 }
4694 }
4695
4696 /// Resolve the bindings visible at one `eval` call.
4697 fn resolve_eval_site(
4698 &mut self,
4699 span: Span,
4700 site_block: u64,
4701 site_in_params: bool,
4702 private_names: Vec<EvalPrivate>,
4703 arguments_allowed: bool,
4704 ) {
4705 /// How near a binding is: function distance first, then block depth, then the
4706 /// later declaration (which shadows the earlier one in the same block).
4707 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4708
4709 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4710 // walked, innermost function first: a direct `eval` sees every enclosing
4711 // function's bindings, and none of them can be resolved at run time because the
4712 // runtime only has names to go on.
4713 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4714 let deepest = self.stack.len() - 1;
4715 for (level, state) in self.stack.iter().enumerate().rev() {
4716 let owner = (deepest - level) as u32;
4717 // The innermost function's block is the one the call sat in, which is not
4718 // the block the compiler is in now; the enclosing functions are still at
4719 // the point where this one was created.
4720 let here = if level == deepest {
4721 site_block
4722 } else {
4723 state.current_block
4724 };
4725 // The chain of live blocks, innermost first, with a depth for each. The walk
4726 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4727 // block can start at source offset zero.
4728 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4729 let mut block = here;
4730 while let Some(parent) = state
4731 .blocks
4732 .iter()
4733 .find(|candidate| candidate.key == block)
4734 .map(|candidate| candidate.parent)
4735 .filter(|parent| *parent != NO_PARENT)
4736 .filter(|parent| parent != &block)
4737 {
4738 live.push((parent, live.len()));
4739 block = parent;
4740 }
4741 let depth_of = |key: u64| {
4742 live.iter()
4743 .find(|(candidate, _)| *candidate == key)
4744 .map(|(_, depth)| *depth)
4745 // The function scope is the outermost depth there is. A binding of a
4746 // block this site is not inside lands here too, which pushes it
4747 // behind every live one — the right answer: it is out of scope.
4748 .unwrap_or(live.len())
4749 };
4750 for (index, arg) in state.args.iter().enumerate() {
4751 bindings.push((
4752 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4753 EvalVisible {
4754 name: arg.name.clone(),
4755 is_arg: true,
4756 index: index as u32,
4757 owner,
4758 },
4759 ));
4760 }
4761 // A parameter list cannot see the body, so a body `var` is not a binding the
4762 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4763 // not let that eval write the body's `c`.
4764 let hides_body = if level == deepest {
4765 site_in_params
4766 } else {
4767 state.created_in_params
4768 };
4769 for (index, var) in state.vars.iter().enumerate() {
4770 let block = state
4771 .var_block
4772 .get(index)
4773 .copied()
4774 .unwrap_or(FUNCTION_SCOPE);
4775 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4776 continue;
4777 }
4778 bindings.push((
4779 (
4780 owner as usize,
4781 depth_of(block),
4782 std::cmp::Reverse(index as u32),
4783 ),
4784 EvalVisible {
4785 name: var.name.clone(),
4786 is_arg: false,
4787 index: index as u32,
4788 owner,
4789 },
4790 ));
4791 }
4792 }
4793 // Innermost function first, then innermost block, then the later declaration
4794 // (which shadows the earlier one within a block).
4795 bindings.sort_by_key(|(priority, _)| *priority);
4796 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4797 self.state().eval_sites.push(EvalSite {
4798 line: span.start.line,
4799 column: span.start.column,
4800 bindings,
4801 private_names,
4802 arguments_allowed,
4803 });
4804 }
4805
4806 /// The private names visible from the compiler's current position, innermost last.
4807 ///
4808 /// A direct `eval` inherits these because private names are lexically scoped
4809 /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
4810 /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
4811 /// shadowing `ClassPlan::find` gives a use site inside the body.
4812 fn visible_private_names(&self) -> Vec<EvalPrivate> {
4813 let mut out: Vec<EvalPrivate> = Vec::new();
4814 for scope in &self.private_scopes {
4815 for (name, use_) in scope {
4816 if out.iter().any(|entry| &entry.name == name) {
4817 continue;
4818 }
4819 out.push(EvalPrivate {
4820 name: name.clone(),
4821 kind: match use_.kind {
4822 PrivateKind::Field => EvalPrivateKind::Field,
4823 PrivateKind::Method => EvalPrivateKind::Method,
4824 PrivateKind::Getter => EvalPrivateKind::Getter,
4825 PrivateKind::Setter => EvalPrivateKind::Setter,
4826 },
4827 setter: use_.setter.clone(),
4828 });
4829 }
4830 }
4831 out
4832 }
4833
4834 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4835 ///
4836 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4837 /// a bare identifier callee counts.
4838 /// Record everything a direct `eval` call site has to tell the runtime.
4839 ///
4840 /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
4841 /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
4842 /// entirely. Missing the tail-call path is not hypothetical — it is why
4843 /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
4844 /// names were otherwise wired through.
4845 fn note_direct_eval(&mut self, expr: &Expr) {
4846 if !Self::is_direct_eval(expr) {
4847 return;
4848 }
4849 // Every enclosing function is affected too: the eval sees the whole scope chain,
4850 // and a closure it creates can capture a binding of any of them.
4851 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
4852 // because the closure the eval builds outlives the loop iteration.
4853 for state in &mut self.stack {
4854 state.has_direct_eval = true;
4855 }
4856 let block = self.cur().current_block;
4857 let in_params = self.cur().in_params;
4858 // The private names are snapshotted **here**, at the call site, not when the sites
4859 // are materialised: materialisation happens once the whole function is compiled, by
4860 // which point every class scope has been popped and the answer would always be
4861 // empty.
4862 let private = self.visible_private_names();
4863 // An arrow has no `arguments` of its own and inherits the restriction from the
4864 // nearest real function: `x = () => { () => eval('arguments') }` is still a
4865 // class field initializer's arrow, and still has no `arguments` to see.
4866 let arguments_allowed = !self
4867 .stack
4868 .iter()
4869 .rev()
4870 .find(|state| !state.is_arrow)
4871 .is_some_and(|state| state.no_arguments_binding);
4872 self.state().pending_eval_sites.push((
4873 expr.span,
4874 block,
4875 in_params,
4876 private,
4877 arguments_allowed,
4878 ));
4879 }
4880
4881 fn is_direct_eval(expr: &Expr) -> bool {
4882 matches!(
4883 &expr.kind,
4884 ExprKind::Call { callee, .. }
4885 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4886 )
4887 }
4888
4889 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4890 match &expr.kind {
4891 ExprKind::Number(value) => self.push_number(*value),
4892 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4893 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4894 ExprKind::Null => self.emit(Opcode::Null, &[]),
4895 ExprKind::String(text) => self.push_string(text),
4896 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4897 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4898 ExprKind::This => self.this_expression(),
4899 ExprKind::NewTarget => self.new_target_expression(),
4900 ExprKind::Paren(inner) => self.expr(inner)?,
4901 ExprKind::Binary { op, left, right } => {
4902 self.expr(left)?;
4903 self.expr(right)?;
4904 self.emit(binary_opcode(*op), &[]);
4905 }
4906 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4907 ExprKind::Unary {
4908 op: UnaryOp::Minus,
4909 argument,
4910 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4911 let ExprKind::Number(value) = argument.unparen().kind else {
4912 unreachable!("matched above")
4913 };
4914 // The reference folds a negative literal only when the negation is
4915 // exact in the integer range: `-1` becomes `push_minus1` and
4916 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4917 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4918 // `-Infinity`, not `Infinity` — and folding a fraction would change
4919 // which instruction the reference emits.
4920 let negated = -value;
4921 // `-2147483648` is deliberately excluded: its magnitude is one past
4922 // `i32::MAX`, so the reference sends it through the constant pool and
4923 // negates at run time instead.
4924 if value > 0.0
4925 && negated == negated.trunc()
4926 && negated >= -(i32::MAX as f64)
4927 && negated < 0.0
4928 {
4929 self.push_number(negated);
4930 } else {
4931 self.push_number(value);
4932 self.emit(Opcode::Neg, &[]);
4933 }
4934 }
4935 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4936 ExprKind::Conditional { test, cons, alt } => {
4937 let else_label = self.new_label();
4938 let end_label = self.new_label();
4939 self.expr(test)?;
4940 self.emit_jump(Opcode::IfFalse, else_label, &[]);
4941 self.expr(cons)?;
4942 self.emit_jump(Opcode::Goto, end_label, &[]);
4943 self.place_label(else_label);
4944 self.expr(alt)?;
4945 self.place_label(end_label);
4946 }
4947 ExprKind::Assign { op, target, value } => {
4948 let discard = std::mem::take(&mut self.discard_root);
4949 self.assign(*op, target, value, discard)?
4950 }
4951 ExprKind::Update {
4952 op,
4953 argument,
4954 prefix,
4955 } => self.update(*op, argument, *prefix)?,
4956 ExprKind::Sequence(items) => {
4957 for (index, item) in items.iter().enumerate() {
4958 self.expr(item)?;
4959 if index + 1 != items.len() {
4960 self.emit(Opcode::Drop, &[]);
4961 }
4962 }
4963 }
4964 ExprKind::Call { .. } => self.chain_link_top(expr)?,
4965 ExprKind::Member { .. } => self.chain_link_top(expr)?,
4966 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4967 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4968 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4969 ExprKind::Template(template) => self.template_literal(template)?,
4970 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4971 ExprKind::New { callee, arguments } => {
4972 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4973 // The `dup` is not redundant: `call_constructor` takes the
4974 // constructor twice, once as the target and once as `new.target`,
4975 // which is what makes `new.target === C` inside the body.
4976 self.expr(callee)?;
4977 self.emit(Opcode::Dup, &[]);
4978 let args = arguments.as_deref().unwrap_or(&[]);
4979 if Self::has_spread(args) {
4980 // `C C array`: the duplicated callee is already both the target
4981 // and `new.target`, so no reordering is needed before `apply 1`.
4982 self.argument_array(args)?;
4983 self.emit(Opcode::Apply, &[Op::Int(1)]);
4984 return Ok(());
4985 }
4986 for argument in args {
4987 self.expr(argument)?;
4988 }
4989 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4990 }
4991 ExprKind::Class(class) => self.class_definition(class, true)?,
4992 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4993 ExprKind::Yield { argument, delegate } => {
4994 self.yield_expression(argument.as_deref(), *delegate)?
4995 }
4996 ExprKind::Await(argument) => self.await_expression(argument)?,
4997 ExprKind::RegExp { pattern, flags } => {
4998 // A literal is compiled *here*, at parse time, not when the line runs. The
4999 // spec is explicit that an invalid pattern is an early error (§12.9.4:
5000 // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
5001 // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
5002 // also validates `\p{…}` names: 163 conformance cases are patterns that have
5003 // to be rejected before any code runs.
5004 //
5005 // This is the whole reason the engine lives in its own crate rather than
5006 // inside `quickjs-pure`: the compiler could not depend on the interpreter
5007 // (`pure` depends on `compile`), but both need this.
5008 // The lexer already rejected an unknown or repeated flag, so an unparsable
5009 // flag string here would be a bug in the lexer rather than in the script;
5010 // fall back to the default flags instead of inventing a second message.
5011 let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
5012 let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
5013 SyntaxError::new(
5014 format!("invalid regular expression: {}", error.message),
5015 expr.span,
5016 )
5017 })?;
5018 // The tree is thrown away and rebuilt when the literal first runs: keeping it
5019 // would mean serialising the syntax tree into the function's constant pool,
5020 // and a literal is created once per evaluation of its expression anyway.
5021 let _ = parsed;
5022 // The pattern and its flags travel as two string constants; `regexp` builds
5023 // the object. A dedicated opcode (rather than a call to the constructor) is
5024 // what the reference does too, so that a literal never goes through the
5025 // public `RegExp` function and its string-coercion rules.
5026 self.push_string(&Wtf8::new(pattern));
5027 self.push_string(&Wtf8::new(flags));
5028 self.emit(Opcode::Regexp, &[]);
5029 }
5030 ExprKind::Arrow(func) => {
5031 let function = self.compile_function(func)?;
5032 let index = self.push_constant(Constant::Function(Box::new(function)));
5033 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5034 }
5035 ExprKind::Function(func) => {
5036 let function = self.compile_function_with_name(func, true)?;
5037 let index = self.push_constant(Constant::Function(Box::new(function)));
5038 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5039 }
5040 // `import.meta`: the host fills a per-module object at link time.
5041 ExprKind::ImportMeta => {
5042 self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
5043 }
5044 // `import("x")` compiles to a two-slot push followed by one opcode: the
5045 // specifier, then the options object. Both are evaluated, in that order, because
5046 // §13.3.10.1 numbers them that way and their side effects are observable — the
5047 // absent second argument is a literal `undefined`, which evaluates to nothing.
5048 ExprKind::ImportCall(specifier, options) => {
5049 self.expr(specifier)?;
5050 match options {
5051 Some(options) => self.expr(options)?,
5052 None => {
5053 self.emit(Opcode::Undefined, &[]);
5054 }
5055 }
5056 self.emit(Opcode::Import, &[]);
5057 }
5058 ExprKind::PrivateIn { name, object } => {
5059 // `#x in o`: the object, then the binding, then one opcode which decides what
5060 // to do with the second operand. A field's binding holds a symbol and the
5061 // answer is an own-property test; a method's holds a function and the answer
5062 // is a brand check — both live in `private_in`, so the compiler emits the
5063 // same instruction for either.
5064 self.expr(object)?;
5065 self.emit_var(VarAction::Get, &format!("#{}", name.name));
5066 self.emit(Opcode::PrivateIn, &[]);
5067 }
5068 _ => {
5069 return Err(SyntaxError::new(
5070 "this expression form is not supported by the compiler yet",
5071 expr.span,
5072 ));
5073 }
5074 }
5075 Ok(())
5076 }
5077
5078 /// Build one array holding the evaluated call arguments, which is how a call
5079 /// containing a spread is compiled: the reference does the same, building the
5080 /// list on the stack and handing it to `apply`.
5081 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5082 let elements: Vec<Option<ArrayElement>> = arguments
5083 .iter()
5084 .map(|argument| match &argument.unparen().kind {
5085 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
5086 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
5087 })
5088 .collect();
5089 self.array_literal(&elements, Span::default())
5090 }
5091
5092 /// Whether any argument is a spread, which is what selects the `apply` form.
5093 fn has_spread(arguments: &[Expr]) -> bool {
5094 arguments
5095 .iter()
5096 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
5097 }
5098
5099 /// Compile `a${x}b`.
5100 ///
5101 /// A template is a `+` chain built left to right: the leading chunk (or an empty
5102 /// string when the template starts with a substitution), then for each
5103 /// substitution its value, `to_propkey` and `add`, then the following chunk when
5104 /// it is not empty. `to_propkey` is what makes a number or object substitute the
5105 /// way `ToString` would while leaving the result a string for `add` to
5106 /// concatenate.
5107 ///
5108 /// The chunk is an atom rather than a constant-pool string, because a non-empty
5109 /// chunk always lands where a value is pushed and `push_atom_value` is the
5110 /// instruction the reference uses for it; the empty first chunk has its own
5111 /// zero-byte form.
5112 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
5113 let first = template.quasis.first();
5114 match first.and_then(|quasi| quasi.cooked.clone()) {
5115 Some(text) if !text.is_empty() => {
5116 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5117 }
5118 // Either the template begins with a substitution, or the chunk is
5119 // empty — in both cases the chain needs a string to start from.
5120 _ => self.emit(Opcode::PushEmptyString, &[]),
5121 }
5122 for (index, expression) in template.expressions.iter().enumerate() {
5123 self.expr(expression)?;
5124 self.emit(Opcode::ToPropkey, &[]);
5125 self.emit(Opcode::Add, &[]);
5126 if let Some(text) = template
5127 .quasis
5128 .get(index + 1)
5129 .and_then(|quasi| quasi.cooked.clone())
5130 && !text.is_empty()
5131 {
5132 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5133 self.emit(Opcode::Add, &[]);
5134 }
5135 }
5136 Ok(())
5137 }
5138
5139 /// Compile an object literal.
5140 ///
5141 /// The object is built in place: `object` pushes it, and each property leaves it
5142 /// on the stack with one field more, so no temporary is needed and later
5143 /// properties can overwrite earlier ones.
5144 ///
5145 /// The instruction depends on *how* the property was written, not on what kind
5146 /// of value it holds:
5147 ///
5148 /// | source | instruction |
5149 /// |---|---|
5150 /// | `{ a: v }` | `define_field a` |
5151 /// | `{ __proto__: v }` | `set_proto` |
5152 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
5153 /// | `{ m() {} }` | `define_method m,4` |
5154 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
5155 /// | `{ [k]() {} }` | `define_method_computed 4` |
5156 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
5157 ///
5158 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
5159 /// key itself, which is why the trailing `drop` is absent there too.
5160 /// `tag`…``: a call whose first argument is the call site's template object.
5161 ///
5162 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
5163 /// array beside it, so `String.raw` can read the source text back. It is a constant
5164 /// because its contents never change; the reference builds one per call site and
5165 /// reuses it, while this builds one per evaluation, which only `tag` code that
5166 /// compares template objects across calls could tell apart.
5167 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
5168 let cooked = quasi
5169 .quasis
5170 .iter()
5171 .map(|chunk| chunk.cooked.clone())
5172 .collect();
5173 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
5174 let index = self.push_constant(Constant::Template { cooked, raw });
5175 let count = quasi.expressions.len() + 1;
5176 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
5177 if let ExprKind::Member {
5178 object, property, ..
5179 } = &tag.unparen().kind
5180 {
5181 self.expr(object)?;
5182 match property {
5183 MemberProp::Ident(name) => {
5184 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5185 }
5186 MemberProp::Computed(key) => {
5187 self.expr(key)?;
5188 self.emit(Opcode::GetArrayEl2, &[]);
5189 }
5190 MemberProp::Private(name) => {
5191 let binding = format!("#{}", name.name);
5192 let (kind, _) = self.private_use(&binding, tag.span)?;
5193 self.private_callee(&binding, kind)?;
5194 }
5195 }
5196 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5197 for expression in &quasi.expressions {
5198 self.expr(expression)?;
5199 }
5200 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
5201 return Ok(());
5202 }
5203 self.expr(tag)?;
5204 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5205 for expression in &quasi.expressions {
5206 self.expr(expression)?;
5207 }
5208 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
5209 Ok(())
5210 }
5211
5212 fn object_literal(
5213 &mut self,
5214 properties: &[ObjectProperty],
5215 span: Span,
5216 ) -> Result<(), SyntaxError> {
5217 self.emit(Opcode::Object, &[]);
5218 for property in properties {
5219 match property {
5220 ObjectProperty::Spread(value) => {
5221 // `copy_data_properties` takes the target, the source and an
5222 // exclusion list; a literal `null` means "exclude nothing".
5223 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
5224 // exclusion list by stack offset.
5225 self.expr(spread_argument(value))?;
5226 self.emit(Opcode::Null, &[]);
5227 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
5228 self.emit(Opcode::Drop, &[]);
5229 self.emit(Opcode::Drop, &[]);
5230 }
5231 ObjectProperty::Property {
5232 key,
5233 value,
5234 kind,
5235 shorthand,
5236 span: property_span,
5237 } => match key {
5238 PropName::Computed(key_expr) => {
5239 self.expr(key_expr)?;
5240 match kind {
5241 PropertyKind::Value => {
5242 self.emit(Opcode::ToPropkey, &[]);
5243 self.expr(value)?;
5244 self.set_name_if_anonymous_computed(value);
5245 self.emit(Opcode::DefineArrayEl, &[]);
5246 // `define_array_el` leaves the object and the key;
5247 // the key is no longer needed.
5248 self.emit(Opcode::Drop, &[]);
5249 }
5250 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5251 self.emit_method_function(value)?;
5252 self.emit(
5253 Opcode::DefineMethodComputed,
5254 &[Op::Int(define_method_flags(*kind))],
5255 );
5256 }
5257 }
5258 }
5259 PropName::Literal(key) => {
5260 let name = self.property_key_text(key, *property_span)?;
5261 match kind {
5262 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5263 self.emit_method_function(value)?;
5264 self.emit(
5265 Opcode::DefineMethod,
5266 &[
5267 Op::Atom(Atom::from_wtf8(&name)),
5268 Op::Int(define_method_flags(*kind)),
5269 ],
5270 );
5271 }
5272 PropertyKind::Value => {
5273 self.expr(value)?;
5274 // `{__proto__: x}` sets the prototype instead of
5275 // creating a property; the shorthand `{__proto__}`
5276 // is an ordinary property and does not.
5277 if name == "__proto__" && !shorthand {
5278 self.emit(Opcode::SetProto, &[]);
5279 } else {
5280 self.set_name_if_anonymous(value, &name);
5281 self.emit(
5282 Opcode::DefineField,
5283 &[Op::Atom(Atom::from_wtf8(&name))],
5284 );
5285 }
5286 }
5287 }
5288 }
5289 PropName::Private(_) => {
5290 return Err(SyntaxError::new(
5291 "private names are not valid in object literals",
5292 *property_span,
5293 ));
5294 }
5295 },
5296 }
5297 }
5298 let _ = span;
5299 Ok(())
5300 }
5301
5302 /// Emit the function a method/accessor property defines.
5303 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
5304 self.expr(value)
5305 }
5306
5307 /// The name a literal property key contributes.
5308 ///
5309 /// String keys are used as written. A numeric key is converted the way
5310 /// `ToString` would convert it, because the atom is made from that spelling:
5311 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5312 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5313 match key {
5314 PropKey::Str(text) => Ok(text.clone()),
5315 PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5316 }
5317 }
5318
5319 /// Compile an optional chain.
5320 ///
5321 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5322 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5323 /// `undefined`. So the chain is compiled with one end label and every guard
5324 /// jumps to it. The parser hands us the extent of that spine as an
5325 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5326 /// exactly the scope the label has to cover.
5327 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5328 let end = self.new_label();
5329 self.chain_link(inner, end)?;
5330 self.place_label(end);
5331 Ok(())
5332 }
5333
5334 /// A member access or call reached from outside any optional chain.
5335 ///
5336 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5337 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5338 /// still created because [`Self::chain_link`] takes it, and placing it at the
5339 /// end is a no-op that keeps a single code path.
5340 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5341 let end = self.new_label();
5342 self.chain_link(expr, end)?;
5343 self.place_label(end);
5344 Ok(())
5345 }
5346
5347 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5348 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5349 match &expr.kind {
5350 ExprKind::Member {
5351 object,
5352 property,
5353 optional,
5354 } => {
5355 // `super.x` is not a lookup on a value: it starts at the home object's
5356 // prototype and keeps `this` as the receiver, so it cannot go through
5357 // `chain_link` and the ordinary field read.
5358 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5359 self.super_base();
5360 match property {
5361 MemberProp::Ident(name) => self.emit(
5362 Opcode::PushAtomValue,
5363 &[Op::Atom(Atom::from_text(&name.name))],
5364 ),
5365 MemberProp::Computed(index) => self.expr(index)?,
5366 MemberProp::Private(_) => {
5367 return Err(SyntaxError::new(
5368 "private fields are not supported by the compiler yet",
5369 expr.span,
5370 ));
5371 }
5372 }
5373 self.emit(Opcode::GetSuperValue, &[]);
5374 return Ok(());
5375 }
5376 self.chain_link(object, end)?;
5377 if *optional {
5378 self.optional_guard(end);
5379 }
5380 match property {
5381 // `.length` has its own opcode. The reference emits it for every
5382 // object, not just arrays, so a name-based rule is right and
5383 // cheaper than the generic field read.
5384 MemberProp::Ident(name) if name.name == "length" => {
5385 self.emit(Opcode::GetLength, &[]);
5386 }
5387 MemberProp::Ident(name) => {
5388 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5389 }
5390 MemberProp::Computed(index) => {
5391 self.expr(index)?;
5392 self.emit(Opcode::GetArrayEl, &[]);
5393 }
5394 MemberProp::Private(name) => {
5395 // The binding comes from the class scope, so a read from outside the
5396 // class cannot name it at all. `?.` checks the object, not the field:
5397 // `o?.#x` guards on `o` being nullish.
5398 let binding = format!("#{}", name.name);
5399 let (kind, _) = self.private_use(&binding, expr.span)?;
5400 self.private_load(&binding, kind, expr.span)?;
5401 }
5402 }
5403 Ok(())
5404 }
5405 ExprKind::Call {
5406 callee,
5407 arguments,
5408 optional,
5409 } => {
5410 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5411 // cannot: it reads the function and then calls it with no
5412 // receiver at all. The reference's answer is to keep the object
5413 // under the function value — `get_field2` reads a field and leaves
5414 // its base in place — and to use `call_method`, which takes the
5415 // receiver from the stack. Missing this does not just cost an
5416 // instruction, it loses the `this` binding.
5417 if let ExprKind::Member {
5418 object,
5419 property,
5420 optional: member_optional,
5421 } = &callee.unparen().kind
5422 {
5423 // `super.m()` reads the method off the home object's prototype but
5424 // calls it with `this`, so the receiver goes under the read instead of
5425 // being replaced by it.
5426 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5427 self.super_base();
5428 match property {
5429 MemberProp::Ident(name) => self.emit(
5430 Opcode::PushAtomValue,
5431 &[Op::Atom(Atom::from_text(&name.name))],
5432 ),
5433 MemberProp::Computed(index) => self.expr(index)?,
5434 MemberProp::Private(_) => {
5435 return Err(SyntaxError::new(
5436 "private fields are not supported by the compiler yet",
5437 expr.span,
5438 ));
5439 }
5440 }
5441 // The two-output form would drop the receiver; this one replaces
5442 // the prototype and the key, leaving `this` underneath.
5443 self.emit(Opcode::GetArrayEl, &[]);
5444 if Self::has_spread(arguments) {
5445 self.argument_array(arguments)?;
5446 self.emit(Opcode::Perm3, &[]);
5447 self.emit(Opcode::Apply, &[Op::Int(0)]);
5448 return Ok(());
5449 }
5450 for argument in arguments {
5451 self.expr(argument)?;
5452 }
5453 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5454 return Ok(());
5455 }
5456 self.chain_link(object, end)?;
5457 if *member_optional {
5458 self.optional_guard(end);
5459 }
5460 match property {
5461 MemberProp::Ident(name) => {
5462 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5463 }
5464 MemberProp::Computed(index) => {
5465 self.expr(index)?;
5466 // The key is not needed after the read, so this is the
5467 // two-output form: object, value.
5468 self.emit(Opcode::GetArrayEl2, &[]);
5469 }
5470 MemberProp::Private(name) => {
5471 // The receiver is already under the callee, which is exactly the
5472 // shape `call_method` and `apply` want — so nothing is dropped.
5473 let binding = format!("#{}", name.name);
5474 let (kind, _) = self.private_use(&binding, expr.span)?;
5475 self.private_callee(&binding, kind)?;
5476 }
5477 }
5478 if Self::has_spread(arguments) {
5479 // Stack is `obj func`; the array goes on top, then `perm3`
5480 // reorders to the `func this array` that `apply` wants.
5481 self.argument_array(arguments)?;
5482 self.emit(Opcode::Perm3, &[]);
5483 self.emit(Opcode::Apply, &[Op::Int(0)]);
5484 return Ok(());
5485 }
5486 for argument in arguments {
5487 self.expr(argument)?;
5488 }
5489 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5490 return Ok(());
5491 }
5492 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5493 // with `get_field2` so the base stays under it, and on the short-circuit
5494 // path pushes an extra `undefined` as a placeholder receiver — the call
5495 // then throws, which is what calling a missing optional chain should do.
5496 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5497 && let ExprKind::Member {
5498 object,
5499 property,
5500 optional: member_optional,
5501 } = &inner.unparen().kind
5502 {
5503 let call = self.new_label();
5504 // A guard target of its own: the outer `end` skips the whole
5505 // expression, and a short-circuited receiver still has to reach the
5506 // call so that calling it throws.
5507 let short = self.new_label();
5508 self.chain_link(object, end)?;
5509 if *member_optional {
5510 self.optional_guard(short);
5511 }
5512 match property {
5513 MemberProp::Ident(name) => {
5514 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5515 }
5516 MemberProp::Computed(index) => {
5517 self.expr(index)?;
5518 self.emit(Opcode::GetArrayEl2, &[]);
5519 }
5520 MemberProp::Private(name) => {
5521 let binding = format!("#{}", name.name);
5522 let (kind, _) = self.private_use(&binding, expr.span)?;
5523 self.private_callee(&binding, kind)?;
5524 }
5525 }
5526 self.emit_jump(Opcode::Goto, call, &[]);
5527 self.place_label(short);
5528 self.emit(Opcode::Undefined, &[]);
5529 self.place_label(call);
5530 if Self::has_spread(arguments) {
5531 self.argument_array(arguments)?;
5532 self.emit(Opcode::Perm3, &[]);
5533 self.emit(Opcode::Apply, &[Op::Int(0)]);
5534 return Ok(());
5535 }
5536 for argument in arguments {
5537 self.expr(argument)?;
5538 }
5539 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5540 return Ok(());
5541 }
5542 self.chain_link(callee, end)?;
5543 if *optional {
5544 self.optional_guard(end);
5545 }
5546 if Self::has_spread(arguments) {
5547 // `func array -> func undefined array`, which is the plain-call
5548 // form of `apply`: the receiver is `undefined`.
5549 self.argument_array(arguments)?;
5550 self.emit(Opcode::Undefined, &[]);
5551 self.emit(Opcode::Swap, &[]);
5552 self.emit(Opcode::Apply, &[Op::Int(0)]);
5553 return Ok(());
5554 }
5555 for argument in arguments {
5556 self.expr(argument)?;
5557 }
5558 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5559 Ok(())
5560 }
5561 _ => self.expr(expr),
5562 }
5563 }
5564
5565 /// Compile `expr` as a tail call when it is one, reporting whether it was.
5566 ///
5567 /// `tail_call` reuses the current frame instead of pushing a new one, so a
5568 /// tail-recursive function runs in constant stack space. It also has to be the
5569 /// *last* thing the function does, which is why only a `return` reaches here.
5570 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5571 let ExprKind::Call {
5572 callee,
5573 arguments,
5574 optional: false,
5575 } = &expr.unparen().kind
5576 else {
5577 return Ok(false);
5578 };
5579 // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5580 // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5581 // as an ordinary call costs the one frame the optimisation was saving and keeps the
5582 // semantics — the alternative was reaching the spread expression below and failing
5583 // with "this expression form is not supported", which is how `return super.m(...a)`
5584 // stopped compiling. Checked before anything is emitted, because the decision cannot
5585 // be taken back once `super_base` or a `get_field2` is on the stack.
5586 if Self::has_spread(arguments) {
5587 return Ok(false);
5588 }
5589 let end = self.new_label();
5590 if let ExprKind::Member {
5591 object,
5592 property,
5593 optional: false,
5594 } = &callee.unparen().kind
5595 {
5596 // `super.m()` in tail position is still an ordinary method call with `this`
5597 // as the receiver; only the read of the method differs.
5598 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5599 self.super_base();
5600 match property {
5601 MemberProp::Ident(name) => self.emit(
5602 Opcode::PushAtomValue,
5603 &[Op::Atom(Atom::from_text(&name.name))],
5604 ),
5605 MemberProp::Computed(index) => self.expr(index)?,
5606 MemberProp::Private(_) => return Ok(false),
5607 }
5608 self.emit(Opcode::GetArrayEl, &[]);
5609 for argument in arguments {
5610 self.expr(argument)?;
5611 }
5612 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5613 self.place_label(end);
5614 return Ok(true);
5615 }
5616 self.chain_link(object, end)?;
5617 match property {
5618 MemberProp::Ident(name) => {
5619 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5620 }
5621 MemberProp::Computed(index) => {
5622 self.expr(index)?;
5623 self.emit(Opcode::GetArrayEl2, &[]);
5624 }
5625 MemberProp::Private(_) => return Ok(false),
5626 }
5627 for argument in arguments {
5628 self.expr(argument)?;
5629 }
5630 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5631 self.place_label(end);
5632 return Ok(true);
5633 }
5634 self.chain_link(callee, end)?;
5635 for argument in arguments {
5636 self.expr(argument)?;
5637 }
5638 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5639 self.place_label(end);
5640 Ok(true)
5641 }
5642
5643 /// The `?.` guard: keep the value if it is neither null nor undefined,
5644 /// otherwise replace it with `undefined` and leave the whole chain.
5645 fn optional_guard(&mut self, end: Label) {
5646 let cont = self.new_label();
5647 self.emit(Opcode::Dup, &[]);
5648 self.emit(Opcode::IsUndefinedOrNull, &[]);
5649 self.emit_jump(Opcode::IfFalse, cont, &[]);
5650 self.emit(Opcode::Drop, &[]);
5651 self.emit(Opcode::Undefined, &[]);
5652 self.emit_jump(Opcode::Goto, end, &[]);
5653 self.place_label(cont);
5654 }
5655
5656 fn push_number(&mut self, value: f64) {
5657 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5658 // goes into the constant pool.
5659 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5660 let int = value as i32;
5661 if (-1..=7).contains(&int) {
5662 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5663 return;
5664 }
5665 if (-128..=127).contains(&int) {
5666 self.emit(Opcode::PushI8, &[Op::Int(int)]);
5667 return;
5668 }
5669 if (-32768..=32767).contains(&int) {
5670 self.emit(Opcode::PushI16, &[Op::Int(int)]);
5671 return;
5672 }
5673 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5674 return;
5675 }
5676 let index = self.push_constant(Constant::Number(value));
5677 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5678 }
5679
5680 /// Push a `BigInt` literal.
5681 ///
5682 /// A value that fits an `i32` uses the immediate form, which is what the reference
5683 /// emits too; anything larger goes into the constant pool, because the operand of
5684 /// `push_bigint` is only four bytes wide.
5685 fn push_bigint(&mut self, digits: &str, radix: u32) {
5686 if radix == 10
5687 && let Ok(value) = digits.parse::<i64>()
5688 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5689 {
5690 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5691 return;
5692 }
5693 let index = self.push_constant(Constant::BigInt {
5694 digits: digits.to_string(),
5695 radix,
5696 });
5697 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5698 }
5699
5700 fn push_string(&mut self, text: &Wtf8) {
5701 if text.is_empty() {
5702 self.emit(Opcode::PushEmptyString, &[]);
5703 return;
5704 }
5705 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5706 }
5707
5708 /// Name an anonymous function from the binding it is assigned to.
5709 ///
5710 /// `var f = function(){}` produces a function whose `name` is `f`, which the
5711 /// runtime cannot know without being told: the function object is created
5712 /// before the store. `set_name` carries the name across.
5713 fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5714 if value.is_anonymous_function_definition() {
5715 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5716 }
5717 }
5718
5719 /// The same, for a computed key: the name comes from the value on the stack
5720 /// rather than from an atom, so a different instruction carries it.
5721 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5722 if value.is_anonymous_function_definition() {
5723 self.emit(Opcode::SetNameComputed, &[]);
5724 }
5725 }
5726
5727 /// Compile a function body that exists only in the compiler's head — a class's
5728 /// implicit constructor or its field initialiser.
5729 ///
5730 /// Everything structural is the same as a written function: a fresh `FnState`, its
5731 /// own body block, and resolution while the frame is still on the stack. Only the
5732 /// statements differ.
5733 fn compile_synthetic_function(
5734 &mut self,
5735 name: &str,
5736 strict: bool,
5737 span: Span,
5738 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5739 ) -> Result<CompiledFunction, SyntaxError> {
5740 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5741 state.span = Some((span.start.offset as usize, span.end.offset as usize));
5742 state.strict = strict;
5743 state.created_in_block = self.cur().current_block;
5744 state.with_names = self.cur().with_names.clone();
5745 state.line = span.start.line;
5746 state.column = span.start.column;
5747 let depth = self.stack.len();
5748 self.stack.push(state);
5749 let body_key = span.start.offset as u64;
5750 self.push_block(body_key, NO_PARENT);
5751 self.state().body_block = body_key;
5752 let result = (|| {
5753 self.emit_scope_enter(body_key);
5754 body(self)?;
5755 if self.end_is_reachable() {
5756 self.emit(Opcode::ReturnUndef, &[]);
5757 }
5758 Ok(())
5759 })();
5760 if result.is_err() {
5761 self.stack.truncate(depth);
5762 return result.map(|()| unreachable!());
5763 }
5764 Ok(self.finish_current())
5765 }
5766
5767 /// The implicit return of a class constructor.
5768 ///
5769 /// A constructor that falls off the end initialises its instance fields first, and a
5770 /// derived one returns `this` — which is what makes `new D()` the object `super()`
5771 /// built rather than `undefined`.
5772 fn emit_class_constructor_tail(&mut self) {
5773 match self.cur().ctor_kind {
5774 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5775 // Nothing to install: a base constructor did it in its prologue and a derived
5776 // one at each `super()` site, which is where `this` first exists.
5777 CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5778 CtorKind::Derived => {
5779 // `get_loc_check` rather than `get_loc`: reaching the end without ever
5780 // running `super()` is a ReferenceError, not `undefined`.
5781 self.emit_var(VarAction::Get, "this");
5782 self.emit(Opcode::Return, &[]);
5783 }
5784 }
5785 }
5786
5787 /// `yield expr` / `yield* expr`.
5788 ///
5789 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5790 /// it to the caller and parks the frame. On resume the stack holds the value the
5791 /// caller passed *and* a "magic" number saying which method resumed it — `next`
5792 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5793 /// `if_false <continue>` asks whether this was an ordinary `next`:
5794 ///
5795 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5796 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5797 /// and uses the value sitting under the magic number.
5798 ///
5799 /// A `throw` never reaches here: the interpreter unwinds instead (see
5800 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5801 fn yield_expression(
5802 &mut self,
5803 argument: Option<&Expr>,
5804 delegate: bool,
5805 ) -> Result<(), SyntaxError> {
5806 if delegate {
5807 return self.yield_star(argument);
5808 }
5809 // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5810 // does the same for the `return(v)` that can resume it — which is why an async
5811 // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5812 // generator's is just `yield`.
5813 let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5814 match argument {
5815 Some(value) => self.expr(value)?,
5816 None => self.emit(Opcode::Undefined, &[]),
5817 }
5818 if is_async {
5819 self.emit(Opcode::Await, &[]);
5820 self.state().has_await = true;
5821 }
5822 self.emit(Opcode::Yield, &[]);
5823 let resume = self.new_label();
5824 self.emit_jump(Opcode::IfFalse, resume, &[]);
5825 // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5826 // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5827 // finished the generator and never ran the `finally`.
5828 if is_async {
5829 self.emit(Opcode::Await, &[]);
5830 }
5831 self.emit_unwind_for_return(true);
5832 self.emit(Opcode::ReturnAsync, &[]);
5833 self.place_label(resume);
5834 // Nothing is emitted here: the value the caller passed to `next` *is* the value
5835 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5836 // it through the ordinary expression-statement discard.
5837 Ok(())
5838 }
5839
5840 /// `yield* iterable`.
5841 ///
5842 /// The shape is the reference's, and it is a fall-through chain rather than a
5843 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5844 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5845 /// the inner iterator and finishes, `throw` forwards the exception into it and
5846 /// continues only if it has a `throw` method.
5847 ///
5848 /// The stack is `iter next catch value` throughout, `catch` being the offset
5849 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5850 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5851 match argument {
5852 Some(value) => self.expr(value)?,
5853 // The parser rejects a bare `yield*`, so this is unreachable in practice.
5854 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5855 }
5856 // `for await of` is the same protocol as `for of` with two differences that matter
5857 // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5858 // every `next()` result is a promise the delegate has to await.
5859 let is_async = self.cur().kind.is_async();
5860 self.emit(
5861 if is_async {
5862 Opcode::ForAwaitOfStart
5863 } else {
5864 Opcode::ForOfStart
5865 },
5866 &[],
5867 );
5868 self.emit(Opcode::Drop, &[]);
5869 self.emit(Opcode::Undefined, &[]);
5870 self.emit(Opcode::Undefined, &[]);
5871 let next = self.new_label();
5872 let resume = self.new_label();
5873 let finished = self.new_label();
5874 let rethrow = self.new_label();
5875 let throw_no_method = self.new_label();
5876 let done = self.new_label();
5877 self.place_label(next);
5878 self.emit(Opcode::IteratorNext, &[]);
5879 if is_async {
5880 self.emit(Opcode::Await, &[]);
5881 self.state().has_await = true;
5882 }
5883 self.emit(Opcode::IteratorCheckObject, &[]);
5884 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5885 self.emit_jump(Opcode::IfTrue, done, &[]);
5886 // The suspension. `resume` is both the label the return path jumps back to in order
5887 // to yield one more value and where the caller's answer arrives, as the value
5888 // followed by the magic number.
5889 //
5890 // The two forms differ in what they hand the suspension: `yield_star` takes the
5891 // result object itself, `async_yield_star` takes `.value`, because an async
5892 // generator awaits and re-wraps whatever it yields.
5893 self.place_label(resume);
5894 if is_async {
5895 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5896 self.emit(Opcode::AsyncYieldStar, &[]);
5897 } else {
5898 self.emit(Opcode::YieldStar, &[]);
5899 }
5900 self.emit(Opcode::Dup, &[]);
5901 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5902 self.emit(Opcode::Drop, &[]);
5903 self.emit_jump(Opcode::Goto, next, &[]);
5904
5905 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5906 self.place_label(rethrow);
5907 self.emit(Opcode::PushI32, &[Op::Int(2)]);
5908 self.emit(Opcode::StrictEq, &[]);
5909 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5910 // A `return` closes the inner iterator; if it had none, the delegate simply
5911 // finishes with the requested value. In an async generator both the call and its
5912 // result are awaited, because the inner `return` may itself be async.
5913 if is_async {
5914 self.emit(Opcode::Await, &[]);
5915 }
5916 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5917 self.emit_jump(Opcode::IfTrue, finished, &[]);
5918 if is_async {
5919 self.emit(Opcode::Await, &[]);
5920 }
5921 self.emit(Opcode::IteratorCheckObject, &[]);
5922 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5923 self.emit_jump(Opcode::IfFalse, resume, &[]);
5924 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5925 self.place_label(finished);
5926 self.emit(Opcode::Nip, &[]);
5927 self.emit(Opcode::Nip, &[]);
5928 self.emit(Opcode::Nip, &[]);
5929 // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5930 // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5931 // awaits the value in an async generator and then runs the same `finally`/iterator
5932 // unwinding a written `return` would. Skipping the unwinding made
5933 // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5934 if is_async {
5935 self.emit(Opcode::Await, &[]);
5936 }
5937 self.emit_unwind_for_return(true);
5938 self.emit(Opcode::ReturnAsync, &[]);
5939
5940 // `throw(e)`: forward it into the inner iterator.
5941 self.place_label(throw_no_method);
5942 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5943 let no_throw = self.new_label();
5944 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5945 if is_async {
5946 self.emit(Opcode::Await, &[]);
5947 }
5948 self.emit(Opcode::IteratorCheckObject, &[]);
5949 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5950 self.emit_jump(Opcode::IfFalse, resume, &[]);
5951 self.emit_jump(Opcode::Goto, done, &[]);
5952 // No `throw` method: close the iterator, then report the spec's TypeError. The
5953 // `if_true` before the `await` is the reference's shape — the flag it consumes is
5954 // what `iterator_call` leaves behind, and a close that *did* find no `return`
5955 // method has nothing to await.
5956 self.place_label(no_throw);
5957 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5958 let no_close = self.new_label();
5959 self.emit_jump(Opcode::IfTrue, no_close, &[]);
5960 if is_async {
5961 self.emit(Opcode::Await, &[]);
5962 }
5963 self.place_label(no_close);
5964 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5965
5966 // The inner iterator finished: the delegate's value is the `yield*` expression's
5967 // value, so it is left on the stack for whatever consumes it.
5968 self.place_label(done);
5969 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5970 self.emit(Opcode::Nip, &[]);
5971 self.emit(Opcode::Nip, &[]);
5972 self.emit(Opcode::Nip, &[]);
5973 Ok(())
5974 }
5975
5976 /// `await expr`: exactly one instruction.
5977 ///
5978 /// No resume-magic branch follows it. The reference's `await` leaves a single value
5979 /// on the stack and completion is signalled by the `return_async` at the end of the
5980 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5981 /// reference never emits, and a `for await` loop — which reaches `await` through the
5982 /// same opcode — would then spill a value the loop's unpacking does not expect.
5983 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5984 self.expr(argument)?;
5985 self.emit(Opcode::Await, &[]);
5986 self.state().has_await = true;
5987 Ok(())
5988 }
5989
5990 /// The `super` base: the receiver followed by the home object's prototype.
5991 ///
5992 /// Everything `super` does needs both. A *read* starts at the prototype but reports
5993 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5994 /// prototype but calls it with the receiver.
5995 fn super_base(&mut self) {
5996 self.this_expression();
5997 self.home_object();
5998 self.emit(Opcode::GetSuper, &[]);
5999 }
6000
6001 /// `[[HomeObject]]` as `super` sees it.
6002 ///
6003 /// A method, a constructor and a field initialiser each carry one — `set_home_object`
6004 /// put it there — so for them the special object *is* the answer. An arrow and a
6005 /// static block have none: they read the enclosing function's, which has to be
6006 /// materialised into a local, exactly as `this` is for an arrow.
6007 ///
6008 /// The name matches what the reference stores, so the disassembly agrees; it is not a
6009 /// name any program can write.
6010 fn home_object(&mut self) {
6011 if !self.cur().is_arrow {
6012 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
6013 return;
6014 }
6015 if let Some(target) = self.enclosing_function() {
6016 self.state_at(target).needs_home_object_local = true;
6017 self.declare_at(target, HOME_OBJECT);
6018 }
6019 self.emit_var(VarAction::Get, HOME_OBJECT);
6020 }
6021
6022 /// `super(args)`: construct the parent class and adopt the result as `this`.
6023 ///
6024 /// The parent is the prototype of the constructor that is running, which is exactly
6025 /// what `extends` set up. `new.target` is passed through unchanged so that
6026 /// `new.target` inside the parent is the class actually being constructed.
6027 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
6028 self.active_func_expression();
6029 self.emit(Opcode::GetSuper, &[]);
6030 self.new_target_expression();
6031 if Self::has_spread(arguments) {
6032 self.argument_array(arguments)?;
6033 self.emit(Opcode::Apply, &[Op::Int(1)]);
6034 } else {
6035 for argument in arguments {
6036 self.expr(argument)?;
6037 }
6038 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
6039 }
6040 // The value stays on the stack: `super()` is an expression, and a derived
6041 // constructor's `this` may only be initialised once.
6042 self.emit(Opcode::Dup, &[]);
6043 self.emit_var(VarAction::PutInitChecked, "this");
6044 // Instance fields are installed here, not at the top of the body: a derived
6045 // constructor has no `this` to install them on until `super()` returns. The
6046 // reference emits the same call at every `super()` site.
6047 self.call_field_initialiser();
6048 Ok(())
6049 }
6050
6051 /// `this` as a local, which every class constructor and field initialiser needs.
6052 ///
6053 /// The reference materialises the receiver into a local rather than reading
6054 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
6055 /// and a field initialiser has to see the final value.
6056 fn begin_this_local(&mut self) {
6057 self.declare_hidden_local("this", VarKind::Normal);
6058 self.emit(Opcode::PushThis, &[]);
6059 self.emit_var(VarAction::Put, "this");
6060 // The store is already at the top of the body, so `provide_this_local` has
6061 // nothing left to prepend. Without this the initialiser ended up with
6062 // `push_this; put_loc0 this` twice whenever the class also held a field
6063 // initialiser whose body read `this` through an arrow.
6064 self.state().has_this_prologue = true;
6065 }
6066
6067 /// Compile a constructor the class wrote.
6068 ///
6069 /// The flags have to be in place before the body is compiled, but
6070 /// `compile_function_with_name` creates its own state — so the caller's state is
6071 /// marked instead and the new one inherits it. That is the same trick the parameter
6072 /// prologue uses, and it keeps one code path for both.
6073 fn compile_class_constructor(
6074 &mut self,
6075 func: &ast::Function,
6076 has_heritage: bool,
6077 ) -> Result<CompiledFunction, SyntaxError> {
6078 let saved = self.cur().ctor_kind;
6079 self.state().class_ctor_pending = Some(if has_heritage {
6080 CtorKind::Derived
6081 } else {
6082 CtorKind::Base
6083 });
6084 let result = self.compile_function_with_name(func, false);
6085 self.state().ctor_kind = saved;
6086 self.state().class_ctor_pending = None;
6087 result
6088 }
6089
6090 /// The constructor a class gets when it does not declare one.
6091 ///
6092 /// A base class's is empty; a derived class's forwards every argument to the parent
6093 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
6094 /// instance field initialiser afterwards when the class has fields, which is why the
6095 /// initialiser is captured rather than inlined.
6096 fn compile_implicit_constructor(
6097 &mut self,
6098 class: &Class,
6099 has_heritage: bool,
6100 ) -> Result<CompiledFunction, SyntaxError> {
6101 self.compile_synthetic_function(
6102 "",
6103 true,
6104 Span::new(class.body_end, class.body_end),
6105 |compiler| {
6106 if has_heritage {
6107 // A derived constructor's `this` does not exist until `super()` returns,
6108 // so it starts in the dead zone and `init_ctor` fills it.
6109 compiler.declare("this", VarDef::lexical("this"));
6110 compiler.emit(
6111 Opcode::SetLocUninitialized,
6112 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6113 );
6114 compiler.emit(Opcode::InitCtor, &[]);
6115 compiler.emit(
6116 Opcode::PutLocCheckInit,
6117 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6118 );
6119 } else {
6120 compiler.begin_this_local();
6121 compiler.emit(Opcode::CheckCtor, &[]);
6122 }
6123 compiler.call_field_initialiser();
6124 // A derived constructor returns `this`, the object `super()` built. Without
6125 // this the implicit constructor fell through to `return_undef`, and `new B()`
6126 // handed back the empty object `construct` had made instead of the one the
6127 // parent constructor initialised.
6128 if has_heritage {
6129 compiler.emit_var(VarAction::Get, "this");
6130 compiler.emit(Opcode::Return, &[]);
6131 }
6132 Ok(())
6133 },
6134 )
6135 }
6136
6137 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
6138 ///
6139 /// A class with no instance fields leaves the binding `undefined`, and calling it
6140 /// would throw; the reference emits the same guard rather than branching at compile
6141 /// time because a class can be extended by a subclass whose fields still have to run.
6142 fn call_field_initialiser(&mut self) {
6143 let skip = self.new_label();
6144 self.emit_var(VarAction::Get, "<class_fields_init>");
6145 self.emit(Opcode::Dup, &[]);
6146 self.emit_jump(Opcode::IfFalse, skip, &[]);
6147 self.emit_var(VarAction::Get, "this");
6148 self.emit(Opcode::Swap, &[]);
6149 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6150 self.place_label(skip);
6151 self.emit(Opcode::Drop, &[]);
6152 }
6153
6154 /// The function that defines one class's fields on `this`, and runs its static blocks.
6155 ///
6156 /// `define_field` rather than `put_field`: a field is an own property created
6157 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
6158 /// `x = 1` field must not call the setter.
6159 ///
6160 /// One function serves the whole class: it is called once per instance (or once, for
6161 /// the static half) and walks the members in source order. Static blocks are compiled
6162 /// into the same function because they *are* part of the same sequence — `static a =
6163 /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
6164 /// different values, so the two kinds cannot be split apart.
6165 fn compile_field_initialiser(
6166 &mut self,
6167 items: &[StaticInitItem<'_>],
6168 span: Span,
6169 instance: bool,
6170 add_brand: bool,
6171 ) -> Result<CompiledFunction, SyntaxError> {
6172 self.compile_synthetic_function("", true, span, |compiler| {
6173 // A field initialiser and a static block are not functions, so neither has an
6174 // `arguments` of its own; see `FnState::no_arguments_binding`.
6175 let current = compiler.stack.len() - 1;
6176 compiler.stack[current].no_arguments_binding = true;
6177 if instance {
6178 // An instance initialiser always carries a `<home_object>` local, because the
6179 // brand block below reads it — even when that block turns out to be dead. The
6180 // reference has the same artefact, and the store is visible in its dump.
6181 let current = compiler.stack.len() - 1;
6182 compiler.stack[current].needs_home_object_local = true;
6183 }
6184 compiler.begin_this_local();
6185 if instance {
6186 // `this` gets the brand the prototype created, before any field is defined —
6187 // which is what makes `#m()` usable from inside a field initialiser.
6188 //
6189 // The reference always emits `push_false; if_false L; this; home; add_brand;
6190 // L:` and patches the `push_false` to `push_true` from the class parse when
6191 // the class has private methods; either way the branch folds, but the *mark*
6192 // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
6193 // `this` local from being fused into a `set_loc`.
6194 let skip = compiler.new_label();
6195 if add_brand {
6196 compiler.emit(Opcode::PushTrue, &[]);
6197 } else {
6198 compiler.emit(Opcode::PushFalse, &[]);
6199 }
6200 compiler.emit_jump(Opcode::IfFalse, skip, &[]);
6201 compiler.emit_var(VarAction::Get, "this");
6202 compiler.emit_var(VarAction::Get, HOME_OBJECT);
6203 compiler.emit(Opcode::AddBrand, &[]);
6204 compiler.place_label(skip);
6205 }
6206 for item in items {
6207 match item {
6208 StaticInitItem::Field(key, value) => {
6209 // A private field is *defined*, not assigned: `define_private_field`
6210 // reads `obj symbol value`, and its point is that it fails on a
6211 // receiver that is not this class's — which `put_field` would not.
6212 //
6213 // The three shapes are the reference's: `define_field <atom>` for a
6214 // static name, `define_array_el` for a key that is only known at run
6215 // time (`obj key value`), `define_private_field` for `#x`, and a
6216 // computed key is read from its binding rather than recomputed.
6217 compiler.emit_var(VarAction::Get, "this");
6218 match key {
6219 FieldKey::Private(binding) | FieldKey::Computed(binding) => {
6220 compiler.emit_var(VarAction::Get, binding);
6221 }
6222 FieldKey::Literal(_) => {}
6223 }
6224 match value {
6225 Some(value) => compiler.expr(value)?,
6226 None => compiler.emit(Opcode::Undefined, &[]),
6227 }
6228 match key {
6229 FieldKey::Literal(literal) => {
6230 let text = compiler.property_key_text(literal, span)?;
6231 compiler
6232 .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
6233 }
6234 FieldKey::Computed(_) => {
6235 compiler.emit(Opcode::DefineArrayEl, &[]);
6236 // `define_array_el` leaves `obj key`; the key is consumed by
6237 // the copy the pattern machinery wants, so both go.
6238 compiler.emit(Opcode::Drop, &[]);
6239 }
6240 FieldKey::Private(_) => {
6241 compiler.emit(Opcode::DefinePrivateField, &[]);
6242 }
6243 }
6244 compiler.emit(Opcode::Drop, &[]);
6245 }
6246 StaticInitItem::Block { body, body_start } => {
6247 let block = compiler.compile_static_block(body, *body_start)?;
6248 let index = compiler.push_constant(Constant::Function(Box::new(block)));
6249 // `this fclosure`, so `call_method` finds the receiver below the
6250 // callee: the block runs with `this` bound to the class.
6251 compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
6252 compiler.emit_var(VarAction::Get, "this");
6253 compiler.emit(Opcode::Swap, &[]);
6254 compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
6255 // Nothing the block evaluates is wanted; its effects are the point.
6256 compiler.emit(Opcode::Drop, &[]);
6257 }
6258 }
6259 }
6260 Ok(())
6261 })
6262 }
6263
6264 /// Compile a `static { … }` body into the function the class calls for it.
6265 ///
6266 /// Shaped like an arrow, because that is the one function form with no `this`,
6267 /// `new.target` or `arguments` of its own: all three reach the enclosing static
6268 /// initialiser, and through it the class. `arguments` never gets that far — the parser
6269 /// rejects the reference — but `this` and `super` both depend on it.
6270 ///
6271 /// The body is hoisted like a function body's, because the reference parses it as one:
6272 /// `var` inside a block is a local of the block's function, not of whatever encloses
6273 /// the class.
6274 fn compile_static_block(
6275 &mut self,
6276 body: &[Stmt],
6277 body_start: Position,
6278 ) -> Result<CompiledFunction, SyntaxError> {
6279 let mut state = FnState::new(String::new(), FunctionKind::Normal);
6280 // Class bodies are strict, so a static block is too.
6281 state.strict = true;
6282 // The one property that makes this an arrow: nothing of its own to bind `this` to,
6283 // so `this` and `super` come from the initialiser that calls it.
6284 state.is_arrow = true;
6285 state.created_in_block = self.cur().current_block;
6286 state.with_names = self.cur().with_names.clone();
6287 state.line = body_start.line;
6288 state.column = body_start.column;
6289 let depth = self.stack.len();
6290 self.stack.push(state);
6291 let body_key = body_start.offset as u64;
6292 self.push_block(body_key, NO_PARENT);
6293 self.state().body_block = body_key;
6294 let result = (|| {
6295 self.hoist(body, body_key)?;
6296 self.emit_scope_enter(body_key);
6297 for statement in body {
6298 self.stmt(statement)?;
6299 }
6300 if self.end_is_reachable() {
6301 self.emit(Opcode::ReturnUndef, &[]);
6302 }
6303 Ok(())
6304 })();
6305 if result.is_err() {
6306 self.stack.truncate(depth);
6307 return result.map(|()| unreachable!());
6308 }
6309 Ok(self.finish_current())
6310 }
6311
6312 /// Compile a class, leaving the constructor on the stack when `keep`.
6313 ///
6314 /// The shape follows the reference: the class body is its own scope holding the
6315 /// class's *inner* name as a `const` — which is what lets a method refer to the
6316 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6317 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6318 /// on the top of the stack: the prototype for instance members, the constructor
6319 /// itself for `static` ones, which is why a static member costs an extra `swap`.
6320 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6321 let parent_block = self.cur().current_block;
6322 let key = class.span.start.offset as u64;
6323 self.push_block(key, parent_block);
6324 let name = class.name.as_ref().map(|ident| ident.name.clone());
6325 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6326 // resolves `E` without a global lookup. An *unnamed* class expression has no such
6327 // binding, and `define_class` is handed the empty name.
6328 if let Some(name) = &name {
6329 self.declare(name, VarDef::constant(name.clone()));
6330 }
6331 self.emit_scope_enter(key);
6332
6333 // The heritage clause is evaluated outside the class's own scope: it cannot see
6334 // the class binding it is about to initialise.
6335 let saved_block = self.cur().current_block;
6336 self.state().current_block = parent_block;
6337 match &class.super_class {
6338 Some(parent) => self.expr(parent)?,
6339 None => self.emit(Opcode::Undefined, &[]),
6340 }
6341 self.state().current_block = saved_block;
6342 let has_heritage = class.super_class.is_some();
6343
6344 // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6345 // lands after the heritage's code — which is where the reference puts it, because it
6346 // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6347 // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6348 // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6349 // came out in the opposite order from the reference's.
6350 //
6351 // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6352 // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6353 // a const accepts — so the old comment's worry ("a const would refuse the second
6354 // store") did not apply: there is no second store.
6355 // Every `#name` the class declares gets a `const` binding in the class scope, and so
6356 // does every computed field key. That is how the reference does it
6357 // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6358 // what makes a private name resolve like any other class-scope variable — including
6359 // through a nested function's closure — while remaining invisible outside.
6360 //
6361 // All of them are declared *before* `<class_fields_init>`, in member order, because
6362 // that is when the reference's parser creates them.
6363 let plan = ClassPlan::build(class);
6364 // The body's private names are visible from here to the end of the class, and shadow
6365 // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6366 // — it is compiled first because `define_class` consumes it, but its body can name
6367 // `#x` like any other member's.
6368 self.private_scopes.push(plan.uses.clone());
6369 let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6370 for binding in &plan.bindings {
6371 class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6372 }
6373 let fci = self.declare(
6374 "<class_fields_init>",
6375 VarDef::constant("<class_fields_init>"),
6376 );
6377 // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6378 // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6379 // members' bindings follow in reverse.
6380 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6381 for slot in class_slots.iter().rev() {
6382 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6383 }
6384
6385 // The constructor is compiled before `define_class` because that instruction
6386 // consumes it; a class without one gets the implicit version.
6387 let constructor = class.elements.iter().find_map(|element| match element {
6388 ClassElement::Method {
6389 kind: MethodKind::Constructor,
6390 func,
6391 ..
6392 } => Some(&**func),
6393 _ => None,
6394 });
6395 // A constructor is compiled differently from a method: it owns `this`. The flags
6396 // go on the *enclosing* state because a constructor is a nested function and
6397 // `compile_function_with_name` starts a fresh one.
6398 let ctor = match constructor {
6399 Some(func) => self.compile_class_constructor(func, has_heritage)?,
6400 None => self.compile_implicit_constructor(class, has_heritage)?,
6401 };
6402 // A closure, not the bare constant: the constructor captures
6403 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6404 // has to hold the cell rather than a copy of its value.
6405 //
6406 // The pool slot is left unassigned for now, because the reference gives the
6407 // constructor the *last* index of the members' range: `js_parse_class` emits a
6408 // `push_const` whose operand is patched at the end of the class parse, after every
6409 // method has taken a slot. Emitting the members first and the constant second is how
6410 // the numbering comes out the same; the instruction itself stays where it is.
6411 let ctor_insn = self.cur().insns.len();
6412 self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6413 let flags = if has_heritage { 1 } else { 0 };
6414 self.emit(
6415 Opcode::DefineClass,
6416 &[
6417 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6418 Op::Int(flags),
6419 ],
6420 );
6421
6422 // Instance fields and static fields are two different functions: the first runs
6423 // per instance from the constructor, the second runs once, here.
6424 let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6425 let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6426 for (index, element) in class.elements.iter().enumerate() {
6427 match element {
6428 ClassElement::Method {
6429 key: member_key,
6430 is_static,
6431 kind,
6432 func,
6433 span,
6434 } => {
6435 if *kind == MethodKind::Constructor {
6436 continue;
6437 }
6438 // `static(x)` is a *method* named `static`, not a static method; the
6439 // parser already decided which by putting it in `kind`.
6440 if *is_static {
6441 self.emit(Opcode::Swap, &[]);
6442 }
6443 // A computed key is evaluated *here*, before the method's closure
6444 // exists, and stays under it: `define_method_computed` pops
6445 // `function, key, object`, so the stack has to read
6446 // `[class, prototype, key, function]`. Evaluating the key after the
6447 // `fclosure` and swapping the two put the prototype *below* the
6448 // closure, which defined the method on the function and lost the
6449 // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6450 // also the spec's — a class body evaluates every element's name before
6451 // that element's function.
6452 if let PropName::Computed(key) = member_key {
6453 self.expr(key)?;
6454 }
6455 let function = self.compile_function_with_name(func, true)?;
6456 let index = self.push_constant(Constant::Function(Box::new(function)));
6457 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6458 match member_key {
6459 // A private method is not a property of the prototype: it is a
6460 // closure in the class scope, which is why nothing outside can reach
6461 // it and why a use site has to brand-check. `set_name` gives the
6462 // function its `name` (`#m`), which an accessor does not get — the
6463 // reference leaves that commented out.
6464 PropName::Private(ident) => {
6465 let name = format!("#{}", ident.name);
6466 // `set_home_object` first: the brand check reads the function's
6467 // home object, and for a method that is the prototype.
6468 self.emit(Opcode::SetHomeObject, &[]);
6469 let binding = if *kind == MethodKind::Set {
6470 format!("{name}<set>")
6471 } else {
6472 name.clone()
6473 };
6474 if *kind == MethodKind::Method {
6475 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6476 }
6477 self.emit_var(VarAction::PutInit, &binding);
6478 }
6479 PropName::Computed(_) => {
6480 self.emit(
6481 Opcode::DefineMethodComputed,
6482 &[Op::Int(class_method_flags(*kind))],
6483 );
6484 }
6485 PropName::Literal(literal) => {
6486 let text = self.property_key_text(literal, *span)?;
6487 self.emit(
6488 Opcode::DefineMethod,
6489 &[
6490 Op::Atom(Atom::from_wtf8(&text)),
6491 Op::Int(class_method_flags(*kind)),
6492 ],
6493 );
6494 }
6495 }
6496 if *is_static {
6497 self.emit(Opcode::Swap, &[]);
6498 }
6499 }
6500 ClassElement::Field {
6501 key: field_key,
6502 is_static,
6503 value,
6504 ..
6505 } => {
6506 // A private field's *symbol* is created here, at the member, and stored
6507 // in its binding: the field's property is keyed by it, so it has to exist
6508 // before any initialiser runs, and a fresh one per class body is what
6509 // makes two classes that both write `#x` independent.
6510 //
6511 // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6512 // whose `toString` has a side effect must not run again per instance.
6513 let key = match field_key {
6514 PropName::Private(ident) => {
6515 let binding = format!("#{}", ident.name);
6516 if *is_static {
6517 self.emit(Opcode::Swap, &[]);
6518 }
6519 self.emit(
6520 Opcode::PrivateSymbol,
6521 &[Op::Atom(Atom::from_text(&binding))],
6522 );
6523 self.emit_var(VarAction::PutInit, &binding);
6524 if *is_static {
6525 self.emit(Opcode::Swap, &[]);
6526 }
6527 FieldKey::Private(binding)
6528 }
6529 PropName::Computed(expression) => {
6530 let binding = plan
6531 .computed
6532 .get(&index)
6533 .cloned()
6534 .expect("every computed key got a binding");
6535 if *is_static {
6536 self.emit(Opcode::Swap, &[]);
6537 }
6538 self.expr(expression)?;
6539 self.emit(Opcode::ToPropkey, &[]);
6540 self.emit_var(VarAction::PutInit, &binding);
6541 if *is_static {
6542 self.emit(Opcode::Swap, &[]);
6543 }
6544 FieldKey::Computed(binding)
6545 }
6546 PropName::Literal(literal) => FieldKey::Literal(literal),
6547 };
6548 if *is_static {
6549 static_items.push(StaticInitItem::Field(key, value.as_deref()));
6550 } else {
6551 instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6552 }
6553 }
6554 ClassElement::StaticBlock {
6555 body, body_start, ..
6556 } => static_items.push(StaticInitItem::Block {
6557 body,
6558 body_start: *body_start,
6559 }),
6560 }
6561 }
6562
6563 // Now that every member has its slot, the constructor can have the next one and the
6564 // `fclosure` above can name it.
6565 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6566 match self.state().insns.get_mut(ctor_insn) {
6567 Some(Insn::Fixed { operands, .. }) => {
6568 operands[0] = Op::Const(ctor_index);
6569 }
6570 // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6571 // loudly beats emitting a `fclosure` of slot 4294967295.
6572 _ => {
6573 return Err(SyntaxError::new(
6574 "the class constructor's fclosure went missing",
6575 class.span,
6576 ));
6577 }
6578 }
6579
6580 // The instance brand: a symbol created once on the prototype, which every instance
6581 // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6582 // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6583 // copy is created. The prototype is on top of the stack at this point.
6584 if plan.instance_brand {
6585 self.emit(Opcode::Dup, &[]);
6586 self.emit(Opcode::Null, &[]);
6587 self.emit(Opcode::Swap, &[]);
6588 self.emit(Opcode::AddBrand, &[]);
6589 }
6590
6591 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6592 // class has no instance fields. The constructor calls it only when it is defined.
6593 //
6594 // A class with private *methods* but no fields still needs one, because adding the
6595 // brand to each new instance is the initialiser's job.
6596 if instance_fields.is_empty() && !plan.instance_brand {
6597 self.emit(Opcode::Undefined, &[]);
6598 } else {
6599 let initialiser = self.compile_field_initialiser(
6600 &instance_fields,
6601 class.span,
6602 true,
6603 plan.instance_brand,
6604 )?;
6605 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6606 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6607 // `set_home_object` reads `obj func`, so the prototype stays where it is.
6608 self.emit(Opcode::SetHomeObject, &[]);
6609 }
6610 self.emit_var(VarAction::PutInit, "<class_fields_init>");
6611 // The prototype has done its job: every instance member is defined on it. What
6612 // is left under it is the constructor.
6613 self.emit(Opcode::Drop, &[]);
6614
6615 // The static brand, for `static #m() {}`: same opcode, but the home object is the
6616 // constructor itself, so the symbol lands on the class and the class carries it.
6617 if plan.static_brand {
6618 self.emit(Opcode::Dup, &[]);
6619 self.emit(Opcode::Dup, &[]);
6620 self.emit(Opcode::AddBrand, &[]);
6621 }
6622
6623 // The class binding is initialised *before* static fields run, so a static field
6624 // can refer to the class by name (`static y = S.x`).
6625 // `set_loc` leaves the constructor on the stack, which is what the static field
6626 // call and the outer store both consume.
6627 //
6628 // Only when there *is* such a binding: an anonymous class expression declares no
6629 // class-scope name, and asking for one by the empty string resolved to nothing —
6630 // which made `var x = class {}` assign `undefined` and put a bogus global store in
6631 // the instruction stream.
6632 if let Some(name) = &name {
6633 self.emit_var(VarAction::SetInit, name);
6634 }
6635 if !static_items.is_empty() {
6636 // The static half has no brand prologue of its own: the constructor got its
6637 // brand above, before this runs.
6638 let initialiser =
6639 self.compile_field_initialiser(&static_items, class.span, false, false)?;
6640 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6641 self.emit(Opcode::Dup, &[]);
6642 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6643 self.emit(Opcode::SetHomeObject, &[]);
6644 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6645 self.emit(Opcode::Drop, &[]);
6646 }
6647 // The body is over, and with it this class's private names.
6648 let _ = self.private_scopes.pop();
6649 self.emit_scope_leave(key);
6650 self.state().current_block = parent_block;
6651 if keep {
6652 // A class *expression* is its own value; the class-scope binding was only
6653 // ever an alias for it.
6654 return Ok(());
6655 }
6656 // A declaration stores into the binding the enclosing statement declared.
6657 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6658 Ok(())
6659 }
6660
6661 fn push_this(&mut self) {
6662 self.emit(Opcode::PushThis, &[]);
6663 }
6664
6665 /// `this`, which an arrow does not have of its own.
6666 ///
6667 /// The reference gives the enclosing function a local named `this`, initialised from
6668 /// `push_this` at the top of its body, and the arrow then reads it as a captured
6669 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6670 /// the arrow is called with none.
6671 fn this_expression(&mut self) {
6672 // In a class constructor `this` is a local: a derived constructor only gets one
6673 // when `super()` returns, and reading the raw receiver would give the *outer*
6674 // one instead.
6675 if self.cur().ctor_kind != CtorKind::None {
6676 self.emit_var(VarAction::Get, "this");
6677 return;
6678 }
6679 if !self.cur().is_arrow {
6680 self.push_this();
6681 return;
6682 }
6683 // An arrow at the **top level** of a script or module has no enclosing function,
6684 // but it still inherits `this` — the script's or module's own. Falling through to
6685 // `emit_var(Get, "this")` without a target made that a *global* lookup, so
6686 // `var f = () => typeof this` at top level reported
6687 // `ReferenceError: 'this' is not defined` instead of `"object"`
6688 // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
6689 // is the test262 case that reaches it, through a native `forEach`).
6690 //
6691 // The script state is the bottom of the stack, so it is the fallback target. Its
6692 // own `provide_this_local` then prepends the `push_this` the arrow reads.
6693 let target = self.enclosing_function().unwrap_or(0);
6694 self.state_at(target).needs_this_local = true;
6695 self.declare_at(target, "this");
6696 self.emit_var(VarAction::Get, "this");
6697 }
6698
6699 /// `new.target`, which an arrow likewise does not own.
6700 fn new_target_expression(&mut self) {
6701 if !self.cur().is_arrow {
6702 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6703 return;
6704 }
6705 if let Some(target) = self.enclosing_function() {
6706 self.state_at(target).needs_new_target_local = true;
6707 self.declare_at(target, NEW_TARGET);
6708 }
6709 self.emit_var(VarAction::Get, NEW_TARGET);
6710 }
6711
6712 /// `this.active_func`: the function `super()` resolves against.
6713 ///
6714 /// In a constructor or a method that is the function being run, so the special object
6715 /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6716 /// a closure variable — see [`FnState::needs_active_func_local`].
6717 fn active_func_expression(&mut self) {
6718 if !self.cur().is_arrow {
6719 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6720 return;
6721 }
6722 if let Some(target) = self.enclosing_function() {
6723 self.state_at(target).needs_active_func_local = true;
6724 self.declare_at(target, ACTIVE_FUNC);
6725 }
6726 self.emit_var(VarAction::Get, ACTIVE_FUNC);
6727 }
6728
6729 /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6730 fn provide_active_func_local(&mut self) {
6731 let current = self.stack.len() - 1;
6732 if !self.stack[current].needs_active_func_local {
6733 return;
6734 }
6735 if !self.stack[current]
6736 .vars
6737 .iter()
6738 .any(|var| var.name == ACTIVE_FUNC)
6739 {
6740 self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6741 }
6742 self.prepend_initialiser(
6743 ACTIVE_FUNC,
6744 Insn::Fixed {
6745 op: Opcode::SpecialObject,
6746 operands: vec![Op::Int(2)],
6747 },
6748 );
6749 }
6750
6751 /// Give the function a local `new.target`, for an arrow inside it to capture.
6752 fn provide_new_target_local(&mut self) {
6753 let current = self.stack.len() - 1;
6754 if !self.stack[current].needs_new_target_local {
6755 return;
6756 }
6757 if !self.stack[current]
6758 .vars
6759 .iter()
6760 .any(|var| var.name == NEW_TARGET)
6761 {
6762 self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6763 }
6764 self.prepend_initialiser(
6765 NEW_TARGET,
6766 Insn::Fixed {
6767 op: Opcode::SpecialObject,
6768 operands: vec![Op::Int(3)],
6769 },
6770 );
6771 }
6772
6773 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6774 /// function.
6775 fn ensure_enclosing_arguments(&mut self) {
6776 // An arrow created in a parameter list needs the *parameter* scope's
6777 // `arguments`, not the body's: the two are separate bindings and the arrow was
6778 // born before the body existed.
6779 let from_params = self.cur().created_in_params;
6780 if let Some(target) = self.enclosing_function() {
6781 self.state_at(target).needs_arguments_local = true;
6782 if from_params {
6783 self.state_at(target).needs_param_arguments = true;
6784 // Declare it now, not at the enclosing function's `finish_current`: the
6785 // arrow resolves its own `arguments` before that runs, and a binding that
6786 // does not exist yet resolves as a global.
6787 declare_param_var_at(&mut self.stack[target], "arguments");
6788 }
6789 self.declare_at(target, "arguments");
6790 }
6791 }
6792
6793 /// The innermost enclosing frame that is a real function — an arrow inherits from it
6794 /// rather than starting a scope of its own.
6795 /// The innermost enclosing frame that can own a lexical binding an arrow reads —
6796 /// a real function, or a **script** top level.
6797 ///
6798 /// A script is in the list because an `eval` body is compiled as one and an arrow
6799 /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
6800 /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
6801 /// a *global* lookup of `new.target`, which no frame provides — so it raised
6802 /// `ReferenceError` instead of answering the caller's value
6803 /// (`arrow-body-direct-eval-err-contains-newtarget`).
6804 fn enclosing_function(&self) -> Option<usize> {
6805 (0..self.stack.len())
6806 .rev()
6807 .find(|index| !self.stack[*index].is_arrow)
6808 }
6809
6810 fn state_at(&mut self, index: usize) -> &mut FnState {
6811 &mut self.stack[index]
6812 }
6813
6814 /// Declare a `var` binding directly in a specific frame.
6815 fn declare_at(&mut self, index: usize, name: &str) {
6816 let state = &mut self.stack[index];
6817 if state.vars.iter().any(|var| var.name == name) {
6818 return;
6819 }
6820 state.var_block.push(FUNCTION_SCOPE);
6821 state.vars.push(VarDef::var(name));
6822 }
6823
6824 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6825 /// the reference calls a `special_object` gets initialised on entry.
6826 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6827 let current = self.stack.len() - 1;
6828 let init = [
6829 producer,
6830 Insn::Var {
6831 action: VarAction::Put,
6832 name: name.to_string(),
6833 block: 0,
6834 // A prologue initialiser runs before the body proper, but it is body
6835 // code: `this` and `arguments` are provided for it, not by it.
6836 in_params: false,
6837 },
6838 ];
6839 let inserted = init.len();
6840 for (index, instruction) in init.into_iter().enumerate() {
6841 self.stack[current].insns.insert(index, instruction);
6842 }
6843 for placed in self.stack[current].labels.iter_mut().flatten() {
6844 *placed += inserted;
6845 }
6846 self.stack[current].label_since_insn = true;
6847 }
6848
6849 fn push_constant(&mut self, constant: Constant) -> u32 {
6850 let state = self.state();
6851 let index = state.cpool.len() as u32;
6852 state.cpool.push(constant);
6853 index
6854 }
6855
6856 /// Compile `a && b`, `a || b`, `a ?? b`.
6857 ///
6858 /// A run of the *same* operator shares one end label, so `a || b || c` tests
6859 /// `a` once and jumps past everything when it is truthy, instead of falling
6860 /// into `b`'s test. The parser builds such a run left-associated —
6861 /// `((a || b) || c)` — so the operands are collected off the left spine.
6862 ///
6863 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6864 /// `||`'s label, because the inner chain really does end before `&&` begins.
6865 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6866 let mut operands = Vec::new();
6867 collect_same_operator(op, left, &mut operands);
6868 operands.push(right);
6869
6870 let end = self.new_label();
6871 // Every operand but the last decides whether the chain stops here.
6872 let last = operands.pop().expect("the right operand is always present");
6873 for operand in operands {
6874 self.expr(operand)?;
6875 self.emit(Opcode::Dup, &[]);
6876 match op {
6877 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6878 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6879 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6880 // `0 || b` is `b`. The dedicated test keeps the value unless it is
6881 // null-ish, so the jump is taken on `false`.
6882 LogicalOp::Coalesce => {
6883 self.emit(Opcode::IsUndefinedOrNull, &[]);
6884 self.emit_jump(Opcode::IfFalse, end, &[]);
6885 }
6886 }
6887 self.emit(Opcode::Drop, &[]);
6888 }
6889 self.expr(last)?;
6890 self.place_label(end);
6891 Ok(())
6892 }
6893
6894 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6895 match op {
6896 UnaryOp::Typeof => {
6897 // `typeof x` must not throw on an undeclared name.
6898 if let ExprKind::Ident(name) = &argument.kind {
6899 self.emit_var(VarAction::GetUndef, &name.name);
6900 } else {
6901 self.expr(argument)?;
6902 }
6903 self.emit(Opcode::Typeof, &[]);
6904 }
6905 UnaryOp::Delete => {
6906 // `delete obj.prop` really deletes, and answers whether it could.
6907 // Deleting a *binding* is always `false`: a local, an argument and a
6908 // declared global are all non-configurable, which the reference encodes
6909 // as a constant `push_false` rather than a runtime check. Only a
6910 // property access has anything to do at run time.
6911 // `delete super.x` is not a delete at all: the spec refuses it, and the
6912 // reference encodes the refusal as a `throw_error`. The receiver and the
6913 // key are still evaluated first, which is what keeps the evaluation order
6914 // of the operand intact.
6915 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6916 // nothing to delete, and a failed delete is not the same as a skipped
6917 // one. The reference emits the guards so they land on a `drop; push_true`
6918 // tail, which is what this reproduces.
6919 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6920 && let ExprKind::Member {
6921 object, property, ..
6922 } = &inner.unparen().kind
6923 {
6924 let end = self.new_label();
6925 let done = self.new_label();
6926 self.chain_link(object, end)?;
6927 match property {
6928 MemberProp::Ident(name) => self.emit(
6929 Opcode::PushAtomValue,
6930 &[Op::Atom(Atom::from_text(&name.name))],
6931 ),
6932 MemberProp::Computed(index) => self.expr(index)?,
6933 MemberProp::Private(_) => {
6934 return Err(SyntaxError::new(
6935 "deleting a private field is not allowed",
6936 argument.span,
6937 ));
6938 }
6939 }
6940 self.emit(Opcode::Delete, &[]);
6941 self.emit_jump(Opcode::Goto, done, &[]);
6942 self.place_label(end);
6943 self.emit(Opcode::Drop, &[]);
6944 self.emit(Opcode::PushTrue, &[]);
6945 self.place_label(done);
6946 return Ok(());
6947 }
6948 if let ExprKind::Member { object, .. } = &argument.unparen().kind
6949 && matches!(object.unparen().kind, ExprKind::SuperProp)
6950 {
6951 self.super_base();
6952 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6953 return Ok(());
6954 }
6955 // Parentheses are transparent to `delete`: `(x)` is still a Reference to
6956 // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
6957 // does, and `delete (a().b)` still evaluates `a()`. Matching on the
6958 // unparenthesised operand is what keeps both — matching on `argument.kind`
6959 // sent every parenthesised form to the "not a Reference" arm, which cost
6960 // `delete(__variable) === false` in test262's `S12.2_A2`.
6961 match &argument.unparen().kind {
6962 ExprKind::Member {
6963 object, property, ..
6964 } => {
6965 self.expr(object)?;
6966 match property {
6967 MemberProp::Ident(name) => {
6968 self.emit(
6969 Opcode::PushAtomValue,
6970 &[Op::Atom(Atom::from_text(&name.name))],
6971 );
6972 }
6973 MemberProp::Computed(index) => self.expr(index)?,
6974 MemberProp::Private(_) => {
6975 return Err(SyntaxError::new(
6976 "deleting a private field is not allowed",
6977 argument.span,
6978 ));
6979 }
6980 }
6981 self.emit(Opcode::Delete, &[]);
6982 }
6983 ExprKind::Ident(name) => {
6984 self.delete_ident(&name.name);
6985 }
6986 // §13.5.1.2 step 2: an operand that is **not** a Reference Record
6987 // answers `true` — there is nothing to delete, and "nothing needed
6988 // deleting" is success. `delete !0`, `delete (1 + 2)` and
6989 // `delete typeof 0` are all `true`, and the operand is still evaluated
6990 // (which is why it is `Drop`ed rather than skipped:
6991 // `delete f()` must call `f`).
6992 //
6993 // Answering `false` here is the C reference's old behaviour and was
6994 // wrong in an observable way: test262's
6995 // `dynamic-import/assignment-expression/logical-and-expr` builds a
6996 // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
6997 // half turned the whole `&&` into `false`, so the import asked for a
6998 // module named "false".
6999 _ => {
7000 self.expr(argument)?;
7001 self.emit(Opcode::Drop, &[]);
7002 self.emit(Opcode::PushTrue, &[]);
7003 }
7004 }
7005 }
7006 UnaryOp::Void => {
7007 self.expr(argument)?;
7008 self.emit(Opcode::Drop, &[]);
7009 self.emit(Opcode::Undefined, &[]);
7010 }
7011 UnaryOp::Minus => {
7012 self.expr(argument)?;
7013 self.emit(Opcode::Neg, &[]);
7014 }
7015 UnaryOp::Plus => {
7016 self.expr(argument)?;
7017 self.emit(Opcode::Plus, &[]);
7018 }
7019 UnaryOp::Not => {
7020 self.expr(argument)?;
7021 self.emit(Opcode::Lnot, &[]);
7022 }
7023 UnaryOp::BitNot => {
7024 self.expr(argument)?;
7025 self.emit(Opcode::Not, &[]);
7026 }
7027 }
7028 Ok(())
7029 }
7030
7031 /// A store to `name` while a `with` may capture it.
7032 ///
7033 /// The reference is resolved **first**, before the right-hand side runs. That order is
7034 /// the whole point: in `x = (delete env.x, 0)` the resolution has already decided that
7035 /// `x` is `env`'s property, so `PutValue` then finds it gone and strict code throws
7036 /// `ReferenceError` (`set-mutable-binding-binding-deleted-with-typed-array-in-
7037 /// proto-chain-strict-mode`). The ordinary path evaluates the right-hand side before
7038 /// the guard runs, which put the guard *after* the mutation.
7039 ///
7040 /// Shapes mirror [`Compiler::assign_ident_plain`] and the member arms of
7041 /// [`Compiler::assign`], with `dup; with_get_var` in place of `get_field2` and
7042 /// `with_put_var` in place of `put_field` — the same stack effects, but each half also
7043 /// asks the `HasProperty` that `GetBindingValue`/`SetMutableBinding` require.
7044 fn with_assign(
7045 &mut self,
7046 with_local: &str,
7047 name: &Ident,
7048 op: AssignOp,
7049 value: &Expr,
7050 keep: bool,
7051 ) -> Result<(), SyntaxError> {
7052 let atom = Atom::from_text(&name.name);
7053 self.state().cur_pos = Some(name.span.start);
7054 match op {
7055 AssignOp::Assign => {
7056 self.expr(value)?;
7057 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7058 if keep {
7059 self.emit(Opcode::Dup, &[]);
7060 }
7061 self.state().no_value = !keep;
7062 self.emit_var(VarAction::Get, with_local);
7063 self.emit(Opcode::Swap, &[]);
7064 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7065 }
7066 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7067 let (keep_label, end) = (self.new_label(), self.new_label());
7068 self.emit_var(VarAction::Get, with_local);
7069 self.emit(Opcode::Dup, &[]);
7070 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7071 // `obj value` — the object stays underneath for the store.
7072 self.emit(Opcode::Dup, &[]);
7073 self.emit_logical_test(op);
7074 self.emit_jump(logical_jump(op), keep_label, &[]);
7075 self.emit(Opcode::Drop, &[]);
7076 self.expr(value)?;
7077 self.emit(Opcode::Insert2, &[]);
7078 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7079 self.emit_jump(Opcode::Goto, end, &[]);
7080 self.place_label(keep_label);
7081 self.emit(Opcode::Nip, &[]);
7082 self.place_label(end);
7083 }
7084 _ => {
7085 self.emit_var(VarAction::Get, with_local);
7086 self.emit(Opcode::Dup, &[]);
7087 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7088 self.expr(value)?;
7089 self.state().cur_pos = Some(name.span.start);
7090 self.emit(compound_opcode(op), &[]);
7091 self.state().no_value = !keep;
7092 if keep {
7093 self.emit(Opcode::Insert2, &[]);
7094 }
7095 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7096 }
7097 }
7098 Ok(())
7099 }
7100
7101 /// `x++` / `++x` while a `with` may capture `x`, with one resolution for both halves.
7102 fn with_update(
7103 &mut self,
7104 with_local: &str,
7105 name: &Ident,
7106 op: UpdateOp,
7107 prefix: bool,
7108 ) -> Result<(), SyntaxError> {
7109 let instruction = match (op, prefix) {
7110 (UpdateOp::Increment, true) => Opcode::Inc,
7111 (UpdateOp::Increment, false) => Opcode::PostInc,
7112 (UpdateOp::Decrement, true) => Opcode::Dec,
7113 (UpdateOp::Decrement, false) => Opcode::PostDec,
7114 };
7115 let atom = Atom::from_text(&name.name);
7116 self.state().cur_pos = Some(name.span.start);
7117 self.emit_var(VarAction::Get, with_local);
7118 self.emit(Opcode::Dup, &[]);
7119 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7120 self.emit(instruction, &[]);
7121 self.emit(
7122 if prefix {
7123 Opcode::Insert2
7124 } else {
7125 Opcode::Perm3
7126 },
7127 &[],
7128 );
7129 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7130 Ok(())
7131 }
7132
7133 /// A store to a plain identifier, with no `with` in the way.
7134 fn assign_ident_plain(
7135 &mut self,
7136 op: AssignOp,
7137 name: &Ident,
7138 value: &Expr,
7139 discard: bool,
7140 ) -> Result<(), SyntaxError> {
7141 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7142 // about, so it is set only when this assignment *is* that expression.
7143 let keep = !discard;
7144 // A *simple* store is blamed on the identifier, not on the `=`: a
7145 // strict-mode `not_def = 1` raises when the name is written, which the
7146 // reference reports at the name's column. A compound store is blamed on
7147 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
7148 // which the reference reports at the `+=`), so only the simple case
7149 // moves the position.
7150 let saved = self.cur().cur_pos;
7151 let name_pos = Some(name.span.start);
7152 if matches!(op, AssignOp::Assign) {
7153 self.state().cur_pos = name_pos;
7154 }
7155 // A *compound* store reads the binding before it combines, and that read
7156 // is blamed on the identifier: `not_def += 2` fails while reading
7157 // `not_def`, so the position is the name's, not the `+=`'s. The
7158 // combination that follows is blamed on the operator, which is why
7159 // `cur_pos` is put back to the operator position before it is emitted.
7160 self.state().cur_pos = name_pos;
7161 match op {
7162 AssignOp::Assign => {
7163 self.expr(value)?;
7164 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7165 // A discarded store to a *slot* consumes its value, so no copy
7166 // is needed. A global store goes through `put_var`, which the
7167 // reference always pairs with a `dup` — matching it keeps the
7168 // bytecode identical. Getting this wrong is not only an extra
7169 // instruction: a stray copy gives the peephole a chance to fold
7170 // the store into an unrelated later read.
7171 let slot = self.is_slot(&name.name);
7172 if keep || !slot {
7173 self.emit(Opcode::Dup, &[]);
7174 }
7175 self.state().no_value = !keep && slot;
7176 self.emit_var(VarAction::Put, &name.name);
7177 }
7178 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7179 let end = self.new_label();
7180 self.emit_var(VarAction::Get, &name.name);
7181 self.state().cur_pos = saved;
7182 self.emit(Opcode::Dup, &[]);
7183 self.emit_logical_test(op);
7184 self.emit_jump(logical_jump(op), end, &[]);
7185 self.emit(Opcode::Drop, &[]);
7186 self.expr(value)?;
7187 self.emit(Opcode::Dup, &[]);
7188 self.emit_var(VarAction::Put, &name.name);
7189 self.place_label(end);
7190 }
7191 _ => {
7192 self.emit_var(VarAction::Get, &name.name);
7193 self.expr(value)?;
7194 self.state().cur_pos = saved;
7195 self.emit(compound_opcode(op), &[]);
7196 self.emit(Opcode::Dup, &[]);
7197 self.emit_var(VarAction::Put, &name.name);
7198 }
7199 }
7200 self.state().cur_pos = saved;
7201 Ok(())
7202 }
7203
7204 /// Compile an assignment.
7205 ///
7206 /// Three operator families, three shapes:
7207 ///
7208 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
7209 /// the value is kept, because `put_field`/`put_array_el` consume both the
7210 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
7211 /// the pair it wants and leaves a copy on top.
7212 /// * **compound** `+=` … — read the place, apply the operator, store. A member
7213 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
7214 /// index) underneath the value precisely so the store can follow.
7215 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
7216 /// right-hand side. The test *keeps* the current value and skips the store
7217 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
7218 /// `a` is already truthy.
7219 fn assign(
7220 &mut self,
7221 op: AssignOp,
7222 target: &Pattern,
7223 value: &Expr,
7224 discard: bool,
7225 ) -> Result<(), SyntaxError> {
7226 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7227 // about, so it is set only when this assignment *is* that expression.
7228 let keep = !discard;
7229 match &target.kind {
7230 PatternKind::Ident(name) => {
7231 // Any store to a name a `with` may capture resolves the reference first and
7232 // keeps that resolution for both halves — see [`Compiler::with_assign`].
7233 // Plain `=` needs it just as much as `+=`: `x = (delete env.x, 0)` must
7234 // resolve `x` before the right-hand side deletes it.
7235 let plain_name = name.name.clone();
7236 if !self.visible_with_names(&plain_name).is_empty() {
7237 return self.with_reference(
7238 &plain_name,
7239 &mut |compiler, with_local| {
7240 compiler.with_assign(with_local, name, op, value, !discard)
7241 },
7242 &mut |compiler| compiler.assign_ident_plain(op, name, value, discard),
7243 );
7244 }
7245 self.assign_ident_plain(op, name, value, discard)
7246 }
7247 PatternKind::Member(member) => {
7248 // `super.x = v` is not a store through a value: it starts at the home
7249 // object's prototype but writes to `this`, so it goes through
7250 // `put_super_value` rather than `put_field`. The receiver, prototype, key
7251 // and value are handed over together.
7252 if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
7253 return self.assign_super(member, op, value);
7254 }
7255 // A store is blamed on the selector punctuator (`.` or `[`), the same
7256 // token a load is blamed on — the reference records `put_field obj.a`
7257 // at the `.`, so a setter that throws reports that column and not the
7258 // `=` of the assignment it sits in. The inner expressions restore their
7259 // own positions, so the selector's sticks for the store instructions.
7260 let saved = self.cur().cur_pos;
7261 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7262 self.expr(&member.object)?;
7263 match &member.property {
7264 MemberProp::Ident(property) => {
7265 let atom = Atom::from_text(&property.name);
7266 match op {
7267 AssignOp::Assign => {
7268 self.expr(value)?;
7269 // `put_field` consumes the object and the value, so
7270 // without `insert2` nothing is left over for the
7271 // statement to drop.
7272 self.state().no_value = !keep;
7273 if keep {
7274 self.emit(Opcode::Insert2, &[]);
7275 }
7276 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7277 }
7278 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7279 // `get_field2` leaves the object under the value, so
7280 // the keep path has an object to dispose of. The store
7281 // path must jump *over* that cleanup: falling into it
7282 // would `nip` a stack that only holds the value.
7283 let (keep_label, end) = (self.new_label(), self.new_label());
7284 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7285 self.emit(Opcode::Dup, &[]);
7286 self.emit_logical_test(op);
7287 self.emit_jump(logical_jump(op), keep_label, &[]);
7288 self.emit(Opcode::Drop, &[]);
7289 self.expr(value)?;
7290 self.emit(Opcode::Insert2, &[]);
7291 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7292 self.emit_jump(Opcode::Goto, end, &[]);
7293 self.place_label(keep_label);
7294 self.emit(Opcode::Nip, &[]);
7295 self.place_label(end);
7296 }
7297 _ => {
7298 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7299 self.expr(value)?;
7300 self.emit(compound_opcode(op), &[]);
7301 self.state().no_value = !keep;
7302 if keep {
7303 self.emit(Opcode::Insert2, &[]);
7304 }
7305 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7306 }
7307 }
7308 }
7309 MemberProp::Computed(index) => {
7310 self.expr(index)?;
7311 match op {
7312 AssignOp::Assign => {
7313 self.expr(value)?;
7314 self.state().no_value = !keep;
7315 if keep {
7316 self.emit(Opcode::Insert3, &[]);
7317 }
7318 self.emit(Opcode::PutArrayEl, &[]);
7319 }
7320 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7321 let (keep_label, end) = (self.new_label(), self.new_label());
7322 self.emit(Opcode::GetArrayEl3, &[]);
7323 self.emit(Opcode::Dup, &[]);
7324 self.emit_logical_test(op);
7325 self.emit_jump(logical_jump(op), keep_label, &[]);
7326 self.emit(Opcode::Drop, &[]);
7327 self.expr(value)?;
7328 self.emit(Opcode::Insert3, &[]);
7329 self.emit(Opcode::PutArrayEl, &[]);
7330 self.emit_jump(Opcode::Goto, end, &[]);
7331 self.place_label(keep_label);
7332 // Both the object and the index are left over.
7333 self.emit(Opcode::Nip, &[]);
7334 self.emit(Opcode::Nip, &[]);
7335 self.place_label(end);
7336 }
7337 _ => {
7338 self.emit(Opcode::GetArrayEl3, &[]);
7339 self.expr(value)?;
7340 self.emit(compound_opcode(op), &[]);
7341 self.state().no_value = !keep;
7342 if keep {
7343 self.emit(Opcode::Insert3, &[]);
7344 }
7345 self.emit(Opcode::PutArrayEl, &[]);
7346 }
7347 }
7348 }
7349 MemberProp::Private(name) => {
7350 // `obj value` is on the stack, and every private store wants exactly
7351 // that. A top-level private name cannot be assigned (the parser rejects
7352 // `#x = 1`), so the only way here is `this.#x = …` inside the class.
7353 //
7354 // The reference emits `insert2` whether or not the value is wanted,
7355 // so this does too: the copy left behind is the assignment expression's
7356 // value, and a discarded one is simply never read.
7357 let binding = format!("#{}", name.name);
7358 let (kind, setter) = self.private_use(&binding, member.span)?;
7359 match op {
7360 AssignOp::Assign => {
7361 self.expr(value)?;
7362 if keep {
7363 self.emit(Opcode::Insert2, &[]);
7364 }
7365 self.private_store(&binding, kind, setter.as_deref())?;
7366 self.state().no_value = !keep;
7367 }
7368 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7369 let (keep_label, end) = (self.new_label(), self.new_label());
7370 self.emit(Opcode::Dup, &[]);
7371 self.private_load(&binding, kind, member.span)?;
7372 self.emit(Opcode::Dup, &[]);
7373 self.emit_logical_test(op);
7374 self.emit_jump(logical_jump(op), keep_label, &[]);
7375 self.emit(Opcode::Drop, &[]);
7376 self.expr(value)?;
7377 self.emit(Opcode::Insert2, &[]);
7378 self.private_store(&binding, kind, setter.as_deref())?;
7379 self.emit_jump(Opcode::Goto, end, &[]);
7380 self.place_label(keep_label);
7381 self.emit(Opcode::Nip, &[]);
7382 self.place_label(end);
7383 }
7384 _ => {
7385 self.emit(Opcode::Dup, &[]);
7386 self.private_load(&binding, kind, member.span)?;
7387 self.expr(value)?;
7388 self.emit(compound_opcode(op), &[]);
7389 self.emit(Opcode::Insert2, &[]);
7390 self.private_store(&binding, kind, setter.as_deref())?;
7391 }
7392 }
7393 }
7394 }
7395 self.state().cur_pos = saved;
7396 Ok(())
7397 }
7398 // A destructuring assignment: the right-hand side is the expression's own
7399 // value, so it is evaluated once and kept under the pattern's stores.
7400 PatternKind::Array { .. } | PatternKind::Object { .. } => {
7401 self.expr(value)?;
7402 if keep {
7403 self.emit(Opcode::Dup, &[]);
7404 }
7405 self.destructure(target, None)?;
7406 self.state().no_value = !keep;
7407 Ok(())
7408 }
7409 _ => Err(SyntaxError::new(
7410 "this assignment target is not supported by the compiler yet",
7411 target.span,
7412 )),
7413 }
7414 }
7415
7416 /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
7417 ///
7418 /// The stack has to carry four values — receiver, prototype, key, value — because
7419 /// `put_super_value` takes them together; the receiver is what makes a setter found on
7420 /// the prototype run with `this`, and the key has to survive until the store, which is
7421 /// why a compound form converts it to a property key once and `dup3`s rather than
7422 /// evaluating it twice.
7423 fn assign_super(
7424 &mut self,
7425 member: &MemberPattern,
7426 op: AssignOp,
7427 value: &Expr,
7428 ) -> Result<(), SyntaxError> {
7429 let saved = self.cur().cur_pos;
7430 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7431 self.super_base();
7432 match &member.property {
7433 MemberProp::Ident(property) => self.emit(
7434 Opcode::PushAtomValue,
7435 &[Op::Atom(Atom::from_text(&property.name))],
7436 ),
7437 MemberProp::Computed(index) => self.expr(index)?,
7438 MemberProp::Private(_) => {
7439 return Err(SyntaxError::new(
7440 "private fields are not supported by the compiler yet",
7441 member.span,
7442 ));
7443 }
7444 }
7445 match op {
7446 AssignOp::Assign => {
7447 // The key is only converted once, by `put_super_value` itself, so a
7448 // computed key's `toString` runs exactly once.
7449 self.expr(value)?;
7450 self.emit(Opcode::Insert4, &[]);
7451 self.emit(Opcode::PutSuperValue, &[]);
7452 }
7453 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7454 let (keep_label, end) = (self.new_label(), self.new_label());
7455 self.emit(Opcode::ToPropkey, &[]);
7456 self.emit(Opcode::Dup3, &[]);
7457 self.emit(Opcode::GetSuperValue, &[]);
7458 self.emit(Opcode::Dup, &[]);
7459 self.emit_logical_test(op);
7460 self.emit_jump(logical_jump(op), keep_label, &[]);
7461 self.emit(Opcode::Drop, &[]);
7462 self.expr(value)?;
7463 self.emit(Opcode::Insert4, &[]);
7464 self.emit(Opcode::PutSuperValue, &[]);
7465 self.emit_jump(Opcode::Goto, end, &[]);
7466 self.place_label(keep_label);
7467 // The prototype and the key are still under the value that was read.
7468 self.emit(Opcode::Nip, &[]);
7469 self.emit(Opcode::Nip, &[]);
7470 self.emit(Opcode::Nip, &[]);
7471 self.place_label(end);
7472 }
7473 _ => {
7474 self.emit(Opcode::ToPropkey, &[]);
7475 self.emit(Opcode::Dup3, &[]);
7476 self.emit(Opcode::GetSuperValue, &[]);
7477 self.expr(value)?;
7478 self.emit(compound_opcode(op), &[]);
7479 self.emit(Opcode::Insert4, &[]);
7480 self.emit(Opcode::PutSuperValue, &[]);
7481 }
7482 }
7483 // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7484 // is still on the stack when the store finishes, and the expression statement is
7485 // what disposes of it — the same arrangement as `put_field`, reached from the other
7486 // side: there the store consumes the value (`no_value`), here it leaves it
7487 // (`keep` already false, so nothing tells the statement otherwise).
7488 self.state().cur_pos = saved;
7489 Ok(())
7490 }
7491
7492 /// The test a logical assignment applies to the current value.
7493 ///
7494 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7495 /// assign, while `0 ||= b` must not.
7496 fn emit_logical_test(&mut self, op: AssignOp) {
7497 if op == AssignOp::Coalesce {
7498 self.emit(Opcode::IsUndefinedOrNull, &[]);
7499 }
7500 }
7501
7502 /// The private name `#name` this use site resolves against.
7503 ///
7504 /// The parser has already rejected a name no enclosing class declares, so a miss here
7505 /// means the compiler lost track of a class scope — which is worth a real error rather
7506 /// than an `unwrap`.
7507 fn private_use(
7508 &self,
7509 binding: &str,
7510 span: Span,
7511 ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7512 ClassPlan::find(self, binding)
7513 .map(|use_| (use_.kind, use_.setter.clone()))
7514 .ok_or_else(|| {
7515 SyntaxError::new(
7516 format!("the private name '{binding}' is out of scope here"),
7517 span,
7518 )
7519 })
7520 }
7521
7522 /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7523 ///
7524 /// The three readable kinds take three different instructions, because a private name
7525 /// holds three different things — a symbol, a method function, a getter function — and
7526 /// only the first one is a property read at all.
7527 fn private_load(
7528 &mut self,
7529 binding: &str,
7530 kind: PrivateKind,
7531 span: Span,
7532 ) -> Result<(), SyntaxError> {
7533 match kind {
7534 PrivateKind::Field => {
7535 self.emit_var(VarAction::Get, binding);
7536 self.emit(Opcode::GetPrivateField, &[]);
7537 }
7538 PrivateKind::Method => {
7539 self.emit_var(VarAction::Get, binding);
7540 self.emit(Opcode::CheckBrand, &[]);
7541 // `check_brand` reads `obj func` and leaves both; the method itself is what
7542 // `this.#m` evaluates to.
7543 self.emit(Opcode::Nip, &[]);
7544 }
7545 PrivateKind::Getter => {
7546 self.emit_var(VarAction::Get, binding);
7547 self.emit(Opcode::CheckBrand, &[]);
7548 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7549 }
7550 // `#a` is declared but never filled when only a setter exists, so reading it is
7551 // the same refusal as assigning to a `const`. The reference reports it with the
7552 // generic read-only wording and leaves the better message as a `XXX`.
7553 PrivateKind::Setter => self.emit(
7554 Opcode::ThrowError,
7555 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7556 ),
7557 }
7558 let _ = span;
7559 Ok(())
7560 }
7561
7562 /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
7563 fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
7564 match kind {
7565 // A method *is* the callee, so only the check goes in between.
7566 PrivateKind::Method => {
7567 self.emit_var(VarAction::Get, binding);
7568 self.emit(Opcode::CheckBrand, &[]);
7569 }
7570 _ => self.private_load(binding, kind, Span::default())?,
7571 }
7572 Ok(())
7573 }
7574
7575 /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
7576 /// wanted back.
7577 ///
7578 /// A getter/setter pair is a *method call*, not a property store: the reference reads
7579 /// the setter out of its own binding and calls it with the receiver, which is why the
7580 /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
7581 /// keeps the assignment's value for an expression context.
7582 fn private_store(
7583 &mut self,
7584 binding: &str,
7585 kind: PrivateKind,
7586 setter: Option<&str>,
7587 ) -> Result<(), SyntaxError> {
7588 match kind {
7589 PrivateKind::Field => {
7590 self.emit_var(VarAction::Get, binding);
7591 self.emit(Opcode::PutPrivateField, &[]);
7592 }
7593 PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
7594 Some(setter) => {
7595 self.emit_var(VarAction::Get, setter);
7596 // `obj func value` -> `value obj func` for the check, and back again for
7597 // the call, which wants `obj func arg`.
7598 self.emit(Opcode::Swap, &[]);
7599 self.emit(Opcode::Rot3r, &[]);
7600 self.emit(Opcode::CheckBrand, &[]);
7601 self.emit(Opcode::Rot3l, &[]);
7602 self.emit(Opcode::CallMethod, &[Op::Int(1)]);
7603 // The setter's return value is discarded; the assignment's own value is
7604 // whatever the caller left underneath.
7605 self.emit(Opcode::Drop, &[]);
7606 }
7607 None => self.emit(
7608 Opcode::ThrowError,
7609 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7610 ),
7611 },
7612 }
7613 Ok(())
7614 }
7615
7616 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
7617 // `x++` inside a `with` is a read-modify-write of a *property*, so the object is
7618 // resolved once for both halves. See [`Compiler::with_reference`].
7619 let unparened = argument.unparen();
7620 if let ExprKind::Ident(ident) = &unparened.kind {
7621 let name = ident.name.clone();
7622 if !self.visible_with_names(&name).is_empty() {
7623 return self.with_reference(
7624 &name,
7625 &mut |compiler, with_local| compiler.with_update(with_local, ident, op, prefix),
7626 &mut |compiler| compiler.update_plain(op, unparened, prefix),
7627 );
7628 }
7629 }
7630 self.update_plain(op, argument, prefix)
7631 }
7632
7633 fn update_plain(
7634 &mut self,
7635 op: UpdateOp,
7636 argument: &Expr,
7637 prefix: bool,
7638 ) -> Result<(), SyntaxError> {
7639 let instruction = match (op, prefix) {
7640 (UpdateOp::Increment, true) => Opcode::Inc,
7641 (UpdateOp::Increment, false) => Opcode::PostInc,
7642 (UpdateOp::Decrement, true) => Opcode::Dec,
7643 (UpdateOp::Decrement, false) => Opcode::PostDec,
7644 };
7645 // `(y)++` and `((o.x))++` are the same updates as the unparenthesised forms: §13.4
7646 // evaluates the operand as a `LeftHandSideExpression` and the parentheses around a
7647 // reference change nothing — they do not copy the value. Reading `argument.kind`
7648 // directly therefore rejected every parenthesised target with "increment of a
7649 // non-variable", which is not a thing the language has (`target-cover-id`).
7650 let argument = argument.unparen();
7651 if let ExprKind::Member {
7652 object,
7653 property,
7654 optional: _,
7655 } = &argument.kind
7656 {
7657 // `o.x++` needs the receiver twice, so the last link is read with the
7658 // `get_*2`/`get_*3` form that keeps it, and the update is written back
7659 // with `put_field`/`put_array_el`. The reordering in between is what puts
7660 // the old value below the receiver for a postfix update and the new one
7661 // above it for a prefix one:
7662 //
7663 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
7664 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
7665 //
7666 // This mirrors the reference instruction for instruction.
7667 self.expr(object)?;
7668 match property {
7669 MemberProp::Ident(name) => {
7670 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
7671 self.emit(instruction, &[]);
7672 self.emit(
7673 if prefix {
7674 Opcode::Insert2
7675 } else {
7676 Opcode::Perm3
7677 },
7678 &[],
7679 );
7680 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
7681 }
7682 MemberProp::Computed(index) => {
7683 self.expr(index)?;
7684 self.emit(Opcode::GetArrayEl3, &[]);
7685 self.emit(instruction, &[]);
7686 self.emit(
7687 if prefix {
7688 Opcode::Insert3
7689 } else {
7690 Opcode::Perm4
7691 },
7692 &[],
7693 );
7694 self.emit(Opcode::PutArrayEl, &[]);
7695 }
7696 MemberProp::Private(name) => {
7697 // The receiver is duplicated and the read keeps it, exactly as `get_field2`
7698 // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
7699 // `perm3` -> `old obj new` -> store.
7700 let binding = format!("#{}", name.name);
7701 let (kind, setter) = self.private_use(&binding, argument.span)?;
7702 self.emit(Opcode::Dup, &[]);
7703 self.private_load(&binding, kind, argument.span)?;
7704 self.emit(instruction, &[]);
7705 self.emit(
7706 if prefix {
7707 Opcode::Insert2
7708 } else {
7709 Opcode::Perm3
7710 },
7711 &[],
7712 );
7713 self.private_store(&binding, kind, setter.as_deref())?;
7714 }
7715 }
7716 return Ok(());
7717 }
7718 let ExprKind::Ident(name) = &argument.kind else {
7719 return Err(SyntaxError::new(
7720 "increment of a non-variable is not supported by the compiler yet",
7721 argument.span,
7722 ));
7723 };
7724 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
7725 // reference's `inc_loc` folds those three into one, but it does so only in some
7726 // positions (a `for` update and not a bare statement, and never for a lexical
7727 // binding), so emitting it unconditionally would move *away* from its output.
7728 // The instruction is equivalent either way; matching the reference matters more
7729 // than saving two instructions.
7730 let _ = !std::mem::take(&mut self.state().discard_value);
7731 self.emit_var(VarAction::Get, &name.name);
7732 self.emit(instruction, &[]);
7733 if prefix {
7734 self.emit(Opcode::Dup, &[]);
7735 }
7736 self.emit_var(VarAction::Put, &name.name);
7737 Ok(())
7738 }
7739
7740 /// Compile an array literal.
7741 ///
7742 /// The reference splits this into three phases, and the split is load-bearing
7743 /// rather than an optimisation detail:
7744 ///
7745 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
7746 /// the array in one instruction.
7747 /// 2. **Everything up to the first spread** is appended with explicit indices
7748 /// (`define_field <index>`), because a hole has no element to pass to
7749 /// `array_from`. A hole here is what makes `length` need fixing up: an
7750 /// explicit index does not extend the array the way a pushed element does.
7751 /// 3. **From the first spread on** the index lives on the stack, so `append` and
7752 /// `define_array_el` can consume it and `inc` advances it.
7753 ///
7754 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
7755 /// forces phase 2, and `[...a]` forces phase 3.
7756 fn array_literal(
7757 &mut self,
7758 elements: &[Option<ArrayElement>],
7759 span: Span,
7760 ) -> Result<(), SyntaxError> {
7761 let _ = span;
7762 let mut index: u32 = 0;
7763 let mut cursor = 0usize;
7764
7765 // Phase 1: a leading run of plain elements, at most 32 of them.
7766 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
7767 if index >= 32 {
7768 break;
7769 }
7770 self.expr(element)?;
7771 index += 1;
7772 cursor += 1;
7773 }
7774 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
7775
7776 // Phase 2: explicit indices, up to the first spread.
7777 let mut need_length = false;
7778 while let Some(element) = elements.get(cursor) {
7779 if matches!(element, Some(ArrayElement::Spread(_))) {
7780 break;
7781 }
7782 need_length = true;
7783 if let Some(ArrayElement::Expr(expression)) = element {
7784 self.expr(expression)?;
7785 self.emit_define_index(index);
7786 need_length = false;
7787 }
7788 index += 1;
7789 cursor += 1;
7790 }
7791
7792 if cursor >= elements.len() {
7793 if need_length {
7794 // `define_field` cannot set `length`, which is not configurable.
7795 self.emit(Opcode::Dup, &[]);
7796 self.push_number(index as f64);
7797 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7798 }
7799 return Ok(());
7800 }
7801
7802 // Phase 3: the index moves onto the stack for the spreading tail.
7803 //
7804 // `need_length` deliberately carries over from phase 2: a hole before the
7805 // first spread still has to be reflected in `length`, and only the final
7806 // check can do it because the array is not finished until the tail is
7807 // appended.
7808 self.push_number(index as f64);
7809 while let Some(element) = elements.get(cursor) {
7810 match element {
7811 Some(ArrayElement::Spread(expression)) => {
7812 // `append` copies an iterable and leaves the next index behind,
7813 // so no `inc` is needed here.
7814 self.expr(spread_argument(expression))?;
7815 self.emit(Opcode::Append, &[]);
7816 }
7817 None | Some(ArrayElement::Expr(_)) => {
7818 need_length = true;
7819 if let Some(ArrayElement::Expr(expression)) = element {
7820 self.expr(expression)?;
7821 self.emit(Opcode::DefineArrayEl, &[]);
7822 need_length = false;
7823 }
7824 self.emit(Opcode::Inc, &[]);
7825 }
7826 }
7827 cursor += 1;
7828 }
7829 if need_length {
7830 self.emit(Opcode::Dup1, &[]);
7831 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7832 } else {
7833 self.emit(Opcode::Drop, &[]);
7834 }
7835 Ok(())
7836 }
7837
7838 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
7839 fn emit_define_index(&mut self, index: u32) {
7840 self.emit(
7841 Opcode::DefineField,
7842 &[Op::Atom(Atom::from_text(&index.to_string()))],
7843 );
7844 }
7845
7846 // -- functions ---------------------------------------------------------
7847
7848 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
7849 self.compile_function_with_name(func, false)
7850 }
7851
7852 /// Compile a function, recording whether it is a *named function expression*.
7853 ///
7854 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
7855 /// must not leak outside. The reference does that by declaring `g` as a local of
7856 /// the function itself and initialising it with `special_object 2` (the current
7857 /// function), which is why this has to be known at compile time.
7858 fn compile_function_with_name(
7859 &mut self,
7860 func: &ast::Function,
7861 is_expression: bool,
7862 ) -> Result<CompiledFunction, SyntaxError> {
7863 let kind = match (func.is_generator, func.is_async) {
7864 (false, false) => FunctionKind::Normal,
7865 (true, false) => FunctionKind::Generator,
7866 (false, true) => FunctionKind::Async,
7867 (true, true) => FunctionKind::AsyncGenerator,
7868 };
7869 let mut state = FnState::new(
7870 func.name
7871 .as_ref()
7872 .map(|n| n.name.clone())
7873 .unwrap_or_default(),
7874 kind,
7875 );
7876 // The function's own mode, recorded by the parser. Inheriting the enclosing
7877 // function's instead let a nested `"use strict"` directive be ignored, so the
7878 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
7879 state.strict = func.strict;
7880 // A function defined inside a `with` block keeps seeing that object: the guard
7881 // chain names the enclosing `<with>` locals, which resolve outward into closure
7882 // variables exactly like any other captured binding.
7883 state.inherited_with_names = self.cur().with_names.len();
7884 state.with_names = self.cur().with_names.clone();
7885 state.is_arrow = func.is_arrow;
7886 state.created_in_block = self.cur().current_block;
7887 // A default anywhere in the parameter list is what gives the function two
7888 // variable environments. The reference decides this the same way: it scans the
7889 // parenthesis for a top-level `=`, so a destructured name without a default
7890 // stays a plain function-scope binding.
7891 state.in_params = false;
7892 // The reference scans the parenthesis for *any* `=`, including one nested inside
7893 // a pattern, so `function f({a = 1})` has parameter expressions even though the
7894 // parameter itself carries no initialiser.
7895 state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7896 // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
7897 // flag above this looks at the *shape* of each parameter, not just for `=`.
7898 state.simple_parameter_list = func
7899 .params
7900 .iter()
7901 .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
7902 // A function born inside a parameter list inherits the prohibition: it must not
7903 // see the body bindings of the function it was created in.
7904 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
7905 // A class constructor knows what it is only because the class told it.
7906 if let Some(kind) = self.cur().class_ctor_pending {
7907 state.ctor_kind = kind;
7908 }
7909 // A named *expression* binds its own name; a declaration's name is already
7910 // bound in the enclosing scope.
7911 state.self_name = if is_expression && !func.is_arrow {
7912 func.name.as_ref().map(|n| n.name.clone())
7913 } else {
7914 None
7915 };
7916 // Keep the written range so `Function.prototype.toString` can answer with the
7917 // original text rather than `[native code]`.
7918 //
7919 // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
7920 // accessor and generator prefixes, and for a method it must not include the name
7921 // or a leading `static`. `params_span` is exactly that boundary.
7922 // A *method* keeps the old `[native code]` answer: its reported text is defined
7923 // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
7924 // the comments in between kept verbatim), and reconstructing that from a byte
7925 // span got it wrong in more cases than it got right. A plain function and an
7926 // arrow are the shapes libraries actually introspect, and those are exact.
7927 // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
7928 // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
7929 // so the same slice works for every form. (`Params_span` is the boundary that
7930 // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
7931 // `source_span` is set only where the reported text is not the function's own
7932 // range — a class's constructor reports the whole class definition.
7933 let reported = func.source_span.unwrap_or(func.span);
7934 state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
7935 state.line = func.span.start.line;
7936 state.column = func.span.start.column;
7937 // A function body has no hidden `<ret>` local; the value comes back on
7938 // the stack. Only a script keeps one.
7939 // Parameters are positional, so even a pattern occupies one argument slot. A
7940 // simple name is that slot itself; anything else (a pattern, a default, a rest
7941 // parameter) takes an anonymous slot and is unpicked into locals at the top of
7942 // the body, which is the only way one argument can bind several names.
7943 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
7944 // `.length` stops at the first parameter that can be substituted: a default
7945 // fills a missing argument in, and a rest parameter absorbs the rest.
7946 let mut defined_args = func.params.len() as u32;
7947 for (index, param) in func.params.iter().enumerate() {
7948 match simple_parameter(param) {
7949 Some(name) => state.args.push(VarDef::var(name.name.clone())),
7950 None => {
7951 state.args.push(VarDef::var(ANONYMOUS_BINDING));
7952 prologue.push((index, param.clone()));
7953 }
7954 }
7955 }
7956 // A default anywhere before the end also ends the count, which the loop above
7957 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
7958 for (position, param) in func.params.iter().enumerate() {
7959 if matches!(
7960 param.kind,
7961 PatternKind::Assign { .. } | PatternKind::Rest(_)
7962 ) {
7963 defined_args = position as u32;
7964 break;
7965 }
7966 }
7967 state.defined_args = defined_args;
7968 state.param_prologue = prologue;
7969 let depth = self.stack.len();
7970 self.stack.push(state);
7971 let result = self.compile_function_body(func);
7972 if result.is_err() {
7973 // A failed compile must not leave its `FnState` behind. Every caller
7974 // reads `self.state()` as "the function being compiled", so a leftover
7975 // frame silently retargets all later bookkeeping at a dead function.
7976 self.stack.truncate(depth);
7977 }
7978 result
7979 }
7980
7981 /// The body of a function, with its frame already pushed.
7982 fn compile_function_body(
7983 &mut self,
7984 func: &ast::Function,
7985 ) -> Result<CompiledFunction, SyntaxError> {
7986 let body_key = func.params_span.end.offset as u64;
7987 // Where the body begins, in source order. The runtime needs this to tell a
7988 // closure created by a default expression from one the body creates — the two see
7989 // different variable environments — and a bytecode offset would not survive the
7990 // instruction shuffling that building the frame does. Positions are in source
7991 // order, so a comparison answers it.
7992 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7993 self.push_block(body_key, NO_PARENT);
7994 self.state().body_block = body_key;
7995 // An arrow with an expression body has no statements; the expression is
7996 // its `return`. Building the statement here keeps one code path below, and
7997 // matters for correctness beyond convenience: returning early with the new
7998 // `FnState` still on the stack would leave the compiler looking at the
7999 // wrong function, which surfaces as an unrelated underflow later.
8000 let concise = match &func.body {
8001 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
8002 StmtKind::Return(Some(Box::new((**value).clone()))),
8003 value.span,
8004 )),
8005 js_parse::ast::FunctionBody::Block(_) => None,
8006 };
8007 let body: &[Stmt] = match &concise {
8008 Some(stmt) => std::slice::from_ref(stmt),
8009 None => func
8010 .body
8011 .statements()
8012 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
8013 };
8014 let prologue = std::mem::take(&mut self.state().param_prologue);
8015 let has_param_scope = self.cur().has_parameter_expressions;
8016 // The parameter scope's own bindings, declared in source order.
8017 //
8018 // With parameter expressions the list gets a variable environment of its own, and
8019 // every name it binds is a `let` there. That is what puts the *list* in the
8020 // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
8021 // and `function f(x = y, y){}` does the same, where a single shared environment
8022 // would answer `undefined` to both.
8023 if has_param_scope {
8024 let mut declared: Vec<String> = Vec::new();
8025 for param in &func.params {
8026 let mut names = Vec::new();
8027 param.bound_names(&mut names);
8028 for name in names {
8029 if declared.contains(&name.name) {
8030 continue;
8031 }
8032 declared.push(name.name.clone());
8033 self.declare_param_binding(&name.name);
8034 }
8035 }
8036 }
8037 // A pattern parameter binds its names as function-scope locals, so they have to
8038 // exist — and be unpicked from the argument — before the body runs. With a
8039 // parameter scope these are the *second* environment: the pattern fills the
8040 // parameter's copy, and the body's binding is filled from it afterwards.
8041 for (_, pattern) in &prologue {
8042 let mut names = Vec::new();
8043 pattern.bound_names(&mut names);
8044 for name in names {
8045 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
8046 }
8047 }
8048 self.hoist(body, body_key)?;
8049 // A constructor's prologue is not a parameter unpacking but the `this` binding:
8050 // a base constructor takes the receiver, a derived one starts in the dead zone
8051 // because only `super()` may produce it.
8052 match self.cur().ctor_kind {
8053 CtorKind::None => {}
8054 CtorKind::Base => {
8055 self.begin_this_local();
8056 self.emit(Opcode::CheckCtor, &[]);
8057 // Instance fields are installed at the top of a base constructor's body,
8058 // before any statement — `class C { x = 1; constructor() { this.x } }` sees
8059 // `1`. This used to be emitted at the *tail*, which made every field read
8060 // `undefined` inside the constructor that declared it.
8061 self.call_field_initialiser();
8062 }
8063 CtorKind::Derived => {
8064 self.declare("this", VarDef::lexical("this"));
8065 let slot = self.cur().vars.len() as u32 - 1;
8066 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8067 self.emit(Opcode::CheckCtor, &[]);
8068 }
8069 }
8070 // Entering the parameter list: everything it binds starts in the dead zone.
8071 // The order is the reference's — it walks the scope chain, which is prepended, so
8072 // the bindings come out newest first.
8073 for name in self.param_binding_names().into_iter().rev() {
8074 if let Some(slot) = self.param_binding_slot(&name) {
8075 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8076 }
8077 }
8078 // The whole parameter list is one scope, and nothing in the body exists yet, so
8079 // every name it mentions resolves against the parameter bindings and outward.
8080 self.state().in_params = has_param_scope;
8081 for (index, param) in func.params.iter().enumerate() {
8082 if let Some(pattern) = prologue_pattern(&prologue, index) {
8083 // A destructuring parameter *initialises* its bindings: with a parameter
8084 // scope they are the list's own `let`s, which is why the stores skip the
8085 // dead-zone check, and why the reference reads their properties with
8086 // `get_field2` — a `let` needs no reference.
8087 let kind = if has_param_scope {
8088 VarDeclKind::Let
8089 } else {
8090 VarDeclKind::Var
8091 };
8092 match &pattern.kind {
8093 // `...rest` collects what is left rather than reading one slot.
8094 PatternKind::Rest(inner) => {
8095 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8096 self.destructure(inner, Some(kind))?;
8097 }
8098 _ => {
8099 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8100 self.destructure(pattern, Some(kind))?;
8101 }
8102 }
8103 continue;
8104 }
8105 // A plain name binds straight from its argument slot. With a parameter scope
8106 // the slot is also copied into the parameter binding, which is what a later
8107 // default (or a closure made among the defaults) reads.
8108 let Some(name) = simple_parameter(param) else {
8109 continue;
8110 };
8111 let target = self.param_binding_slot(&name.name);
8112 if matches!(param.kind, PatternKind::Rest(_)) {
8113 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8114 if let Some(slot) = target {
8115 self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
8116 }
8117 // `put_arg` rather than `set_arg`: the array is the last thing on the
8118 // stack and nothing keeps it. Named by hand because a name in the
8119 // parameter list resolves to the parameter binding, and this store has to
8120 // reach the *argument* — that is what the body reads.
8121 self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
8122 continue;
8123 }
8124 if let PatternKind::Assign { default, .. } = ¶m.kind {
8125 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8126 let has_value = self.new_label();
8127 self.emit(Opcode::Dup, &[]);
8128 self.emit(Opcode::IsUndefined, &[]);
8129 self.emit_jump(Opcode::IfFalse, has_value, &[]);
8130 self.emit(Opcode::Drop, &[]);
8131 self.expr(default)?;
8132 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
8133 // The argument slot keeps the substituted value, because the *body* reads
8134 // the slot rather than the parameter binding — so this store is named
8135 // explicitly, like the rest parameter's.
8136 self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8137 self.place_label(has_value);
8138 if let Some(slot) = target {
8139 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8140 }
8141 continue;
8142 }
8143 if let Some(slot) = target {
8144 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8145 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8146 }
8147 }
8148 // Copy the parameter scope into the body. A plain parameter needs nothing: the
8149 // body reads its argument slot, and the list kept the two in step. A name a
8150 // pattern bound has no argument slot of its own, so the body gets a `var` filled
8151 // from the parameter's copy — and *that* is why an assignment inside a default
8152 // does not reach the body.
8153 if has_param_scope {
8154 for (_, pattern) in &prologue {
8155 let mut names = Vec::new();
8156 pattern.bound_names(&mut names);
8157 for name in names {
8158 let Some(slot) = self.param_binding_slot(&name.name) else {
8159 continue;
8160 };
8161 let Some(body) = self.body_var_slot(&name.name) else {
8162 continue;
8163 };
8164 self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
8165 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
8166 }
8167 }
8168 }
8169 // The parameter list is over; from here on a direct `eval` belongs to the body.
8170 self.state().in_params = false;
8171 // Entering the body's own scope comes *after* the parameter list: the body's
8172 // `let`s are not in existence while the defaults run, and the reference emits
8173 // their `set_loc_uninitialized` only once the parameters are bound.
8174 self.emit_scope_enter(body_key);
8175 // A generator starts suspended: `initial_yield` parks the body so that creating one
8176 // runs no body code until the first `next()`.
8177 //
8178 // It comes *after* the parameter unpacking, not before, because a parameter
8179 // initialiser is not body code — `function* g(a = sideEffect())` must run
8180 // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
8181 // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
8182 // until the first `next()` and 29 test262 cases that check for a synchronous throw
8183 // saw none at all.
8184 //
8185 // An async function does **not** get one. Its body runs synchronously up to the
8186 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
8187 // before its caller's next statement — so an `initial_yield` here would park the
8188 // body before it started, which is not fixable at run time: the suspension looks
8189 // exactly like a real `await`.
8190 if self.cur().kind.is_generator() {
8191 self.emit(Opcode::InitialYield, &[]);
8192 }
8193 // Through `stmts`: the body is a block, and a `using` declaration in it is a
8194 // disposal region.
8195 self.stmts(body)?;
8196 // The implicit return only exists if control can actually get here: an
8197 // infinite loop never falls off the end.
8198 if self.end_is_reachable() {
8199 if self.cur().is_suspending() {
8200 // Falling off the end finishes the generator with `undefined`, and the
8201 // value is what tells the resume machinery "completed" rather than
8202 // "suspended".
8203 self.emit(Opcode::Undefined, &[]);
8204 self.emit(Opcode::ReturnAsync, &[]);
8205 } else {
8206 self.emit_class_constructor_tail();
8207 }
8208 }
8209 // Resolution runs while this function is still on the stack: capturing a
8210 // variable from an enclosing function means reaching into that
8211 // function's state, which requires the whole chain to be present.
8212 Ok(self.finish_current())
8213 }
8214
8215 /// Put every binding of a function that contains a direct `eval` into a cell.
8216 ///
8217 /// A direct eval can name any binding in scope, and any closure it creates has to
8218 /// keep sharing that binding after the function returns — `for (let i …)
8219 /// eval("push(() => i)")` collects one closure per iteration and each must read its
8220 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
8221 /// a cell. Doing this unconditionally for such functions is the cheap, honest
8222 /// answer: the alternative is knowing at compile time which names a string will
8223 /// mention.
8224 fn capture_everything_for_eval(&mut self) {
8225 let current = self.stack.len() - 1;
8226 if !self.stack[current].has_direct_eval {
8227 return;
8228 }
8229 for arg in &mut self.stack[current].args {
8230 arg.is_captured = true;
8231 }
8232 for var in &mut self.stack[current].vars {
8233 var.is_captured = true;
8234 }
8235 }
8236
8237 /// Whether the current position in the instruction stream can be reached.
8238 ///
8239 /// A walk over the control-flow graph, using labels as instruction indices.
8240 /// The reference does the same thing to decide whether an implicit
8241 /// `return_undef` is needed.
8242 fn end_is_reachable(&self) -> bool {
8243 let state = self.cur();
8244 reachable_instructions(state, state.insns.len())[state.insns.len()]
8245 }
8246
8247 /// Resolve and assemble the function on top of the compiler stack, then pop
8248 /// it.
8249 fn finish_current(&mut self) -> CompiledFunction {
8250 self.provide_param_arguments();
8251 self.provide_arguments();
8252 self.provide_this_local();
8253 self.provide_new_target_local();
8254 self.provide_home_object_local();
8255 self.provide_active_func_local();
8256 self.provide_self_name();
8257 self.materialize_eval_sites();
8258 self.capture_everything_for_eval();
8259 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
8260 // Captured bindings need a reference cell; the count goes in the header so
8261 // the runtime knows how many cells to allocate on entry.
8262 let current = self.stack.len() - 1;
8263 let captured = self.stack[current]
8264 .args
8265 .iter()
8266 .filter(|a| a.is_captured)
8267 .count()
8268 + self.stack[current]
8269 .vars
8270 .iter()
8271 .filter(|v| v.is_captured)
8272 .count();
8273 self.stack[current].var_ref_count = captured as u32;
8274 // The scope chain is only final now that every binding is known.
8275 rebuild_scope_chain(&mut self.stack[current]);
8276 let (code, stack_size, positions) =
8277 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
8278 let _ = &mut resolved;
8279 let mut state = self.stack.pop().expect("a function is being compiled");
8280 CompiledFunction {
8281 name: state.name,
8282 kind: state.kind,
8283 strict: state.strict,
8284 is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
8285 is_arrow: state.is_arrow,
8286 has_parameter_expressions: state.has_parameter_expressions,
8287 simple_parameter_list: state.simple_parameter_list,
8288 body_start: state.body_start,
8289 args: state.args,
8290 defined_args: state.defined_args,
8291 vars: state.vars,
8292 closure_vars: state.closure_vars,
8293 cpool: state.cpool,
8294 atoms: state.atoms,
8295 code,
8296 stack_size,
8297 var_ref_count: state.var_ref_count,
8298 positions,
8299 source: self.function_source(state.span, state.line, state.column),
8300 line: state.line,
8301 column: state.column,
8302 filename: None,
8303 eval_sites: state.eval_sites,
8304 module: state.module.take().map(Box::new),
8305 }
8306 }
8307}
8308
8309/// Assign each binding a scope level and rebuild the scope chains.
8310///
8311/// Levels are numbered in the order the blocks appear, with 0 reserved for the
8312/// function scope where `var` and hoisted functions live. Every binding outside
8313/// level 0 gets a `scope_next` link to the next binding visible from the same
8314/// point, so walking a block's chain enumerates exactly the bindings live there.
8315///
8316/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
8317/// point at `b`, which is declared later in the source but earlier in the chain.
8318fn rebuild_scope_chain(state: &mut FnState) {
8319 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
8320 // real block that happens to start at offset zero keeps its own level instead of
8321 // being merged into the function scope.
8322 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
8323 for block in &state.blocks {
8324 if !levels.contains(&block.key) {
8325 levels.push(block.key);
8326 }
8327 }
8328 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
8329 let parent_level = |level: usize| -> usize {
8330 if level == 0 {
8331 return 0;
8332 }
8333 let key = levels[level];
8334 let parent = state
8335 .blocks
8336 .iter()
8337 .find(|b| b.key == key)
8338 .map(|b| b.parent)
8339 .unwrap_or(FUNCTION_SCOPE);
8340 level_of(parent)
8341 };
8342
8343 // Own bindings per level, in declaration order.
8344 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
8345 let keys: Vec<u64> = (0..state.vars.len())
8346 .map(|index| {
8347 state
8348 .var_block
8349 .get(index)
8350 .copied()
8351 .unwrap_or(FUNCTION_SCOPE)
8352 })
8353 .collect();
8354 for (index, key) in keys.into_iter().enumerate() {
8355 // The parameter scope is not a block: it is a level of its own with no parent,
8356 // assigned below. Letting it land in level 0 would chain the body's bindings onto
8357 // it, which the reference does not do — the two environments are siblings.
8358 if key == PARAM_SCOPE {
8359 continue;
8360 }
8361 let level = level_of(key);
8362 state.vars[index].scope_level = level as u32;
8363 // A `catch` parameter is part of the runtime scope chain even though it is
8364 // not lexical: the handler's own bindings chain on to it, which is why the
8365 // reference prints `let y [next:1]` with `e` at 1.
8366 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
8367 {
8368 own[level].push(index);
8369 }
8370 }
8371
8372 // A scope's chain is its own bindings in reverse declaration order followed
8373 // by the enclosing scope's chain.
8374 let mut head = vec![-1i32; levels.len()];
8375 for level in 0..levels.len() {
8376 let inherited = if level == 0 {
8377 -1
8378 } else {
8379 head[parent_level(level)]
8380 };
8381 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
8382 head[level] = chain.first().map_or(inherited, |first| *first as i32);
8383 for (position, &index) in chain.iter().enumerate() {
8384 let next = chain
8385 .get(position + 1)
8386 .map_or(inherited, |next| *next as i32);
8387 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
8388 }
8389 }
8390 state.block_heads = head;
8391
8392 // The parameter list is a scope of its own, and it has no parent: the reference pops
8393 // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
8394 // the `-1` a block uses. A level past every real block keeps it out of the walk above
8395 // — nothing but the dump reads it — and the links run newest-to-oldest through the
8396 // bindings themselves, which is the order `set_loc_uninitialized` walks.
8397 let param_level = levels.len() as u32;
8398 let mut previous: Option<usize> = None;
8399 for index in 0..state.vars.len() {
8400 if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
8401 {
8402 continue;
8403 }
8404 state.vars[index].scope_level = param_level;
8405 state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
8406 previous = Some(index);
8407 }
8408}
8409
8410/// This is where names become slots and where the temporal dead zone shows up in
8411/// the instruction stream: a read of a `let`/`const` binding compiles to
8412/// `get_loc_check`, which throws if the binding is still uninitialised.
8413///
8414/// The peephole pass from the reference implementation is applied at the end,
8415/// for the same reason it is applied to resolved bytecode there: the patterns are
8416/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
8417/// resolution. Deleted instructions stay in the list as `None` so that label
8418/// indices remain valid; [`Assembler`] maps them to byte offsets.
8419/// A resolved instruction and the source position it came from.
8420type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
8421
8422/// A resolved instruction paired with its position, which is what `assemble` consumes.
8423type PositionedInsn = (Opcode, Vec<Op>);
8424
8425fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
8426 let current = stack.len() - 1;
8427 // Dead-code elimination, on the symbolic form where labels are still
8428 // instruction indices. A `break` inside a loop leaves the trailing `goto`
8429 // unreachable, and a `return` leaves everything after it unreachable; the
8430 // reference drops both. Doing it here means the emitter never has to think
8431 // about reachability.
8432 strip_empty_gosubs(stack, current);
8433 eliminate_dead_code(stack, current);
8434 let insns = std::mem::take(&mut stack[current].insns);
8435 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
8436 // `insns`, and every arm below pushes exactly one instruction, so the positions
8437 // stay aligned with `out`.
8438 let positions = std::mem::take(&mut stack[current].insn_pos);
8439 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
8440 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8441 for (index, insn) in insns.iter().enumerate() {
8442 let pos = positions.get(index).copied().flatten();
8443 out_pos.push(pos);
8444 match insn {
8445 Insn::Fixed { op, operands } => {
8446 let operands = operands
8447 .iter()
8448 .map(|operand| match operand {
8449 Op::Atom(atom) => {
8450 Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
8451 }
8452 other => other.clone(),
8453 })
8454 .collect();
8455 out.push(Some((*op, operands)));
8456 }
8457 Insn::Var {
8458 action,
8459 name,
8460 block,
8461 in_params,
8462 } => {
8463 // Both reads and writes in the parameter list address the parameter
8464 // scope. That is what puts the list in the temporal dead zone — a read of
8465 // a later parameter is `get_loc_check` on an uninitialised slot — and it
8466 // is also what keeps an assignment made inside a default away from the
8467 // body, which sees a separate environment.
8468 let slot = resolve_slot(stack, current, name, *block, *in_params);
8469 // A store to the name of a named function expression is special: the
8470 // reference drops it in sloppy mode and throws in strict mode, because
8471 // the binding is immutable but only *checked* when the body is strict.
8472 // The same rule applies when the name is reached through a closure:
8473 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8474 // the store in the arrow too, not just in the function that owns the
8475 // binding. Reaching the owner means walking the chain of closure
8476 // entries, which is what `self_name_binding` does.
8477 let self_name = matches!(action, VarAction::Put | VarAction::Set)
8478 .then(|| {
8479 // A local of this function is the common case and needs no
8480 // chain walk; only an access that resolves elsewhere can be
8481 // pointing at an enclosing function's name binding.
8482 if let Slot::Loc(index) = slot {
8483 stack[current]
8484 .vars
8485 .get(index as usize)
8486 .filter(|var| var.kind == VarKind::FunctionName)
8487 .map(|var| var.is_const)
8488 } else {
8489 self_name_binding(stack, current, name, *block)
8490 }
8491 })
8492 .flatten();
8493 if let Some(is_const) = self_name {
8494 out.push(Some(if is_const {
8495 (
8496 Opcode::ThrowError,
8497 vec![
8498 Op::AtomId(intern_atom(&mut stack[current], name)),
8499 Op::Int(0),
8500 ],
8501 )
8502 } else {
8503 (Opcode::Drop, Vec::new())
8504 }));
8505 continue;
8506 }
8507 out.push(Some(variable_instruction(stack, current, *action, slot)));
8508 }
8509 Insn::CloseCaptured { name, block } => {
8510 // The block matters: a loop variable is scoped to the `for` head's own
8511 // block, so resolving it against block 0 would miss it entirely and
8512 // silently emit nothing.
8513 let slot = resolve_slot(stack, current, name, *block, false);
8514 // Only a local with a reference cell has anything to close. A global
8515 // or a never-captured local resolves to no instruction at all, which
8516 // keeps the bytecode identical to the reference's.
8517 if let Slot::Loc(index) = slot
8518 && stack[current]
8519 .vars
8520 .get(index as usize)
8521 .is_some_and(|v| v.is_captured)
8522 {
8523 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
8524 } else {
8525 out.push(None);
8526 }
8527 }
8528 Insn::DeleteVar { name } => {
8529 // A binding — a local, an argument, or a declared global — cannot be
8530 // deleted, and the reference encodes that as a constant `push_false`.
8531 // Only an implicit global needs the runtime lookup.
8532 if matches!(
8533 resolve_slot(stack, current, name, 0, false),
8534 Slot::Global(_)
8535 ) {
8536 let atom = intern_atom(&mut stack[current], name);
8537 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
8538 } else {
8539 out.push(Some((Opcode::PushFalse, Vec::new())));
8540 }
8541 }
8542 Insn::Dead => out.push(None),
8543 }
8544 }
8545 // Which label (if any) sits on each instruction, so the jump patterns can
8546 // tell whether they would cross a jump target.
8547 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
8548 for (id, placed) in stack[current].labels.iter().enumerate() {
8549 if let Some(index) = *placed
8550 && index < label_at.len()
8551 && label_at[index].is_none()
8552 {
8553 label_at[index] = Some(id as u32);
8554 }
8555 }
8556 if std::env::var_os("QJS_DEBUG").is_some() {
8557 eprintln!("--- peephole entry ---");
8558 for (i, e) in out.iter().enumerate() {
8559 eprintln!("{i}: {e:?}");
8560 }
8561 eprintln!("label_at: {label_at:?}");
8562 }
8563 peephole(&mut out, &label_at, &stack[current].labels);
8564 (out, out_pos)
8565}
8566
8567/// Find where `name` lives, capturing it in an enclosing function when needed.
8568///
8569/// The search runs outward through the enclosing functions' states, which are
8570/// still on the compiler stack while a nested function is resolved. Finding the
8571/// name in an enclosing function is what creates a closure reference, and every
8572/// function in between has to forward it — a function can only reach its own
8573/// parent's frame.
8574///
8575/// A name declared nowhere is a global. The reference does *not* look it up by
8576/// name from the inner function: the top-level function gets one `[global]`
8577/// entry and every nested function gets a `[global_ref<n>]` pointing at its
8578/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
8579/// rather than `[global]`.
8580/// The lexical blocks enclosing `block`, innermost first.
8581fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
8582 let mut chain = Vec::new();
8583 let mut current = Some(block);
8584 while let Some(key) = current {
8585 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
8586 // explicitly (rather than on "no block with this key") is what keeps a block
8587 // that happens to sit at offset zero from being mistaken for the terminator.
8588 if key == NO_PARENT || chain.contains(&key) {
8589 break;
8590 }
8591 chain.push(key);
8592 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
8593 }
8594 chain
8595}
8596
8597/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
8598///
8599/// The binding may be several functions away: an arrow nested in `function myfunc`
8600/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
8601/// means following `Ref` entries down and then reading the owning function's var table.
8602fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
8603 let state = stack.get(current)?;
8604 // A parameter shadows everything and is never a function-expression name.
8605 if state.args.iter().any(|arg| arg.name == name) {
8606 return None;
8607 }
8608 // A local of this very function: the answer is in its var table.
8609 if let Some(index) = local_slot_index(state, name, block) {
8610 let var = state.vars.get(index)?;
8611 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8612 }
8613 // Otherwise the name lives further out, and the closure entry says how to get
8614 // there. `Local` names the owner's slot directly; `Ref` names the next level's
8615 // closure entry, so the walk continues downwards.
8616 let mut level = current;
8617 let mut index = state
8618 .closure_vars
8619 .iter()
8620 .position(|closure| closure.name == name)?;
8621 loop {
8622 let state = stack.get(level)?;
8623 let closure = state.closure_vars.get(index)?;
8624 match closure.closure_type {
8625 ClosureType::Local => {
8626 let owner = stack.get(level.checked_sub(1)?)?;
8627 let var = owner.vars.get(closure.var_idx as usize)?;
8628 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8629 }
8630 ClosureType::Arg => return None,
8631 ClosureType::Ref => {
8632 level -= 1;
8633 index = closure.var_idx as usize;
8634 }
8635 // A global is never a function-expression name.
8636 ClosureType::Global
8637 | ClosureType::GlobalDecl
8638 | ClosureType::GlobalRef
8639 | ClosureType::ModuleDecl
8640 | ClosureType::ModuleImport => return None,
8641 }
8642 }
8643}
8644
8645/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
8646fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
8647 block_chain(state, block).into_iter().find_map(|scope| {
8648 state.vars.iter().enumerate().find_map(|(index, var)| {
8649 (var.name == name && state.var_block.get(index).copied() == Some(scope))
8650 .then_some(index)
8651 })
8652 })
8653}
8654
8655/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
8656fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
8657 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
8658 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
8659 }) {
8660 return index as u32;
8661 }
8662 state.var_block.push(PARAM_SCOPE);
8663 state.vars.push(VarDef::var(name));
8664 state.vars.len() as u32 - 1
8665}
8666
8667/// The name a parameter binds straight from its argument slot, if it has one.
8668///
8669/// A plain name does — with or without a default, and with or without `...`. Everything
8670/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
8671/// reference names the argument in the first case and leaves it `<null>` in the second,
8672/// so both the dump and the closures that capture the argument depend on this.
8673fn simple_parameter(param: &Pattern) -> Option<&Ident> {
8674 match ¶m.kind {
8675 PatternKind::Ident(name) => Some(name),
8676 PatternKind::Assign { target, .. } => match &target.kind {
8677 PatternKind::Ident(name) => Some(name),
8678 _ => None,
8679 },
8680 PatternKind::Rest(inner) => match &inner.kind {
8681 PatternKind::Ident(name) => Some(name),
8682 _ => None,
8683 },
8684 _ => None,
8685 }
8686}
8687
8688/// The pattern a parameter list has to unpick, if `index` is one of them.
8689fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
8690 prologue
8691 .iter()
8692 .find(|(at, _)| *at == index)
8693 .map(|(_, pattern)| pattern)
8694}
8695
8696fn pattern_has_default(pattern: &Pattern) -> bool {
8697 match &pattern.kind {
8698 PatternKind::Assign { .. } => true,
8699 PatternKind::Rest(inner) => pattern_has_default(inner),
8700 PatternKind::Array { elements, rest } => {
8701 elements.iter().flatten().any(element_has_default)
8702 || rest.as_deref().is_some_and(rest_has_default)
8703 }
8704 PatternKind::Object { properties, rest } => {
8705 properties.iter().flatten().any(element_has_default)
8706 || rest.as_deref().is_some_and(rest_has_default)
8707 }
8708 _ => false,
8709 }
8710}
8711
8712fn element_has_default(element: &PatternElement) -> bool {
8713 match element {
8714 PatternElement::Pattern(pattern) => pattern_has_default(pattern),
8715 PatternElement::Property { value, .. } => pattern_has_default(value),
8716 }
8717}
8718
8719fn rest_has_default(rest: &RestElement) -> bool {
8720 match rest {
8721 RestElement::Pattern(pattern) => pattern_has_default(pattern),
8722 RestElement::Member(_) => false,
8723 }
8724}
8725
8726/// Whether a function-scope binding is visible to the parameter list.
8727///
8728/// The parameter list runs before the body, so the body's `var`s and function
8729/// declarations do not exist yet — a name that only the body declares has to resolve
8730/// outward instead. What *does* exist by then is the compiler's own prologue: the
8731/// self-name of a named function expression (bound by `special_object 2` before anything
8732/// else), `this` and `new.target`. Those stay visible, which is what makes
8733/// `function f(a = this)` and `var f = function f(a = f)` work.
8734///
8735/// `arguments` is handled separately, as a binding of the parameter scope itself: with
8736/// parameter expressions the reference creates two of them, and the one the parameter
8737/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
8738fn visible_in_params(var: &VarDef) -> bool {
8739 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
8740}
8741
8742fn resolve_slot(
8743 stack: &mut [FnState],
8744 current: usize,
8745 name: &str,
8746 block: u64,
8747 in_params: bool,
8748) -> Slot {
8749 // The parameter list's own bindings. They are consulted first because they shadow
8750 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
8751 // `a` in the parameter scope, so a closure made there reads the parameter even after
8752 // the body assigns to its own `a`.
8753 if in_params
8754 && let Some(index) = stack[current]
8755 .vars
8756 .iter()
8757 .enumerate()
8758 .position(|(index, var)| {
8759 var.name == name
8760 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
8761 })
8762 {
8763 return Slot::Loc(index as u32);
8764 }
8765 // A name can be bound more than once: two `catch` parameters in nested
8766 // handlers are two slots. The binding that wins is the one whose scope encloses
8767 // the access, and among those the innermost — so the blocks are walked outward
8768 // and the first binding found on the way is the one that counts. A binding in
8769 // no block (`var`) is reachable from anywhere, which is why the function scope
8770 // is the end of the walk.
8771 //
8772 // The block walk comes *before* the argument slots, because a block may shadow a
8773 // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
8774 // slot is only the answer once nothing nearer claims the name.
8775 let chain = block_chain(&stack[current], block);
8776 for scope in &chain {
8777 let found = stack[current]
8778 .vars
8779 .iter()
8780 .enumerate()
8781 .find(|(index, var)| {
8782 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
8783 })
8784 .map(|(index, _)| index);
8785 if let Some(index) = found {
8786 return Slot::Loc(index as u32);
8787 }
8788 }
8789 // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
8790 // its own slot, and `var` of the same name in the body is the same binding.
8791 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
8792 return Slot::Arg(index as u32);
8793 }
8794 // Function-scope bindings — `var` and function declarations — are recorded with
8795 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
8796 // them. They are reachable from anywhere in the function, which is exactly what
8797 // the sentinel means.
8798 //
8799 // This pass is *only* for those. A lexical binding has to be found through the
8800 // chain or not at all, and looking a name up without its block is precisely how
8801 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
8802 // block leaked out of it.
8803 let function_scoped = stack[current]
8804 .vars
8805 .iter()
8806 .enumerate()
8807 .find(|(index, var)| {
8808 var.name == name
8809 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
8810 && (!in_params || visible_in_params(var))
8811 })
8812 .map(|(index, _)| index);
8813 if let Some(index) = function_scoped {
8814 return Slot::Loc(index as u32);
8815 }
8816 if let Some(index) = stack[current]
8817 .closure_vars
8818 .iter()
8819 .position(|c| c.name == name)
8820 {
8821 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
8822 }
8823
8824 for owner in (0..current).rev() {
8825 // The nested function was created inside one of this frame's blocks, and the
8826 // outermost visible binding is the innermost block on that chain — not whatever
8827 // comes first in the variable table. `function f(){ class S{} }` has two `S`
8828 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
8829 // the class body is the one a method may see.
8830 let entry = stack
8831 .get(owner + 1)
8832 .map(|s| s.created_in_block)
8833 .unwrap_or(0);
8834 let lexical = block_chain(&stack[owner], entry)
8835 .into_iter()
8836 .find_map(|scope| {
8837 stack[owner]
8838 .vars
8839 .iter()
8840 .enumerate()
8841 .find(|(index, var)| {
8842 var.name == name
8843 && stack[owner].var_block.get(*index).copied() == Some(scope)
8844 })
8845 .map(|(index, _)| index)
8846 });
8847 // A function born in a parameter list sees that list's bindings, not the body's:
8848 // the parameter scope is the environment it was created in.
8849 let in_param_scope = stack
8850 .get(owner + 1)
8851 .is_some_and(|child| child.created_in_params)
8852 .then(|| {
8853 stack[owner]
8854 .vars
8855 .iter()
8856 .enumerate()
8857 .position(|(index, var)| {
8858 var.name == name
8859 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
8860 })
8861 })
8862 .flatten();
8863 let found = if let Some(index) = in_param_scope {
8864 let var = &stack[owner].vars[index];
8865 Some(Found::Local(
8866 ClosureType::Local,
8867 index as u32,
8868 var.is_const,
8869 var.needs_check(),
8870 ))
8871 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
8872 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
8873 } else if let Some(index) = lexical {
8874 let var = &stack[owner].vars[index];
8875 Some(Found::Local(
8876 ClosureType::Local,
8877 index as u32,
8878 var.is_const,
8879 var.needs_check(),
8880 ))
8881 } else if let Some(index) = stack[owner]
8882 .vars
8883 .iter()
8884 .enumerate()
8885 .find_map(|(index, var)| {
8886 // A function created inside a parameter list must not see the body of the
8887 // function it was born in; see [`FnState::created_in_params`].
8888 let hidden = stack
8889 .get(owner + 1)
8890 .is_some_and(|child| child.created_in_params);
8891 (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
8892 })
8893 {
8894 let var = &stack[owner].vars[index];
8895 Some(Found::Local(
8896 ClosureType::Local,
8897 index as u32,
8898 var.is_const,
8899 var.needs_check(),
8900 ))
8901 } else if stack[owner].self_name.as_deref() == Some(name) {
8902 // A named function expression's own name. The reference declares it here,
8903 // on the first lookup that fails, rather than up front — and that is what
8904 // makes it reachable from a *nested* function: the nested lookup is what
8905 // walks out and creates the binding. A direct reference in the body is
8906 // caught the same way, which is why `provide_self_name` only has to add
8907 // the prologue.
8908 let strict = stack[owner].strict;
8909 stack[owner].var_block.push(FUNCTION_SCOPE);
8910 stack[owner].vars.push(VarDef {
8911 kind: VarKind::FunctionName,
8912 // In strict mode the name is immutable, so a store raises; sloppy
8913 // mode drops the store instead (see `variable_instruction`).
8914 is_const: strict,
8915 ..VarDef::var(name)
8916 });
8917 let index = stack[owner].vars.len() as u32 - 1;
8918 Some(Found::Local(ClosureType::Local, index, strict, false))
8919 } else if let Some(index) = stack[owner]
8920 .closure_vars
8921 .iter()
8922 .position(|c| c.name == name)
8923 {
8924 let closure = &stack[owner].closure_vars[index];
8925 Some(match closure.closure_type {
8926 // `GlobalRef` belongs here too: it is a *global* reached through this
8927 // frame's reference table, so treating it as a `Ref` to a local cell makes
8928 // the reader look for a cell no frame ever fills. That is how a second
8929 // function using `eval` in its parameter list read `undefined` after a
8930 // sibling had already made `eval` a closure entry.
8931 ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
8932 Found::Global(index as u32)
8933 }
8934 // A module variable is a cell in the *module's* environment, which is
8935 // the module body's parent as far as a nested function is concerned — so
8936 // it is captured as a plain reference, not looked up as a global.
8937 ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
8938 ClosureType::Ref,
8939 index as u32,
8940 closure.is_const,
8941 closure.is_lexical,
8942 ),
8943 _ => Found::Local(
8944 ClosureType::Ref,
8945 index as u32,
8946 closure.is_const,
8947 closure.is_lexical,
8948 ),
8949 })
8950 } else {
8951 None
8952 };
8953 let Some(found) = found else { continue };
8954
8955 let (is_const, is_lexical) = match found {
8956 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
8957 Found::Global(_) => (false, false),
8958 };
8959 // Mark the owner's binding as captured so it moves into a reference cell.
8960 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
8961 let slot = match found {
8962 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8963 _ => &mut stack[owner].vars[index as usize],
8964 };
8965 slot.is_captured = true;
8966 }
8967 // Forward the reference through every function in between.
8968 let mut previous = match found {
8969 Found::Local(kind, index, _, _) => (kind, index),
8970 Found::Global(index) => (ClosureType::Global, index),
8971 };
8972 for level in owner + 1..=current {
8973 let kind = match (previous.0, level) {
8974 // A global stays a global at *every* level. Without `GlobalRef` in
8975 // this arm the second nested function over the same global got a
8976 // `Ref` to a cell no frame ever held, so the innermost closure read
8977 // `undefined` — which is how a two-deep getter lost its outer
8978 // variable.
8979 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8980 ClosureType::GlobalRef
8981 }
8982 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8983 _ => ClosureType::Ref,
8984 };
8985 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8986 previous = (kind, index);
8987 }
8988 let index = previous.1;
8989 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8990 }
8991
8992 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8993 // creating a property. The top-level function holds the entry.
8994 let mut previous = (
8995 ClosureType::Global,
8996 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8997 );
8998 for level in 1..=current {
8999 let index = ensure_closure(
9000 stack,
9001 level,
9002 name,
9003 false,
9004 false,
9005 ClosureType::GlobalRef,
9006 previous.1,
9007 );
9008 previous = (ClosureType::GlobalRef, index);
9009 }
9010 Slot::Global(previous.1)
9011}
9012
9013/// What an outward search turned up.
9014#[derive(Debug, Clone, Copy)]
9015enum Found {
9016 /// A binding in an enclosing function, reachable through a closure of this
9017 /// type, with its const/lexical flags.
9018 Local(ClosureType, u32, bool, bool),
9019 /// A global, reached through the enclosing function's closure entry.
9020 Global(u32),
9021}
9022
9023/// Add a closure entry to `level` if it is not there yet.
9024fn ensure_closure(
9025 stack: &mut [FnState],
9026 level: usize,
9027 name: &str,
9028 is_const: bool,
9029 is_lexical: bool,
9030 closure_type: ClosureType,
9031 var_idx: u32,
9032) -> u32 {
9033 if let Some(index) = stack[level]
9034 .closure_vars
9035 .iter()
9036 .position(|c| c.name == name)
9037 {
9038 return index as u32;
9039 }
9040 stack[level].closure_vars.push(ClosureVar {
9041 name: name.to_string(),
9042 is_const,
9043 is_lexical,
9044 closure_type,
9045 var_idx: var_idx as u16,
9046 });
9047 stack[level].closure_vars.len() as u32 - 1
9048}
9049
9050fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
9051 match closure.closure_type {
9052 // A `global_ref` only says *how* the binding is found (through the
9053 // parent's closure table); the access itself is an ordinary global one.
9054 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
9055 ClosureType::GlobalDecl => Slot::GlobalDecl(index),
9056 // A module variable is a real cell in the module's environment, so it is reached
9057 // exactly like a captured local — the host, not the global object, is what fills
9058 // the slot.
9059 ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
9060 _ => Slot::VarRef(index),
9061 }
9062}
9063
9064/// Pick the opcode for one variable access.
9065///
9066/// The `_check` variants are what enforce the temporal dead zone. They are used
9067/// for every access to a `let`/`const` binding except its own initialisation —
9068/// which is exactly the operation that takes the binding out of the dead zone.
9069fn variable_instruction(
9070 stack: &[FnState],
9071 current: usize,
9072 action: VarAction,
9073 slot: Slot,
9074) -> (Opcode, Vec<Op>) {
9075 let lexical = match slot {
9076 Slot::Loc(index) => stack[current]
9077 .vars
9078 .get(index as usize)
9079 .is_some_and(|v| v.needs_check()),
9080 Slot::VarRef(index) => stack[current]
9081 .closure_vars
9082 .get(index as usize)
9083 .is_some_and(|c| c.is_lexical),
9084 _ => false,
9085 };
9086 let operand = vec![Op::Slot(slot)];
9087 match (action, slot) {
9088 (VarAction::Get, Slot::Loc(index)) => (
9089 if lexical {
9090 Opcode::GetLocCheck
9091 } else {
9092 Opcode::GetLoc
9093 },
9094 vec![Op::Slot(Slot::Loc(index))],
9095 ),
9096 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
9097 (VarAction::Get, Slot::VarRef(index)) => (
9098 if lexical {
9099 Opcode::GetVarRefCheck
9100 } else {
9101 Opcode::GetVarRef
9102 },
9103 vec![Op::Slot(Slot::VarRef(index))],
9104 ),
9105 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
9106 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
9107 // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
9108 // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
9109 // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
9110 // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
9111 // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
9112 // `ReferenceError`.
9113 (VarAction::GetUndef, Slot::Loc(index)) => (
9114 if lexical {
9115 Opcode::GetLocCheck
9116 } else {
9117 Opcode::GetLoc
9118 },
9119 vec![Op::Slot(Slot::Loc(index))],
9120 ),
9121 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
9122 (VarAction::GetUndef, Slot::VarRef(index)) => (
9123 if lexical {
9124 Opcode::GetVarRefCheck
9125 } else {
9126 Opcode::GetVarRef
9127 },
9128 vec![Op::Slot(Slot::VarRef(index))],
9129 ),
9130 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9131 (Opcode::GetVarUndef, operand)
9132 }
9133
9134 (VarAction::Put, Slot::Loc(_)) => (
9135 if lexical {
9136 Opcode::PutLocCheck
9137 } else {
9138 Opcode::PutLoc
9139 },
9140 operand,
9141 ),
9142 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
9143 (VarAction::Put, Slot::VarRef(_)) => (
9144 if lexical {
9145 Opcode::PutVarRefCheck
9146 } else {
9147 Opcode::PutVarRef
9148 },
9149 operand,
9150 ),
9151 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
9152 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9153 // Initialisation is what ends the dead zone, so it never checks.
9154 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9155 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
9156 // `this` in a derived constructor is always a local, so these cannot happen;
9157 // routing them to the ordinary forms keeps the match total without inventing
9158 // opcodes the reference does not have.
9159 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
9160 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9161 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9162 (Opcode::PutVarInit, operand)
9163 }
9164 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
9165 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9166 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9167 (Opcode::PutVarInit, operand)
9168 }
9169 (VarAction::Set, Slot::Loc(_)) => (
9170 if lexical {
9171 Opcode::SetLocCheck
9172 } else {
9173 Opcode::SetLoc
9174 },
9175 operand,
9176 ),
9177 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
9178 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
9179 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9180 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9181 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
9182 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9183 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
9184 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
9185 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9186 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
9187 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9188 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
9189 }
9190}
9191
9192/// The instruction-rewriting pass.
9193///
9194/// These are the reference implementation's patterns, restricted to the ones the
9195/// constructs this compiler supports can produce. Each entry is a comment on the
9196/// bytecode it removes, because the whole point is that the result is one
9197/// instruction shorter than the literal translation of the AST.
9198fn peephole(
9199 insns: &mut [Option<(Opcode, Vec<Op>)>],
9200 label_at: &[Option<u32>],
9201 placed: &[Option<usize>],
9202) {
9203 fold_dup_patterns(insns, label_at);
9204
9205 // `drop` before `return_undef` is dead: the return discards the whole frame
9206 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
9207 // consumes its own `drop`; removing the drop first would leave the `dup` and
9208 // produce a `set_` where the reference has a `put_`.
9209 for index in 0..insns.len() {
9210 if opcode_at(insns, index) != Some(Opcode::Drop) {
9211 continue;
9212 }
9213 // Skip over a run of drops, but stop at a jump target: removing code on
9214 // one side of a label would silently retarget the jump.
9215 let mut next = index + 1;
9216 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
9217 next += 1;
9218 }
9219 if is_label_at(label_at, next) {
9220 continue;
9221 }
9222 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
9223 for entry in &mut insns[index..next] {
9224 *entry = None;
9225 }
9226 }
9227 }
9228
9229 // The rewrites below all decide against one fixed snapshot, which is what the
9230 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
9231 // the pass, so a rule never observes what an earlier rule removed. Gathering
9232 // every deletion first and applying them together reproduces that.
9233 let snapshot: Vec<Option<Opcode>> = insns
9234 .iter()
9235 .map(|entry| entry.as_ref().map(|(op, _)| *op))
9236 .collect();
9237 // The next instruction that is still there. Holes left by dead-code
9238 // elimination are not instructions, so a rule looks past them.
9239 let next_op = |index: usize| -> Option<usize> {
9240 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
9241 };
9242
9243 let mut doomed = vec![false; insns.len()];
9244 for index in 0..insns.len() {
9245 // A constant pushed only to be dropped does nothing at all. This is what a
9246 // comma expression with a literal left operand compiles to — `(0, f)()` — and
9247 // the reference removes the pair rather than making the reader step over it.
9248 let constant = matches!(
9249 snapshot[index],
9250 Some(
9251 Opcode::Undefined
9252 | Opcode::Null
9253 | Opcode::PushMinus1
9254 | Opcode::Push0
9255 | Opcode::Push1
9256 | Opcode::Push2
9257 | Opcode::Push3
9258 | Opcode::Push4
9259 | Opcode::Push5
9260 | Opcode::Push6
9261 | Opcode::Push7
9262 | Opcode::PushTrue
9263 | Opcode::PushFalse
9264 | Opcode::PushI32
9265 )
9266 );
9267 if constant
9268 && let Some(next) = next_op(index)
9269 && snapshot[next] == Some(Opcode::Drop)
9270 {
9271 doomed[index] = true;
9272 doomed[next] = true;
9273 }
9274 }
9275 for (index, entry) in insns.iter_mut().enumerate() {
9276 if doomed[index] {
9277 *entry = None;
9278 }
9279 }
9280
9281 // A conditional whose destination is the very next instruction just pops its
9282 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
9283 // compiles to.
9284 //
9285 // Order matters, and it is the reference's order: this runs *before* the
9286 // folding below, on the instruction the conditional originally had. Folding
9287 // moves a conditional's destination, and the reference never re-examines it
9288 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
9289 // a conditional even though folding leaves it pointing at the next
9290 // instruction.
9291 for (index, entry) in insns.iter_mut().enumerate() {
9292 let Some((op, operands)) = entry.clone() else {
9293 continue;
9294 };
9295 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
9296 continue;
9297 }
9298 let Some(id) = label_id(&operands) else {
9299 continue;
9300 };
9301 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
9302 *entry = Some((Opcode::Drop, Vec::new()));
9303 }
9304 }
9305
9306 // A constant condition is decided here rather than at run time.
9307 fold_constant_conditions(insns, label_at);
9308 // The conditional folding below is about pairs of *real* branches, so it runs
9309 // before a jump to the next instruction is dropped: `do { … if (c) continue }
9310 // while (t)` puts `continue` exactly on the condition, and the reference inverts
9311 // the branch first and only then notices the jump goes nowhere.
9312 fold_conditional_jumps(insns, label_at, placed);
9313
9314 // A jump whose destination is the very next instruction does nothing, which is
9315 // what constant folding leaves behind for `while (1) { … }`.
9316 remove_jump_to_next(insns, placed);
9317
9318 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
9319 // a use of the same variable boils down to.
9320 for index in 0..insns.len() {
9321 let Some((put_op, _)) = insns[index].clone() else {
9322 continue;
9323 };
9324 if !is_foldable_put(put_op) {
9325 continue;
9326 }
9327 if is_label_at(label_at, index + 1) {
9328 continue;
9329 }
9330 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
9331 continue;
9332 };
9333 if get_op != get_form_of(put_op) {
9334 continue;
9335 }
9336 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
9337 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
9338 continue;
9339 }
9340 insns[index] = Some((set_form_of(put_op), get_operands));
9341 insns[index + 1] = None;
9342 }
9343}
9344
9345/// Drop `gosub`s that call an empty subroutine.
9346///
9347/// A `gosub` whose target starts with `ret` returns immediately, so the reference
9348/// drops the call. This is how `try`/`catch` without a `finally` loses its
9349/// finalizer plumbing: the finalizer block is empty, its first instruction is
9350/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
9351/// [`eliminate_dead_code`] then removes.
9352fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
9353 let state = &stack[current];
9354 let mut targets = Vec::new();
9355 for insn in &state.insns {
9356 if let Insn::Fixed { op, operands } = insn
9357 && *op == Opcode::Gosub
9358 && let Some(id) = label_id(operands)
9359 && let Some(target) = state.labels.get(id as usize).copied().flatten()
9360 {
9361 targets.push(target);
9362 }
9363 }
9364 let empty: Vec<usize> = targets
9365 .into_iter()
9366 .filter(|target| {
9367 stack[current]
9368 .insns
9369 .get(*target)
9370 .map(|insn| {
9371 matches!(
9372 insn,
9373 Insn::Fixed {
9374 op: Opcode::Ret,
9375 ..
9376 }
9377 )
9378 })
9379 .unwrap_or(false)
9380 })
9381 .collect();
9382 if empty.is_empty() {
9383 return;
9384 }
9385 for insn in stack[current].insns.iter_mut() {
9386 if let Insn::Fixed { op, operands } = insn
9387 && *op == Opcode::Gosub
9388 && let Some(id) = label_id(operands)
9389 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
9390 && empty.contains(&target)
9391 {
9392 *insn = Insn::Dead;
9393 }
9394 }
9395}
9396
9397/// Replace unreachable instructions with [`Insn::Dead`].
9398fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
9399 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
9400 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
9401 if !reachable[index] {
9402 *insn = Insn::Dead;
9403 }
9404 }
9405}
9406
9407/// Mark every instruction index reachable from the entry, plus the index one past
9408/// the last instruction.
9409///
9410/// `seen[len]` answers "can control reach the end of this function", and the
9411/// entries before it identify dead code. Both DCE and the implicit-return decision
9412/// read the same result, which keeps them from disagreeing.
9413fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
9414 let mut seen = vec![false; count + 1];
9415 let mut worklist = vec![0usize];
9416 while let Some(index) = worklist.pop() {
9417 if index > count || seen[index] {
9418 continue;
9419 }
9420 seen[index] = true;
9421 if index == count {
9422 continue;
9423 }
9424 let (op, operands) = match &state.insns[index] {
9425 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
9426 // A variable access never transfers control, and a removed
9427 // instruction is only reachable if it is already marked.
9428 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
9429 worklist.push(index + 1);
9430 continue;
9431 }
9432 };
9433 match op {
9434 // A return, a throw and a `ret` all leave this instruction stream: the
9435 // first two give control to the caller or the handler, and `ret`
9436 // returns to a `gosub` elsewhere.
9437 // A tail call leaves the function too: the callee's result becomes this
9438 // function's result, so nothing after it runs.
9439 Opcode::Return
9440 | Opcode::ReturnUndef
9441 | Opcode::ReturnAsync
9442 | Opcode::TailCall
9443 | Opcode::TailCallMethod
9444 | Opcode::Throw
9445 | Opcode::ThrowError
9446 | Opcode::Ret => {}
9447 // A `catch` records where exceptions from the code that follows go.
9448 // That code is not reachable through normal control flow, but it is
9449 // reachable — through the exception edge — so the walk has to follow
9450 // it, or dead-code elimination would delete every handler.
9451 Opcode::Catch => {
9452 if let Some(target) = placed_label(state, operands) {
9453 worklist.push(target);
9454 }
9455 worklist.push(index + 1);
9456 }
9457 // A `gosub` calls a subroutine and then continues, so both edges count.
9458 Opcode::Gosub => {
9459 if let Some(target) = placed_label(state, operands) {
9460 worklist.push(target);
9461 }
9462 worklist.push(index + 1);
9463 }
9464 Opcode::Goto => {
9465 if let Some(target) = placed_label(state, operands) {
9466 worklist.push(target);
9467 }
9468 }
9469 Opcode::IfTrue | Opcode::IfFalse => {
9470 if let Some(target) = placed_label(state, operands) {
9471 worklist.push(target);
9472 }
9473 worklist.push(index + 1);
9474 }
9475 _ => worklist.push(index + 1),
9476 }
9477 }
9478 seen
9479}
9480
9481/// The instruction index a jump operand points at, resolved through the label
9482/// placement table.
9483fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
9484 let id = label_id(operands)?;
9485 state.labels.get(id as usize).copied().flatten()
9486}
9487
9488/// The label an instruction refers to.
9489fn label_id(operands: &[Op]) -> Option<u32> {
9490 operands.iter().find_map(|operand| match operand {
9491 Op::Label(label) => Some(label.0),
9492 _ => None,
9493 })
9494}
9495
9496/// Turn `if_false L; goto M; L:` into `if_true M`.
9497///
9498/// A conditional whose alternate branch is an unconditional jump needs one jump,
9499/// not two. This is the shape `if (c) break;` produces, so folding it removes an
9500/// instruction and a label from every conditional `break`.
9501/// The boolean a constant-push instruction produces, or `None` if it is not one.
9502///
9503/// Only the operators whose truthiness is decided by the opcode are covered; a
9504/// constant that needs the constant pool (a string) is left alone, because reading it
9505/// would mean threading the pool through the peephole for a case the reference also
9506/// skips.
9507fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
9508 match op {
9509 // `push_0` returns -1 for zero, `push_1` 1, and so on.
9510 Opcode::PushMinus1 => Some(true),
9511 Opcode::Push0 => Some(false),
9512 Opcode::Push1
9513 | Opcode::Push2
9514 | Opcode::Push3
9515 | Opcode::Push4
9516 | Opcode::Push5
9517 | Opcode::Push6
9518 | Opcode::Push7 => Some(true),
9519 Opcode::PushTrue => Some(true),
9520 Opcode::PushFalse => Some(false),
9521 Opcode::Undefined | Opcode::Null => Some(false),
9522 Opcode::PushI32 => match operands.first() {
9523 Some(Op::Int(value)) => Some(*value != 0),
9524 _ => None,
9525 },
9526 _ => None,
9527 }
9528}
9529
9530/// Fold a branch on a constant condition.
9531///
9532/// `if (0) a() else b()` must not test anything at run time, and the reference
9533/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
9534/// which is why the bytecode for a `while (1)` loop has no condition at all.
9535///
9536/// Two instructions become one, so the slot the test occupied is left empty rather
9537/// than shifting everything after it: labels have already been resolved to indices.
9538fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9539 for index in 0..insns.len() {
9540 let Some((push_op, push_operands)) = insns[index].clone() else {
9541 continue;
9542 };
9543 let Some(truth) = constant_truth(push_op, &push_operands) else {
9544 continue;
9545 };
9546 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
9547 continue;
9548 };
9549 // A label on the branch means something else jumps *here* — the value is on the
9550 // stack and the conditional is what pops it. Deleting the branch would leave that
9551 // jump with no instruction, and a label whose slot is empty resolves to the next
9552 // one that is not, i.e. to the far side of the branch. That is how
9553 // `if (a && false) then else` jumped to `then`: `&&` ends its chain on a label, and
9554 // the constant `false` sits directly in front of the statement's own conditional.
9555 if is_label_at(label_at, index + 1) {
9556 continue;
9557 }
9558 let (destination, taken) = match branch_op {
9559 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
9560 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
9561 _ => continue,
9562 };
9563 let Some(destination) = destination else {
9564 continue;
9565 };
9566 insns[index] = if taken {
9567 // The branch is always taken, so it becomes an unconditional jump.
9568 Some((Opcode::Goto, vec![destination]))
9569 } else {
9570 // The branch never runs: both instructions disappear and control falls
9571 // through to what came after.
9572 None
9573 };
9574 insns[index + 1] = None;
9575 }
9576}
9577
9578/// Remove a jump whose destination is the instruction right after it.
9579///
9580/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
9581/// its test into nothing, and the loop-end jump then points at the following
9582/// instruction. The reference drops them, so `stack_size` and the listing agree.
9583fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
9584 for index in 0..insns.len() {
9585 let Some((op, operands)) = insns[index].clone() else {
9586 continue;
9587 };
9588 if !is_goto(op) {
9589 continue;
9590 }
9591 let Some(id) = label_id(&operands) else {
9592 continue;
9593 };
9594 // The next instruction that still exists, which is what "the instruction
9595 // after this jump" means once earlier folds have punched holes.
9596 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
9597 if placed.get(id as usize).copied().flatten() == next {
9598 insns[index] = None;
9599 }
9600 }
9601}
9602
9603fn fold_conditional_jumps(
9604 insns: &mut [Option<(Opcode, Vec<Op>)>],
9605 label_at: &[Option<u32>],
9606 placed: &[Option<usize>],
9607) {
9608 for index in 0..insns.len() {
9609 let Some((op, operands)) = insns[index].clone() else {
9610 continue;
9611 };
9612 let inverted = match op {
9613 Opcode::IfFalse => Opcode::IfTrue,
9614 Opcode::IfTrue => Opcode::IfFalse,
9615 _ => continue,
9616 };
9617 // Next must be an unconditional jump that is not itself a target, and the
9618 // instruction after it must be exactly where the conditional goes.
9619 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
9620 continue;
9621 };
9622 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
9623 continue;
9624 }
9625 // The conditional must land on the instruction *after* the jump. Several
9626 // labels can share a position, so this asks where *this* label was put
9627 // rather than what label happens to sit there.
9628 let Some(taken) = label_id(&operands) else {
9629 continue;
9630 };
9631 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
9632 continue;
9633 }
9634 let Some(destination) = next_operands.first().cloned() else {
9635 continue;
9636 };
9637 insns[index] = Some((inverted, vec![destination]));
9638 insns[index + 1] = None;
9639 }
9640}
9641
9642/// Whether a jump target is placed at this instruction index.
9643fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
9644 label_at.get(index).copied().flatten().is_some()
9645}
9646
9647fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9648 // `dup put_x(n)` -> `set_x(n)`
9649 // `dup put_x(n) drop` -> `put_x(n)`
9650 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
9651 for index in 0..insns.len() {
9652 if opcode_at(insns, index) != Some(Opcode::Dup) {
9653 continue;
9654 }
9655 if is_label_at(label_at, index + 1) {
9656 continue;
9657 }
9658 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
9659 continue;
9660 };
9661 if !is_foldable_put(put_op) {
9662 continue;
9663 }
9664 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
9665 continue;
9666 };
9667 let mut new_op = set_form_of(put_op);
9668 let mut end = index + 2;
9669 if is_label_at(label_at, end) {
9670 // The `put` has to stay as it is; only the `dup` can be folded.
9671 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
9672 insns[index + 1] = None;
9673 continue;
9674 }
9675 // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
9676 // Deleting it moves the label's target onto whatever follows, and the code that
9677 // jumps there arrives with a different stack than the fall-through path: that is
9678 // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
9679 // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
9680 // an empty stack. The store had already consumed the value it was supposed to
9681 // leave behind.
9682 if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
9683 new_op = put_op;
9684 end += 1;
9685 if opcode_at(insns, end) == Some(get_form_of(put_op))
9686 && !is_label_at(label_at, end)
9687 && insns[end]
9688 .as_ref()
9689 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
9690 {
9691 new_op = set_form_of(put_op);
9692 end += 1;
9693 }
9694 }
9695 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
9696 for entry in &mut insns[index + 1..end] {
9697 *entry = None;
9698 }
9699 }
9700}
9701
9702fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
9703 insns
9704 .get(index)
9705 .and_then(|entry| entry.as_ref())
9706 .map(|(op, _)| *op)
9707}
9708
9709/// The four `put_` families that have a `set_` twin. Deliberately not including
9710/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
9711/// these, and folding the others would produce instructions that do not exist.
9712fn is_foldable_put(op: Opcode) -> bool {
9713 matches!(
9714 op,
9715 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
9716 )
9717}
9718
9719fn set_form_of(op: Opcode) -> Opcode {
9720 match op {
9721 Opcode::PutLoc => Opcode::SetLoc,
9722 Opcode::PutLocCheck => Opcode::SetLocCheck,
9723 Opcode::PutArg => Opcode::SetArg,
9724 Opcode::PutVarRef => Opcode::SetVarRef,
9725 other => other,
9726 }
9727}
9728
9729fn get_form_of(op: Opcode) -> Opcode {
9730 match op {
9731 Opcode::PutLoc => Opcode::GetLoc,
9732 Opcode::PutLocCheck => Opcode::GetLocCheck,
9733 Opcode::PutArg => Opcode::GetArg,
9734 Opcode::PutVarRef => Opcode::GetVarRef,
9735 other => other,
9736 }
9737}
9738
9739/// Atom interning, per function.
9740///
9741/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
9742/// identifiers, so the array-index rule applies here rather than at the handful of
9743/// call sites that build property keys.
9744fn intern_atom(state: &mut FnState, name: &str) -> u32 {
9745 intern_atom_value(state, Atom::from_text(name))
9746}
9747
9748/// [`intern_atom`] for an operand that is already an [`Atom`].
9749///
9750/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
9751/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
9752/// would have looked up.
9753fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
9754 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
9755 return index as u32;
9756 }
9757 state.atoms.push(atom);
9758 state.atoms.len() as u32 - 1
9759}
9760
9761fn binary_opcode(op: BinaryOp) -> Opcode {
9762 match op {
9763 BinaryOp::Add => Opcode::Add,
9764 BinaryOp::Sub => Opcode::Sub,
9765 BinaryOp::Mul => Opcode::Mul,
9766 BinaryOp::Div => Opcode::Div,
9767 BinaryOp::Mod => Opcode::Mod,
9768 BinaryOp::Pow => Opcode::Pow,
9769 BinaryOp::BitOr => Opcode::Or,
9770 BinaryOp::BitXor => Opcode::Xor,
9771 BinaryOp::BitAnd => Opcode::And,
9772 BinaryOp::Shl => Opcode::Shl,
9773 BinaryOp::Shr => Opcode::Sar,
9774 BinaryOp::UShr => Opcode::Shr,
9775 BinaryOp::Lt => Opcode::Lt,
9776 BinaryOp::LtEq => Opcode::Lte,
9777 BinaryOp::Gt => Opcode::Gt,
9778 BinaryOp::GtEq => Opcode::Gte,
9779 BinaryOp::Eq => Opcode::Eq,
9780 BinaryOp::NotEq => Opcode::Neq,
9781 BinaryOp::StrictEq => Opcode::StrictEq,
9782 BinaryOp::StrictNotEq => Opcode::StrictNeq,
9783 BinaryOp::In => Opcode::In,
9784 BinaryOp::Instanceof => Opcode::Instanceof,
9785 }
9786}
9787
9788fn compound_opcode(op: AssignOp) -> Opcode {
9789 match op {
9790 AssignOp::Add => Opcode::Add,
9791 AssignOp::Sub => Opcode::Sub,
9792 AssignOp::Mul => Opcode::Mul,
9793 AssignOp::Div => Opcode::Div,
9794 AssignOp::Mod => Opcode::Mod,
9795 AssignOp::Pow => Opcode::Pow,
9796 AssignOp::Shl => Opcode::Shl,
9797 AssignOp::Shr => Opcode::Sar,
9798 AssignOp::UShr => Opcode::Shr,
9799 AssignOp::BitOr => Opcode::Or,
9800 AssignOp::BitXor => Opcode::Xor,
9801 AssignOp::BitAnd => Opcode::And,
9802 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
9803 }
9804}
9805
9806/// Encode the resolved instruction stream, choosing short forms where possible.
9807///
9808/// The peephole pass leaves holes in the instruction list so that label indices
9809/// stay valid. A label names an *instruction index*, and an index that was
9810/// deleted has to resolve to the next surviving instruction, which is what
9811/// [`resolve_label`] does before the byte offsets are known.
9812fn assemble(
9813 insns: &mut [Option<(Opcode, Vec<Op>)>],
9814 insn_pos: &[Option<Position>],
9815 state: &mut FnState,
9816) -> (Vec<u8>, u32, Vec<LineCol>) {
9817 // Compaction: surviving instructions in order, plus the index mapping.
9818 //
9819 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
9820 // point below where instructions are removed — otherwise a stack trace would point
9821 // at the wrong source line as soon as dead-code elimination kicked in.
9822 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
9823 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
9824 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
9825 for (original, entry) in insns.iter_mut().enumerate() {
9826 if let Some((op, operands)) = entry.take() {
9827 original_to_kept[original] = Some(kept.len());
9828 kept.push((op, operands));
9829 spans.push(insn_pos.get(original).copied().flatten());
9830 }
9831 }
9832
9833 if std::env::var_os("QJS_DEBUG").is_some() {
9834 eprintln!("--- assemble entry --- {kept:?}");
9835 }
9836 // How many labels are real, as opposed to the per-instruction ones allocated
9837 // just below. Only a real label marks a spot in the source program.
9838 let real_labels = state.labels.len();
9839
9840 // Give every surviving instruction a label of its own. Jump cleanup below
9841 // redirects jumps to arbitrary instructions, and a jump target has to be a
9842 // label; pre-allocating one per index means a redirect never has to invent
9843 // anything.
9844 let existing = state.labels.len();
9845 let base = kept.len();
9846 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
9847 for offset in 0..=kept.len() {
9848 state.labels.push(Some(0));
9849 index_label.push(Label((existing + offset) as u32));
9850 }
9851 // Point each pre-allocated label at its instruction, reusing the count from
9852 // `original_to_kept` so the mapping survives compaction.
9853 let place_index_labels = |state: &mut FnState,
9854 original_to_kept: &[Option<usize>],
9855 kept_len: usize,
9856 index_label: &[Label]| {
9857 for (original, mapped) in original_to_kept.iter().enumerate() {
9858 if let Some(kept_index) = mapped {
9859 let label = index_label[*kept_index].0 as usize;
9860 state.labels[label] = Some(original);
9861 }
9862 }
9863 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
9864 };
9865 place_index_labels(state, &original_to_kept, base, &index_label);
9866
9867 // Resolve every label to a kept index once; the placement table maps labels
9868 // to original indices, so a second hop lands in kept space.
9869 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
9870 for (id, placed) in state.labels.iter().enumerate() {
9871 let Some(original) = placed else { continue };
9872 label_kept[id] = if *original == usize::MAX {
9873 Some(base)
9874 } else {
9875 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
9876 };
9877 }
9878
9879 // Code after an unconditional transfer is unreachable, and the reference drops it
9880 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
9881 // scans forward until it finds a label something still jumps to, so a run of
9882 // dead instructions between a `throw` and the next live target disappears.
9883 //
9884 // The scan repeats because dropping a jump lowers the reference count of the
9885 // label it pointed at, which can strand what follows. Only a real label keeps an
9886 // instruction alive here; the per-instruction labels allocated above belong to
9887 // this pass, not to the program.
9888 loop {
9889 let mut references = vec![false; kept.len() + 1];
9890 for (_, operands) in &kept {
9891 if let Some(target) = target_kept_index(operands, &label_kept)
9892 && target < references.len()
9893 {
9894 references[target] = true;
9895 }
9896 }
9897 let mut doomed = vec![false; kept.len()];
9898 let mut any = false;
9899 for (index, (op, _)) in kept.iter().enumerate() {
9900 if !is_transfer(*op) {
9901 continue;
9902 }
9903 for next in index + 1..kept.len() {
9904 if references[next] {
9905 break;
9906 }
9907 doomed[next] = true;
9908 any = true;
9909 }
9910 }
9911 if !any {
9912 break;
9913 }
9914 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
9915 }
9916
9917 // A label that lands on an unconditional jump stands for wherever that jump
9918 // goes, so retarget it once and every jump to the label follows for free.
9919 // This is what makes `continue` in a `for` head reach the loop top instead of
9920 // stopping at the update's trailing jump.
9921 let folded: Vec<Option<usize>> = label_kept
9922 .iter()
9923 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
9924 .collect();
9925 label_kept = folded;
9926
9927 // Jump cleanup, in compacted index space. Two rewrites the reference also
9928 // applies while it resolves labels:
9929 // * a jump whose destination is the very next instruction does nothing;
9930 // * a jump to a jump is redirected to its final destination.
9931 // The second can expose the first, so this repeats until it settles.
9932 loop {
9933 let mut delete = vec![false; kept.len()];
9934 let mut changed = false;
9935 for index in 0..kept.len() {
9936 let (op, operands) = &kept[index];
9937 if !is_goto(*op) {
9938 continue;
9939 }
9940 let Some(immediate) = target_kept_index(operands, &label_kept) else {
9941 continue;
9942 };
9943 let target = follow_jump_chain(&kept, &label_kept, immediate);
9944 if target == index + 1 {
9945 delete[index] = true;
9946 changed = true;
9947 } else if matches!(
9948 kept.get(target).map(|(op, _)| *op),
9949 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
9950 ) {
9951 // Jumping straight to a return or throw is the same as doing it
9952 // here, so the jump becomes that instruction.
9953 kept[index] = (kept[target].0, Vec::new());
9954 changed = true;
9955 } else if target != immediate {
9956 // Redirect to the end of the chain.
9957 let label = index_label[target];
9958 kept[index].1 = vec![Op::Label(label)];
9959 changed = true;
9960 }
9961 }
9962 if !changed {
9963 break;
9964 }
9965 if !delete.iter().any(|deleted| *deleted) {
9966 break;
9967 }
9968 // Drop the deleted instructions and renumber everything.
9969 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9970 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9971 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9972 for (old, entry) in kept.into_iter().enumerate() {
9973 if delete[old] {
9974 continue;
9975 }
9976 moved[old] = Some(next.len());
9977 next.push(entry);
9978 next_spans.push(spans[old]);
9979 }
9980 for (id, slot) in label_kept.iter_mut().enumerate() {
9981 let Some(old) = *slot else { continue };
9982 *slot = match moved.get(old).copied().flatten() {
9983 Some(new) => Some(new),
9984 // The target was deleted: the jump now lands on whatever follows.
9985 None => (old..moved.len())
9986 .find_map(|i| moved[i])
9987 .or(Some(next.len())),
9988 };
9989 let _ = id;
9990 }
9991 kept = next;
9992 spans = next_spans;
9993 }
9994
9995 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9996 // jump to the next instruction and is deleted, leaving the label at the end with
9997 // nothing pointing at it. If that also strands the last instruction, it goes
9998 // too — which is how a `try` whose body always returns ends on its `ret` rather
9999 // than an implicit `return_undef`.
10000 // Which instructions something still jumps to. Reading the surviving jumps is
10001 // what the reference's reference counts amount to: once a jump has been folded
10002 // away the label it named is unreferenced, even though the program still has a
10003 // label there.
10004 let mut references = vec![false; kept.len() + 1];
10005 let _ = real_labels;
10006 for (_, operands) in &kept {
10007 if let Some(target) = target_kept_index(operands, &label_kept)
10008 && target < references.len()
10009 {
10010 references[target] = true;
10011 }
10012 }
10013 let mut end = kept.len();
10014 while end > 0 {
10015 let last = end - 1;
10016 let reachable = references[last] || end < kept.len();
10017 if reachable {
10018 break;
10019 }
10020 let after_transfer = last
10021 .checked_sub(1)
10022 .map(|previous| {
10023 matches!(
10024 kept[previous].0,
10025 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
10026 )
10027 })
10028 .unwrap_or(false);
10029 if !after_transfer {
10030 break;
10031 }
10032 end = last;
10033 }
10034 kept.truncate(end);
10035 spans.truncate(end);
10036
10037 // Choose an opcode for each instruction and its size, so label offsets can be
10038 // computed.
10039 let chosen = choose_opcodes(&kept, &label_kept);
10040 let offsets = instruction_offsets(&chosen);
10041 let offset = *offsets.last().unwrap_or(&0);
10042
10043 let mut code = Vec::with_capacity(offset);
10044 for (position, (_, operands)) in kept.iter().enumerate() {
10045 let op = chosen[position];
10046 code.push(op as u8);
10047 let operands = retarget_labels(operands, &label_kept, kept.len());
10048 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
10049 }
10050 let stack_size = compute_stack_size(&code);
10051 // Keep only the offsets where the position actually changes: a run of
10052 // instructions on one line is one table entry, and the runtime binary searches
10053 // the table for the frame's pc.
10054 //
10055 // The table always starts at pc 0 with the *function's own* position, because the
10056 // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
10057 // last_line_num)` from `fd->source_pos`, the token the function definition starts at
10058 // (`function`, `async`, a method's property name). An instruction before the first
10059 // recorded operator therefore reports the function's own start, which is what makes a
10060 // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
10061 let mut positions: Vec<LineCol> = vec![LineCol {
10062 pc: 0,
10063 line: state.line,
10064 column: state.column,
10065 }];
10066 let mut last: Option<Position> = None;
10067 for (index, span) in spans.iter().enumerate() {
10068 let Some(pos) = *span else { continue };
10069 if last == Some(pos) {
10070 continue;
10071 }
10072 last = Some(pos);
10073 if pos.line == state.line && pos.column == state.column {
10074 // Already the seed entry above.
10075 continue;
10076 }
10077 positions.push(LineCol {
10078 pc: offsets[index] as u32,
10079 line: pos.line,
10080 column: pos.column,
10081 });
10082 }
10083 (code, stack_size, positions)
10084}
10085
10086/// Whether an instruction always transfers control away, so anything after it in the
10087/// same stream is unreachable.
10088fn is_transfer(op: Opcode) -> bool {
10089 matches!(
10090 op,
10091 Opcode::Goto
10092 | Opcode::Goto8
10093 | Opcode::Goto16
10094 | Opcode::Return
10095 | Opcode::ReturnUndef
10096 | Opcode::Throw
10097 | Opcode::ThrowError
10098 | Opcode::Ret
10099 )
10100}
10101
10102/// Remove the marked instructions and renumber the label table so it keeps pointing
10103/// at the same instructions. A label whose instruction went away moves to whatever
10104/// follows it, since a jump is never left with nowhere to land.
10105fn drop_instructions(
10106 kept: Vec<(Opcode, Vec<Op>)>,
10107 spans: Vec<Option<Position>>,
10108 label_kept: &mut [Option<usize>],
10109 doomed: &[bool],
10110) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
10111 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10112 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10113 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10114 for (old, entry) in kept.into_iter().enumerate() {
10115 if doomed.get(old).copied().unwrap_or(false) {
10116 continue;
10117 }
10118 moved[old] = Some(result.len());
10119 result.push(entry);
10120 result_spans.push(spans[old]);
10121 }
10122 for slot in label_kept.iter_mut() {
10123 let Some(old) = *slot else { continue };
10124 *slot = match moved.get(old).copied().flatten() {
10125 Some(new) => Some(new),
10126 None => (old..moved.len())
10127 .find_map(|i| moved[i])
10128 .or(Some(result.len())),
10129 };
10130 }
10131 (result, result_spans)
10132}
10133
10134fn is_goto(op: Opcode) -> bool {
10135 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
10136}
10137
10138/// The kept index a jump operand points at.
10139fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
10140 let id = label_id(operands)?;
10141 label_kept.get(id as usize).copied().flatten()
10142}
10143
10144/// Follow a chain of unconditional jumps to its first real destination.
10145fn follow_jump_chain(
10146 kept: &[(Opcode, Vec<Op>)],
10147 label_kept: &[Option<usize>],
10148 start: usize,
10149) -> usize {
10150 let mut current = start;
10151 // `for(;;)` jumps to itself, so the walk has to be bounded.
10152 for _ in 0..kept.len() {
10153 let Some((op, operands)) = kept.get(current) else {
10154 return current;
10155 };
10156 if !is_goto(*op) {
10157 return current;
10158 }
10159 let Some(next) = target_kept_index(operands, label_kept) else {
10160 return current;
10161 };
10162 if next == current {
10163 return current;
10164 }
10165 current = next;
10166 }
10167 current
10168}
10169
10170/// Rewrite label operands from label ids to kept instruction indices.
10171fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
10172 operands
10173 .iter()
10174 .map(|operand| match operand {
10175 Op::Label(label) => {
10176 let target = label_kept
10177 .get(label.0 as usize)
10178 .copied()
10179 .flatten()
10180 .unwrap_or(kept_len);
10181 Op::Label(Label(target as u32))
10182 }
10183 other => other.clone(),
10184 })
10185 .collect()
10186}
10187
10188/// Encode the resolved instruction stream, choosing short forms where possible.
10189///
10190/// Compute the maximum value-stack depth by exploring the control-flow graph.
10191///
10192/// This is a breadth-first walk from the first instruction, tracking the stack
10193/// depth on entry to each instruction. Every instruction has at most two
10194/// successors (fall through, and a jump target), so a worklist over byte offsets
10195/// is enough. The reference does the same thing in `compute_stack_size`, which is
10196/// why the resulting numbers match exactly.
10197///
10198/// Instructions that pop a variable number of values (`call`, `array_from`, …)
10199/// encode that count in their operand, which is added to the static `n_pop`.
10200fn compute_stack_size(code: &[u8]) -> u32 {
10201 let mut depth_at = vec![u16::MAX; code.len()];
10202 // Each entry carries the enclosing `catch` levels, innermost last, because
10203 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
10204 // offset and forgets that level.
10205 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
10206 let mut max_depth = 0u32;
10207
10208 while let Some((pc, depth, catch_levels)) = worklist.pop() {
10209 if pc >= code.len() {
10210 continue;
10211 }
10212 if depth_at[pc] != u16::MAX {
10213 continue;
10214 }
10215 force_depth(&mut depth_at, pc, depth);
10216
10217 let Some(op) = Opcode::from_u8(code[pc]) else {
10218 break;
10219 };
10220 let info = op.info();
10221 let next = pc + info.size as usize;
10222 if next > code.len() {
10223 break;
10224 }
10225 let mut n_pop = info.n_pop as u32;
10226 let mut n_push = info.n_push as u32;
10227 // Variable-length forms carry their count in the operand.
10228 match info.format {
10229 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
10230 n_pop += read_u16(code, pc + 1) as u32;
10231 }
10232 crate::opcode::OpFormat::Npopx => {
10233 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
10234 }
10235 _ => {}
10236 }
10237 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
10238 // are the `set_` variant; the table already records that, so nothing to
10239 // adjust here.
10240 let _ = &mut n_push;
10241
10242 // The depth before this instruction's own push, which is what a `catch`
10243 // records as its level.
10244 let depth_before = depth;
10245 let mut depth = depth.saturating_sub(n_pop) + n_push;
10246 let mut catch_levels = catch_levels;
10247 if op == Opcode::NipCatch {
10248 // Discard everything above the innermost catch offset, keeping the value
10249 // on top: the frame the code after this sees is the same shape it would
10250 // have had if the `try` were not there.
10251 if let Some(base) = catch_levels.pop() {
10252 depth = base + 1;
10253 }
10254 }
10255 max_depth = max_depth.max(depth);
10256
10257 // Successors.
10258 let target = jump_target_of(code, pc, op);
10259 match op {
10260 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10261 if let Some(target) = target {
10262 worklist.push((target, depth, catch_levels));
10263 }
10264 }
10265 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
10266 if let Some(target) = target {
10267 worklist.push((target, depth, catch_levels.clone()));
10268 }
10269 worklist.push((next, depth, catch_levels));
10270 }
10271 // A `catch` records an exception edge to the handler. The handler is
10272 // entered with the thrown value on top of the stack, in the slot the
10273 // catch offset occupies on the normal path — which is why the handler's
10274 // first instruction can `put_loc` the exception away, and why the depth
10275 // is the same on both paths.
10276 Opcode::Catch => {
10277 if let Some(target) = target {
10278 // The handler is protected by the *enclosing* catch, not by this
10279 // one: an error raised inside it is what the handler's own
10280 // `catch` catches.
10281 worklist.push((target, depth, catch_levels.clone()));
10282 }
10283 catch_levels.push(depth_before);
10284 worklist.push((next, depth, catch_levels));
10285 }
10286 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
10287 // rewind past it too. Its level sits one slot higher than a `catch`'s:
10288 // the iterator and next-method slots occupy the offset's place.
10289 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
10290 if let Some(target) = target {
10291 worklist.push((target, depth, catch_levels.clone()));
10292 }
10293 catch_levels.push(depth_before + 1);
10294 worklist.push((next, depth, catch_levels));
10295 }
10296 // `gosub` calls a subroutine with the return address on top. The opcode
10297 // table records no push for it — `ret` is what pops the slot — so the
10298 // extra one is added here, where the depth of the subroutine's first
10299 // instruction is being computed.
10300 Opcode::Gosub => {
10301 if let Some(target) = target {
10302 worklist.push((target, depth + 1, catch_levels.clone()));
10303 }
10304 worklist.push((next, depth, catch_levels));
10305 }
10306 // `ret` goes back to a `gosub`; nothing here follows it.
10307 Opcode::Ret
10308 | Opcode::Return
10309 | Opcode::ReturnUndef
10310 | Opcode::Throw
10311 | Opcode::ThrowError => {}
10312 _ => worklist.push((next, depth, catch_levels)),
10313 }
10314 }
10315 max_depth
10316}
10317
10318/// Record the stack depth on entry to `pc`, keeping the deeper value if the
10319/// instruction is reachable more than once.
10320fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
10321 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
10322 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
10323 depth_at[pc] = clamped;
10324 }
10325}
10326
10327fn read_u16(code: &[u8], at: usize) -> u16 {
10328 let mut value = 0u16;
10329 for i in 0..2 {
10330 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
10331 }
10332 value
10333}
10334
10335/// The absolute target of a jump instruction, if it has one.
10336fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
10337 let info = op.info();
10338 let position = pc + 1;
10339 match info.format {
10340 crate::opcode::OpFormat::Label8 => {
10341 let offset = *code.get(position)? as i8 as i64;
10342 Some((position as i64 + offset) as usize)
10343 }
10344 crate::opcode::OpFormat::Label16 => {
10345 let offset = read_u16(code, position) as i16 as i64;
10346 Some((position as i64 + offset) as usize)
10347 }
10348 crate::opcode::OpFormat::Label => {
10349 let mut offset = 0i32;
10350 for i in 0..4 {
10351 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
10352 }
10353 Some((position as i64 + offset as i64) as usize)
10354 }
10355 _ => None,
10356 }
10357}
10358
10359fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
10360 use Opcode::*;
10361 match (op, operands.first()) {
10362 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
10363 op.short_form(*value as u32).unwrap_or(op)
10364 }
10365 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
10366 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
10367 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
10368 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
10369 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
10370 // A declared global is reached through its reference cell, so it shares
10371 // the `var_ref` encodings, short forms included.
10372 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
10373 op.short_form(*index).unwrap_or(op)
10374 }
10375 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
10376 op.short_form(*count as u32).unwrap_or(op)
10377 }
10378 _ => op,
10379 }
10380}
10381
10382/// The byte offset each instruction will start at, plus the total code size.
10383fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
10384 let mut offsets = Vec::with_capacity(chosen.len() + 1);
10385 let mut offset = 0usize;
10386 for op in chosen {
10387 offsets.push(offset);
10388 offset += op.size() as usize;
10389 }
10390 offsets.push(offset);
10391 offsets
10392}
10393
10394/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
10395/// the offset actually fits.
10396///
10397/// The choice is circular: an instruction's size decides the offsets of everything after
10398/// it, and the offsets decide whether a jump may be short. So this starts with every jump
10399/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
10400/// Shrinking only ever *shortens* distances, so the loop converges.
10401///
10402/// Doing it in one pass instead — which is what this used to do — silently truncated any
10403/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
10404/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
10405/// with four closures in its body simply stopped, with no error and no output past the
10406/// first iteration.
10407fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
10408 let mut chosen: Vec<Opcode> = kept
10409 .iter()
10410 .map(|(op, operands)| choose_short_form(*op, operands))
10411 .collect();
10412 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
10413 let candidates = |op: Opcode| match op {
10414 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
10415 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
10416 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
10417 _ => None,
10418 };
10419 loop {
10420 let offsets = instruction_offsets(&chosen);
10421 let mut changed = false;
10422 for index in 0..kept.len() {
10423 let (op, operands) = &kept[index];
10424 let Some((short, medium, has_medium)) = candidates(*op) else {
10425 continue;
10426 };
10427 if chosen[index] == short {
10428 continue;
10429 }
10430 let Some(target) = target_kept_index(operands, label_kept) else {
10431 continue;
10432 };
10433 let Some(&target_offset) = offsets.get(target) else {
10434 continue;
10435 };
10436 // A jump is relative to the byte after its opcode, which is the convention
10437 // `jump_target_of` decodes with.
10438 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
10439 if (-128..=127).contains(&relative) {
10440 chosen[index] = short;
10441 changed = true;
10442 } else if has_medium
10443 && chosen[index] == Opcode::Goto
10444 && (-32_768..=32_767).contains(&relative)
10445 {
10446 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
10447 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
10448 // the reference encodes them.
10449 chosen[index] = medium;
10450 changed = true;
10451 }
10452 }
10453 if !changed {
10454 return chosen;
10455 }
10456 }
10457}
10458
10459fn encode_operands(
10460 code: &mut Vec<u8>,
10461 op: Opcode,
10462 operands: &[Op],
10463 position: usize,
10464 offsets: &[usize],
10465) {
10466 use crate::opcode::OpFormat::*;
10467 let info = op.info();
10468 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
10469 let index = match slot {
10470 Slot::Arg(i)
10471 | Slot::Loc(i)
10472 | Slot::VarRef(i)
10473 | Slot::Global(i)
10474 | Slot::GlobalDecl(i) => i,
10475 };
10476 code.extend_from_slice(&(index as u16).to_be_bytes());
10477 };
10478 match info.format {
10479 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
10480 U8 | Const8 => {
10481 if let Some(value) = operands.first().and_then(operand_uint) {
10482 code.push(value as u8);
10483 }
10484 }
10485 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
10486 // like their wide counterparts, only one byte wide.
10487 Loc8 => {
10488 if let Some(Op::Slot(slot)) = operands.first() {
10489 let index = match slot {
10490 Slot::Arg(i)
10491 | Slot::Loc(i)
10492 | Slot::VarRef(i)
10493 | Slot::Global(i)
10494 | Slot::GlobalDecl(i) => *i,
10495 };
10496 code.push(index as u8);
10497 }
10498 }
10499 I8 => {
10500 if let Some(value) = operands.first().and_then(operand_int) {
10501 code.push(value as i8 as u8);
10502 }
10503 }
10504 U16 | Npop => {
10505 if let Some(value) = operands.first().and_then(operand_int) {
10506 code.extend_from_slice(&(value as u16).to_be_bytes());
10507 }
10508 }
10509 I16 => {
10510 if let Some(value) = operands.first().and_then(operand_int) {
10511 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
10512 }
10513 }
10514 I32 => {
10515 if let Some(value) = operands.first().and_then(operand_int) {
10516 code.extend_from_slice(&value.to_be_bytes());
10517 }
10518 }
10519 U32 | Const => {
10520 if let Some(value) = operands.first().and_then(operand_uint) {
10521 code.extend_from_slice(&value.to_be_bytes());
10522 }
10523 }
10524 Loc | Arg | VarRef => {
10525 if let Some(Op::Slot(slot)) = operands.first() {
10526 write_slot(code, *slot);
10527 }
10528 }
10529 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
10530 if let Some(Op::AtomId(index)) = operands.first() {
10531 code.extend_from_slice(&index.to_be_bytes());
10532 }
10533 // The trailing immediate means different things per format, and the
10534 // atom forms that carry a *label* have to resolve it like any other
10535 // jump, so they cannot share the `U8`/`U16` arms above.
10536 match info.format {
10537 AtomU8 | AtomLabelU8 => {
10538 if let Some(value) = operands.get(1).and_then(operand_uint) {
10539 code.push(value as u8);
10540 }
10541 }
10542 AtomU16 | AtomLabelU16 => {
10543 if let Some(value) = operands.get(1).and_then(operand_uint) {
10544 code.extend_from_slice(&(value as u16).to_be_bytes());
10545 }
10546 }
10547 _ => {}
10548 }
10549 }
10550 NpopU16 => {
10551 for operand in operands.iter().take(2) {
10552 if let Some(value) = operand_uint(operand) {
10553 code.extend_from_slice(&(value as u16).to_be_bytes());
10554 }
10555 }
10556 }
10557 Label | Label8 | Label16 | LabelU16 => {
10558 if let Some(Op::Label(label)) = operands.first() {
10559 // Labels were already remapped to kept-instruction indices.
10560 let Some(&target) = offsets.get(label.0 as usize) else {
10561 debug_assert!(false, "label {} is past the end", label.0);
10562 return;
10563 };
10564 let relative = target as i64 - (position as i64 + 1);
10565 match info.format {
10566 Label8 => code.push(relative as i8 as u8),
10567 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
10568 // `label_u16` stores the target followed by an unrelated u16.
10569 LabelU16 => {
10570 code.extend_from_slice(&(relative as i32).to_be_bytes());
10571 if let Some(value) = operands.get(1).and_then(operand_uint) {
10572 code.extend_from_slice(&(value as u16).to_be_bytes());
10573 }
10574 }
10575 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
10576 }
10577 }
10578 }
10579 }
10580}
10581
10582fn operand_int(op: &Op) -> Option<i32> {
10583 match op {
10584 Op::Int(value) => Some(*value),
10585 _ => None,
10586 }
10587}
10588
10589fn operand_uint(op: &Op) -> Option<u32> {
10590 match op {
10591 Op::Const(value) | Op::AtomId(value) => Some(*value),
10592 Op::Int(value) => Some(*value as u32),
10593 _ => None,
10594 }
10595}
10596
10597/// Disassemble a compiled function.
10598pub fn disassemble(function: &CompiledFunction) -> String {
10599 disasm::disassemble_program(function)
10600}
10601
10602/// How many of an object pattern's keys are computed.
10603///
10604/// Only the count matters: a rest element needs a run-time key log exactly when at least one
10605/// key is not a literal, and the log is sized by walking the pattern anyway.
10606fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
10607 properties
10608 .iter()
10609 .flatten()
10610 .filter(|element| {
10611 matches!(
10612 element,
10613 PatternElement::Property {
10614 key: PropName::Computed(_),
10615 ..
10616 }
10617 )
10618 })
10619 .count()
10620}