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 // A derived constructor's return is not just the value: a non-object answer
2045 // becomes `this`, so the frame has to survive to run that.
2046 && self.cur().ctor_kind != CtorKind::Derived
2047 && self
2048 .cur()
2049 .jump_targets
2050 .iter()
2051 .all(|target| target.finally_label.is_none() && !target.has_iterator);
2052 if plain && self.expr_if_tail_call(expr)? {
2053 // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
2054 // happen here as well.
2055 self.note_direct_eval(expr);
2056 return Ok(());
2057 }
2058 self.expr(expr)?;
2059 }
2060 // `return v` in an *async generator* awaits `v` before anything else happens —
2061 // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
2062 // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
2063 // exactly that reason ("the await must be done before handling the finally in case
2064 // it raises an exception").
2065 if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
2066 self.emit(Opcode::Await, &[]);
2067 self.state().has_await = true;
2068 }
2069 has_value = self.emit_unwind_for_return(has_value);
2070 // A generator or async function does not return to its caller: it either
2071 // finishes, and the value becomes `{value, done: true}`, or it suspends.
2072 // `return_async` is the "finished" half, and it reads the value off the stack
2073 // rather than carrying it, which is what the resume machinery expects.
2074 if self.cur().is_suspending() {
2075 if !has_value {
2076 self.emit(Opcode::Undefined, &[]);
2077 }
2078 self.emit(Opcode::ReturnAsync, &[]);
2079 return Ok(());
2080 }
2081 // A derived constructor's result is `this` whenever the body does not answer an
2082 // object, and `this` is a local in the dead zone until `super()` returns — which is
2083 // why reading it here is also what turns `constructor(){ return; }` into the
2084 // ReferenceError the reference reports. The interpreter could not do this on its
2085 // own: by the time it sees `undefined` come back, the frame that held `this` is
2086 // gone, and `construct`'s own idea of `this` is the placeholder it made before the
2087 // body ran (`derived-class-return-override-with-{undefined,empty}`).
2088 if self.cur().ctor_kind == CtorKind::Derived {
2089 if !has_value {
2090 self.emit_var(VarAction::Get, "this");
2091 self.emit(Opcode::Return, &[]);
2092 return Ok(());
2093 }
2094 // `return <expr>` is only *sometimes* `this`: `undefined` is, any other
2095 // primitive is a `TypeError` (raised by `construct`), and an object replaces
2096 // `this` outright. Which one it is can only be known at run time.
2097 let keep = self.new_label();
2098 self.emit(Opcode::Dup, &[]);
2099 self.emit(Opcode::IsUndefined, &[]);
2100 self.emit_jump(Opcode::IfFalse, keep, &[]);
2101 self.emit(Opcode::Drop, &[]);
2102 self.emit_var(VarAction::Get, "this");
2103 self.place_label(keep);
2104 self.emit(Opcode::Return, &[]);
2105 return Ok(());
2106 }
2107 if has_value {
2108 self.emit(Opcode::Return, &[]);
2109 } else {
2110 self.emit(Opcode::ReturnUndef, &[]);
2111 }
2112 Ok(())
2113 }
2114
2115 /// Close an iterator: the reference's `emit_iterator_close`.
2116 ///
2117 /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
2118 /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
2119 /// sequence, and three details in it are load-bearing:
2120 ///
2121 /// * the iterator object is compared against `undefined` first, because a loop that
2122 /// ran to completion clears that slot rather than closing an exhausted iterator;
2123 /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
2124 /// * `preserve_completion` keeps whatever was underneath (the return value of the
2125 /// function being left), which is why one branch ends on `nip` and the other on `drop`.
2126 fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
2127 if !is_async {
2128 if preserve_completion {
2129 self.emit(Opcode::Rot3r, &[]);
2130 self.emit(Opcode::Undefined, &[]);
2131 }
2132 self.emit(Opcode::IteratorClose, &[]);
2133 return;
2134 }
2135 if preserve_completion {
2136 // `iter next completion -> completion iter`
2137 self.emit(Opcode::Nip, &[]);
2138 self.emit(Opcode::Swap, &[]);
2139 } else {
2140 // `iter next catch_offset -> iter`
2141 self.emit(Opcode::Drop, &[]);
2142 self.emit(Opcode::Drop, &[]);
2143 }
2144 let done = self.new_label();
2145 let no_return = self.new_label();
2146 self.emit(Opcode::Dup, &[]);
2147 self.emit(Opcode::IsUndefined, &[]);
2148 self.emit_jump(Opcode::IfTrue, done, &[]);
2149 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
2150 self.emit(Opcode::Dup, &[]);
2151 self.emit(Opcode::IsUndefinedOrNull, &[]);
2152 self.emit_jump(Opcode::IfTrue, no_return, &[]);
2153 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
2154 self.emit(Opcode::Await, &[]);
2155 self.state().has_await = true;
2156 self.emit_jump(Opcode::Goto, done, &[]);
2157 self.place_label(no_return);
2158 self.emit(Opcode::Drop, &[]);
2159 self.place_label(done);
2160 self.emit(Opcode::Drop, &[]);
2161 }
2162
2163 /// Emit the finalizer/iterator cleanup for leaving the current position with a
2164 /// return, and report whether a value is now on the stack for it to carry.
2165 ///
2166 /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
2167 /// enclosing `finally` at once, and the two used to be separate — the `yield` path
2168 /// simply emitted `return_async`, so `it.return()` ended the generator without ever
2169 /// running `finally` blocks the body was sitting inside.
2170 fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
2171 let targets = self.cur().jump_targets.clone();
2172 for target in targets.iter().rev() {
2173 if target.finally_label.is_none() && !target.has_iterator {
2174 continue;
2175 }
2176 if !has_value {
2177 // The cleanup expects a value to pass through; with nothing to
2178 // return, `undefined` stands in.
2179 self.emit(Opcode::Undefined, &[]);
2180 has_value = true;
2181 }
2182 self.emit(Opcode::NipCatch, &[]);
2183 if target.has_iterator {
2184 // Rewind to the loop's own slots and hand the close a dummy catch offset:
2185 // the loop is being abandoned, so there is nothing left to catch.
2186 self.emit_iterator_close(target.is_async_iterator, true);
2187 } else if let Some(finally) = target.finally_label {
2188 self.emit_jump(Opcode::Gosub, finally, &[]);
2189 }
2190 }
2191 has_value
2192 }
2193
2194 /// Compile a statement list, stopping at the first statement that cannot
2195 /// fall through.
2196 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2197 for (index, stmt) in body.iter().enumerate() {
2198 // A `using` declaration is not just a binding: everything after it, to the end
2199 // of the list, runs inside its disposal region. Compiling the rest of the list
2200 // recursively is what gives nested regions their innermost-first order.
2201 if Self::using_declaration(stmt).is_some() {
2202 return self.using_region(stmt, &body[index + 1..]);
2203 }
2204 self.stmt(stmt)?;
2205 if Self::terminates(stmt) {
2206 break;
2207 }
2208 }
2209 Ok(())
2210 }
2211
2212 /// The declaration a `using` statement carries, if it is one.
2213 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2214 match &stmt.kind {
2215 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2216 _ => None,
2217 }
2218 }
2219
2220 /// Compile `decl` and then the rest of its block, disposing when the block ends.
2221 ///
2222 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2223 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2224 /// exception — and this engine already funnels all of those through `catch` plus
2225 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2226 /// `return` and `break` dispose without knowing anything about `using`.
2227 ///
2228 /// ```text
2229 /// <declaration> value -> x, method -> x+1
2230 /// catch CATCH <- an exception in the rest lands here
2231 /// REST:
2232 /// <the rest of the block>
2233 /// drop <- the catch offset, on the fall-through path
2234 /// undefined; gosub DISPOSE; drop
2235 /// goto END
2236 /// CATCH:
2237 /// using_dispose x <- merges the failure into the pending exception
2238 /// throw
2239 /// DISPOSE:
2240 /// using_dispose_init
2241 /// using_dispose x
2242 /// using_dispose_end <- rethrows if a dispose failed
2243 /// ret
2244 /// END:
2245 /// ```
2246 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2247 let Some(decl) = Self::using_declaration(stmt) else {
2248 unreachable!("using_region is only called for a using declaration");
2249 };
2250 // `using` binds exactly one name and has no pattern form, which the parser
2251 // enforces; the region still has to know *which* slot to dispose.
2252 let name = decl
2253 .declarators
2254 .first()
2255 .and_then(|declarator| match &declarator.target.kind {
2256 PatternKind::Ident(ident) => Some(ident.name.clone()),
2257 _ => None,
2258 });
2259 self.stmt(stmt)?;
2260 let Some(name) = name else {
2261 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2262 // must not make the compiler panic.
2263 return self.stmts(rest);
2264 };
2265 let Some(value_slot) = self.using_value_slot(&name) else {
2266 // Declared globally, which the parser rules out for a script; a module's
2267 // top level is a scope, and there the disposal stays a known gap.
2268 return self.stmts(rest);
2269 };
2270 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2271 // exit path already disposed.
2272 let live = !rest.last().is_some_and(Self::terminates);
2273 self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
2274 }
2275
2276 /// The slot a `using` binding's value lives in.
2277 fn using_value_slot(&self, name: &str) -> Option<u32> {
2278 self.cur()
2279 .vars
2280 .iter()
2281 .position(|var| var.name == name && var.kind == VarKind::Using)
2282 .map(|index| index as u32)
2283 }
2284
2285 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2286 ///
2287 /// Shared between a `using` statement — which owns the rest of its block — and a
2288 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2289 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2290 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2291 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2292 /// target with a `finally_label` is what makes `return` and `break` dispose without
2293 /// knowing anything about `using`.
2294 ///
2295 /// ```text
2296 /// catch CATCH <- an exception inside lands here
2297 /// <inside>
2298 /// drop <- the catch offset, on the fall-through path
2299 /// undefined; gosub DISPOSE; drop
2300 /// goto END
2301 /// CATCH:
2302 /// using_dispose slot <- merges the failure into the pending exception
2303 /// throw
2304 /// DISPOSE:
2305 /// using_dispose_init
2306 /// using_dispose slot
2307 /// using_dispose_end <- rethrows if a dispose failed
2308 /// ret
2309 /// END:
2310 /// ```
2311 fn using_region_around(
2312 &mut self,
2313 value_slot: u32,
2314 live: bool,
2315 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2316 ) -> Result<(), SyntaxError> {
2317 let catch_label = self.new_label();
2318 let end_label = self.new_label();
2319 let dispose_label = self.new_label();
2320
2321 self.emit_jump(Opcode::Catch, catch_label, &[]);
2322 self.push_jump_target(JumpTarget {
2323 names: Vec::new(),
2324 break_label: None,
2325 continue_label: None,
2326 // The catch offset is the one thing on the stack that leaving has to remove.
2327 drop_count: 1,
2328 finally_label: Some(dispose_label),
2329 is_regular_stmt: false,
2330 has_iterator: false,
2331 is_async_iterator: false,
2332 });
2333 inside(self)?;
2334 self.pop_jump_target();
2335
2336 if live {
2337 self.emit(Opcode::Drop, &[]);
2338 self.emit(Opcode::Undefined, &[]);
2339 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2340 self.emit(Opcode::Drop, &[]);
2341 self.emit_jump(Opcode::Goto, end_label, &[]);
2342 }
2343
2344 // An exception unwinds to here with the thrown value on the stack, which is exactly
2345 // the shape `using_dispose` expects as its error state.
2346 self.place_label(catch_label);
2347 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2348 self.emit(Opcode::Throw, &[]);
2349
2350 self.place_label(dispose_label);
2351 // Inside the subroutine the return value and the `gosub` return address are both
2352 // live, and neither an outer finalizer nor another region may run before this one
2353 // has finished.
2354 self.push_jump_target(JumpTarget {
2355 names: Vec::new(),
2356 break_label: None,
2357 continue_label: None,
2358 drop_count: 2,
2359 finally_label: None,
2360 is_regular_stmt: false,
2361 has_iterator: false,
2362 is_async_iterator: false,
2363 });
2364 self.emit(Opcode::UsingDisposeInit, &[]);
2365 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2366 self.emit(Opcode::UsingDisposeEnd, &[]);
2367 self.pop_jump_target();
2368 self.emit(Opcode::Ret, &[]);
2369 self.place_label(end_label);
2370 Ok(())
2371 }
2372
2373 /// Declare every name a statement list introduces, before compiling any of
2374 /// it, so a reference that appears textually before a declaration still
2375 /// resolves.
2376 ///
2377 /// Declarations are walked in source order because that is the order the
2378 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2379 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2380 /// declarations hoist out to the function scope; lexical names belong to the
2381 /// block they were written in, which `block` records.
2382 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2383 let saved = self.cur().current_block;
2384 self.state().current_block = block;
2385 let result = self.hoist_list(body);
2386 // Only now is every binding of this scope known, so the deferred function
2387 // bodies can be compiled against the finished list. Compiled at its own
2388 // declaration instead, a body that names a `var` written further down would
2389 // have resolved that name as a global.
2390 if result.is_ok() {
2391 let deferred = std::mem::take(&mut self.state().deferred_funcs);
2392 let mut outcome = Ok(());
2393 for (owner, func) in deferred {
2394 let previous = self.cur().current_block;
2395 self.state().current_block = owner;
2396 outcome = self.func_decl(&func);
2397 self.state().current_block = previous;
2398 if outcome.is_err() {
2399 break;
2400 }
2401 }
2402 self.state().current_block = saved;
2403 return outcome;
2404 }
2405 // `current_block` is restored by the caller for a block statement, since
2406 // it needs it set while compiling; only clean up on the hoist path.
2407 self.state().current_block = saved;
2408 result
2409 }
2410
2411 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2412 for stmt in body {
2413 self.hoist_stmt(stmt)?;
2414 }
2415 Ok(())
2416 }
2417
2418 /// Whether a statement always transfers control away, making everything after
2419 /// it in the same list unreachable.
2420 ///
2421 /// The reference drops such statements in `skip_dead_code`, so `return 1;
2422 /// let x = 2;` compiles to the same bytecode as `return 1;`.
2423 fn terminates(stmt: &Stmt) -> bool {
2424 matches!(
2425 stmt.kind,
2426 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2427 )
2428 }
2429
2430 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2431 match &stmt.kind {
2432 StmtKind::VarDecl(decl) => {
2433 for declarator in &decl.declarators {
2434 let mut names = Vec::new();
2435 declarator.target.bound_names(&mut names);
2436 for name in names {
2437 let text = name.name.clone();
2438 if decl.kind == VarDeclKind::Var {
2439 let def = VarDef::var(text.clone());
2440 self.declare_var(&text, def);
2441 } else if decl.kind.is_using() {
2442 // Two adjacent slots: the resource, then the dispose method
2443 // snapshotted at declaration. `using_dispose` reads them as a
2444 // pair `(slot, slot + 1)`, so nothing may be declared between
2445 // them — which is why both are declared here, in one step,
2446 // rather than the method being added at emission time.
2447 self.declare_using(&text);
2448 } else {
2449 let def = if decl.kind == VarDeclKind::Const {
2450 VarDef::constant(text.clone())
2451 } else {
2452 VarDef::lexical(text.clone())
2453 };
2454 self.declare(&text, def);
2455 }
2456 }
2457 }
2458 }
2459 StmtKind::FuncDecl(func) => {
2460 if let Some(name) = &func.name {
2461 // A function declaration is a `var` binding that happens to
2462 // hold a function, not a lexical one.
2463 let def = VarDef::var(name.name.clone());
2464 self.declare_var(&name.name.clone(), def);
2465 }
2466 // The function object is created when the scope is entered, so it
2467 // exists before the declaration is reached. Its body is compiled
2468 // *after* this scope's hoisting finishes, so a name it uses resolves
2469 // even when the `var` that declares it comes later in the source.
2470 let owner = self.cur().current_block;
2471 self.state().deferred_funcs.push((owner, func.clone()));
2472 }
2473 StmtKind::ClassDecl(class) => {
2474 if let Some(name) = &class.name {
2475 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2476 }
2477 }
2478 // A module's imports are bound before any of its code runs, and its exports
2479 // declare the very bindings they export — so both hoist the declarations
2480 // their `StmtKind` arm will later emit code for.
2481 StmtKind::Import(decl) => self.hoist_import(decl)?,
2482 StmtKind::Export(decl) => self.hoist_export(decl)?,
2483 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2484 StmtKind::If { cons, alt, .. } => {
2485 self.hoist_stmt(cons)?;
2486 if let Some(alt) = alt {
2487 self.hoist_stmt(alt)?;
2488 }
2489 }
2490 StmtKind::While { body, .. }
2491 | StmtKind::DoWhile { body, .. }
2492 | StmtKind::Labeled { body, .. }
2493 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2494 StmtKind::For { init, body, .. } => {
2495 // A `for` head gets its own scope even when it declares nothing,
2496 // because `let` in the head is scoped to the loop.
2497 let key = stmt.span.start.offset as u64;
2498 let parent = self.cur().current_block;
2499 self.push_block(key, parent);
2500 if let Some(init) = init
2501 && let ForInit::VarDecl(decl) = init
2502 {
2503 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2504 }
2505 self.hoist_stmt(body)?;
2506 self.state().current_block = parent;
2507 }
2508 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2509 let key = stmt.span.start.offset as u64;
2510 let parent = self.cur().current_block;
2511 self.push_block(key, parent);
2512 if let ForHead::VarDecl(decl) = left {
2513 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2514 }
2515 self.hoist_stmt(body)?;
2516 self.state().current_block = parent;
2517 }
2518 StmtKind::Try {
2519 block,
2520 handler,
2521 finalizer,
2522 } => {
2523 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2524 let try_parent = self.cur().current_block;
2525 if let Some(handler) = handler {
2526 // The catch parameter belongs to the function scope, not to a
2527 // block: it is a `catch` binding rather than a `let`, so it is
2528 // never in the temporal dead zone and `emit_scope_enter` must
2529 // not mark it uninitialised. It still has to be declared before
2530 // the handler body is hoisted, so it takes the slot the
2531 // reference gives it (bindings are numbered in source order).
2532 if let Some(pattern) = &handler.param {
2533 // The parameter gets its own scope, so entering the handler
2534 // does not have to re-declare it. It is not lexical, so it
2535 // is never marked uninitialised.
2536 let key = Self::try_block_key(stmt, TryPart::Param);
2537 let parent = self.cur().current_block;
2538 self.push_block(key, parent);
2539 // A destructuring parameter binds several names, one slot each,
2540 // in the order they are written. The reference declares those as
2541 // `let`s rather than as one `catch` binding — its dump prints
2542 // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2543 // so the kind follows the shape of the parameter.
2544 //
2545 // Neither form is in the dead zone: the stores run as the handler
2546 // is entered, so both use the unchecked `put_loc`.
2547 let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2548 let mut names = Vec::new();
2549 pattern.bound_names(&mut names);
2550 for name in names {
2551 let def = VarDef {
2552 name: name.name.clone(),
2553 is_const: false,
2554 is_lexical: destructures,
2555 kind: if destructures {
2556 crate::bytecode::VarKind::LexicalCatch
2557 } else {
2558 crate::bytecode::VarKind::Catch
2559 },
2560 is_captured: false,
2561 scope_level: 0,
2562 scope_next: None,
2563 };
2564 self.declare_local(&name.name.clone(), def);
2565 }
2566 // The handler body nests inside the parameter's scope, so the
2567 // body's bindings chain on to the parameter (the reference
2568 // prints `let y [next:1]`, pointing at `e`).
2569 self.state().current_block = key;
2570 }
2571 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2572 // Back to the block the `try` itself lives in, so the finalizer
2573 // is a sibling of the handler rather than nested in it.
2574 self.state().current_block = try_parent;
2575 }
2576 if let Some(finalizer) = finalizer {
2577 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2578 }
2579 }
2580 StmtKind::Switch { cases, .. } => {
2581 let key = stmt.span.start.offset as u64;
2582 let parent = self.cur().current_block;
2583 self.push_block(key, parent);
2584 for case in cases {
2585 self.hoist_list(&case.body)?;
2586 }
2587 self.state().current_block = parent;
2588 }
2589 _ => {}
2590 }
2591 Ok(())
2592 }
2593
2594 /// Hoist a nested statement list, which is its own lexical scope.
2595 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2596 let parent = self.cur().current_block;
2597 self.push_block(key, parent);
2598 self.hoist_list(body)?;
2599 self.state().current_block = parent;
2600 Ok(())
2601 }
2602
2603 /// A block key for one part of a `try` statement.
2604 ///
2605 /// The three parts are three separate scopes, so they cannot share the key a
2606 /// statement's own offset would give them: the try block, the handler body and
2607 /// the finalizer would then look like one scope, and their `let` bindings would
2608 /// be marked uninitialised only on entering the first of them.
2609 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2610 (stmt.span.start.offset as u64) * 4 + part as u64
2611 }
2612
2613 /// Declare a `var`: it lives in the function's own scope, not the block's.
2614 fn declare_var(&mut self, name: &str, def: VarDef) {
2615 if self.cur().is_module {
2616 self.declare_module(name, &def);
2617 return;
2618 }
2619 if self.cur().declares_globally(&def) {
2620 self.declare_global(name, &def);
2621 return;
2622 }
2623 let state = self.state();
2624 // A binding of the *parameter* scope does not count: the body's `var` of the
2625 // same name is a different binding and needs a slot of its own.
2626 if state.vars.iter().enumerate().any(|(index, v)| {
2627 v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2628 }) {
2629 return;
2630 }
2631 // A `var` belongs to the function scope, never to the enclosing block.
2632 state.var_block.push(FUNCTION_SCOPE);
2633 state.vars.push(def);
2634 }
2635
2636 /// Declare `name` as a binding of the parameter scope, returning its slot.
2637 fn declare_param_var(&mut self, name: &str) -> u32 {
2638 declare_param_var_at(self.state(), name)
2639 }
2640
2641 /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2642 ///
2643 /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2644 /// so each points at the one declared before it and the oldest ends the chain with
2645 /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2646 /// runtime walks when it instantiates them.
2647 fn declare_param_binding(&mut self, name: &str) -> u32 {
2648 let state = self.state();
2649 let previous = state
2650 .vars
2651 .iter()
2652 .enumerate()
2653 .rev()
2654 .find(|(index, var)| {
2655 state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2656 })
2657 .map(|(index, _)| index as i32);
2658 let index = state.vars.len() as u32;
2659 state.var_block.push(PARAM_SCOPE);
2660 let mut def = VarDef::lexical(name);
2661 // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2662 // the function's, and its bindings are initialised one by one rather than all at
2663 // once — which is exactly what the dead zone needs.
2664 def.scope_level = 1;
2665 def.scope_next = Some(previous.unwrap_or(-2));
2666 state.vars.push(def);
2667 index
2668 }
2669
2670 /// The slot of a parameter-list binding, if the list has one by that name.
2671 fn param_binding_slot(&self, name: &str) -> Option<u32> {
2672 let state = self.cur();
2673 state
2674 .vars
2675 .iter()
2676 .enumerate()
2677 .position(|(index, var)| {
2678 var.name == name
2679 && var.is_lexical
2680 && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2681 })
2682 .map(|index| index as u32)
2683 }
2684
2685 /// Every parameter-list binding, in declaration order.
2686 fn param_binding_names(&self) -> Vec<String> {
2687 let state = self.cur();
2688 state
2689 .vars
2690 .iter()
2691 .enumerate()
2692 .filter(|(index, var)| {
2693 var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2694 })
2695 .map(|(_, var)| var.name.clone())
2696 .collect()
2697 }
2698
2699 /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2700 fn body_var_slot(&self, name: &str) -> Option<u32> {
2701 let state = self.cur();
2702 state
2703 .vars
2704 .iter()
2705 .enumerate()
2706 .find(|(index, var)| {
2707 var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2708 })
2709 .map(|(index, _)| index as u32)
2710 }
2711
2712 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2713 /// one.
2714 ///
2715 /// With parameter expressions the reference creates two: an unmapped one in the
2716 /// argument scope, for the defaults and anything they close over, and the body's own.
2717 /// They are separate bindings, which is what makes
2718 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2719 /// report 1 from `p` and 2 from the body.
2720 fn provide_param_arguments(&mut self) {
2721 if !self.cur().has_parameter_expressions {
2722 return;
2723 }
2724 let mentioned = self.cur().needs_param_arguments
2725 || self
2726 .cur()
2727 .insns
2728 .iter()
2729 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2730 if !mentioned {
2731 return;
2732 }
2733 let slot = self.declare_param_var("arguments");
2734 let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2735 0
2736 } else {
2737 1
2738 };
2739 self.prepend_initialiser_to(
2740 slot,
2741 Insn::Fixed {
2742 op: Opcode::SpecialObject,
2743 operands: vec![Op::Int(magic)],
2744 },
2745 );
2746 }
2747
2748 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2749 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2750 let current = self.stack.len() - 1;
2751 let init = [
2752 producer,
2753 Insn::Fixed {
2754 op: Opcode::PutLoc,
2755 operands: vec![Op::Slot(Slot::Loc(slot))],
2756 },
2757 ];
2758 let inserted = init.len();
2759 for (index, instruction) in init.into_iter().enumerate() {
2760 self.stack[current].insns.insert(index, instruction);
2761 }
2762 for placed in self.stack[current].labels.iter_mut().flatten() {
2763 *placed += inserted;
2764 }
2765 self.state().label_since_insn = false;
2766 }
2767
2768 /// Give the function an `arguments` binding if its body mentions one.
2769 ///
2770 /// The check runs on the *instruction* stream rather than the AST: by this point
2771 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2772 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2773 /// would renumber every later local slot and stop the bytecode matching the
2774 /// reference, which only adds the binding when the body uses it.
2775 ///
2776 /// `arguments` is a local, initialised at the top of the body by
2777 /// `special_object`; that is the reference's shape, so the disassembly agrees.
2778 fn provide_arguments(&mut self) {
2779 let current = self.stack.len() - 1;
2780 if self.stack[current].is_script || self.stack[current].is_module {
2781 // A module has no `arguments` binding; referring to it is a ReferenceError,
2782 // which is exactly what an unbound name produces.
2783 return;
2784 }
2785 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2786 // function, which is why `() => arguments` sees the caller's arguments.
2787 if self.stack[current].is_arrow {
2788 if self.mentions("arguments") {
2789 self.ensure_enclosing_arguments();
2790 }
2791 return;
2792 }
2793 // Only a *body* mention needs the body's binding: the parameter list has one of
2794 // its own (see [`Compiler::provide_param_arguments`]).
2795 //
2796 // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2797 // `Var`, so without this the body got no binding at all — the name resolved to
2798 // the global object and `delete` answered `true` for a binding that cannot be
2799 // deleted. The reference answers `false`.
2800 let mentioned = self.cur().insns.iter().any(|insn| match insn {
2801 Insn::Var {
2802 name, in_params, ..
2803 } => name == "arguments" && !*in_params,
2804 Insn::DeleteVar { name } => name == "arguments",
2805 _ => false,
2806 });
2807 // A mention that resolves to the body's *own* lexical `arguments` is not a request
2808 // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
2809 // implicit binding is not created at all. Providing it anyway was worse than useless:
2810 // its prologue store resolved past the shadowing `let` and landed on the **global**,
2811 // so `function f(p = eval("var arguments")) { let arguments; }` defined
2812 // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
2813 // test262's `fn-body-cntns-arguments-lex-bind` family).
2814 //
2815 // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
2816 // var *is* the binding, and the implicit arguments object is initialised into it at
2817 // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
2818 // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
2819 // `typeof arguments` `"undefined"`.
2820 if self
2821 .cur()
2822 .vars
2823 .iter()
2824 .any(|var| var.name == "arguments" && var.needs_check())
2825 {
2826 return;
2827 }
2828 if !mentioned && !self.cur().needs_arguments_local {
2829 return;
2830 }
2831 // The request may have come only from a parameter-list arrow, in which case the
2832 // parameter scope's binding already answers for it and the body needs none.
2833 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2834 return;
2835 }
2836 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
2837 //
2838 // With parameter expressions the list and the body are separate environments, so
2839 // an assignment to a parameter cannot be reflected into `arguments` at all — the
2840 // arguments object is unmapped whatever the mode, which is why the reference emits
2841 // `special_object 0` here even in sloppy code.
2842 // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
2843 // object unmapped whatever the mode — §10.4.4 keys the decision on
2844 // `IsSimpleParameterList`, not on strictness alone.
2845 let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
2846 0
2847 } else {
2848 1
2849 };
2850 // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
2851 // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
2852 // The only storage both sides can see is a reference cell, so every parameter the
2853 // object maps gets one — even a parameter no closure captured. Without this the
2854 // slot holds a plain copy and the mapping has nothing to write through.
2855 if magic == 1 {
2856 for arg in &mut self.stack[current].args {
2857 arg.is_captured = true;
2858 }
2859 }
2860 self.prepend_binding("arguments", magic);
2861 }
2862
2863 /// Whether a *body* instruction refers to `arguments`.
2864 fn body_mentions_arguments(&self) -> bool {
2865 self.cur()
2866 .insns
2867 .iter()
2868 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2869 }
2870
2871 /// Whether the function body's instruction stream refers to `name`.
2872 fn mentions(&self, name: &str) -> bool {
2873 let current = self.stack.len() - 1;
2874 // A binding of the parameter scope does not answer for the body: the body's own
2875 // `arguments` (or self-name) still has to be provided for it.
2876 if self.stack[current]
2877 .vars
2878 .iter()
2879 .enumerate()
2880 .any(|(index, v)| {
2881 v.name == name
2882 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2883 })
2884 {
2885 return false;
2886 }
2887 self.stack[current]
2888 .insns
2889 .iter()
2890 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2891 }
2892
2893 /// Bind the name a named function expression uses to refer to itself.
2894 ///
2895 /// The value is `special_object 2`, the function currently running, so the binding
2896 /// is the closure itself and not a copy. It is a local of this function, which is
2897 /// what keeps `g` out of the enclosing scope.
2898 /// Give the function a local `this`, for an arrow inside it to capture.
2899 fn provide_this_local(&mut self) {
2900 let current = self.stack.len() - 1;
2901 if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2902 return;
2903 }
2904 if !self.stack[current]
2905 .vars
2906 .iter()
2907 .any(|var| var.name == "this")
2908 {
2909 self.declare_hidden_local("this", VarKind::Normal);
2910 }
2911 self.prepend_initialiser(
2912 "this",
2913 Insn::Fixed {
2914 op: Opcode::PushThis,
2915 operands: vec![],
2916 },
2917 );
2918 }
2919
2920 /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2921 /// to read through `super`.
2922 fn provide_home_object_local(&mut self) {
2923 let current = self.stack.len() - 1;
2924 if !self.stack[current].needs_home_object_local {
2925 return;
2926 }
2927 if !self.stack[current]
2928 .vars
2929 .iter()
2930 .any(|var| var.name == HOME_OBJECT)
2931 {
2932 self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2933 }
2934 self.prepend_initialiser(
2935 HOME_OBJECT,
2936 Insn::Fixed {
2937 op: Opcode::SpecialObject,
2938 operands: vec![Op::Int(4)],
2939 },
2940 );
2941 }
2942
2943 fn provide_self_name(&mut self) {
2944 let current = self.stack.len() - 1;
2945 let Some(name) = self.stack[current].self_name.clone() else {
2946 return;
2947 };
2948 if self.stack[current].self_name_initialized {
2949 return;
2950 }
2951 // Either the body refers to the name, or a nested function already forced the
2952 // binding into existence while being resolved. A direct `eval` can name it
2953 // without mentioning it, so its presence is a third reason: in strict mode
2954 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2955 // that only happens if the binding exists.
2956 let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2957 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2958 return;
2959 }
2960 self.stack[current].self_name_initialized = true;
2961 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2962 }
2963
2964 /// Insert `special_object magic` plus the store to `name` at the top of the body.
2965 ///
2966 /// Prepending shifts every label that has been placed, so they are all moved by
2967 /// the number of instructions inserted.
2968 fn prepend_binding(&mut self, name: &str, magic: i32) {
2969 self.prepend_binding_with(name, magic, VarKind::Normal);
2970 }
2971
2972 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2973 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2974 let current = self.stack.len() - 1;
2975 // A function-expression's own name is immutable in strict mode, which is what
2976 // makes `f = 1` inside a strict body throw instead of being dropped.
2977 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2978 self.declare_var(
2979 name,
2980 VarDef {
2981 kind,
2982 is_const,
2983 ..VarDef::var(name)
2984 },
2985 );
2986 let init = [
2987 Insn::Fixed {
2988 op: Opcode::SpecialObject,
2989 operands: vec![Op::Int(magic)],
2990 },
2991 Insn::Var {
2992 // An initialisation, not an assignment: sloppy mode drops stores to a
2993 // function-expression's own name, and the prologue is what puts the
2994 // value there in the first place.
2995 action: if kind == VarKind::FunctionName {
2996 VarAction::PutInit
2997 } else {
2998 VarAction::Put
2999 },
3000 name: name.to_string(),
3001 block: 0,
3002 in_params: false,
3003 },
3004 ];
3005 let inserted = init.len();
3006 for (index, instruction) in init.into_iter().enumerate() {
3007 self.stack[current].insns.insert(index, instruction);
3008 }
3009 for placed in self.stack[current].labels.iter_mut().flatten() {
3010 *placed += inserted;
3011 }
3012 // A store sits at the insertion point now, so the `put`/`get` fold must not
3013 // reach across it.
3014 self.stack[current].label_since_insn = true;
3015 }
3016
3017 /// Record a top-level script declaration as a global.
3018 ///
3019 /// A script's top-level `var`/`let`/`function` create properties of the
3020 /// global object, not slots in the script's frame, so they show up as closure
3021 /// variables instead.
3022 fn declare_global(&mut self, name: &str, def: &VarDef) {
3023 let state = self.state();
3024 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3025 // The name was already referenced, from a function compiled before this
3026 // declaration was reached — `function a(){ b() } function b(){}` resolves
3027 // `b` while `b` is still unknown, and that guess has to be corrected here.
3028 // Leaving it as a plain global meant the declaration was never registered,
3029 // so the binding did not exist at run time and `a()` threw
3030 // `b is not defined`.
3031 if matches!(existing.closure_type, ClosureType::Global) {
3032 existing.closure_type = ClosureType::GlobalDecl;
3033 existing.is_const = def.is_const;
3034 existing.is_lexical = def.is_lexical;
3035 }
3036 return;
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::GlobalDecl,
3043 var_idx: 0,
3044 });
3045 }
3046
3047 /// Record a module-level declaration as a module variable.
3048 ///
3049 /// The binding is a closure variable of the module body, so reads and writes are
3050 /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
3051 /// *who fills the cell*: the module record does, before the body runs, and an import
3052 /// points its cell at the exporting module's, which is what makes bindings live and
3053 /// cycles work.
3054 fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
3055 let state = self.state();
3056 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3057 // The name may have been referenced before this declaration was hoisted,
3058 // which resolved it as a plain global. Correct that here, the way
3059 // `declare_global` does.
3060 if matches!(existing.closure_type, ClosureType::Global) {
3061 existing.closure_type = ClosureType::ModuleDecl;
3062 existing.is_const = def.is_const;
3063 existing.is_lexical = def.is_lexical;
3064 }
3065 return 0;
3066 }
3067 state.closure_vars.push(ClosureVar {
3068 name: name.to_string(),
3069 is_const: def.is_const,
3070 is_lexical: def.is_lexical,
3071 closure_type: ClosureType::ModuleDecl,
3072 var_idx: 0,
3073 });
3074 0
3075 }
3076
3077 /// Declare a module variable and answer its closure-variable index.
3078 ///
3079 /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
3080 /// module variable is not one. The import table needs the real index instead, because
3081 /// that is the position the host writes the cell into.
3082 fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
3083 self.declare_module(name, def);
3084 self.cur()
3085 .closure_vars
3086 .iter()
3087 .position(|c| c.name == name)
3088 .map(|index| index as u32)
3089 .unwrap_or(0)
3090 }
3091
3092 /// Declare one imported binding as a module variable.
3093 ///
3094 /// Returns the closure-variable index, which is what the import table records: the
3095 /// host writes the exporter's cell into that slot before the body runs.
3096 fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
3097 let state = self.state();
3098 if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
3099 // Keep the slot, fix the kind: the name may already have been referenced.
3100 state.closure_vars[index].closure_type = ClosureType::ModuleImport;
3101 state.closure_vars[index].is_const = is_const;
3102 return index as u32;
3103 }
3104 state.closure_vars.push(ClosureVar {
3105 name: name.to_string(),
3106 // An imported binding cannot be assigned: `x = 1` on an import is a
3107 // `TypeError` at run time, which the const flag is what produces.
3108 is_const: true,
3109 // Lexical, so reads go through `get_var_ref_check`: before linking has filled
3110 // the cell an import is in its dead zone, and reading it there must say so
3111 // rather than answer `undefined`.
3112 is_lexical: true,
3113 closure_type: ClosureType::ModuleImport,
3114 var_idx: 0,
3115 });
3116 state.closure_vars.len() as u32 - 1
3117 }
3118
3119 /// Emit the code an `export` needs.
3120 ///
3121 /// Only `export default <expr>` has any: everything else is a table entry whose
3122 /// binding is declared elsewhere. The expression is stored into the hidden
3123 /// `*default*` variable rather than returned, because the module body has no value
3124 /// to speak of.
3125 fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3126 match &decl.kind {
3127 ExportKind::Declaration(stmt) => self.stmt(stmt),
3128 ExportKind::Default(expr) => {
3129 // `export default class Foo {}`: evaluate the declaration (which binds
3130 // `Foo`), then copy its value into the hidden `*default*` binding, because a
3131 // class declaration is a *statement* and `expr` cannot be compiled as one.
3132 if let ExprKind::Class(class) = &expr.kind
3133 && class.name.is_some()
3134 {
3135 self.stmt(&Stmt {
3136 kind: StmtKind::ClassDecl(class.clone()),
3137 span: expr.span,
3138 })?;
3139 let Some(name) = &class.name else {
3140 return Ok(());
3141 };
3142 self.emit_var(VarAction::Get, &name.name);
3143 let index = self.declare_export_default();
3144 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3145 return Ok(());
3146 }
3147 // A named default function/class is already a module binding; the export
3148 // points at it and there is nothing to evaluate.
3149 if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
3150 return Ok(());
3151 }
3152 self.expr(expr)?;
3153 // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
3154 // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
3155 // name is observable — `imported.default.name` — and without this an
3156 // anonymous `export default class {}` arrived with the empty name.
3157 self.set_name_if_anonymous(expr, &Wtf8::new("default"));
3158 let index = self.declare_export_default();
3159 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3160 Ok(())
3161 }
3162 ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
3163 }
3164 }
3165
3166 /// A module name as the string it denotes.
3167 fn module_name_text(name: &ModuleName) -> &str {
3168 match name {
3169 ModuleName::Ident(ident) => &ident.name,
3170 ModuleName::Str(text) => text,
3171 }
3172 }
3173
3174 /// Bind `import`'s local names and record where each one comes from.
3175 ///
3176 /// Nothing is emitted: an import is not an instruction, it is a promise that the
3177 /// binding's cell will be filled before the body runs. The cell lands in the module's
3178 /// environment at a fixed index, and the host fills it from the exporter's cell —
3179 /// which is why a cyclic import can bind before the other module has evaluated.
3180 fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
3181 let request = self.module_request(&decl.source, &decl.attributes);
3182 for specifier in &decl.specifiers {
3183 let (local, name, is_star) = match specifier {
3184 ImportSpecifier::Default(ident) => {
3185 (ident.name.clone(), "default".to_string(), false)
3186 }
3187 ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3188 ImportSpecifier::Named { imported, local } => (
3189 local.name.clone(),
3190 Self::module_name_text(imported).to_string(),
3191 false,
3192 ),
3193 };
3194 // `import * as ns` is *not* a live binding of another module's variable —
3195 // it is a value of its own, which is why the reference declares it like a
3196 // module variable and the host stores the namespace object in that cell.
3197 let var_idx = if is_star {
3198 // `const`: a namespace object is a value, and the binding is immutable.
3199 self.declare_module_var(&local, &VarDef::constant(local.clone()))
3200 } else {
3201 self.declare_import(&local, true)
3202 };
3203 self.module_meta().imports.push(ImportEntry {
3204 module: request,
3205 name,
3206 var_idx,
3207 is_star,
3208 });
3209 }
3210 Ok(())
3211 }
3212
3213 /// Record what an `export` offers, declaring the binding it exports.
3214 ///
3215 /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3216 fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3217 match &decl.kind {
3218 ExportKind::Declaration(stmt) => {
3219 // The inner declaration keeps its own hoisting, then every name it binds
3220 // becomes an export of the same name.
3221 self.hoist_stmt(stmt)?;
3222 let mut names = Vec::new();
3223 Self::declared_names(stmt, &mut names);
3224 for name in names {
3225 let var_idx = self.module_binding_index(&name);
3226 self.exports_local(&name, var_idx);
3227 }
3228 }
3229 ExportKind::Default(expr) => {
3230 // The reference puts a default export in a hidden `*default*` variable,
3231 // so `export default function f(){}` can export a *value* while `f` stays
3232 // a binding of the module.
3233 if let ExprKind::Function(func) = &expr.kind
3234 && let Some(name) = &func.name
3235 {
3236 let text = name.name.clone();
3237 self.hoist_stmt(&Stmt {
3238 kind: StmtKind::FuncDecl(func.clone()),
3239 span: expr.span,
3240 })?;
3241 let var_idx = self.module_binding_index(&text);
3242 self.module_meta().exports.push(ExportEntry::Local {
3243 export_name: "default".to_string(),
3244 var_idx,
3245 });
3246 return Ok(());
3247 }
3248 if let ExprKind::Class(class) = &expr.kind
3249 && class.name.is_some()
3250 {
3251 // `export default class Foo {}` binds `Foo` in the module scope **and**
3252 // stores the class into the hidden `*default*` binding — it is a
3253 // declaration *and* a value, unlike `export default class {}` which is
3254 // only a value.
3255 //
3256 // Pointing the `default` export straight at `Foo` looked simpler and was
3257 // wrong twice over: `module_binding_index` did not find the lexical
3258 // binding the hoist had just made, so it declared a second one that
3259 // nothing ever wrote, and `export_stmt` then had no code to emit for the
3260 // declaration either. `imported.default` came out `undefined` and `Foo`
3261 // was not in scope inside its own module.
3262 self.hoist_stmt(&Stmt {
3263 kind: StmtKind::ClassDecl(class.clone()),
3264 span: expr.span,
3265 })?;
3266 let var_idx = self.declare_export_default();
3267 self.exports_local("default", var_idx);
3268 return Ok(());
3269 }
3270 let var_idx = self.declare_export_default();
3271 self.module_meta().exports.push(ExportEntry::Local {
3272 export_name: "default".to_string(),
3273 var_idx,
3274 });
3275 }
3276 ExportKind::Named {
3277 specifiers,
3278 source,
3279 attributes,
3280 } => match source {
3281 Some(source) => {
3282 let request = self.module_request(source, attributes);
3283 for specifier in specifiers {
3284 self.module_meta().exports.push(ExportEntry::Indirect {
3285 export_name: Self::module_name_text(&specifier.exported).to_string(),
3286 module: request,
3287 import_name: Self::module_name_text(&specifier.local).to_string(),
3288 });
3289 }
3290 }
3291 None => {
3292 for specifier in specifiers {
3293 let local = Self::module_name_text(&specifier.local).to_string();
3294 let export_name = Self::module_name_text(&specifier.exported).to_string();
3295 // `export { x }` where `x` is itself an **import** re-exports the
3296 // binding the import names, not a binding of this module
3297 // (§16.2.1.6.3: a local export whose local name is imported resolves
3298 // through the imported module). Recording it as a local made two
3299 // modules that both forward one import look like two different
3300 // bindings, and the name was reported ambiguous
3301 // (`import-and-export-propagates-binding`;
3302 // `namespace-unambiguous-if-import-star-as-and-export`).
3303 let closure_names: Vec<String> = self
3304 .cur()
3305 .closure_vars
3306 .iter()
3307 .map(|var| var.name.clone())
3308 .collect();
3309 let forwarded = self
3310 .module_meta()
3311 .imports
3312 .iter()
3313 .filter(|entry| {
3314 closure_names
3315 .get(entry.var_idx as usize)
3316 .is_some_and(|name| *name == local)
3317 })
3318 .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3319 .find(|(_, name, is_star)| !is_star || name.is_empty());
3320 if let Some((request, name, is_star)) = forwarded {
3321 // A namespace import has no export *name* of its own; the
3322 // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3323 // which is what the marker below records.
3324 let import_name = if is_star {
3325 "*namespace*".to_string()
3326 } else {
3327 name
3328 };
3329 self.module_meta().exports.push(ExportEntry::Indirect {
3330 export_name,
3331 module: request,
3332 import_name,
3333 });
3334 continue;
3335 }
3336 let var_idx = self.module_binding_index(&local);
3337 self.module_meta().exports.push(ExportEntry::Local {
3338 export_name,
3339 var_idx,
3340 });
3341 }
3342 }
3343 },
3344 ExportKind::All {
3345 source,
3346 exported,
3347 attributes,
3348 } => {
3349 let request = self.module_request(source, attributes);
3350 match exported {
3351 Some(name) => {
3352 self.module_meta().exports.push(ExportEntry::StarAs {
3353 export_name: Self::module_name_text(name).to_string(),
3354 module: request,
3355 });
3356 }
3357 None => {
3358 self.module_meta()
3359 .exports
3360 .push(ExportEntry::Star { module: request });
3361 }
3362 }
3363 }
3364 }
3365 Ok(())
3366 }
3367
3368 /// The names a declaration binds, which is what `export <decl>` exports.
3369 fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3370 match &stmt.kind {
3371 StmtKind::VarDecl(decl) => {
3372 for declarator in &decl.declarators {
3373 let mut names = Vec::new();
3374 declarator.target.bound_names(&mut names);
3375 out.extend(names.into_iter().map(|name| name.name));
3376 }
3377 }
3378 StmtKind::FuncDecl(func) => {
3379 if let Some(name) = &func.name {
3380 out.push(name.name.clone());
3381 }
3382 }
3383 StmtKind::ClassDecl(class) => {
3384 if let Some(name) = &class.name {
3385 out.push(name.name.clone());
3386 }
3387 }
3388 _ => {}
3389 }
3390 }
3391
3392 /// The closure-variable index of a module binding, declaring it if the name was
3393 /// exported without being declared here.
3394 ///
3395 /// `export { x }` where `x` is not declared in the module is a link-time
3396 /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3397 fn module_binding_index(&mut self, name: &str) -> u32 {
3398 if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3399 return index as u32;
3400 }
3401 self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3402 }
3403
3404 fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3405 self.module_meta().exports.push(ExportEntry::Local {
3406 export_name: export_name.to_string(),
3407 var_idx,
3408 });
3409 }
3410
3411 /// The hidden `*default*` binding `export default <expr>` stores into.
3412 fn declare_export_default(&mut self) -> u32 {
3413 const DEFAULT: &str = "*default*";
3414 if let Some(index) = self
3415 .cur()
3416 .closure_vars
3417 .iter()
3418 .position(|c| c.name == DEFAULT)
3419 {
3420 return index as u32;
3421 }
3422 self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3423 }
3424
3425 /// The module tables, which only the top-level state has.
3426 fn module_meta(&mut self) -> &mut ModuleMeta {
3427 self.state()
3428 .module
3429 .as_mut()
3430 .expect("module tables are only touched while compiling a module")
3431 }
3432
3433 /// The index of `specifier`'s request, adding it if it is new.
3434 ///
3435 /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3436 /// JSON and once as text is two modules with two different contents, which is exactly
3437 /// what `hello_module.js` does.
3438 fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3439 let attributes: Vec<(String, String)> = attributes
3440 .iter()
3441 .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3442 .collect();
3443 let meta = self.module_meta();
3444 if let Some(index) = meta
3445 .requests
3446 .iter()
3447 .position(|request| request.specifier == specifier && request.attributes == attributes)
3448 {
3449 return index as u32;
3450 }
3451 meta.requests.push(ModuleRequest {
3452 specifier: specifier.to_string(),
3453 attributes,
3454 });
3455 meta.requests.len() as u32 - 1
3456 }
3457
3458 /// Compile a loop body with a `break`/`continue` target pushed for it.
3459 fn loop_body(
3460 &mut self,
3461 body: &Stmt,
3462 labels: &[String],
3463 continue_label: Label,
3464 break_label: Label,
3465 ) -> Result<(), SyntaxError> {
3466 self.push_jump_target(JumpTarget {
3467 names: labels.to_vec(),
3468 break_label: Some(break_label),
3469 continue_label: Some(continue_label),
3470 // A loop leaves nothing of its own on the value stack.
3471 drop_count: 0,
3472 finally_label: None,
3473 is_regular_stmt: false,
3474 has_iterator: false,
3475 is_async_iterator: false,
3476 });
3477 let result = self.stmt(body);
3478 self.pop_jump_target();
3479 result
3480 }
3481
3482 fn push_jump_target(&mut self, target: JumpTarget) {
3483 self.state().jump_targets.push(target);
3484 }
3485
3486 fn pop_jump_target(&mut self) {
3487 self.state().jump_targets.pop();
3488 }
3489
3490 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3491 let (label, is_break) = match &stmt.kind {
3492 StmtKind::Break(label) => (label.as_ref(), true),
3493 StmtKind::Continue(label) => (label.as_ref(), false),
3494 _ => unreachable!("control_transfer is only called for break and continue"),
3495 };
3496
3497 // Walk outward from the innermost construct. Everything considered before
3498 // the match is a construct control is leaving, and leaving it has a cost:
3499 // its stack slots go, and its finalizer runs.
3500 let targets = self.cur().jump_targets.clone();
3501 for target in targets.iter().rev() {
3502 let destination = match (label, is_break) {
3503 // An unlabelled `break` skips a labelled non-loop statement: `break`
3504 // may name one, but the bare form only means "leave the loop".
3505 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3506 (None, false) => target.continue_label,
3507 (Some(name), true) => target
3508 .break_label
3509 .filter(|_| target.names.contains(&name.name)),
3510 (Some(name), false) => target
3511 .continue_label
3512 .filter(|_| target.names.contains(&name.name)),
3513 };
3514
3515 if let Some(destination) = destination {
3516 self.emit_jump(Opcode::Goto, destination, &[]);
3517 return Ok(());
3518 }
3519
3520 // Closing the iterator consumes the three slots the loop keeps on the
3521 // stack (iterator, next method, catch offset), so those are not dropped
3522 // again below.
3523 let mut remaining = target.drop_count;
3524 if target.has_iterator {
3525 self.emit_iterator_close(target.is_async_iterator, false);
3526 remaining = remaining.saturating_sub(3);
3527 }
3528 for _ in 0..remaining {
3529 self.emit(Opcode::Drop, &[]);
3530 }
3531 if let Some(finally) = target.finally_label {
3532 // The finalizer runs as a subroutine and is handed a dummy return
3533 // value, which is dropped afterwards to keep the stack the depth it
3534 // had before.
3535 self.emit(Opcode::Undefined, &[]);
3536 self.emit_jump(Opcode::Gosub, finally, &[]);
3537 self.emit(Opcode::Drop, &[]);
3538 }
3539 }
3540
3541 // The parser rejects a break/continue with no target, so reaching here
3542 // means the compiler's own bookkeeping is wrong.
3543 Err(SyntaxError::new(
3544 if is_break {
3545 "break has no enclosing loop or switch"
3546 } else {
3547 "continue has no enclosing loop"
3548 },
3549 stmt.span,
3550 ))
3551 }
3552
3553 /// Compile a labelled statement.
3554 ///
3555 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3556 /// that loop's targets, so the chain is collected and handed to the loop. A
3557 /// label on a non-loop statement only provides a `break` target, because
3558 /// `continue` may not target it.
3559 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3560 let mut names = vec![label.name.clone()];
3561 let mut inner = body;
3562 while let StmtKind::Labeled {
3563 label: next,
3564 body: deeper,
3565 } = &inner.kind
3566 {
3567 names.push(next.name.clone());
3568 inner = deeper;
3569 }
3570 if Self::is_loop(inner) {
3571 return self.stmt_labelled(inner, &names);
3572 }
3573 let end = self.new_label();
3574 self.push_jump_target(JumpTarget {
3575 names,
3576 break_label: Some(end),
3577 continue_label: None,
3578 drop_count: 0,
3579 finally_label: None,
3580 is_regular_stmt: true,
3581 has_iterator: false,
3582 is_async_iterator: false,
3583 });
3584 let result = self.stmt(inner);
3585 self.pop_jump_target();
3586 result?;
3587 self.place_label(end);
3588 let _ = stmt;
3589 Ok(())
3590 }
3591
3592 /// Whether a statement is a loop, i.e. a valid target for `continue`.
3593 fn is_loop(stmt: &Stmt) -> bool {
3594 matches!(
3595 stmt.kind,
3596 StmtKind::While { .. }
3597 | StmtKind::DoWhile { .. }
3598 | StmtKind::For { .. }
3599 | StmtKind::ForIn { .. }
3600 | StmtKind::ForOf { .. }
3601 )
3602 }
3603
3604 /// Compile `switch`.
3605 ///
3606 /// The discriminant is evaluated once and stays on the value stack while the
3607 /// clauses compare against copies of it, so it is dropped at the end — which is
3608 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3609 /// clause's body jumps over the *next* clause's tests straight into its body.
3610 ///
3611 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3612 /// the next run's tests. Only the last run's miss reaches the `default` body, or
3613 /// the end of the switch when there is no `default`. That failure path can point
3614 /// backwards (`default` written first), so the runs and their labels are worked
3615 /// out before any code is emitted.
3616 fn switch(
3617 &mut self,
3618 discriminant: &Expr,
3619 cases: &[SwitchCase],
3620 stmt: &Stmt,
3621 ) -> Result<(), SyntaxError> {
3622 self.reset_value();
3623 // The discriminant is evaluated outside the switch's block scope, before
3624 // any `case` clause exists.
3625 self.expr(discriminant)?;
3626
3627 let switch_key = stmt.span.start.offset as u64;
3628 let switch_parent = self.cur().current_block;
3629 self.push_block(switch_key, switch_parent);
3630 self.emit_scope_enter(switch_key);
3631
3632 let break_label = self.new_label();
3633 self.push_jump_target(JumpTarget {
3634 names: Vec::new(),
3635 break_label: Some(break_label),
3636 // `switch` is a valid `break` target but not a `continue` target.
3637 continue_label: None,
3638 // The discriminant stays on the value stack for the whole statement, so
3639 // a `break` aimed further out has to discard it.
3640 drop_count: 1,
3641 finally_label: None,
3642 is_regular_stmt: false,
3643 has_iterator: false,
3644 is_async_iterator: false,
3645 });
3646
3647 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3648 // its label to the clause after it, so both tests reach the same body.
3649 let mut runs: Vec<(usize, usize)> = Vec::new();
3650 let mut scan = 0;
3651 while scan < cases.len() {
3652 if cases[scan].test.is_some() {
3653 let mut last = scan;
3654 while last + 1 < cases.len()
3655 && cases[last].test.is_some()
3656 && cases[last].body.is_empty()
3657 && cases[last + 1].test.is_some()
3658 {
3659 last += 1;
3660 }
3661 runs.push((scan, last));
3662 scan = last + 1;
3663 } else {
3664 scan += 1;
3665 }
3666 }
3667
3668 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3669 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3670 let default_at = cases.iter().position(|case| case.test.is_none());
3671 // Where the last run sends control when nothing matched.
3672 let miss_target = match default_at {
3673 Some(index) => body_labels[index],
3674 None => break_label,
3675 };
3676
3677 // When `default` comes first, control has to jump over it to reach the
3678 // tests. It only needs to when some clause actually has a test; otherwise
3679 // the default body is the entry point.
3680 let mut entry = None;
3681 if default_at == Some(0) && !runs.is_empty() {
3682 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3683 entry = Some(run_labels[0]);
3684 }
3685
3686 let mut index = 0;
3687 let mut run = 0;
3688 let result = (|| -> Result<(), SyntaxError> {
3689 while index < cases.len() {
3690 if cases[index].test.is_some() {
3691 let (first, last) = runs[run];
3692 // Reaching these tests from the preceding body is a
3693 // fallthrough, which continues inside the body and skips them.
3694 if index > 0 {
3695 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3696 }
3697 if let Some(label) = entry.take() {
3698 self.place_label(label);
3699 }
3700 self.place_label(run_labels[run]);
3701
3702 for (offset, case) in cases[first..=last].iter().enumerate() {
3703 let test = case.test.as_ref().unwrap();
3704 self.emit(Opcode::Dup, &[]);
3705 self.expr(test)?;
3706 self.emit(Opcode::StrictEq, &[]);
3707 if first + offset < last {
3708 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3709 } else {
3710 // Hand over to the next run's tests, or give up.
3711 let next = match runs.get(run + 1) {
3712 Some(_) => run_labels[run + 1],
3713 None => miss_target,
3714 };
3715 self.emit_jump(Opcode::IfFalse, next, &[]);
3716 }
3717 }
3718
3719 self.place_label(body_labels[index]);
3720 for case in &cases[first..=last] {
3721 self.stmts(&case.body)?;
3722 }
3723 index = last + 1;
3724 run += 1;
3725 } else {
3726 // `default`: control arrives here either by falling through or
3727 // because every test missed.
3728 self.place_label(body_labels[index]);
3729 self.stmts(&cases[index].body)?;
3730 index += 1;
3731 }
3732 }
3733 Ok(())
3734 })();
3735
3736 if result.is_ok() {
3737 self.place_label(break_label);
3738 // Discard the discriminant now that no test needs it.
3739 self.emit(Opcode::Drop, &[]);
3740 }
3741
3742 self.pop_jump_target();
3743 self.emit_scope_leave(switch_key);
3744 self.state().current_block = switch_parent;
3745 result
3746 }
3747
3748 /// Compile `try`/`catch`/`finally`.
3749 ///
3750 /// The shape is an exception table built out of `catch` instructions, each of
3751 /// which records where control goes if the instructions that follow raise:
3752 ///
3753 /// ```text
3754 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
3755 /// <guarded block>
3756 /// drop <- discard the catch offset
3757 /// undefined; gosub FINALLY; drop
3758 /// goto END
3759 /// HANDLER:
3760 /// <bind the catch parameter>
3761 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
3762 /// <handler body>
3763 /// drop; undefined; gosub FINALLY; drop; goto END
3764 /// CATCH2:
3765 /// gosub FINALLY; throw <- run the finalizer, then let the error out
3766 /// FINALLY:
3767 /// <finalizer>
3768 /// ret <- return to the `gosub`
3769 /// END:
3770 /// ```
3771 ///
3772 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3773 /// of the finalizer serves the normal path, the handler path and the
3774 /// propagating-exception path.
3775 ///
3776 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3777 /// runs with `ret_value` on the stack, and the normal path has no value to
3778 /// keep, so it pushes one to keep the stack depth identical on every path.
3779 fn try_stmt(
3780 &mut self,
3781 stmt: &Stmt,
3782 block: &[Stmt],
3783 handler: &Option<CatchClause>,
3784 finalizer: Option<&[Stmt]>,
3785 ) -> Result<(), SyntaxError> {
3786 self.reset_value();
3787
3788 let catch_label = self.new_label();
3789 let catch2_label = self.new_label();
3790 let finally_label = self.new_label();
3791 let end_label = self.new_label();
3792
3793 self.emit_jump(Opcode::Catch, catch_label, &[]);
3794
3795 // The guarded block. `break` may not target it, so its entry exists purely
3796 // to unwind: a jump out has to discard the catch offset and run the
3797 // finalizer.
3798 self.push_jump_target(JumpTarget {
3799 names: Vec::new(),
3800 break_label: None,
3801 continue_label: None,
3802 drop_count: 1,
3803 finally_label: Some(finally_label),
3804 is_regular_stmt: false,
3805 has_iterator: false,
3806 is_async_iterator: false,
3807 });
3808
3809 let block_key = Self::try_block_key(stmt, TryPart::Block);
3810 let block_parent = self.cur().current_block;
3811 self.push_block(block_key, block_parent);
3812 self.emit_scope_enter(block_key);
3813 self.stmts(block)?;
3814 self.emit_scope_leave(block_key);
3815 self.state().current_block = block_parent;
3816 // A guarded block that ends in a `return`/`throw` never reaches the
3817 // epilogue, so the reference does not emit one.
3818 self.pop_jump_target();
3819 let block_live = !block.last().is_some_and(Self::terminates);
3820
3821 if block_live {
3822 self.emit(Opcode::Drop, &[]);
3823 self.emit(Opcode::Undefined, &[]);
3824 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3825 self.emit(Opcode::Drop, &[]);
3826 self.emit_jump(Opcode::Goto, end_label, &[]);
3827 }
3828
3829 if let Some(handler) = handler {
3830 self.place_label(catch_label);
3831 // The thrown value is on top of the stack: bind it, or discard it for
3832 // `catch { }`.
3833 match &handler.param {
3834 Some(pattern) => {
3835 // The stores resolve the names, so they have to run inside the
3836 // parameter's own scope; otherwise a same-named `catch` further out
3837 // could win. A `catch` binding is never in the dead zone, so the store
3838 // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3839 let param_key = Self::try_block_key(stmt, TryPart::Param);
3840 let param_parent = self.cur().current_block;
3841 self.push_block(param_key, param_parent);
3842 self.destructure(pattern, Some(VarDeclKind::Var))?;
3843 self.state().current_block = param_parent;
3844 }
3845 None => self.emit(Opcode::Drop, &[]),
3846 }
3847 self.emit_jump(Opcode::Catch, catch2_label, &[]);
3848
3849 self.push_jump_target(JumpTarget {
3850 names: Vec::new(),
3851 break_label: None,
3852 continue_label: None,
3853 drop_count: 1,
3854 finally_label: Some(finally_label),
3855 is_regular_stmt: false,
3856 has_iterator: false,
3857 is_async_iterator: false,
3858 });
3859 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3860 let catch_parent = self.cur().current_block;
3861 self.push_block(catch_key, catch_parent);
3862 self.emit_scope_enter(catch_key);
3863 self.stmts(&handler.body)?;
3864 self.emit_scope_leave(catch_key);
3865 self.state().current_block = catch_parent;
3866 self.pop_jump_target();
3867 let handler_live = !handler.body.last().is_some_and(Self::terminates);
3868
3869 if handler_live {
3870 self.emit(Opcode::Drop, &[]);
3871 self.emit(Opcode::Undefined, &[]);
3872 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3873 self.emit(Opcode::Drop, &[]);
3874 self.emit_jump(Opcode::Goto, end_label, &[]);
3875 }
3876
3877 // An error raised inside the handler still has to run the finalizer.
3878 self.place_label(catch2_label);
3879 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3880 self.emit(Opcode::Throw, &[]);
3881 } else {
3882 // `try`/`finally` with no handler: the finalizer runs, then the error
3883 // keeps propagating.
3884 self.place_label(catch_label);
3885 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3886 self.emit(Opcode::Throw, &[]);
3887 }
3888
3889 self.place_label(finally_label);
3890 // Inside the finalizer, leaving has a different cost: the return value and
3891 // the `gosub` return address are both on the stack, and neither finalizer nor
3892 // any outer one may run before the block has finished.
3893 self.push_jump_target(JumpTarget {
3894 names: Vec::new(),
3895 break_label: None,
3896 continue_label: None,
3897 drop_count: 2,
3898 finally_label: None,
3899 is_regular_stmt: false,
3900 has_iterator: false,
3901 is_async_iterator: false,
3902 });
3903 if let Some(finalizer) = finalizer {
3904 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3905 let finally_parent = self.cur().current_block;
3906 self.push_block(finally_key, finally_parent);
3907 self.emit_scope_enter(finally_key);
3908 self.stmts(finalizer)?;
3909 self.emit_scope_leave(finally_key);
3910 self.state().current_block = finally_parent;
3911 }
3912 self.pop_jump_target();
3913 self.emit(Opcode::Ret, &[]);
3914 self.place_label(end_label);
3915 Ok(())
3916 }
3917
3918 /// Compile `for`/`in` and `for`/`of`.
3919 ///
3920 /// Both keep an enumeration record on the value stack for the whole loop, which
3921 /// is what makes leaving early expensive: the record has to be dropped, or the
3922 /// iterator closed. The layout is
3923 ///
3924 /// ```text
3925 /// <iterated expression>
3926 /// for_in_start | for_of_start <- pushes the record
3927 /// goto TEST
3928 /// NEXT:
3929 /// <bind the loop variable>
3930 /// <body>
3931 /// TEST:
3932 /// for_in_next | for_of_next 0
3933 /// if_false NEXT <- not finished: next iteration
3934 /// drop <- finished: discard the leftover value
3935 /// BREAK:
3936 /// drop | iterator_close <- the one cleanup `break` also uses
3937 /// ```
3938 ///
3939 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3940 /// normal exit share one copy — which is why `break` inside the loop emits nothing
3941 /// of its own, and only a jump that passes *through* the loop pays for its record.
3942 fn for_in_of(
3943 &mut self,
3944 stmt: &Stmt,
3945 left: &ForHead,
3946 right: &Expr,
3947 body: &Stmt,
3948 kind: ForLoopKind,
3949 labels: &[String],
3950 ) -> Result<(), SyntaxError> {
3951 self.reset_value();
3952
3953 let loop_key = stmt.span.start.offset as u64;
3954 let loop_parent = self.cur().current_block;
3955 self.push_block(loop_key, loop_parent);
3956 self.emit_scope_enter(loop_key);
3957
3958 // The iterated expression is evaluated inside the loop's scope, after the
3959 // bindings exist in the temporal dead zone.
3960 self.expr(right)?;
3961
3962 let next = self.new_label();
3963 let test = self.new_label();
3964 let break_target = self.new_label();
3965
3966 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3967 match kind {
3968 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3969 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3970 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3971 }
3972 self.emit_jump(Opcode::Goto, test, &[]);
3973
3974 self.push_jump_target(JumpTarget {
3975 // `outer: for (x of xs) … break outer` needs the name here. Without it the
3976 // loop had no label to break to, and the compiler reported "break has no
3977 // enclosing loop" for a loop that was plainly enclosing it.
3978 names: labels.to_vec(),
3979 break_label: Some(break_target),
3980 continue_label: Some(test),
3981 // Passing through the loop has to dispose of its record. A `for`/`of`
3982 // record is three slots, and closing the iterator consumes all of them.
3983 drop_count: if has_iterator { 3 } else { 1 },
3984 finally_label: None,
3985 is_regular_stmt: false,
3986 has_iterator,
3987 is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3988 });
3989
3990 self.place_label(next);
3991 self.bind_loop_variable(left)?;
3992
3993 // The reference marks the body with its own label here. Nothing jumps to it
3994 // once the loop is laid out, but it is not decoration: a label between the
3995 // store and the body is why `put_loc v; get_loc v` does *not* fold into
3996 // `set_loc v` when the body starts by reading the loop variable.
3997 let body_label = self.new_label();
3998 self.place_label(body_label);
3999 // `for (using x of …)` disposes once per iteration, so the body is a disposal
4000 // region rather than the whole loop: the resource is the element that this
4001 // iteration produced.
4002 let using_slot = match left {
4003 ForHead::VarDecl(decl) if decl.kind.is_using() => {
4004 decl.declarators
4005 .first()
4006 .and_then(|declarator| match &declarator.target.kind {
4007 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
4008 _ => None,
4009 })
4010 }
4011 _ => None,
4012 };
4013 match using_slot {
4014 Some(slot) => {
4015 let live = !Self::terminates(body);
4016 self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
4017 }
4018 None => self.stmt(body)?,
4019 }
4020
4021 // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
4022 // binding each iteration**, so a closure the body creates keeps that iteration's
4023 // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
4024 // a new reference cell holding the current value.
4025 //
4026 // The position is the *end* of the body, not the start: closing before the body
4027 // would leave the closures pointing at the cell the next `put_loc` overwrites, and
4028 // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
4029 for name in Self::loop_binding_names(left) {
4030 let pos = self.cur().cur_pos;
4031 self.state().insns.push(Insn::CloseCaptured {
4032 name,
4033 block: loop_key,
4034 });
4035 self.state().insn_pos.push(pos);
4036 }
4037 self.place_label(test);
4038 match kind {
4039 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
4040 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
4041 ForLoopKind::AwaitOf => {
4042 // The reference's shape: step, `await` the result, then unpack it.
4043 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
4044 self.emit(Opcode::Await, &[]);
4045 self.state().has_await = true;
4046 self.emit(Opcode::IteratorGetValueDone, &[]);
4047 }
4048 }
4049 self.emit_jump(Opcode::IfFalse, next, &[]);
4050 // The loop is finished; `for_xx_next` left an `undefined` behind.
4051 self.emit(Opcode::Drop, &[]);
4052
4053 self.pop_jump_target();
4054 self.place_label(break_target);
4055 if has_iterator {
4056 // A loop that ran to completion finds its iterator slot already cleared (see
4057 // `iterator_get_value_done`), so this closes only an iterator abandoned by a
4058 // `break` that jumped here.
4059 self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
4060 } else {
4061 self.emit(Opcode::Drop, &[]);
4062 }
4063
4064 self.emit_scope_leave(loop_key);
4065 self.state().current_block = loop_parent;
4066 Ok(())
4067 }
4068
4069 /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
4070 /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
4071 fn loop_binding_names(left: &ForHead) -> Vec<String> {
4072 let ForHead::VarDecl(decl) = left else {
4073 return Vec::new();
4074 };
4075 if decl.kind == VarDeclKind::Var {
4076 return Vec::new();
4077 }
4078 let mut names = Vec::new();
4079 for declarator in &decl.declarators {
4080 let mut idents = Vec::new();
4081 declarator.target.bound_names(&mut idents);
4082 names.extend(idents.into_iter().map(|ident| ident.name));
4083 }
4084 names
4085 }
4086
4087 /// Store the value `for_xx_next` left on the stack into the loop variable.
4088 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
4089 // A declaration *initialises* the binding, which is what takes a `let` out of
4090 // the temporal dead zone, so the store is the unchecked form. Assigning to a
4091 // binding declared elsewhere is an ordinary write and keeps its check.
4092 let (pattern, action) = match left {
4093 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
4094 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
4095 };
4096 match &pattern.kind {
4097 PatternKind::Ident(name) => {
4098 // `for (using x of …)` validates and snapshots each iteration's value
4099 // before the body runs, which is what makes a non-disposable element fail
4100 // on the iteration that produced it rather than at the end of the loop.
4101 if let ForHead::VarDecl(decl) = left
4102 && decl.kind.is_using()
4103 {
4104 let method_slot = self
4105 .using_method_slot(&name.name)
4106 .expect("a using binding was declared during hoisting");
4107 self.emit(
4108 Opcode::UsingCheck,
4109 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4110 );
4111 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4112 }
4113 self.emit_var(action, &name.name);
4114 Ok(())
4115 }
4116 // Every other target stores through the same path an assignment pattern
4117 // uses, which is what makes `for (a[0] in obj)` write each key into the
4118 // property instead of refusing the loop outright.
4119 _ => self.destructure(
4120 pattern,
4121 match left {
4122 ForHead::VarDecl(decl) => Some(decl.kind),
4123 ForHead::Assign(_) => None,
4124 },
4125 ),
4126 }
4127 }
4128
4129 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
4130 for declarator in &decl.declarators {
4131 let Some(init) = &declarator.init else {
4132 // `var x;` stays `undefined`. A lexical binding is different: it
4133 // has to be *initialised* to leave the temporal dead zone, so the
4134 // compiler supplies an explicit `undefined`.
4135 if decl.kind.is_lexical() {
4136 // A lexical binding has to be *initialised* to leave the temporal
4137 // dead zone, and a destructuring one is no different — `let {a}`
4138 // with no initialiser is a syntax error, but `let [a] = []` still
4139 // needs `a` to be initialised from an empty source, which the
4140 // pattern does on its own.
4141 self.emit(Opcode::Undefined, &[]);
4142 self.destructure(&declarator.target, Some(decl.kind))?;
4143 }
4144 continue;
4145 };
4146 match &declarator.target.kind {
4147 PatternKind::Ident(name) => {
4148 self.expr(init)?;
4149 self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
4150 if decl.kind.is_using() {
4151 // `using_check` validates the value and snapshots its dispose
4152 // method: `value -> value, method`. The snapshot is what makes a
4153 // later change to `Symbol.dispose` irrelevant, and validating here
4154 // is what keeps the body from running at all when the value is not
4155 // disposable.
4156 let method_slot = self
4157 .using_method_slot(&name.name)
4158 .expect("a using binding was declared during hoisting");
4159 self.emit(
4160 Opcode::UsingCheck,
4161 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4162 );
4163 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4164 self.emit_var(VarAction::PutInit, &name.name);
4165 continue;
4166 }
4167 // A declaration statement produces no value, so nothing is
4168 // duplicated onto the stack.
4169 match decl.kind {
4170 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
4171 _ => self.emit_var(VarAction::PutInit, &name.name),
4172 }
4173 }
4174 _ => {
4175 // A destructuring declaration keeps nothing on the stack: the
4176 // pattern consumes the initialiser.
4177 self.expr(init)?;
4178 self.destructure(&declarator.target, Some(decl.kind))?;
4179 }
4180 }
4181 }
4182 Ok(())
4183 }
4184
4185 /// Bind a destructuring pattern from the value on top of the stack.
4186 ///
4187 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4188 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4189 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4190 /// *assignment*, where a member expression is a legal target and the store is an
4191 /// ordinary property write.
4192 ///
4193 /// The value is consumed. An assignment expression's own result is the right-hand
4194 /// side, which the caller keeps separately — the spec does not make the pattern's
4195 /// last store produce it.
4196 fn destructure(
4197 &mut self,
4198 pattern: &Pattern,
4199 decl: Option<VarDeclKind>,
4200 ) -> Result<(), SyntaxError> {
4201 match &pattern.kind {
4202 PatternKind::Ident(name) => {
4203 match decl {
4204 Some(VarDeclKind::Var) | None => {
4205 self.emit_var(VarAction::Put, &name.name);
4206 }
4207 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4208 }
4209 Ok(())
4210 }
4211 PatternKind::Assign { target, default } => {
4212 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4213 // keeps `null`.
4214 //
4215 // The shape is the reference's: test for `undefined`, and when the value is
4216 // present fall **through** to a single store both paths share. The
4217 // alternatives — branching to the store on each side — need a second store
4218 // and a jump between them, which is what the dump used to show.
4219 let has_value = self.new_label();
4220 self.emit(Opcode::Dup, &[]);
4221 self.emit(Opcode::IsUndefined, &[]);
4222 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4223 self.emit(Opcode::Drop, &[]);
4224 self.expr(default)?;
4225 // `var {f = function(){}} = {}` names the function `f`, like a plain
4226 // `var f = function(){}` does. Both pattern forms do it:
4227 // `BindingInitialization` names the value for a *binding* target, and since
4228 // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4229 // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4230 // no name to give, which is why only an identifier qualifies.
4231 if let PatternKind::Ident(name) = &target.kind {
4232 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4233 }
4234 self.place_label(has_value);
4235 self.destructure(target, decl)
4236 }
4237 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4238 PatternKind::Object { properties, rest } => {
4239 self.destructure_object(properties, rest, decl, pattern)
4240 }
4241 PatternKind::Member(member) if decl.is_none() => {
4242 // An assignment pattern may store into a property. The value is on the
4243 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4244 // put the three in the order `put_array_el`/`put_field` expect.
4245 self.expr(&member.object)?;
4246 match &member.property {
4247 MemberProp::Ident(name) => {
4248 // `value obj` -> `obj value`, the order `put_field` takes.
4249 // Nothing needs to be left behind: a pattern element's value is
4250 // consumed by its own store.
4251 self.emit(Opcode::Swap, &[]);
4252 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4253 }
4254 MemberProp::Computed(index) => {
4255 self.expr(index)?;
4256 // `value obj key` -> `obj key value`.
4257 self.emit(Opcode::Rot3l, &[]);
4258 self.emit(Opcode::PutArrayEl, &[]);
4259 }
4260 MemberProp::Private(name) => {
4261 // `value obj` -> `obj value`, and the store half of the assignment is
4262 // the same one `obj.#x = value` uses — only without `insert2`,
4263 // because a pattern element's value is not wanted back.
4264 let binding = format!("#{}", name.name);
4265 let (kind, setter) = self.private_use(&binding, member.span)?;
4266 self.emit(Opcode::Swap, &[]);
4267 self.private_store(&binding, kind, setter.as_deref())?;
4268 }
4269 }
4270 Ok(())
4271 }
4272 PatternKind::Rest(inner) => self.destructure(inner, decl),
4273 PatternKind::Invalid(expr) => {
4274 Err(SyntaxError::new("invalid assignment target", expr.span))
4275 }
4276 _ => Err(SyntaxError::new(
4277 "this destructuring target is not supported by the compiler yet",
4278 pattern.span,
4279 )),
4280 }
4281 }
4282
4283 /// `[…]` on the left: drain an iterator, binding one target per element.
4284 ///
4285 /// A target that stores into a **property** — `[o.p] = it` — has its reference worked
4286 /// out *before* the value is pulled. That ordering is observable twice over
4287 /// (`array-elem-iter-thrw-close`):
4288 ///
4289 /// * `next` must not have been called yet when the reference throws, so
4290 /// `[ {}[thrower()] ] = iterable` reports `nextCount === 0`;
4291 /// * the iterator must still be closed, because the throw happens while the record is
4292 /// live — which is `catch_here`'s `catch_offset 0` doing its work.
4293 ///
4294 /// Doing it the other way round — pull the value, then evaluate the reference — got
4295 /// both wrong: an extra `next` call, and, when the reference threw, an iterator that had
4296 /// already been drained past.
4297 fn destructure_array(
4298 &mut self,
4299 elements: &[Option<PatternElement>],
4300 rest: &Option<Box<RestElement>>,
4301 decl: Option<VarDeclKind>,
4302 ) -> Result<(), SyntaxError> {
4303 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4304 // pattern accepts any iterable and closes the iterator when the pattern ends
4305 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4306 // first because it is on top.
4307 //
4308 // It also counts as an open iterator for `return` and `break`: a pattern is not a
4309 // loop, but the record is live across everything the pattern evaluates, so
4310 // `function* g(){ [ {} = yield ] = it }` resumed with `return()` has to close it
4311 // (`array-elem-iter-rtrn-close`). `emit_unwind_for_return` finds it by this entry
4312 // and `nip_catch` uncovers exactly the `iter next` pairs it left behind.
4313 //
4314 // A `break`/`continue` cannot occur inside a pattern, so `names` and both labels
4315 // are empty and `drop_count` — read only by that unreachable path — keeps the
4316 // reference's 2.
4317 self.push_jump_target(JumpTarget {
4318 names: Vec::new(),
4319 break_label: None,
4320 continue_label: None,
4321 drop_count: 2,
4322 finally_label: None,
4323 is_regular_stmt: false,
4324 has_iterator: true,
4325 is_async_iterator: false,
4326 });
4327 self.emit(Opcode::ForOfStart, &[]);
4328 for element in elements {
4329 match element {
4330 Some(PatternElement::Pattern(pattern)) => {
4331 match Self::member_element_target(pattern, decl) {
4332 // A prepared reference sits above the record, so `for_of_next` is
4333 // told how many values are in the way.
4334 Some(member) => {
4335 let extra = self.prepare_member_target(member)?;
4336 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4337 self.emit(Opcode::Drop, &[]);
4338 self.destructure_prepared(pattern, member)?;
4339 }
4340 None => {
4341 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4342 self.emit(Opcode::Drop, &[]);
4343 self.destructure(pattern, decl)?;
4344 }
4345 }
4346 }
4347 Some(PatternElement::Property { span, .. }) => {
4348 return Err(SyntaxError::new(
4349 "a property pattern is not a valid array element",
4350 *span,
4351 ));
4352 }
4353 // An elision skips the value, which is already on the stack.
4354 None => {
4355 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4356 self.emit(Opcode::Drop, &[]);
4357 self.emit(Opcode::Drop, &[]);
4358 }
4359 }
4360 }
4361 if let Some(rest) = rest {
4362 // The remaining values go into a fresh array. The target and its running
4363 // index stay on the stack above the iterator, which is what the operand of
4364 // `for_of_next` accounts for: two values sit above the iterator triple.
4365 let prepared = match decl {
4366 None => Self::member_rest_target(rest),
4367 // A binding pattern cannot store into a property.
4368 Some(_) => None,
4369 };
4370 let extra = match prepared {
4371 Some(member) => 2 + self.prepare_member_target(member)?,
4372 None => 2,
4373 };
4374 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4375 self.emit(Opcode::Push0, &[]);
4376 let top = self.new_label();
4377 self.place_label(top);
4378 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4379 let done = self.new_label();
4380 self.emit_jump(Opcode::IfTrue, done, &[]);
4381 self.emit(Opcode::DefineArrayEl, &[]);
4382 self.emit(Opcode::Inc, &[]);
4383 self.emit_jump(Opcode::Goto, top, &[]);
4384 self.place_label(done);
4385 self.emit(Opcode::Drop, &[]);
4386 self.emit(Opcode::Drop, &[]);
4387 match prepared {
4388 Some(member) => self.store_member_value(member)?,
4389 None => self.destructure_rest(rest, decl)?,
4390 }
4391 }
4392 self.emit(Opcode::IteratorClose, &[]);
4393 self.pop_jump_target();
4394 Ok(())
4395 }
4396
4397 /// The property an array element stores into, when it stores into one at all.
4398 ///
4399 /// `Assign` is peeled because `[o.p = d] = it` evaluates `o.p`'s reference at the same
4400 /// point `[o.p] = it` does; the default value is applied afterwards, on the pulled
4401 /// value. Nothing deeper is: a nested pattern's own targets are reached by recursing
4402 /// into `destructure`, and those never straddle a `for_of_next`.
4403 fn member_element_target(
4404 pattern: &Pattern,
4405 decl: Option<VarDeclKind>,
4406 ) -> Option<&ast::MemberPattern> {
4407 if decl.is_some() {
4408 return None;
4409 }
4410 match &pattern.kind {
4411 PatternKind::Member(member) => Some(member),
4412 PatternKind::Assign { target, .. } => Self::member_element_target(target, decl),
4413 _ => None,
4414 }
4415 }
4416
4417 /// The same, for a rest element.
4418 fn member_rest_target(rest: &RestElement) -> Option<&ast::MemberPattern> {
4419 match rest {
4420 RestElement::Member(member) => Some(member),
4421 RestElement::Pattern(pattern) => match &pattern.kind {
4422 PatternKind::Member(member) => Some(member),
4423 _ => None,
4424 },
4425 }
4426 }
4427
4428 /// Push a member target's reference — the object, and the key when the property is
4429 /// computed — and answer how many values that put above the iterator record.
4430 fn prepare_member_target(&mut self, member: &ast::MemberPattern) -> Result<i32, SyntaxError> {
4431 self.expr(&member.object)?;
4432 match &member.property {
4433 MemberProp::Ident(_) | MemberProp::Private(_) => Ok(1),
4434 MemberProp::Computed(index) => {
4435 self.expr(index)?;
4436 Ok(2)
4437 }
4438 }
4439 }
4440
4441 /// Store the value on top of the stack through a prepared member reference.
4442 ///
4443 /// `obj value` for a named property, `obj key value` for a computed one — the orders
4444 /// `put_field` and `put_array_el` take, so no reordering is needed here. The `swap` and
4445 /// `rot3l` in [`Compiler::destructure`]'s member case exist only because *it* starts
4446 /// with the value already on the stack.
4447 fn store_member_value(&mut self, member: &ast::MemberPattern) -> Result<(), SyntaxError> {
4448 match &member.property {
4449 MemberProp::Ident(name) => {
4450 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4451 }
4452 MemberProp::Computed(_) => self.emit(Opcode::PutArrayEl, &[]),
4453 MemberProp::Private(name) => {
4454 let binding = format!("#{}", name.name);
4455 let (kind, setter) = self.private_use(&binding, member.span)?;
4456 self.private_store(&binding, kind, setter.as_deref())?;
4457 }
4458 }
4459 Ok(())
4460 }
4461
4462 /// The value of an array element whose member reference is already prepared.
4463 ///
4464 /// Only the default-value test differs from [`Compiler::destructure`]: the reference
4465 /// and the value are both on the stack while the test runs, which is why the object is
4466 /// evaluated before the default rather than after it.
4467 fn destructure_prepared(
4468 &mut self,
4469 pattern: &Pattern,
4470 member: &ast::MemberPattern,
4471 ) -> Result<(), SyntaxError> {
4472 if let PatternKind::Assign { default, .. } = &pattern.kind {
4473 let has_value = self.new_label();
4474 self.emit(Opcode::Dup, &[]);
4475 self.emit(Opcode::IsUndefined, &[]);
4476 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4477 self.emit(Opcode::Drop, &[]);
4478 self.expr(default)?;
4479 self.place_label(has_value);
4480 }
4481 self.store_member_value(member)
4482 }
4483
4484 /// `{…}` on the left: read properties off one boxed source object.
4485 fn destructure_object(
4486 &mut self,
4487 properties: &[Option<PatternElement>],
4488 rest: &Option<Box<RestElement>>,
4489 decl: Option<VarDeclKind>,
4490 pattern: &Pattern,
4491 ) -> Result<(), SyntaxError> {
4492 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4493 // aside for the rest element below.
4494 self.emit(Opcode::ToObject, &[]);
4495 let mut taken: Vec<Wtf8> = Vec::new();
4496 // A computed key's *value* is only known at run time, so with a rest element the
4497 // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4498 // local array that every key is written into as the pattern is walked — literal
4499 // keys by name, computed ones by the value the expression produced. Without this,
4500 // `let { [k]: a, ...rest } = o` was refused outright.
4501 let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4502 let key_log = if needs_key_log {
4503 let name = "<rest_exclude>";
4504 self.declare_hidden_local(name, VarKind::Normal);
4505 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4506 self.emit_var(VarAction::Put, name);
4507 Some(name)
4508 } else {
4509 None
4510 };
4511 for property in properties {
4512 let Some(PatternElement::Property {
4513 key, value, span, ..
4514 }) = property
4515 else {
4516 return Err(SyntaxError::new(
4517 "a bare pattern is not a valid object property",
4518 properties
4519 .iter()
4520 .flatten()
4521 .map(|element| match element {
4522 PatternElement::Pattern(pattern) => pattern.span,
4523 PatternElement::Property { span, .. } => *span,
4524 })
4525 .next()
4526 .unwrap_or(pattern.span),
4527 ));
4528 };
4529 // Every read needs the source twice: to read from, and to keep for the next
4530 // property. `get_field2` is that duplicate-and-read in one instruction, but it
4531 // leaves the copy *under* the value, so it is only usable when whatever
4532 // consumes the value tolerates that. See [`reads_with_get_field2`].
4533 let nested = reads_with_get_field2(decl, value);
4534 if !nested {
4535 self.emit(Opcode::Dup, &[]);
4536 }
4537 let slot = taken.len();
4538 match key {
4539 PropName::Literal(literal) => {
4540 let name = self.property_key_text(literal, *span)?;
4541 taken.push(name.clone());
4542 if let Some(log) = &key_log {
4543 // `arr index key -> arr`: the key is written into the log before
4544 // the read, so the order of observable operations is unchanged.
4545 self.emit_var(VarAction::Get, log);
4546 self.push_number(slot as f64);
4547 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4548 self.emit(Opcode::PutArrayEl, &[]);
4549 }
4550 self.emit(
4551 if nested {
4552 Opcode::GetField2
4553 } else {
4554 Opcode::GetField
4555 },
4556 &[Op::Atom(Atom::from_wtf8(&name))],
4557 );
4558 }
4559 PropName::Computed(index) => {
4560 self.expr(index)?;
4561 // `key key`: one stays on the stack for the read, the other goes into
4562 // the exclusion log. The index is a compile-time constant, so no counter
4563 // local is needed.
4564 if let Some(log) = &key_log {
4565 taken.push(Wtf8::default());
4566 self.emit(Opcode::Dup, &[]);
4567 self.emit_var(VarAction::Get, log);
4568 self.emit(Opcode::Swap, &[]);
4569 self.push_number(slot as f64);
4570 self.emit(Opcode::Swap, &[]);
4571 self.emit(Opcode::PutArrayEl, &[]);
4572 }
4573 self.emit(Opcode::GetArrayEl, &[]);
4574 }
4575 PropName::Private(_) => {
4576 return Err(SyntaxError::new(
4577 "private fields are not supported by the compiler yet",
4578 value.span,
4579 ));
4580 }
4581 }
4582 self.destructure(value, decl)?;
4583 }
4584 match rest {
4585 Some(rest) => {
4586 // `target src exclude`: the exclusion list is an array of the keys the
4587 // literal part already took, so the rest object gets only the others.
4588 self.emit(Opcode::Object, &[]);
4589 self.emit(Opcode::Swap, &[]);
4590 match &key_log {
4591 // Built while walking the pattern; see `needs_key_log`.
4592 Some(log) => {
4593 self.emit_var(VarAction::Get, log);
4594 }
4595 None => {
4596 for name in &taken {
4597 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4598 }
4599 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4600 }
4601 }
4602 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4603 self.emit(Opcode::Drop, &[]);
4604 self.emit(Opcode::Drop, &[]);
4605 self.destructure_rest(rest, decl)?;
4606 }
4607 // The source was only kept for a rest element.
4608 None => self.emit(Opcode::Drop, &[]),
4609 }
4610 Ok(())
4611 }
4612
4613 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4614 fn destructure_rest(
4615 &mut self,
4616 rest: &RestElement,
4617 decl: Option<VarDeclKind>,
4618 ) -> Result<(), SyntaxError> {
4619 match rest {
4620 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4621 // `[...a.b] = c` stores into a property.
4622 RestElement::Member(member) => {
4623 let pattern = Pattern {
4624 kind: PatternKind::Member(member.clone()),
4625 span: member.span,
4626 };
4627 self.destructure(&pattern, decl)
4628 }
4629 }
4630 }
4631
4632 /// Compile a function declaration and queue it for instantiation at scope
4633 /// entry.
4634 ///
4635 /// A declaration is visible before the statement that declares it, so the
4636 /// code that creates the function object belongs at the top of the enclosing
4637 /// scope, not at the declaration.
4638 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4639 let name = func.name.as_ref().expect("a declaration has a name");
4640 let function = self.compile_function(func)?;
4641 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4642 let target = self.hoist_target(&name.name);
4643 let block = self.cur().current_block;
4644 self.state().hoisted.push((block, target, pool_index));
4645 Ok(())
4646 }
4647
4648 /// Where a name lives, for a hoisted declaration.
4649 fn hoist_target(&self, name: &str) -> HoistTarget {
4650 let state = self.cur();
4651 if let Some(index) = state.args.iter().position(|a| a.name == name) {
4652 return HoistTarget::Arg(index as u32);
4653 }
4654 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4655 return HoistTarget::Loc(index as u32);
4656 }
4657 // A global function declaration is not a slot at all.
4658 HoistTarget::Global(name.to_string())
4659 }
4660
4661 // -- expressions -------------------------------------------------------
4662
4663 /// Compile one expression, recording where its instructions sit.
4664 ///
4665 /// The position is the node's operator when it has one and its first token
4666 /// otherwise, and it is restored on the way out so a parent's own instructions —
4667 /// which are emitted *after* its children — are blamed on the parent. Without the
4668 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4669 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4670 // `discard_value` belongs to the *statement* that is about to be compiled, so it
4671 // may only be honoured by that statement's own top-level expression. Taking it here
4672 // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4673 // the argument list is a different expression — it must still leave its value on the
4674 // stack. Without this the argument vanished, and `call` then consumed the callee as
4675 // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4676 // function).
4677 self.discard_root = std::mem::take(&mut self.state().discard_value);
4678 let saved = self.cur().cur_pos;
4679 // Only the node kinds the reference calls `emit_source_pos` for record a position:
4680 // the operator a node exists for, and a variable *read*, which the reference
4681 // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4682 // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4683 // start, a parenthesised group, an anonymous function expression — leaves the
4684 // previous position in place, because a table entry the reference never writes is
4685 // one we must not write either: the instruction that inherits a position (the
4686 // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4687 // report a more recent token than the reference does.
4688 let pos = expr.op_pos.or(match &expr.kind {
4689 ExprKind::Ident(ident) => Some(ident.span.start),
4690 _ => None,
4691 });
4692 match pos {
4693 Some(pos) => self.state().cur_pos = Some(pos),
4694 // A node the reference records nothing for: its own instructions stay
4695 // unpositioned, so they inherit whatever was written last — which is what an
4696 // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4697 // enclosing position instead would blame them on a token the reference has not
4698 // reached yet: a spread's `iterator_open` reports the expression it follows, and
4699 // a template's `to_propkey` the interpolation.
4700 None => self.state().cur_pos = None,
4701 }
4702 // Note a direct `eval` call before compiling it, because the *whole* function
4703 // is affected: an eval can name any binding the function declares, so every one
4704 // of them has to live in a cell for a closure it creates to capture it.
4705 self.note_direct_eval(expr);
4706 let result = self.expr_inner(expr);
4707 self.discard_root = false;
4708 self.state().cur_pos = saved;
4709 result
4710 }
4711
4712 /// Record which bindings are in scope at a direct `eval` call.
4713 ///
4714 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4715 /// resolves names from a string at run time, so the only chance to pin down *which*
4716 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4717 /// its block is the current block, an enclosing one, or the function scope.
4718 fn materialize_eval_sites(&mut self) {
4719 let pending = std::mem::take(&mut self.state().pending_eval_sites);
4720 for (span, site_block, in_params, private, arguments_allowed) in pending {
4721 self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
4722 }
4723 }
4724
4725 /// Resolve the bindings visible at one `eval` call.
4726 fn resolve_eval_site(
4727 &mut self,
4728 span: Span,
4729 site_block: u64,
4730 site_in_params: bool,
4731 private_names: Vec<EvalPrivate>,
4732 arguments_allowed: bool,
4733 ) {
4734 /// How near a binding is: function distance first, then block depth, then the
4735 /// later declaration (which shadows the earlier one in the same block).
4736 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4737
4738 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4739 // walked, innermost function first: a direct `eval` sees every enclosing
4740 // function's bindings, and none of them can be resolved at run time because the
4741 // runtime only has names to go on.
4742 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4743 let deepest = self.stack.len() - 1;
4744 for (level, state) in self.stack.iter().enumerate().rev() {
4745 let owner = (deepest - level) as u32;
4746 // The innermost function's block is the one the call sat in, which is not
4747 // the block the compiler is in now; the enclosing functions are still at
4748 // the point where this one was created.
4749 let here = if level == deepest {
4750 site_block
4751 } else {
4752 state.current_block
4753 };
4754 // The chain of live blocks, innermost first, with a depth for each. The walk
4755 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4756 // block can start at source offset zero.
4757 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4758 let mut block = here;
4759 while let Some(parent) = state
4760 .blocks
4761 .iter()
4762 .find(|candidate| candidate.key == block)
4763 .map(|candidate| candidate.parent)
4764 .filter(|parent| *parent != NO_PARENT)
4765 .filter(|parent| parent != &block)
4766 {
4767 live.push((parent, live.len()));
4768 block = parent;
4769 }
4770 let depth_of = |key: u64| {
4771 live.iter()
4772 .find(|(candidate, _)| *candidate == key)
4773 .map(|(_, depth)| *depth)
4774 // The function scope is the outermost depth there is. A binding of a
4775 // block this site is not inside lands here too, which pushes it
4776 // behind every live one — the right answer: it is out of scope.
4777 .unwrap_or(live.len())
4778 };
4779 for (index, arg) in state.args.iter().enumerate() {
4780 bindings.push((
4781 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4782 EvalVisible {
4783 name: arg.name.clone(),
4784 is_arg: true,
4785 index: index as u32,
4786 owner,
4787 },
4788 ));
4789 }
4790 // A parameter list cannot see the body, so a body `var` is not a binding the
4791 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4792 // not let that eval write the body's `c`.
4793 let hides_body = if level == deepest {
4794 site_in_params
4795 } else {
4796 state.created_in_params
4797 };
4798 for (index, var) in state.vars.iter().enumerate() {
4799 let block = state
4800 .var_block
4801 .get(index)
4802 .copied()
4803 .unwrap_or(FUNCTION_SCOPE);
4804 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4805 continue;
4806 }
4807 bindings.push((
4808 (
4809 owner as usize,
4810 depth_of(block),
4811 std::cmp::Reverse(index as u32),
4812 ),
4813 EvalVisible {
4814 name: var.name.clone(),
4815 is_arg: false,
4816 index: index as u32,
4817 owner,
4818 },
4819 ));
4820 }
4821 }
4822 // Innermost function first, then innermost block, then the later declaration
4823 // (which shadows the earlier one within a block).
4824 bindings.sort_by_key(|(priority, _)| *priority);
4825 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4826 self.state().eval_sites.push(EvalSite {
4827 line: span.start.line,
4828 column: span.start.column,
4829 bindings,
4830 private_names,
4831 arguments_allowed,
4832 });
4833 }
4834
4835 /// The private names visible from the compiler's current position, innermost last.
4836 ///
4837 /// A direct `eval` inherits these because private names are lexically scoped
4838 /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
4839 /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
4840 /// shadowing `ClassPlan::find` gives a use site inside the body.
4841 fn visible_private_names(&self) -> Vec<EvalPrivate> {
4842 let mut out: Vec<EvalPrivate> = Vec::new();
4843 for scope in &self.private_scopes {
4844 for (name, use_) in scope {
4845 if out.iter().any(|entry| &entry.name == name) {
4846 continue;
4847 }
4848 out.push(EvalPrivate {
4849 name: name.clone(),
4850 kind: match use_.kind {
4851 PrivateKind::Field => EvalPrivateKind::Field,
4852 PrivateKind::Method => EvalPrivateKind::Method,
4853 PrivateKind::Getter => EvalPrivateKind::Getter,
4854 PrivateKind::Setter => EvalPrivateKind::Setter,
4855 },
4856 setter: use_.setter.clone(),
4857 });
4858 }
4859 }
4860 out
4861 }
4862
4863 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4864 ///
4865 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4866 /// a bare identifier callee counts.
4867 /// Record everything a direct `eval` call site has to tell the runtime.
4868 ///
4869 /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
4870 /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
4871 /// entirely. Missing the tail-call path is not hypothetical — it is why
4872 /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
4873 /// names were otherwise wired through.
4874 fn note_direct_eval(&mut self, expr: &Expr) {
4875 if !Self::is_direct_eval(expr) {
4876 return;
4877 }
4878 // Every enclosing function is affected too: the eval sees the whole scope chain,
4879 // and a closure it creates can capture a binding of any of them.
4880 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
4881 // because the closure the eval builds outlives the loop iteration.
4882 for state in &mut self.stack {
4883 state.has_direct_eval = true;
4884 }
4885 let block = self.cur().current_block;
4886 let in_params = self.cur().in_params;
4887 // The private names are snapshotted **here**, at the call site, not when the sites
4888 // are materialised: materialisation happens once the whole function is compiled, by
4889 // which point every class scope has been popped and the answer would always be
4890 // empty.
4891 let private = self.visible_private_names();
4892 // An arrow has no `arguments` of its own and inherits the restriction from the
4893 // nearest real function: `x = () => { () => eval('arguments') }` is still a
4894 // class field initializer's arrow, and still has no `arguments` to see.
4895 let arguments_allowed = !self
4896 .stack
4897 .iter()
4898 .rev()
4899 .find(|state| !state.is_arrow)
4900 .is_some_and(|state| state.no_arguments_binding);
4901 self.state().pending_eval_sites.push((
4902 expr.span,
4903 block,
4904 in_params,
4905 private,
4906 arguments_allowed,
4907 ));
4908 }
4909
4910 fn is_direct_eval(expr: &Expr) -> bool {
4911 matches!(
4912 &expr.kind,
4913 ExprKind::Call { callee, .. }
4914 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4915 )
4916 }
4917
4918 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4919 match &expr.kind {
4920 ExprKind::Number(value) => self.push_number(*value),
4921 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4922 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4923 ExprKind::Null => self.emit(Opcode::Null, &[]),
4924 ExprKind::String(text) => self.push_string(text),
4925 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4926 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4927 ExprKind::This => self.this_expression(),
4928 ExprKind::NewTarget => self.new_target_expression(),
4929 ExprKind::Paren(inner) => self.expr(inner)?,
4930 ExprKind::Binary { op, left, right } => {
4931 self.expr(left)?;
4932 self.expr(right)?;
4933 self.emit(binary_opcode(*op), &[]);
4934 }
4935 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4936 ExprKind::Unary {
4937 op: UnaryOp::Minus,
4938 argument,
4939 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4940 let ExprKind::Number(value) = argument.unparen().kind else {
4941 unreachable!("matched above")
4942 };
4943 // The reference folds a negative literal only when the negation is
4944 // exact in the integer range: `-1` becomes `push_minus1` and
4945 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4946 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4947 // `-Infinity`, not `Infinity` — and folding a fraction would change
4948 // which instruction the reference emits.
4949 let negated = -value;
4950 // `-2147483648` is deliberately excluded: its magnitude is one past
4951 // `i32::MAX`, so the reference sends it through the constant pool and
4952 // negates at run time instead.
4953 if value > 0.0
4954 && negated == negated.trunc()
4955 && negated >= -(i32::MAX as f64)
4956 && negated < 0.0
4957 {
4958 self.push_number(negated);
4959 } else {
4960 self.push_number(value);
4961 self.emit(Opcode::Neg, &[]);
4962 }
4963 }
4964 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4965 ExprKind::Conditional { test, cons, alt } => {
4966 let else_label = self.new_label();
4967 let end_label = self.new_label();
4968 self.expr(test)?;
4969 self.emit_jump(Opcode::IfFalse, else_label, &[]);
4970 self.expr(cons)?;
4971 self.emit_jump(Opcode::Goto, end_label, &[]);
4972 self.place_label(else_label);
4973 self.expr(alt)?;
4974 self.place_label(end_label);
4975 }
4976 ExprKind::Assign { op, target, value } => {
4977 let discard = std::mem::take(&mut self.discard_root);
4978 self.assign(*op, target, value, discard)?
4979 }
4980 ExprKind::Update {
4981 op,
4982 argument,
4983 prefix,
4984 } => self.update(*op, argument, *prefix)?,
4985 ExprKind::Sequence(items) => {
4986 for (index, item) in items.iter().enumerate() {
4987 self.expr(item)?;
4988 if index + 1 != items.len() {
4989 self.emit(Opcode::Drop, &[]);
4990 }
4991 }
4992 }
4993 ExprKind::Call { .. } => self.chain_link_top(expr)?,
4994 ExprKind::Member { .. } => self.chain_link_top(expr)?,
4995 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4996 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4997 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4998 ExprKind::Template(template) => self.template_literal(template)?,
4999 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
5000 ExprKind::New { callee, arguments } => {
5001 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
5002 // The `dup` is not redundant: `call_constructor` takes the
5003 // constructor twice, once as the target and once as `new.target`,
5004 // which is what makes `new.target === C` inside the body.
5005 self.expr(callee)?;
5006 self.emit(Opcode::Dup, &[]);
5007 let args = arguments.as_deref().unwrap_or(&[]);
5008 if Self::has_spread(args) {
5009 // `C C array`: the duplicated callee is already both the target
5010 // and `new.target`, so no reordering is needed before `apply 1`.
5011 self.argument_array(args)?;
5012 self.emit(Opcode::Apply, &[Op::Int(1)]);
5013 return Ok(());
5014 }
5015 for argument in args {
5016 self.expr(argument)?;
5017 }
5018 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
5019 }
5020 ExprKind::Class(class) => self.class_definition(class, true)?,
5021 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
5022 ExprKind::Yield { argument, delegate } => {
5023 self.yield_expression(argument.as_deref(), *delegate)?
5024 }
5025 ExprKind::Await(argument) => self.await_expression(argument)?,
5026 ExprKind::RegExp { pattern, flags } => {
5027 // A literal is compiled *here*, at parse time, not when the line runs. The
5028 // spec is explicit that an invalid pattern is an early error (§12.9.4:
5029 // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
5030 // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
5031 // also validates `\p{…}` names: 163 conformance cases are patterns that have
5032 // to be rejected before any code runs.
5033 //
5034 // This is the whole reason the engine lives in its own crate rather than
5035 // inside `quickjs-pure`: the compiler could not depend on the interpreter
5036 // (`pure` depends on `compile`), but both need this.
5037 // The lexer already rejected an unknown or repeated flag, so an unparsable
5038 // flag string here would be a bug in the lexer rather than in the script;
5039 // fall back to the default flags instead of inventing a second message.
5040 let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
5041 let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
5042 SyntaxError::new(
5043 format!("invalid regular expression: {}", error.message),
5044 expr.span,
5045 )
5046 })?;
5047 // The tree is thrown away and rebuilt when the literal first runs: keeping it
5048 // would mean serialising the syntax tree into the function's constant pool,
5049 // and a literal is created once per evaluation of its expression anyway.
5050 let _ = parsed;
5051 // The pattern and its flags travel as two string constants; `regexp` builds
5052 // the object. A dedicated opcode (rather than a call to the constructor) is
5053 // what the reference does too, so that a literal never goes through the
5054 // public `RegExp` function and its string-coercion rules.
5055 self.push_string(&Wtf8::new(pattern));
5056 self.push_string(&Wtf8::new(flags));
5057 self.emit(Opcode::Regexp, &[]);
5058 }
5059 ExprKind::Arrow(func) => {
5060 let function = self.compile_function(func)?;
5061 let index = self.push_constant(Constant::Function(Box::new(function)));
5062 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5063 }
5064 ExprKind::Function(func) => {
5065 let function = self.compile_function_with_name(func, true)?;
5066 let index = self.push_constant(Constant::Function(Box::new(function)));
5067 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5068 }
5069 // `import.meta`: the host fills a per-module object at link time.
5070 ExprKind::ImportMeta => {
5071 self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
5072 }
5073 // `import("x")` compiles to a two-slot push followed by one opcode: the
5074 // specifier, then the options object. Both are evaluated, in that order, because
5075 // §13.3.10.1 numbers them that way and their side effects are observable — the
5076 // absent second argument is a literal `undefined`, which evaluates to nothing.
5077 ExprKind::ImportCall(specifier, options) => {
5078 self.expr(specifier)?;
5079 match options {
5080 Some(options) => self.expr(options)?,
5081 None => {
5082 self.emit(Opcode::Undefined, &[]);
5083 }
5084 }
5085 self.emit(Opcode::Import, &[]);
5086 }
5087 ExprKind::PrivateIn { name, object } => {
5088 // `#x in o`: the object, then the binding, then one opcode which decides what
5089 // to do with the second operand. A field's binding holds a symbol and the
5090 // answer is an own-property test; a method's holds a function and the answer
5091 // is a brand check — both live in `private_in`, so the compiler emits the
5092 // same instruction for either.
5093 self.expr(object)?;
5094 self.emit_var(VarAction::Get, &format!("#{}", name.name));
5095 self.emit(Opcode::PrivateIn, &[]);
5096 }
5097 _ => {
5098 return Err(SyntaxError::new(
5099 "this expression form is not supported by the compiler yet",
5100 expr.span,
5101 ));
5102 }
5103 }
5104 Ok(())
5105 }
5106
5107 /// Build one array holding the evaluated call arguments, which is how a call
5108 /// containing a spread is compiled: the reference does the same, building the
5109 /// list on the stack and handing it to `apply`.
5110 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5111 let elements: Vec<Option<ArrayElement>> = arguments
5112 .iter()
5113 .map(|argument| match &argument.unparen().kind {
5114 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
5115 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
5116 })
5117 .collect();
5118 self.array_literal(&elements, Span::default())
5119 }
5120
5121 /// Whether any argument is a spread, which is what selects the `apply` form.
5122 fn has_spread(arguments: &[Expr]) -> bool {
5123 arguments
5124 .iter()
5125 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
5126 }
5127
5128 /// Compile `a${x}b`.
5129 ///
5130 /// A template is a `+` chain built left to right: the leading chunk (or an empty
5131 /// string when the template starts with a substitution), then for each
5132 /// substitution its value, `to_propkey` and `add`, then the following chunk when
5133 /// it is not empty. `to_propkey` is what makes a number or object substitute the
5134 /// way `ToString` would while leaving the result a string for `add` to
5135 /// concatenate.
5136 ///
5137 /// The chunk is an atom rather than a constant-pool string, because a non-empty
5138 /// chunk always lands where a value is pushed and `push_atom_value` is the
5139 /// instruction the reference uses for it; the empty first chunk has its own
5140 /// zero-byte form.
5141 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
5142 let first = template.quasis.first();
5143 match first.and_then(|quasi| quasi.cooked.clone()) {
5144 Some(text) if !text.is_empty() => {
5145 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5146 }
5147 // Either the template begins with a substitution, or the chunk is
5148 // empty — in both cases the chain needs a string to start from.
5149 _ => self.emit(Opcode::PushEmptyString, &[]),
5150 }
5151 for (index, expression) in template.expressions.iter().enumerate() {
5152 self.expr(expression)?;
5153 self.emit(Opcode::ToPropkey, &[]);
5154 self.emit(Opcode::Add, &[]);
5155 if let Some(text) = template
5156 .quasis
5157 .get(index + 1)
5158 .and_then(|quasi| quasi.cooked.clone())
5159 && !text.is_empty()
5160 {
5161 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5162 self.emit(Opcode::Add, &[]);
5163 }
5164 }
5165 Ok(())
5166 }
5167
5168 /// Compile an object literal.
5169 ///
5170 /// The object is built in place: `object` pushes it, and each property leaves it
5171 /// on the stack with one field more, so no temporary is needed and later
5172 /// properties can overwrite earlier ones.
5173 ///
5174 /// The instruction depends on *how* the property was written, not on what kind
5175 /// of value it holds:
5176 ///
5177 /// | source | instruction |
5178 /// |---|---|
5179 /// | `{ a: v }` | `define_field a` |
5180 /// | `{ __proto__: v }` | `set_proto` |
5181 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
5182 /// | `{ m() {} }` | `define_method m,4` |
5183 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
5184 /// | `{ [k]() {} }` | `define_method_computed 4` |
5185 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
5186 ///
5187 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
5188 /// key itself, which is why the trailing `drop` is absent there too.
5189 /// `tag`…``: a call whose first argument is the call site's template object.
5190 ///
5191 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
5192 /// array beside it, so `String.raw` can read the source text back. It is a constant
5193 /// because its contents never change; the reference builds one per call site and
5194 /// reuses it, while this builds one per evaluation, which only `tag` code that
5195 /// compares template objects across calls could tell apart.
5196 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
5197 let cooked = quasi
5198 .quasis
5199 .iter()
5200 .map(|chunk| chunk.cooked.clone())
5201 .collect();
5202 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
5203 let index = self.push_constant(Constant::Template { cooked, raw });
5204 let count = quasi.expressions.len() + 1;
5205 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
5206 if let ExprKind::Member {
5207 object, property, ..
5208 } = &tag.unparen().kind
5209 {
5210 self.expr(object)?;
5211 match property {
5212 MemberProp::Ident(name) => {
5213 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5214 }
5215 MemberProp::Computed(key) => {
5216 self.expr(key)?;
5217 self.emit(Opcode::GetArrayEl2, &[]);
5218 }
5219 MemberProp::Private(name) => {
5220 let binding = format!("#{}", name.name);
5221 let (kind, _) = self.private_use(&binding, tag.span)?;
5222 self.private_callee(&binding, kind)?;
5223 }
5224 }
5225 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5226 for expression in &quasi.expressions {
5227 self.expr(expression)?;
5228 }
5229 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
5230 return Ok(());
5231 }
5232 self.expr(tag)?;
5233 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5234 for expression in &quasi.expressions {
5235 self.expr(expression)?;
5236 }
5237 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
5238 Ok(())
5239 }
5240
5241 fn object_literal(
5242 &mut self,
5243 properties: &[ObjectProperty],
5244 span: Span,
5245 ) -> Result<(), SyntaxError> {
5246 self.emit(Opcode::Object, &[]);
5247 for property in properties {
5248 match property {
5249 ObjectProperty::Spread(value) => {
5250 // `copy_data_properties` takes the target, the source and an
5251 // exclusion list; a literal `null` means "exclude nothing".
5252 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
5253 // exclusion list by stack offset.
5254 self.expr(spread_argument(value))?;
5255 self.emit(Opcode::Null, &[]);
5256 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
5257 self.emit(Opcode::Drop, &[]);
5258 self.emit(Opcode::Drop, &[]);
5259 }
5260 ObjectProperty::Property {
5261 key,
5262 value,
5263 kind,
5264 shorthand,
5265 span: property_span,
5266 } => match key {
5267 PropName::Computed(key_expr) => {
5268 self.expr(key_expr)?;
5269 match kind {
5270 PropertyKind::Value => {
5271 self.emit(Opcode::ToPropkey, &[]);
5272 self.expr(value)?;
5273 self.set_name_if_anonymous_computed(value);
5274 self.emit(Opcode::DefineArrayEl, &[]);
5275 // `define_array_el` leaves the object and the key;
5276 // the key is no longer needed.
5277 self.emit(Opcode::Drop, &[]);
5278 }
5279 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5280 self.emit_method_function(value)?;
5281 self.emit(
5282 Opcode::DefineMethodComputed,
5283 &[Op::Int(define_method_flags(*kind))],
5284 );
5285 }
5286 }
5287 }
5288 PropName::Literal(key) => {
5289 let name = self.property_key_text(key, *property_span)?;
5290 match kind {
5291 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5292 self.emit_method_function(value)?;
5293 self.emit(
5294 Opcode::DefineMethod,
5295 &[
5296 Op::Atom(Atom::from_wtf8(&name)),
5297 Op::Int(define_method_flags(*kind)),
5298 ],
5299 );
5300 }
5301 PropertyKind::Value => {
5302 self.expr(value)?;
5303 // `{__proto__: x}` sets the prototype instead of
5304 // creating a property; the shorthand `{__proto__}`
5305 // is an ordinary property and does not.
5306 if name == "__proto__" && !shorthand {
5307 self.emit(Opcode::SetProto, &[]);
5308 } else {
5309 self.set_name_if_anonymous(value, &name);
5310 self.emit(
5311 Opcode::DefineField,
5312 &[Op::Atom(Atom::from_wtf8(&name))],
5313 );
5314 }
5315 }
5316 }
5317 }
5318 PropName::Private(_) => {
5319 return Err(SyntaxError::new(
5320 "private names are not valid in object literals",
5321 *property_span,
5322 ));
5323 }
5324 },
5325 }
5326 }
5327 let _ = span;
5328 Ok(())
5329 }
5330
5331 /// Emit the function a method/accessor property defines.
5332 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
5333 self.expr(value)
5334 }
5335
5336 /// The name a literal property key contributes.
5337 ///
5338 /// String keys are used as written. A numeric key is converted the way
5339 /// `ToString` would convert it, because the atom is made from that spelling:
5340 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5341 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5342 match key {
5343 PropKey::Str(text) => Ok(text.clone()),
5344 PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5345 }
5346 }
5347
5348 /// Compile an optional chain.
5349 ///
5350 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5351 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5352 /// `undefined`. So the chain is compiled with one end label and every guard
5353 /// jumps to it. The parser hands us the extent of that spine as an
5354 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5355 /// exactly the scope the label has to cover.
5356 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5357 let end = self.new_label();
5358 self.chain_link(inner, end)?;
5359 self.place_label(end);
5360 Ok(())
5361 }
5362
5363 /// A member access or call reached from outside any optional chain.
5364 ///
5365 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5366 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5367 /// still created because [`Self::chain_link`] takes it, and placing it at the
5368 /// end is a no-op that keeps a single code path.
5369 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5370 let end = self.new_label();
5371 self.chain_link(expr, end)?;
5372 self.place_label(end);
5373 Ok(())
5374 }
5375
5376 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5377 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5378 match &expr.kind {
5379 ExprKind::Member {
5380 object,
5381 property,
5382 optional,
5383 } => {
5384 // `super.x` is not a lookup on a value: it starts at the home object's
5385 // prototype and keeps `this` as the receiver, so it cannot go through
5386 // `chain_link` and the ordinary field read.
5387 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5388 self.super_base();
5389 match property {
5390 MemberProp::Ident(name) => self.emit(
5391 Opcode::PushAtomValue,
5392 &[Op::Atom(Atom::from_text(&name.name))],
5393 ),
5394 MemberProp::Computed(index) => self.expr(index)?,
5395 MemberProp::Private(_) => {
5396 return Err(SyntaxError::new(
5397 "private fields are not supported by the compiler yet",
5398 expr.span,
5399 ));
5400 }
5401 }
5402 self.emit(Opcode::GetSuperValue, &[]);
5403 return Ok(());
5404 }
5405 self.chain_link(object, end)?;
5406 if *optional {
5407 self.optional_guard(end);
5408 }
5409 match property {
5410 // `.length` has its own opcode. The reference emits it for every
5411 // object, not just arrays, so a name-based rule is right and
5412 // cheaper than the generic field read.
5413 MemberProp::Ident(name) if name.name == "length" => {
5414 self.emit(Opcode::GetLength, &[]);
5415 }
5416 MemberProp::Ident(name) => {
5417 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5418 }
5419 MemberProp::Computed(index) => {
5420 self.expr(index)?;
5421 self.emit(Opcode::GetArrayEl, &[]);
5422 }
5423 MemberProp::Private(name) => {
5424 // The binding comes from the class scope, so a read from outside the
5425 // class cannot name it at all. `?.` checks the object, not the field:
5426 // `o?.#x` guards on `o` being nullish.
5427 let binding = format!("#{}", name.name);
5428 let (kind, _) = self.private_use(&binding, expr.span)?;
5429 self.private_load(&binding, kind, expr.span)?;
5430 }
5431 }
5432 Ok(())
5433 }
5434 ExprKind::Call {
5435 callee,
5436 arguments,
5437 optional,
5438 } => {
5439 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5440 // cannot: it reads the function and then calls it with no
5441 // receiver at all. The reference's answer is to keep the object
5442 // under the function value — `get_field2` reads a field and leaves
5443 // its base in place — and to use `call_method`, which takes the
5444 // receiver from the stack. Missing this does not just cost an
5445 // instruction, it loses the `this` binding.
5446 if let ExprKind::Member {
5447 object,
5448 property,
5449 optional: member_optional,
5450 } = &callee.unparen().kind
5451 {
5452 // `super.m()` reads the method off the home object's prototype but
5453 // calls it with `this`, so the receiver goes under the read instead of
5454 // being replaced by it.
5455 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5456 self.super_base();
5457 match property {
5458 MemberProp::Ident(name) => self.emit(
5459 Opcode::PushAtomValue,
5460 &[Op::Atom(Atom::from_text(&name.name))],
5461 ),
5462 MemberProp::Computed(index) => self.expr(index)?,
5463 MemberProp::Private(_) => {
5464 return Err(SyntaxError::new(
5465 "private fields are not supported by the compiler yet",
5466 expr.span,
5467 ));
5468 }
5469 }
5470 // The two-output form would drop the receiver; this one replaces
5471 // the prototype and the key, leaving `this` underneath.
5472 self.emit(Opcode::GetArrayEl, &[]);
5473 if Self::has_spread(arguments) {
5474 self.argument_array(arguments)?;
5475 self.emit(Opcode::Perm3, &[]);
5476 self.emit(Opcode::Apply, &[Op::Int(0)]);
5477 return Ok(());
5478 }
5479 for argument in arguments {
5480 self.expr(argument)?;
5481 }
5482 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5483 return Ok(());
5484 }
5485 self.chain_link(object, end)?;
5486 if *member_optional {
5487 self.optional_guard(end);
5488 }
5489 match property {
5490 MemberProp::Ident(name) => {
5491 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5492 }
5493 MemberProp::Computed(index) => {
5494 self.expr(index)?;
5495 // The key is not needed after the read, so this is the
5496 // two-output form: object, value.
5497 self.emit(Opcode::GetArrayEl2, &[]);
5498 }
5499 MemberProp::Private(name) => {
5500 // The receiver is already under the callee, which is exactly the
5501 // shape `call_method` and `apply` want — so nothing is dropped.
5502 let binding = format!("#{}", name.name);
5503 let (kind, _) = self.private_use(&binding, expr.span)?;
5504 self.private_callee(&binding, kind)?;
5505 }
5506 }
5507 if Self::has_spread(arguments) {
5508 // Stack is `obj func`; the array goes on top, then `perm3`
5509 // reorders to the `func this array` that `apply` wants.
5510 self.argument_array(arguments)?;
5511 self.emit(Opcode::Perm3, &[]);
5512 self.emit(Opcode::Apply, &[Op::Int(0)]);
5513 return Ok(());
5514 }
5515 for argument in arguments {
5516 self.expr(argument)?;
5517 }
5518 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5519 return Ok(());
5520 }
5521 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5522 // with `get_field2` so the base stays under it, and on the short-circuit
5523 // path pushes an extra `undefined` as a placeholder receiver — the call
5524 // then throws, which is what calling a missing optional chain should do.
5525 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5526 && let ExprKind::Member {
5527 object,
5528 property,
5529 optional: member_optional,
5530 } = &inner.unparen().kind
5531 {
5532 let call = self.new_label();
5533 // A guard target of its own: the outer `end` skips the whole
5534 // expression, and a short-circuited receiver still has to reach the
5535 // call so that calling it throws.
5536 let short = self.new_label();
5537 self.chain_link(object, end)?;
5538 if *member_optional {
5539 self.optional_guard(short);
5540 }
5541 match property {
5542 MemberProp::Ident(name) => {
5543 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5544 }
5545 MemberProp::Computed(index) => {
5546 self.expr(index)?;
5547 self.emit(Opcode::GetArrayEl2, &[]);
5548 }
5549 MemberProp::Private(name) => {
5550 let binding = format!("#{}", name.name);
5551 let (kind, _) = self.private_use(&binding, expr.span)?;
5552 self.private_callee(&binding, kind)?;
5553 }
5554 }
5555 self.emit_jump(Opcode::Goto, call, &[]);
5556 self.place_label(short);
5557 self.emit(Opcode::Undefined, &[]);
5558 self.place_label(call);
5559 if Self::has_spread(arguments) {
5560 self.argument_array(arguments)?;
5561 self.emit(Opcode::Perm3, &[]);
5562 self.emit(Opcode::Apply, &[Op::Int(0)]);
5563 return Ok(());
5564 }
5565 for argument in arguments {
5566 self.expr(argument)?;
5567 }
5568 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5569 return Ok(());
5570 }
5571 self.chain_link(callee, end)?;
5572 if *optional {
5573 self.optional_guard(end);
5574 }
5575 if Self::has_spread(arguments) {
5576 // `func array -> func undefined array`, which is the plain-call
5577 // form of `apply`: the receiver is `undefined`.
5578 self.argument_array(arguments)?;
5579 self.emit(Opcode::Undefined, &[]);
5580 self.emit(Opcode::Swap, &[]);
5581 self.emit(Opcode::Apply, &[Op::Int(0)]);
5582 return Ok(());
5583 }
5584 for argument in arguments {
5585 self.expr(argument)?;
5586 }
5587 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5588 Ok(())
5589 }
5590 _ => self.expr(expr),
5591 }
5592 }
5593
5594 /// Compile `expr` as a tail call when it is one, reporting whether it was.
5595 ///
5596 /// `tail_call` reuses the current frame instead of pushing a new one, so a
5597 /// tail-recursive function runs in constant stack space. It also has to be the
5598 /// *last* thing the function does, which is why only a `return` reaches here.
5599 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5600 let ExprKind::Call {
5601 callee,
5602 arguments,
5603 optional: false,
5604 } = &expr.unparen().kind
5605 else {
5606 return Ok(false);
5607 };
5608 // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5609 // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5610 // as an ordinary call costs the one frame the optimisation was saving and keeps the
5611 // semantics — the alternative was reaching the spread expression below and failing
5612 // with "this expression form is not supported", which is how `return super.m(...a)`
5613 // stopped compiling. Checked before anything is emitted, because the decision cannot
5614 // be taken back once `super_base` or a `get_field2` is on the stack.
5615 if Self::has_spread(arguments) {
5616 return Ok(false);
5617 }
5618 let end = self.new_label();
5619 if let ExprKind::Member {
5620 object,
5621 property,
5622 optional: false,
5623 } = &callee.unparen().kind
5624 {
5625 // `super.m()` in tail position is still an ordinary method call with `this`
5626 // as the receiver; only the read of the method differs.
5627 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5628 self.super_base();
5629 match property {
5630 MemberProp::Ident(name) => self.emit(
5631 Opcode::PushAtomValue,
5632 &[Op::Atom(Atom::from_text(&name.name))],
5633 ),
5634 MemberProp::Computed(index) => self.expr(index)?,
5635 MemberProp::Private(_) => return Ok(false),
5636 }
5637 self.emit(Opcode::GetArrayEl, &[]);
5638 for argument in arguments {
5639 self.expr(argument)?;
5640 }
5641 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5642 self.place_label(end);
5643 return Ok(true);
5644 }
5645 self.chain_link(object, end)?;
5646 match property {
5647 MemberProp::Ident(name) => {
5648 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5649 }
5650 MemberProp::Computed(index) => {
5651 self.expr(index)?;
5652 self.emit(Opcode::GetArrayEl2, &[]);
5653 }
5654 MemberProp::Private(_) => return Ok(false),
5655 }
5656 for argument in arguments {
5657 self.expr(argument)?;
5658 }
5659 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5660 self.place_label(end);
5661 return Ok(true);
5662 }
5663 self.chain_link(callee, end)?;
5664 for argument in arguments {
5665 self.expr(argument)?;
5666 }
5667 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5668 self.place_label(end);
5669 Ok(true)
5670 }
5671
5672 /// The `?.` guard: keep the value if it is neither null nor undefined,
5673 /// otherwise replace it with `undefined` and leave the whole chain.
5674 fn optional_guard(&mut self, end: Label) {
5675 let cont = self.new_label();
5676 self.emit(Opcode::Dup, &[]);
5677 self.emit(Opcode::IsUndefinedOrNull, &[]);
5678 self.emit_jump(Opcode::IfFalse, cont, &[]);
5679 self.emit(Opcode::Drop, &[]);
5680 self.emit(Opcode::Undefined, &[]);
5681 self.emit_jump(Opcode::Goto, end, &[]);
5682 self.place_label(cont);
5683 }
5684
5685 fn push_number(&mut self, value: f64) {
5686 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5687 // goes into the constant pool.
5688 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5689 let int = value as i32;
5690 if (-1..=7).contains(&int) {
5691 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5692 return;
5693 }
5694 if (-128..=127).contains(&int) {
5695 self.emit(Opcode::PushI8, &[Op::Int(int)]);
5696 return;
5697 }
5698 if (-32768..=32767).contains(&int) {
5699 self.emit(Opcode::PushI16, &[Op::Int(int)]);
5700 return;
5701 }
5702 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5703 return;
5704 }
5705 let index = self.push_constant(Constant::Number(value));
5706 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5707 }
5708
5709 /// Push a `BigInt` literal.
5710 ///
5711 /// A value that fits an `i32` uses the immediate form, which is what the reference
5712 /// emits too; anything larger goes into the constant pool, because the operand of
5713 /// `push_bigint` is only four bytes wide.
5714 fn push_bigint(&mut self, digits: &str, radix: u32) {
5715 if radix == 10
5716 && let Ok(value) = digits.parse::<i64>()
5717 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5718 {
5719 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5720 return;
5721 }
5722 let index = self.push_constant(Constant::BigInt {
5723 digits: digits.to_string(),
5724 radix,
5725 });
5726 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5727 }
5728
5729 fn push_string(&mut self, text: &Wtf8) {
5730 if text.is_empty() {
5731 self.emit(Opcode::PushEmptyString, &[]);
5732 return;
5733 }
5734 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5735 }
5736
5737 /// Name an anonymous function from the binding it is assigned to.
5738 ///
5739 /// `var f = function(){}` produces a function whose `name` is `f`, which the
5740 /// runtime cannot know without being told: the function object is created
5741 /// before the store. `set_name` carries the name across.
5742 fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5743 if !value.is_anonymous_function_definition() {
5744 return;
5745 }
5746 // A class cannot use `set_name`, because its static field initialisers have already
5747 // run by the time the store happens and they can see `this.name`:
5748 // `var E = class { static f = this.name }` has to answer `"E"`. The reference patches
5749 // the `define_class` instruction's name operand instead, which is why
5750 // `set_class_name` is a compile-time marker with no runtime effect
5751 // (`class-name-static-initializer-anonymous`).
5752 if matches!(value.unparen().kind, ExprKind::Class(_)) {
5753 if let Some(index) = self.last_define_class() {
5754 let atom = Atom::from_wtf8(name);
5755 if let Some(Insn::Fixed { operands, .. }) = self.state().insns.get_mut(index) {
5756 // `define_class <atom> <flags>`: the name is operand 0.
5757 operands[0] = Op::Atom(atom);
5758 }
5759 }
5760 return;
5761 }
5762 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5763 }
5764
5765 /// The index of the most recent `define_class` in this function's instruction stream.
5766 ///
5767 /// A backwards scan, because everything the class body emitted for the *enclosing*
5768 /// function is still there after it — the static initialiser's call, the class
5769 /// binding's store, `leave_scope` — and only the `define_class` carries the name.
5770 fn last_define_class(&self) -> Option<usize> {
5771 self.cur().insns.iter().rposition(|insn| {
5772 matches!(
5773 insn,
5774 Insn::Fixed {
5775 op: Opcode::DefineClass,
5776 ..
5777 }
5778 )
5779 })
5780 }
5781
5782 /// The same, for a computed key: the name comes from the value on the stack
5783 /// rather than from an atom, so a different instruction carries it.
5784 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5785 if value.is_anonymous_function_definition() {
5786 self.emit(Opcode::SetNameComputed, &[]);
5787 }
5788 }
5789
5790 /// Compile a function body that exists only in the compiler's head — a class's
5791 /// implicit constructor or its field initialiser.
5792 ///
5793 /// Everything structural is the same as a written function: a fresh `FnState`, its
5794 /// own body block, and resolution while the frame is still on the stack. Only the
5795 /// statements differ.
5796 fn compile_synthetic_function(
5797 &mut self,
5798 name: &str,
5799 strict: bool,
5800 span: Span,
5801 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5802 ) -> Result<CompiledFunction, SyntaxError> {
5803 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5804 state.span = Some((span.start.offset as usize, span.end.offset as usize));
5805 state.strict = strict;
5806 state.created_in_block = self.cur().current_block;
5807 state.with_names = self.cur().with_names.clone();
5808 state.line = span.start.line;
5809 state.column = span.start.column;
5810 let depth = self.stack.len();
5811 self.stack.push(state);
5812 let body_key = span.start.offset as u64;
5813 self.push_block(body_key, NO_PARENT);
5814 self.state().body_block = body_key;
5815 let result = (|| {
5816 self.emit_scope_enter(body_key);
5817 body(self)?;
5818 if self.end_is_reachable() {
5819 self.emit(Opcode::ReturnUndef, &[]);
5820 }
5821 Ok(())
5822 })();
5823 if result.is_err() {
5824 self.stack.truncate(depth);
5825 return result.map(|()| unreachable!());
5826 }
5827 Ok(self.finish_current())
5828 }
5829
5830 /// The implicit return of a class constructor.
5831 ///
5832 /// A constructor that falls off the end initialises its instance fields first, and a
5833 /// derived one returns `this` — which is what makes `new D()` the object `super()`
5834 /// built rather than `undefined`.
5835 fn emit_class_constructor_tail(&mut self) {
5836 match self.cur().ctor_kind {
5837 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5838 // Nothing to install: a base constructor did it in its prologue and a derived
5839 // one at each `super()` site, which is where `this` first exists.
5840 CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5841 CtorKind::Derived => {
5842 // `get_loc_check` rather than `get_loc`: reaching the end without ever
5843 // running `super()` is a ReferenceError, not `undefined`.
5844 self.emit_var(VarAction::Get, "this");
5845 self.emit(Opcode::Return, &[]);
5846 }
5847 }
5848 }
5849
5850 /// `yield expr` / `yield* expr`.
5851 ///
5852 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5853 /// it to the caller and parks the frame. On resume the stack holds the value the
5854 /// caller passed *and* a "magic" number saying which method resumed it — `next`
5855 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5856 /// `if_false <continue>` asks whether this was an ordinary `next`:
5857 ///
5858 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5859 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5860 /// and uses the value sitting under the magic number.
5861 ///
5862 /// A `throw` never reaches here: the interpreter unwinds instead (see
5863 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5864 fn yield_expression(
5865 &mut self,
5866 argument: Option<&Expr>,
5867 delegate: bool,
5868 ) -> Result<(), SyntaxError> {
5869 if delegate {
5870 return self.yield_star(argument);
5871 }
5872 // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5873 // does the same for the `return(v)` that can resume it — which is why an async
5874 // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5875 // generator's is just `yield`.
5876 let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5877 match argument {
5878 Some(value) => self.expr(value)?,
5879 None => self.emit(Opcode::Undefined, &[]),
5880 }
5881 if is_async {
5882 self.emit(Opcode::Await, &[]);
5883 self.state().has_await = true;
5884 }
5885 self.emit(Opcode::Yield, &[]);
5886 let resume = self.new_label();
5887 self.emit_jump(Opcode::IfFalse, resume, &[]);
5888 // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5889 // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5890 // finished the generator and never ran the `finally`.
5891 if is_async {
5892 self.emit(Opcode::Await, &[]);
5893 }
5894 self.emit_unwind_for_return(true);
5895 self.emit(Opcode::ReturnAsync, &[]);
5896 self.place_label(resume);
5897 // Nothing is emitted here: the value the caller passed to `next` *is* the value
5898 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5899 // it through the ordinary expression-statement discard.
5900 Ok(())
5901 }
5902
5903 /// `yield* iterable`.
5904 ///
5905 /// The shape is the reference's, and it is a fall-through chain rather than a
5906 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5907 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5908 /// the inner iterator and finishes, `throw` forwards the exception into it and
5909 /// continues only if it has a `throw` method.
5910 ///
5911 /// The stack is `iter next catch value` throughout, `catch` being the offset
5912 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5913 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5914 match argument {
5915 Some(value) => self.expr(value)?,
5916 // The parser rejects a bare `yield*`, so this is unreachable in practice.
5917 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5918 }
5919 // `for await of` is the same protocol as `for of` with two differences that matter
5920 // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5921 // every `next()` result is a promise the delegate has to await.
5922 let is_async = self.cur().kind.is_async();
5923 self.emit(
5924 if is_async {
5925 Opcode::ForAwaitOfStart
5926 } else {
5927 Opcode::ForOfStart
5928 },
5929 &[],
5930 );
5931 self.emit(Opcode::Drop, &[]);
5932 self.emit(Opcode::Undefined, &[]);
5933 self.emit(Opcode::Undefined, &[]);
5934 let next = self.new_label();
5935 let resume = self.new_label();
5936 let finished = self.new_label();
5937 let rethrow = self.new_label();
5938 let throw_no_method = self.new_label();
5939 let done = self.new_label();
5940 self.place_label(next);
5941 self.emit(Opcode::IteratorNext, &[]);
5942 if is_async {
5943 self.emit(Opcode::Await, &[]);
5944 self.state().has_await = true;
5945 }
5946 self.emit(Opcode::IteratorCheckObject, &[]);
5947 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5948 self.emit_jump(Opcode::IfTrue, done, &[]);
5949 // The suspension. `resume` is both the label the return path jumps back to in order
5950 // to yield one more value and where the caller's answer arrives, as the value
5951 // followed by the magic number.
5952 //
5953 // The two forms differ in what they hand the suspension: `yield_star` takes the
5954 // result object itself, `async_yield_star` takes `.value`, because an async
5955 // generator awaits and re-wraps whatever it yields.
5956 self.place_label(resume);
5957 if is_async {
5958 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5959 self.emit(Opcode::AsyncYieldStar, &[]);
5960 } else {
5961 self.emit(Opcode::YieldStar, &[]);
5962 }
5963 self.emit(Opcode::Dup, &[]);
5964 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5965 self.emit(Opcode::Drop, &[]);
5966 self.emit_jump(Opcode::Goto, next, &[]);
5967
5968 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5969 self.place_label(rethrow);
5970 self.emit(Opcode::PushI32, &[Op::Int(2)]);
5971 self.emit(Opcode::StrictEq, &[]);
5972 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5973 // A `return` closes the inner iterator; if it had none, the delegate simply
5974 // finishes with the requested value. In an async generator both the call and its
5975 // result are awaited, because the inner `return` may itself be async.
5976 if is_async {
5977 self.emit(Opcode::Await, &[]);
5978 }
5979 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5980 self.emit_jump(Opcode::IfTrue, finished, &[]);
5981 if is_async {
5982 self.emit(Opcode::Await, &[]);
5983 }
5984 self.emit(Opcode::IteratorCheckObject, &[]);
5985 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5986 self.emit_jump(Opcode::IfFalse, resume, &[]);
5987 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5988 self.place_label(finished);
5989 self.emit(Opcode::Nip, &[]);
5990 self.emit(Opcode::Nip, &[]);
5991 self.emit(Opcode::Nip, &[]);
5992 // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5993 // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5994 // awaits the value in an async generator and then runs the same `finally`/iterator
5995 // unwinding a written `return` would. Skipping the unwinding made
5996 // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5997 if is_async {
5998 self.emit(Opcode::Await, &[]);
5999 }
6000 self.emit_unwind_for_return(true);
6001 self.emit(Opcode::ReturnAsync, &[]);
6002
6003 // `throw(e)`: forward it into the inner iterator.
6004 self.place_label(throw_no_method);
6005 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
6006 let no_throw = self.new_label();
6007 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
6008 if is_async {
6009 self.emit(Opcode::Await, &[]);
6010 }
6011 self.emit(Opcode::IteratorCheckObject, &[]);
6012 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6013 self.emit_jump(Opcode::IfFalse, resume, &[]);
6014 self.emit_jump(Opcode::Goto, done, &[]);
6015 // No `throw` method: close the iterator, then report the spec's TypeError. The
6016 // `if_true` before the `await` is the reference's shape — the flag it consumes is
6017 // what `iterator_call` leaves behind, and a close that *did* find no `return`
6018 // method has nothing to await.
6019 self.place_label(no_throw);
6020 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
6021 let no_close = self.new_label();
6022 self.emit_jump(Opcode::IfTrue, no_close, &[]);
6023 if is_async {
6024 self.emit(Opcode::Await, &[]);
6025 }
6026 self.place_label(no_close);
6027 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
6028
6029 // The inner iterator finished: the delegate's value is the `yield*` expression's
6030 // value, so it is left on the stack for whatever consumes it.
6031 self.place_label(done);
6032 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6033 self.emit(Opcode::Nip, &[]);
6034 self.emit(Opcode::Nip, &[]);
6035 self.emit(Opcode::Nip, &[]);
6036 Ok(())
6037 }
6038
6039 /// `await expr`: exactly one instruction.
6040 ///
6041 /// No resume-magic branch follows it. The reference's `await` leaves a single value
6042 /// on the stack and completion is signalled by the `return_async` at the end of the
6043 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
6044 /// reference never emits, and a `for await` loop — which reaches `await` through the
6045 /// same opcode — would then spill a value the loop's unpacking does not expect.
6046 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
6047 self.expr(argument)?;
6048 self.emit(Opcode::Await, &[]);
6049 self.state().has_await = true;
6050 Ok(())
6051 }
6052
6053 /// The `super` base: the receiver followed by the home object's prototype.
6054 ///
6055 /// Everything `super` does needs both. A *read* starts at the prototype but reports
6056 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
6057 /// prototype but calls it with the receiver.
6058 fn super_base(&mut self) {
6059 self.this_expression();
6060 self.home_object();
6061 self.emit(Opcode::GetSuper, &[]);
6062 }
6063
6064 /// `[[HomeObject]]` as `super` sees it.
6065 ///
6066 /// A method, a constructor and a field initialiser each carry one — `set_home_object`
6067 /// put it there — so for them the special object *is* the answer. An arrow and a
6068 /// static block have none: they read the enclosing function's, which has to be
6069 /// materialised into a local, exactly as `this` is for an arrow.
6070 ///
6071 /// The name matches what the reference stores, so the disassembly agrees; it is not a
6072 /// name any program can write.
6073 fn home_object(&mut self) {
6074 if !self.cur().is_arrow {
6075 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
6076 return;
6077 }
6078 if let Some(target) = self.enclosing_function() {
6079 self.state_at(target).needs_home_object_local = true;
6080 self.declare_at(target, HOME_OBJECT);
6081 }
6082 self.emit_var(VarAction::Get, HOME_OBJECT);
6083 }
6084
6085 /// `super(args)`: construct the parent class and adopt the result as `this`.
6086 ///
6087 /// The parent is the prototype of the constructor that is running, which is exactly
6088 /// what `extends` set up. `new.target` is passed through unchanged so that
6089 /// `new.target` inside the parent is the class actually being constructed.
6090 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
6091 self.active_func_expression();
6092 self.emit(Opcode::GetSuper, &[]);
6093 self.new_target_expression();
6094 if Self::has_spread(arguments) {
6095 self.argument_array(arguments)?;
6096 self.emit(Opcode::Apply, &[Op::Int(1)]);
6097 } else {
6098 for argument in arguments {
6099 self.expr(argument)?;
6100 }
6101 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
6102 }
6103 // The value stays on the stack: `super()` is an expression, and a derived
6104 // constructor's `this` may only be initialised once.
6105 self.emit(Opcode::Dup, &[]);
6106 self.emit_var(VarAction::PutInitChecked, "this");
6107 // Instance fields are installed here, not at the top of the body: a derived
6108 // constructor has no `this` to install them on until `super()` returns. The
6109 // reference emits the same call at every `super()` site.
6110 self.call_field_initialiser();
6111 Ok(())
6112 }
6113
6114 /// `this` as a local, which every class constructor and field initialiser needs.
6115 ///
6116 /// The reference materialises the receiver into a local rather than reading
6117 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
6118 /// and a field initialiser has to see the final value.
6119 fn begin_this_local(&mut self) {
6120 self.declare_hidden_local("this", VarKind::Normal);
6121 self.emit(Opcode::PushThis, &[]);
6122 self.emit_var(VarAction::Put, "this");
6123 // The store is already at the top of the body, so `provide_this_local` has
6124 // nothing left to prepend. Without this the initialiser ended up with
6125 // `push_this; put_loc0 this` twice whenever the class also held a field
6126 // initialiser whose body read `this` through an arrow.
6127 self.state().has_this_prologue = true;
6128 }
6129
6130 /// Compile a constructor the class wrote.
6131 ///
6132 /// The flags have to be in place before the body is compiled, but
6133 /// `compile_function_with_name` creates its own state — so the caller's state is
6134 /// marked instead and the new one inherits it. That is the same trick the parameter
6135 /// prologue uses, and it keeps one code path for both.
6136 fn compile_class_constructor(
6137 &mut self,
6138 func: &ast::Function,
6139 has_heritage: bool,
6140 ) -> Result<CompiledFunction, SyntaxError> {
6141 let saved = self.cur().ctor_kind;
6142 self.state().class_ctor_pending = Some(if has_heritage {
6143 CtorKind::Derived
6144 } else {
6145 CtorKind::Base
6146 });
6147 let result = self.compile_function_with_name(func, false);
6148 self.state().ctor_kind = saved;
6149 self.state().class_ctor_pending = None;
6150 result
6151 }
6152
6153 /// The constructor a class gets when it does not declare one.
6154 ///
6155 /// A base class's is empty; a derived class's forwards every argument to the parent
6156 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
6157 /// instance field initialiser afterwards when the class has fields, which is why the
6158 /// initialiser is captured rather than inlined.
6159 fn compile_implicit_constructor(
6160 &mut self,
6161 class: &Class,
6162 has_heritage: bool,
6163 ) -> Result<CompiledFunction, SyntaxError> {
6164 self.compile_synthetic_function(
6165 "",
6166 true,
6167 Span::new(class.body_end, class.body_end),
6168 |compiler| {
6169 if has_heritage {
6170 // A derived constructor's `this` does not exist until `super()` returns,
6171 // so it starts in the dead zone and `init_ctor` fills it.
6172 compiler.declare("this", VarDef::lexical("this"));
6173 compiler.emit(
6174 Opcode::SetLocUninitialized,
6175 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6176 );
6177 compiler.emit(Opcode::InitCtor, &[]);
6178 compiler.emit(
6179 Opcode::PutLocCheckInit,
6180 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6181 );
6182 } else {
6183 compiler.begin_this_local();
6184 compiler.emit(Opcode::CheckCtor, &[]);
6185 }
6186 compiler.call_field_initialiser();
6187 // A derived constructor returns `this`, the object `super()` built. Without
6188 // this the implicit constructor fell through to `return_undef`, and `new B()`
6189 // handed back the empty object `construct` had made instead of the one the
6190 // parent constructor initialised.
6191 if has_heritage {
6192 compiler.emit_var(VarAction::Get, "this");
6193 compiler.emit(Opcode::Return, &[]);
6194 }
6195 Ok(())
6196 },
6197 )
6198 }
6199
6200 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
6201 ///
6202 /// A class with no instance fields leaves the binding `undefined`, and calling it
6203 /// would throw; the reference emits the same guard rather than branching at compile
6204 /// time because a class can be extended by a subclass whose fields still have to run.
6205 fn call_field_initialiser(&mut self) {
6206 let skip = self.new_label();
6207 self.emit_var(VarAction::Get, "<class_fields_init>");
6208 self.emit(Opcode::Dup, &[]);
6209 self.emit_jump(Opcode::IfFalse, skip, &[]);
6210 self.emit_var(VarAction::Get, "this");
6211 self.emit(Opcode::Swap, &[]);
6212 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6213 self.place_label(skip);
6214 self.emit(Opcode::Drop, &[]);
6215 }
6216
6217 /// The function that defines one class's fields on `this`, and runs its static blocks.
6218 ///
6219 /// `define_field` rather than `put_field`: a field is an own property created
6220 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
6221 /// `x = 1` field must not call the setter.
6222 ///
6223 /// One function serves the whole class: it is called once per instance (or once, for
6224 /// the static half) and walks the members in source order. Static blocks are compiled
6225 /// into the same function because they *are* part of the same sequence — `static a =
6226 /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
6227 /// different values, so the two kinds cannot be split apart.
6228 fn compile_field_initialiser(
6229 &mut self,
6230 items: &[StaticInitItem<'_>],
6231 span: Span,
6232 instance: bool,
6233 add_brand: bool,
6234 ) -> Result<CompiledFunction, SyntaxError> {
6235 self.compile_synthetic_function("", true, span, |compiler| {
6236 // A field initialiser and a static block are not functions, so neither has an
6237 // `arguments` of its own; see `FnState::no_arguments_binding`.
6238 let current = compiler.stack.len() - 1;
6239 compiler.stack[current].no_arguments_binding = true;
6240 if instance {
6241 // An instance initialiser always carries a `<home_object>` local, because the
6242 // brand block below reads it — even when that block turns out to be dead. The
6243 // reference has the same artefact, and the store is visible in its dump.
6244 let current = compiler.stack.len() - 1;
6245 compiler.stack[current].needs_home_object_local = true;
6246 }
6247 compiler.begin_this_local();
6248 if instance {
6249 // `this` gets the brand the prototype created, before any field is defined —
6250 // which is what makes `#m()` usable from inside a field initialiser.
6251 //
6252 // The reference always emits `push_false; if_false L; this; home; add_brand;
6253 // L:` and patches the `push_false` to `push_true` from the class parse when
6254 // the class has private methods; either way the branch folds, but the *mark*
6255 // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
6256 // `this` local from being fused into a `set_loc`.
6257 let skip = compiler.new_label();
6258 if add_brand {
6259 compiler.emit(Opcode::PushTrue, &[]);
6260 } else {
6261 compiler.emit(Opcode::PushFalse, &[]);
6262 }
6263 compiler.emit_jump(Opcode::IfFalse, skip, &[]);
6264 compiler.emit_var(VarAction::Get, "this");
6265 compiler.emit_var(VarAction::Get, HOME_OBJECT);
6266 compiler.emit(Opcode::AddBrand, &[]);
6267 compiler.place_label(skip);
6268 }
6269 for item in items {
6270 match item {
6271 StaticInitItem::Field(key, value) => {
6272 // A private field is *defined*, not assigned: `define_private_field`
6273 // reads `obj symbol value`, and its point is that it fails on a
6274 // receiver that is not this class's — which `put_field` would not.
6275 //
6276 // The three shapes are the reference's: `define_field <atom>` for a
6277 // static name, `define_array_el` for a key that is only known at run
6278 // time (`obj key value`), `define_private_field` for `#x`, and a
6279 // computed key is read from its binding rather than recomputed.
6280 compiler.emit_var(VarAction::Get, "this");
6281 match key {
6282 FieldKey::Private(binding) | FieldKey::Computed(binding) => {
6283 compiler.emit_var(VarAction::Get, binding);
6284 }
6285 FieldKey::Literal(_) => {}
6286 }
6287 match value {
6288 Some(value) => {
6289 compiler.expr(value)?;
6290 // A field initialiser is a `NamedEvaluation` target:
6291 // `x = function(){}` names the function `"x"`, and a private
6292 // field keeps its `#` (`static #f = () => 1` is named
6293 // `"#f"` (elements/static-field-anonymous-function-name).
6294 match key {
6295 FieldKey::Literal(literal) => {
6296 let text = compiler.property_key_text(literal, span)?;
6297 compiler.set_name_if_anonymous(value, &text);
6298 }
6299 FieldKey::Private(binding) => {
6300 compiler.set_name_if_anonymous(value, &Wtf8::new(binding));
6301 }
6302 // The key is a value on the stack, and `set_name_computed`
6303 // is exactly the instruction for that.
6304 FieldKey::Computed(_) => {
6305 compiler.set_name_if_anonymous_computed(value);
6306 }
6307 }
6308 }
6309 None => compiler.emit(Opcode::Undefined, &[]),
6310 }
6311 match key {
6312 FieldKey::Literal(literal) => {
6313 let text = compiler.property_key_text(literal, span)?;
6314 compiler
6315 .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
6316 }
6317 FieldKey::Computed(_) => {
6318 compiler.emit(Opcode::DefineArrayEl, &[]);
6319 // `define_array_el` leaves `obj key`; the key is consumed by
6320 // the copy the pattern machinery wants, so both go.
6321 compiler.emit(Opcode::Drop, &[]);
6322 }
6323 FieldKey::Private(_) => {
6324 compiler.emit(Opcode::DefinePrivateField, &[]);
6325 }
6326 }
6327 compiler.emit(Opcode::Drop, &[]);
6328 }
6329 StaticInitItem::Block { body, body_start } => {
6330 let block = compiler.compile_static_block(body, *body_start)?;
6331 let index = compiler.push_constant(Constant::Function(Box::new(block)));
6332 // `this fclosure`, so `call_method` finds the receiver below the
6333 // callee: the block runs with `this` bound to the class.
6334 compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
6335 compiler.emit_var(VarAction::Get, "this");
6336 compiler.emit(Opcode::Swap, &[]);
6337 compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
6338 // Nothing the block evaluates is wanted; its effects are the point.
6339 compiler.emit(Opcode::Drop, &[]);
6340 }
6341 }
6342 }
6343 Ok(())
6344 })
6345 }
6346
6347 /// Compile a `static { … }` body into the function the class calls for it.
6348 ///
6349 /// Shaped like an arrow, because that is the one function form with no `this`,
6350 /// `new.target` or `arguments` of its own: all three reach the enclosing static
6351 /// initialiser, and through it the class. `arguments` never gets that far — the parser
6352 /// rejects the reference — but `this` and `super` both depend on it.
6353 ///
6354 /// The body is hoisted like a function body's, because the reference parses it as one:
6355 /// `var` inside a block is a local of the block's function, not of whatever encloses
6356 /// the class.
6357 fn compile_static_block(
6358 &mut self,
6359 body: &[Stmt],
6360 body_start: Position,
6361 ) -> Result<CompiledFunction, SyntaxError> {
6362 let mut state = FnState::new(String::new(), FunctionKind::Normal);
6363 // Class bodies are strict, so a static block is too.
6364 state.strict = true;
6365 // The one property that makes this an arrow: nothing of its own to bind `this` to,
6366 // so `this` and `super` come from the initialiser that calls it.
6367 state.is_arrow = true;
6368 state.created_in_block = self.cur().current_block;
6369 state.with_names = self.cur().with_names.clone();
6370 state.line = body_start.line;
6371 state.column = body_start.column;
6372 let depth = self.stack.len();
6373 self.stack.push(state);
6374 let body_key = body_start.offset as u64;
6375 self.push_block(body_key, NO_PARENT);
6376 self.state().body_block = body_key;
6377 let result = (|| {
6378 self.hoist(body, body_key)?;
6379 self.emit_scope_enter(body_key);
6380 for statement in body {
6381 self.stmt(statement)?;
6382 }
6383 if self.end_is_reachable() {
6384 self.emit(Opcode::ReturnUndef, &[]);
6385 }
6386 Ok(())
6387 })();
6388 if result.is_err() {
6389 self.stack.truncate(depth);
6390 return result.map(|()| unreachable!());
6391 }
6392 Ok(self.finish_current())
6393 }
6394
6395 /// Compile a class, leaving the constructor on the stack when `keep`.
6396 ///
6397 /// The shape follows the reference: the class body is its own scope holding the
6398 /// class's *inner* name as a `const` — which is what lets a method refer to the
6399 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6400 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6401 /// on the top of the stack: the prototype for instance members, the constructor
6402 /// itself for `static` ones, which is why a static member costs an extra `swap`.
6403 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6404 let parent_block = self.cur().current_block;
6405 let key = class.span.start.offset as u64;
6406 self.push_block(key, parent_block);
6407 let name = class.name.as_ref().map(|ident| ident.name.clone());
6408 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6409 // resolves `E` without a global lookup. An *unnamed* class expression has no such
6410 // binding, and `define_class` is handed the empty name.
6411 if let Some(name) = &name {
6412 self.declare(name, VarDef::constant(name.clone()));
6413 }
6414 self.emit_scope_enter(key);
6415
6416 // The heritage clause is evaluated outside the class's own scope: it cannot see
6417 // the class binding it is about to initialise.
6418 let saved_block = self.cur().current_block;
6419 self.state().current_block = parent_block;
6420 match &class.super_class {
6421 Some(parent) => self.expr(parent)?,
6422 None => self.emit(Opcode::Undefined, &[]),
6423 }
6424 self.state().current_block = saved_block;
6425 let has_heritage = class.super_class.is_some();
6426
6427 // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6428 // lands after the heritage's code — which is where the reference puts it, because it
6429 // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6430 // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6431 // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6432 // came out in the opposite order from the reference's.
6433 //
6434 // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6435 // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6436 // a const accepts — so the old comment's worry ("a const would refuse the second
6437 // store") did not apply: there is no second store.
6438 // Every `#name` the class declares gets a `const` binding in the class scope, and so
6439 // does every computed field key. That is how the reference does it
6440 // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6441 // what makes a private name resolve like any other class-scope variable — including
6442 // through a nested function's closure — while remaining invisible outside.
6443 //
6444 // All of them are declared *before* `<class_fields_init>`, in member order, because
6445 // that is when the reference's parser creates them.
6446 let plan = ClassPlan::build(class);
6447 // The body's private names are visible from here to the end of the class, and shadow
6448 // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6449 // — it is compiled first because `define_class` consumes it, but its body can name
6450 // `#x` like any other member's.
6451 self.private_scopes.push(plan.uses.clone());
6452 let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6453 for binding in &plan.bindings {
6454 class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6455 }
6456 let fci = self.declare(
6457 "<class_fields_init>",
6458 VarDef::constant("<class_fields_init>"),
6459 );
6460 // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6461 // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6462 // members' bindings follow in reverse.
6463 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6464 for slot in class_slots.iter().rev() {
6465 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6466 }
6467
6468 // The constructor is compiled before `define_class` because that instruction
6469 // consumes it; a class without one gets the implicit version.
6470 let constructor = class.elements.iter().find_map(|element| match element {
6471 ClassElement::Method {
6472 kind: MethodKind::Constructor,
6473 func,
6474 ..
6475 } => Some(&**func),
6476 _ => None,
6477 });
6478 // A constructor is compiled differently from a method: it owns `this`. The flags
6479 // go on the *enclosing* state because a constructor is a nested function and
6480 // `compile_function_with_name` starts a fresh one.
6481 let ctor = match constructor {
6482 Some(func) => self.compile_class_constructor(func, has_heritage)?,
6483 None => self.compile_implicit_constructor(class, has_heritage)?,
6484 };
6485 // A closure, not the bare constant: the constructor captures
6486 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6487 // has to hold the cell rather than a copy of its value.
6488 //
6489 // The pool slot is left unassigned for now, because the reference gives the
6490 // constructor the *last* index of the members' range: `js_parse_class` emits a
6491 // `push_const` whose operand is patched at the end of the class parse, after every
6492 // method has taken a slot. Emitting the members first and the constant second is how
6493 // the numbering comes out the same; the instruction itself stays where it is.
6494 let ctor_insn = self.cur().insns.len();
6495 self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6496 let flags = if has_heritage { 1 } else { 0 };
6497 self.emit(
6498 Opcode::DefineClass,
6499 &[
6500 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6501 Op::Int(flags),
6502 ],
6503 );
6504
6505 // Instance fields and static fields are two different functions: the first runs
6506 // per instance from the constructor, the second runs once, here.
6507 let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6508 let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6509 for (index, element) in class.elements.iter().enumerate() {
6510 match element {
6511 ClassElement::Method {
6512 key: member_key,
6513 is_static,
6514 kind,
6515 func,
6516 span,
6517 } => {
6518 if *kind == MethodKind::Constructor {
6519 continue;
6520 }
6521 // `static(x)` is a *method* named `static`, not a static method; the
6522 // parser already decided which by putting it in `kind`.
6523 if *is_static {
6524 self.emit(Opcode::Swap, &[]);
6525 }
6526 // A computed key is evaluated *here*, before the method's closure
6527 // exists, and stays under it: `define_method_computed` pops
6528 // `function, key, object`, so the stack has to read
6529 // `[class, prototype, key, function]`. Evaluating the key after the
6530 // `fclosure` and swapping the two put the prototype *below* the
6531 // closure, which defined the method on the function and lost the
6532 // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6533 // also the spec's — a class body evaluates every element's name before
6534 // that element's function.
6535 if let PropName::Computed(key) = member_key {
6536 self.expr(key)?;
6537 }
6538 let function = self.compile_function_with_name(func, true)?;
6539 let index = self.push_constant(Constant::Function(Box::new(function)));
6540 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6541 match member_key {
6542 // A private method is not a property of the prototype: it is a
6543 // closure in the class scope, which is why nothing outside can reach
6544 // it and why a use site has to brand-check. `set_name` gives the
6545 // function its `name` (`#m`), which an accessor does not get — the
6546 // reference leaves that commented out.
6547 PropName::Private(ident) => {
6548 let name = format!("#{}", ident.name);
6549 // `set_home_object` first: the brand check reads the function's
6550 // home object, and for a method that is the prototype.
6551 self.emit(Opcode::SetHomeObject, &[]);
6552 let binding = if *kind == MethodKind::Set {
6553 format!("{name}<set>")
6554 } else {
6555 name.clone()
6556 };
6557 if *kind == MethodKind::Method {
6558 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6559 }
6560 self.emit_var(VarAction::PutInit, &binding);
6561 }
6562 PropName::Computed(_) => {
6563 self.emit(
6564 Opcode::DefineMethodComputed,
6565 &[Op::Int(class_method_flags(*kind))],
6566 );
6567 }
6568 PropName::Literal(literal) => {
6569 let text = self.property_key_text(literal, *span)?;
6570 self.emit(
6571 Opcode::DefineMethod,
6572 &[
6573 Op::Atom(Atom::from_wtf8(&text)),
6574 Op::Int(class_method_flags(*kind)),
6575 ],
6576 );
6577 }
6578 }
6579 if *is_static {
6580 self.emit(Opcode::Swap, &[]);
6581 }
6582 }
6583 ClassElement::Field {
6584 key: field_key,
6585 is_static,
6586 value,
6587 ..
6588 } => {
6589 // A private field's *symbol* is created here, at the member, and stored
6590 // in its binding: the field's property is keyed by it, so it has to exist
6591 // before any initialiser runs, and a fresh one per class body is what
6592 // makes two classes that both write `#x` independent.
6593 //
6594 // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6595 // whose `toString` has a side effect must not run again per instance.
6596 let key = match field_key {
6597 PropName::Private(ident) => {
6598 let binding = format!("#{}", ident.name);
6599 if *is_static {
6600 self.emit(Opcode::Swap, &[]);
6601 }
6602 self.emit(
6603 Opcode::PrivateSymbol,
6604 &[Op::Atom(Atom::from_text(&binding))],
6605 );
6606 self.emit_var(VarAction::PutInit, &binding);
6607 if *is_static {
6608 self.emit(Opcode::Swap, &[]);
6609 }
6610 FieldKey::Private(binding)
6611 }
6612 PropName::Computed(expression) => {
6613 let binding = plan
6614 .computed
6615 .get(&index)
6616 .cloned()
6617 .expect("every computed key got a binding");
6618 if *is_static {
6619 self.emit(Opcode::Swap, &[]);
6620 }
6621 self.expr(expression)?;
6622 self.emit(Opcode::ToPropkey, &[]);
6623 self.emit_var(VarAction::PutInit, &binding);
6624 if *is_static {
6625 self.emit(Opcode::Swap, &[]);
6626 }
6627 FieldKey::Computed(binding)
6628 }
6629 PropName::Literal(literal) => FieldKey::Literal(literal),
6630 };
6631 if *is_static {
6632 static_items.push(StaticInitItem::Field(key, value.as_deref()));
6633 } else {
6634 instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6635 }
6636 }
6637 ClassElement::StaticBlock {
6638 body, body_start, ..
6639 } => static_items.push(StaticInitItem::Block {
6640 body,
6641 body_start: *body_start,
6642 }),
6643 }
6644 }
6645
6646 // Now that every member has its slot, the constructor can have the next one and the
6647 // `fclosure` above can name it.
6648 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6649 match self.state().insns.get_mut(ctor_insn) {
6650 Some(Insn::Fixed { operands, .. }) => {
6651 operands[0] = Op::Const(ctor_index);
6652 }
6653 // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6654 // loudly beats emitting a `fclosure` of slot 4294967295.
6655 _ => {
6656 return Err(SyntaxError::new(
6657 "the class constructor's fclosure went missing",
6658 class.span,
6659 ));
6660 }
6661 }
6662
6663 // The instance brand: a symbol created once on the prototype, which every instance
6664 // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6665 // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6666 // copy is created. The prototype is on top of the stack at this point.
6667 if plan.instance_brand {
6668 self.emit(Opcode::Dup, &[]);
6669 self.emit(Opcode::Null, &[]);
6670 self.emit(Opcode::Swap, &[]);
6671 self.emit(Opcode::AddBrand, &[]);
6672 }
6673
6674 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6675 // class has no instance fields. The constructor calls it only when it is defined.
6676 //
6677 // A class with private *methods* but no fields still needs one, because adding the
6678 // brand to each new instance is the initialiser's job.
6679 if instance_fields.is_empty() && !plan.instance_brand {
6680 self.emit(Opcode::Undefined, &[]);
6681 } else {
6682 let initialiser = self.compile_field_initialiser(
6683 &instance_fields,
6684 class.span,
6685 true,
6686 plan.instance_brand,
6687 )?;
6688 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6689 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6690 // `set_home_object` reads `obj func`, so the prototype stays where it is.
6691 self.emit(Opcode::SetHomeObject, &[]);
6692 }
6693 self.emit_var(VarAction::PutInit, "<class_fields_init>");
6694 // The prototype has done its job: every instance member is defined on it. What
6695 // is left under it is the constructor.
6696 self.emit(Opcode::Drop, &[]);
6697
6698 // The static brand, for `static #m() {}`: same opcode, but the home object is the
6699 // constructor itself, so the symbol lands on the class and the class carries it.
6700 if plan.static_brand {
6701 self.emit(Opcode::Dup, &[]);
6702 self.emit(Opcode::Dup, &[]);
6703 self.emit(Opcode::AddBrand, &[]);
6704 }
6705
6706 // The class binding is initialised *before* static fields run, so a static field
6707 // can refer to the class by name (`static y = S.x`).
6708 // `set_loc` leaves the constructor on the stack, which is what the static field
6709 // call and the outer store both consume.
6710 //
6711 // Only when there *is* such a binding: an anonymous class expression declares no
6712 // class-scope name, and asking for one by the empty string resolved to nothing —
6713 // which made `var x = class {}` assign `undefined` and put a bogus global store in
6714 // the instruction stream.
6715 if let Some(name) = &name {
6716 self.emit_var(VarAction::SetInit, name);
6717 }
6718 if !static_items.is_empty() {
6719 // The static half has no brand prologue of its own: the constructor got its
6720 // brand above, before this runs.
6721 let initialiser =
6722 self.compile_field_initialiser(&static_items, class.span, false, false)?;
6723 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6724 self.emit(Opcode::Dup, &[]);
6725 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6726 self.emit(Opcode::SetHomeObject, &[]);
6727 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6728 self.emit(Opcode::Drop, &[]);
6729 }
6730 // The body is over, and with it this class's private names.
6731 let _ = self.private_scopes.pop();
6732 self.emit_scope_leave(key);
6733 self.state().current_block = parent_block;
6734 if keep {
6735 // A class *expression* is its own value; the class-scope binding was only
6736 // ever an alias for it.
6737 return Ok(());
6738 }
6739 // A declaration stores into the binding the enclosing statement declared.
6740 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6741 Ok(())
6742 }
6743
6744 fn push_this(&mut self) {
6745 self.emit(Opcode::PushThis, &[]);
6746 }
6747
6748 /// `this`, which an arrow does not have of its own.
6749 ///
6750 /// The reference gives the enclosing function a local named `this`, initialised from
6751 /// `push_this` at the top of its body, and the arrow then reads it as a captured
6752 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6753 /// the arrow is called with none.
6754 fn this_expression(&mut self) {
6755 // In a class constructor `this` is a local: a derived constructor only gets one
6756 // when `super()` returns, and reading the raw receiver would give the *outer*
6757 // one instead.
6758 if self.cur().ctor_kind != CtorKind::None {
6759 self.emit_var(VarAction::Get, "this");
6760 return;
6761 }
6762 if !self.cur().is_arrow {
6763 self.push_this();
6764 return;
6765 }
6766 // An arrow at the **top level** of a script or module has no enclosing function,
6767 // but it still inherits `this` — the script's or module's own. Falling through to
6768 // `emit_var(Get, "this")` without a target made that a *global* lookup, so
6769 // `var f = () => typeof this` at top level reported
6770 // `ReferenceError: 'this' is not defined` instead of `"object"`
6771 // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
6772 // is the test262 case that reaches it, through a native `forEach`).
6773 //
6774 // The script state is the bottom of the stack, so it is the fallback target. Its
6775 // own `provide_this_local` then prepends the `push_this` the arrow reads.
6776 let target = self.enclosing_function().unwrap_or(0);
6777 self.state_at(target).needs_this_local = true;
6778 self.declare_at(target, "this");
6779 self.emit_var(VarAction::Get, "this");
6780 }
6781
6782 /// `new.target`, which an arrow likewise does not own.
6783 fn new_target_expression(&mut self) {
6784 if !self.cur().is_arrow {
6785 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6786 return;
6787 }
6788 if let Some(target) = self.enclosing_function() {
6789 self.state_at(target).needs_new_target_local = true;
6790 self.declare_at(target, NEW_TARGET);
6791 }
6792 self.emit_var(VarAction::Get, NEW_TARGET);
6793 }
6794
6795 /// `this.active_func`: the function `super()` resolves against.
6796 ///
6797 /// In a constructor or a method that is the function being run, so the special object
6798 /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6799 /// a closure variable — see [`FnState::needs_active_func_local`].
6800 fn active_func_expression(&mut self) {
6801 if !self.cur().is_arrow {
6802 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6803 return;
6804 }
6805 if let Some(target) = self.enclosing_function() {
6806 self.state_at(target).needs_active_func_local = true;
6807 self.declare_at(target, ACTIVE_FUNC);
6808 }
6809 self.emit_var(VarAction::Get, ACTIVE_FUNC);
6810 }
6811
6812 /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6813 fn provide_active_func_local(&mut self) {
6814 let current = self.stack.len() - 1;
6815 if !self.stack[current].needs_active_func_local {
6816 return;
6817 }
6818 if !self.stack[current]
6819 .vars
6820 .iter()
6821 .any(|var| var.name == ACTIVE_FUNC)
6822 {
6823 self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6824 }
6825 self.prepend_initialiser(
6826 ACTIVE_FUNC,
6827 Insn::Fixed {
6828 op: Opcode::SpecialObject,
6829 operands: vec![Op::Int(2)],
6830 },
6831 );
6832 }
6833
6834 /// Give the function a local `new.target`, for an arrow inside it to capture.
6835 fn provide_new_target_local(&mut self) {
6836 let current = self.stack.len() - 1;
6837 if !self.stack[current].needs_new_target_local {
6838 return;
6839 }
6840 if !self.stack[current]
6841 .vars
6842 .iter()
6843 .any(|var| var.name == NEW_TARGET)
6844 {
6845 self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6846 }
6847 self.prepend_initialiser(
6848 NEW_TARGET,
6849 Insn::Fixed {
6850 op: Opcode::SpecialObject,
6851 operands: vec![Op::Int(3)],
6852 },
6853 );
6854 }
6855
6856 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6857 /// function.
6858 fn ensure_enclosing_arguments(&mut self) {
6859 // An arrow created in a parameter list needs the *parameter* scope's
6860 // `arguments`, not the body's: the two are separate bindings and the arrow was
6861 // born before the body existed.
6862 let from_params = self.cur().created_in_params;
6863 if let Some(target) = self.enclosing_function() {
6864 self.state_at(target).needs_arguments_local = true;
6865 if from_params {
6866 self.state_at(target).needs_param_arguments = true;
6867 // Declare it now, not at the enclosing function's `finish_current`: the
6868 // arrow resolves its own `arguments` before that runs, and a binding that
6869 // does not exist yet resolves as a global.
6870 declare_param_var_at(&mut self.stack[target], "arguments");
6871 }
6872 self.declare_at(target, "arguments");
6873 }
6874 }
6875
6876 /// The innermost enclosing frame that is a real function — an arrow inherits from it
6877 /// rather than starting a scope of its own.
6878 /// The innermost enclosing frame that can own a lexical binding an arrow reads —
6879 /// a real function, or a **script** top level.
6880 ///
6881 /// A script is in the list because an `eval` body is compiled as one and an arrow
6882 /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
6883 /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
6884 /// a *global* lookup of `new.target`, which no frame provides — so it raised
6885 /// `ReferenceError` instead of answering the caller's value
6886 /// (`arrow-body-direct-eval-err-contains-newtarget`).
6887 fn enclosing_function(&self) -> Option<usize> {
6888 (0..self.stack.len())
6889 .rev()
6890 .find(|index| !self.stack[*index].is_arrow)
6891 }
6892
6893 fn state_at(&mut self, index: usize) -> &mut FnState {
6894 &mut self.stack[index]
6895 }
6896
6897 /// Declare a `var` binding directly in a specific frame.
6898 fn declare_at(&mut self, index: usize, name: &str) {
6899 let state = &mut self.stack[index];
6900 if state.vars.iter().any(|var| var.name == name) {
6901 return;
6902 }
6903 state.var_block.push(FUNCTION_SCOPE);
6904 state.vars.push(VarDef::var(name));
6905 }
6906
6907 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6908 /// the reference calls a `special_object` gets initialised on entry.
6909 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6910 let current = self.stack.len() - 1;
6911 let init = [
6912 producer,
6913 Insn::Var {
6914 action: VarAction::Put,
6915 name: name.to_string(),
6916 block: 0,
6917 // A prologue initialiser runs before the body proper, but it is body
6918 // code: `this` and `arguments` are provided for it, not by it.
6919 in_params: false,
6920 },
6921 ];
6922 let inserted = init.len();
6923 for (index, instruction) in init.into_iter().enumerate() {
6924 self.stack[current].insns.insert(index, instruction);
6925 }
6926 for placed in self.stack[current].labels.iter_mut().flatten() {
6927 *placed += inserted;
6928 }
6929 self.stack[current].label_since_insn = true;
6930 }
6931
6932 fn push_constant(&mut self, constant: Constant) -> u32 {
6933 let state = self.state();
6934 let index = state.cpool.len() as u32;
6935 state.cpool.push(constant);
6936 index
6937 }
6938
6939 /// Compile `a && b`, `a || b`, `a ?? b`.
6940 ///
6941 /// A run of the *same* operator shares one end label, so `a || b || c` tests
6942 /// `a` once and jumps past everything when it is truthy, instead of falling
6943 /// into `b`'s test. The parser builds such a run left-associated —
6944 /// `((a || b) || c)` — so the operands are collected off the left spine.
6945 ///
6946 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6947 /// `||`'s label, because the inner chain really does end before `&&` begins.
6948 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6949 let mut operands = Vec::new();
6950 collect_same_operator(op, left, &mut operands);
6951 operands.push(right);
6952
6953 let end = self.new_label();
6954 // Every operand but the last decides whether the chain stops here.
6955 let last = operands.pop().expect("the right operand is always present");
6956 for operand in operands {
6957 self.expr(operand)?;
6958 self.emit(Opcode::Dup, &[]);
6959 match op {
6960 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6961 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6962 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6963 // `0 || b` is `b`. The dedicated test keeps the value unless it is
6964 // null-ish, so the jump is taken on `false`.
6965 LogicalOp::Coalesce => {
6966 self.emit(Opcode::IsUndefinedOrNull, &[]);
6967 self.emit_jump(Opcode::IfFalse, end, &[]);
6968 }
6969 }
6970 self.emit(Opcode::Drop, &[]);
6971 }
6972 self.expr(last)?;
6973 self.place_label(end);
6974 Ok(())
6975 }
6976
6977 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6978 match op {
6979 UnaryOp::Typeof => {
6980 // `typeof x` must not throw on an undeclared name.
6981 if let ExprKind::Ident(name) = &argument.kind {
6982 self.emit_var(VarAction::GetUndef, &name.name);
6983 } else {
6984 self.expr(argument)?;
6985 }
6986 self.emit(Opcode::Typeof, &[]);
6987 }
6988 UnaryOp::Delete => {
6989 // `delete obj.prop` really deletes, and answers whether it could.
6990 // Deleting a *binding* is always `false`: a local, an argument and a
6991 // declared global are all non-configurable, which the reference encodes
6992 // as a constant `push_false` rather than a runtime check. Only a
6993 // property access has anything to do at run time.
6994 // `delete super.x` is not a delete at all: the spec refuses it, and the
6995 // reference encodes the refusal as a `throw_error`. The receiver and the
6996 // key are still evaluated first, which is what keeps the evaluation order
6997 // of the operand intact.
6998 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6999 // nothing to delete, and a failed delete is not the same as a skipped
7000 // one. The reference emits the guards so they land on a `drop; push_true`
7001 // tail, which is what this reproduces.
7002 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
7003 && let ExprKind::Member {
7004 object, property, ..
7005 } = &inner.unparen().kind
7006 {
7007 let end = self.new_label();
7008 let done = self.new_label();
7009 self.chain_link(object, end)?;
7010 match property {
7011 MemberProp::Ident(name) => self.emit(
7012 Opcode::PushAtomValue,
7013 &[Op::Atom(Atom::from_text(&name.name))],
7014 ),
7015 MemberProp::Computed(index) => self.expr(index)?,
7016 MemberProp::Private(_) => {
7017 return Err(SyntaxError::new(
7018 "deleting a private field is not allowed",
7019 argument.span,
7020 ));
7021 }
7022 }
7023 self.emit(Opcode::Delete, &[]);
7024 self.emit_jump(Opcode::Goto, done, &[]);
7025 self.place_label(end);
7026 self.emit(Opcode::Drop, &[]);
7027 self.emit(Opcode::PushTrue, &[]);
7028 self.place_label(done);
7029 return Ok(());
7030 }
7031 if let ExprKind::Member { object, .. } = &argument.unparen().kind
7032 && matches!(object.unparen().kind, ExprKind::SuperProp)
7033 {
7034 self.super_base();
7035 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
7036 return Ok(());
7037 }
7038 // Parentheses are transparent to `delete`: `(x)` is still a Reference to
7039 // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
7040 // does, and `delete (a().b)` still evaluates `a()`. Matching on the
7041 // unparenthesised operand is what keeps both — matching on `argument.kind`
7042 // sent every parenthesised form to the "not a Reference" arm, which cost
7043 // `delete(__variable) === false` in test262's `S12.2_A2`.
7044 match &argument.unparen().kind {
7045 ExprKind::Member {
7046 object, property, ..
7047 } => {
7048 self.expr(object)?;
7049 match property {
7050 MemberProp::Ident(name) => {
7051 self.emit(
7052 Opcode::PushAtomValue,
7053 &[Op::Atom(Atom::from_text(&name.name))],
7054 );
7055 }
7056 MemberProp::Computed(index) => self.expr(index)?,
7057 MemberProp::Private(_) => {
7058 return Err(SyntaxError::new(
7059 "deleting a private field is not allowed",
7060 argument.span,
7061 ));
7062 }
7063 }
7064 self.emit(Opcode::Delete, &[]);
7065 }
7066 ExprKind::Ident(name) => {
7067 self.delete_ident(&name.name);
7068 }
7069 // §13.5.1.2 step 2: an operand that is **not** a Reference Record
7070 // answers `true` — there is nothing to delete, and "nothing needed
7071 // deleting" is success. `delete !0`, `delete (1 + 2)` and
7072 // `delete typeof 0` are all `true`, and the operand is still evaluated
7073 // (which is why it is `Drop`ed rather than skipped:
7074 // `delete f()` must call `f`).
7075 //
7076 // Answering `false` here is the C reference's old behaviour and was
7077 // wrong in an observable way: test262's
7078 // `dynamic-import/assignment-expression/logical-and-expr` builds a
7079 // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
7080 // half turned the whole `&&` into `false`, so the import asked for a
7081 // module named "false".
7082 _ => {
7083 self.expr(argument)?;
7084 self.emit(Opcode::Drop, &[]);
7085 self.emit(Opcode::PushTrue, &[]);
7086 }
7087 }
7088 }
7089 UnaryOp::Void => {
7090 self.expr(argument)?;
7091 self.emit(Opcode::Drop, &[]);
7092 self.emit(Opcode::Undefined, &[]);
7093 }
7094 UnaryOp::Minus => {
7095 self.expr(argument)?;
7096 self.emit(Opcode::Neg, &[]);
7097 }
7098 UnaryOp::Plus => {
7099 self.expr(argument)?;
7100 self.emit(Opcode::Plus, &[]);
7101 }
7102 UnaryOp::Not => {
7103 self.expr(argument)?;
7104 self.emit(Opcode::Lnot, &[]);
7105 }
7106 UnaryOp::BitNot => {
7107 self.expr(argument)?;
7108 self.emit(Opcode::Not, &[]);
7109 }
7110 }
7111 Ok(())
7112 }
7113
7114 /// A store to `name` while a `with` may capture it.
7115 ///
7116 /// The reference is resolved **first**, before the right-hand side runs. That order is
7117 /// the whole point: in `x = (delete env.x, 0)` the resolution has already decided that
7118 /// `x` is `env`'s property, so `PutValue` then finds it gone and strict code throws
7119 /// `ReferenceError` (`set-mutable-binding-binding-deleted-with-typed-array-in-
7120 /// proto-chain-strict-mode`). The ordinary path evaluates the right-hand side before
7121 /// the guard runs, which put the guard *after* the mutation.
7122 ///
7123 /// Shapes mirror [`Compiler::assign_ident_plain`] and the member arms of
7124 /// [`Compiler::assign`], with `dup; with_get_var` in place of `get_field2` and
7125 /// `with_put_var` in place of `put_field` — the same stack effects, but each half also
7126 /// asks the `HasProperty` that `GetBindingValue`/`SetMutableBinding` require.
7127 fn with_assign(
7128 &mut self,
7129 with_local: &str,
7130 name: &Ident,
7131 op: AssignOp,
7132 value: &Expr,
7133 keep: bool,
7134 ) -> Result<(), SyntaxError> {
7135 let atom = Atom::from_text(&name.name);
7136 self.state().cur_pos = Some(name.span.start);
7137 match op {
7138 AssignOp::Assign => {
7139 self.expr(value)?;
7140 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7141 if keep {
7142 self.emit(Opcode::Dup, &[]);
7143 }
7144 self.state().no_value = !keep;
7145 self.emit_var(VarAction::Get, with_local);
7146 self.emit(Opcode::Swap, &[]);
7147 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7148 }
7149 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7150 let (keep_label, end) = (self.new_label(), self.new_label());
7151 self.emit_var(VarAction::Get, with_local);
7152 self.emit(Opcode::Dup, &[]);
7153 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7154 // `obj value` — the object stays underneath for the store.
7155 self.emit(Opcode::Dup, &[]);
7156 self.emit_logical_test(op);
7157 self.emit_jump(logical_jump(op), keep_label, &[]);
7158 self.emit(Opcode::Drop, &[]);
7159 self.expr(value)?;
7160 self.emit(Opcode::Insert2, &[]);
7161 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7162 self.emit_jump(Opcode::Goto, end, &[]);
7163 self.place_label(keep_label);
7164 self.emit(Opcode::Nip, &[]);
7165 self.place_label(end);
7166 }
7167 _ => {
7168 self.emit_var(VarAction::Get, with_local);
7169 self.emit(Opcode::Dup, &[]);
7170 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7171 self.expr(value)?;
7172 self.state().cur_pos = Some(name.span.start);
7173 self.emit(compound_opcode(op), &[]);
7174 self.state().no_value = !keep;
7175 if keep {
7176 self.emit(Opcode::Insert2, &[]);
7177 }
7178 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7179 }
7180 }
7181 Ok(())
7182 }
7183
7184 /// `x++` / `++x` while a `with` may capture `x`, with one resolution for both halves.
7185 fn with_update(
7186 &mut self,
7187 with_local: &str,
7188 name: &Ident,
7189 op: UpdateOp,
7190 prefix: bool,
7191 ) -> Result<(), SyntaxError> {
7192 let instruction = match (op, prefix) {
7193 (UpdateOp::Increment, true) => Opcode::Inc,
7194 (UpdateOp::Increment, false) => Opcode::PostInc,
7195 (UpdateOp::Decrement, true) => Opcode::Dec,
7196 (UpdateOp::Decrement, false) => Opcode::PostDec,
7197 };
7198 let atom = Atom::from_text(&name.name);
7199 self.state().cur_pos = Some(name.span.start);
7200 self.emit_var(VarAction::Get, with_local);
7201 self.emit(Opcode::Dup, &[]);
7202 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7203 self.emit(instruction, &[]);
7204 self.emit(
7205 if prefix {
7206 Opcode::Insert2
7207 } else {
7208 Opcode::Perm3
7209 },
7210 &[],
7211 );
7212 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7213 Ok(())
7214 }
7215
7216 /// A store to a plain identifier, with no `with` in the way.
7217 fn assign_ident_plain(
7218 &mut self,
7219 op: AssignOp,
7220 name: &Ident,
7221 value: &Expr,
7222 discard: bool,
7223 ) -> Result<(), SyntaxError> {
7224 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7225 // about, so it is set only when this assignment *is* that expression.
7226 let keep = !discard;
7227 // A *simple* store is blamed on the identifier, not on the `=`: a
7228 // strict-mode `not_def = 1` raises when the name is written, which the
7229 // reference reports at the name's column. A compound store is blamed on
7230 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
7231 // which the reference reports at the `+=`), so only the simple case
7232 // moves the position.
7233 let saved = self.cur().cur_pos;
7234 let name_pos = Some(name.span.start);
7235 if matches!(op, AssignOp::Assign) {
7236 self.state().cur_pos = name_pos;
7237 }
7238 // A *compound* store reads the binding before it combines, and that read
7239 // is blamed on the identifier: `not_def += 2` fails while reading
7240 // `not_def`, so the position is the name's, not the `+=`'s. The
7241 // combination that follows is blamed on the operator, which is why
7242 // `cur_pos` is put back to the operator position before it is emitted.
7243 self.state().cur_pos = name_pos;
7244 match op {
7245 AssignOp::Assign => {
7246 self.expr(value)?;
7247 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7248 // A discarded store to a *slot* consumes its value, so no copy
7249 // is needed. A global store goes through `put_var`, which the
7250 // reference always pairs with a `dup` — matching it keeps the
7251 // bytecode identical. Getting this wrong is not only an extra
7252 // instruction: a stray copy gives the peephole a chance to fold
7253 // the store into an unrelated later read.
7254 let slot = self.is_slot(&name.name);
7255 if keep || !slot {
7256 self.emit(Opcode::Dup, &[]);
7257 }
7258 self.state().no_value = !keep && slot;
7259 self.emit_var(VarAction::Put, &name.name);
7260 }
7261 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7262 let end = self.new_label();
7263 self.emit_var(VarAction::Get, &name.name);
7264 self.state().cur_pos = saved;
7265 self.emit(Opcode::Dup, &[]);
7266 self.emit_logical_test(op);
7267 self.emit_jump(logical_jump(op), end, &[]);
7268 self.emit(Opcode::Drop, &[]);
7269 self.expr(value)?;
7270 self.emit(Opcode::Dup, &[]);
7271 self.emit_var(VarAction::Put, &name.name);
7272 self.place_label(end);
7273 }
7274 _ => {
7275 self.emit_var(VarAction::Get, &name.name);
7276 self.expr(value)?;
7277 self.state().cur_pos = saved;
7278 self.emit(compound_opcode(op), &[]);
7279 self.emit(Opcode::Dup, &[]);
7280 self.emit_var(VarAction::Put, &name.name);
7281 }
7282 }
7283 self.state().cur_pos = saved;
7284 Ok(())
7285 }
7286
7287 /// Compile an assignment.
7288 ///
7289 /// Three operator families, three shapes:
7290 ///
7291 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
7292 /// the value is kept, because `put_field`/`put_array_el` consume both the
7293 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
7294 /// the pair it wants and leaves a copy on top.
7295 /// * **compound** `+=` … — read the place, apply the operator, store. A member
7296 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
7297 /// index) underneath the value precisely so the store can follow.
7298 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
7299 /// right-hand side. The test *keeps* the current value and skips the store
7300 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
7301 /// `a` is already truthy.
7302 fn assign(
7303 &mut self,
7304 op: AssignOp,
7305 target: &Pattern,
7306 value: &Expr,
7307 discard: bool,
7308 ) -> Result<(), SyntaxError> {
7309 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7310 // about, so it is set only when this assignment *is* that expression.
7311 let keep = !discard;
7312 match &target.kind {
7313 PatternKind::Ident(name) => {
7314 // Any store to a name a `with` may capture resolves the reference first and
7315 // keeps that resolution for both halves — see [`Compiler::with_assign`].
7316 // Plain `=` needs it just as much as `+=`: `x = (delete env.x, 0)` must
7317 // resolve `x` before the right-hand side deletes it.
7318 let plain_name = name.name.clone();
7319 if !self.visible_with_names(&plain_name).is_empty() {
7320 return self.with_reference(
7321 &plain_name,
7322 &mut |compiler, with_local| {
7323 compiler.with_assign(with_local, name, op, value, !discard)
7324 },
7325 &mut |compiler| compiler.assign_ident_plain(op, name, value, discard),
7326 );
7327 }
7328 self.assign_ident_plain(op, name, value, discard)
7329 }
7330 PatternKind::Member(member) => {
7331 // `super.x = v` is not a store through a value: it starts at the home
7332 // object's prototype but writes to `this`, so it goes through
7333 // `put_super_value` rather than `put_field`. The receiver, prototype, key
7334 // and value are handed over together.
7335 if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
7336 return self.assign_super(member, op, value);
7337 }
7338 // A store is blamed on the selector punctuator (`.` or `[`), the same
7339 // token a load is blamed on — the reference records `put_field obj.a`
7340 // at the `.`, so a setter that throws reports that column and not the
7341 // `=` of the assignment it sits in. The inner expressions restore their
7342 // own positions, so the selector's sticks for the store instructions.
7343 let saved = self.cur().cur_pos;
7344 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7345 self.expr(&member.object)?;
7346 match &member.property {
7347 MemberProp::Ident(property) => {
7348 let atom = Atom::from_text(&property.name);
7349 match op {
7350 AssignOp::Assign => {
7351 self.expr(value)?;
7352 // `put_field` consumes the object and the value, so
7353 // without `insert2` nothing is left over for the
7354 // statement to drop.
7355 self.state().no_value = !keep;
7356 if keep {
7357 self.emit(Opcode::Insert2, &[]);
7358 }
7359 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7360 }
7361 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7362 // `get_field2` leaves the object under the value, so
7363 // the keep path has an object to dispose of. The store
7364 // path must jump *over* that cleanup: falling into it
7365 // would `nip` a stack that only holds the value.
7366 let (keep_label, end) = (self.new_label(), self.new_label());
7367 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7368 self.emit(Opcode::Dup, &[]);
7369 self.emit_logical_test(op);
7370 self.emit_jump(logical_jump(op), keep_label, &[]);
7371 self.emit(Opcode::Drop, &[]);
7372 self.expr(value)?;
7373 self.emit(Opcode::Insert2, &[]);
7374 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7375 self.emit_jump(Opcode::Goto, end, &[]);
7376 self.place_label(keep_label);
7377 self.emit(Opcode::Nip, &[]);
7378 self.place_label(end);
7379 }
7380 _ => {
7381 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7382 self.expr(value)?;
7383 self.emit(compound_opcode(op), &[]);
7384 self.state().no_value = !keep;
7385 if keep {
7386 self.emit(Opcode::Insert2, &[]);
7387 }
7388 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7389 }
7390 }
7391 }
7392 MemberProp::Computed(index) => {
7393 self.expr(index)?;
7394 match op {
7395 AssignOp::Assign => {
7396 self.expr(value)?;
7397 self.state().no_value = !keep;
7398 if keep {
7399 self.emit(Opcode::Insert3, &[]);
7400 }
7401 self.emit(Opcode::PutArrayEl, &[]);
7402 }
7403 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7404 let (keep_label, end) = (self.new_label(), self.new_label());
7405 self.emit(Opcode::GetArrayEl3, &[]);
7406 self.emit(Opcode::Dup, &[]);
7407 self.emit_logical_test(op);
7408 self.emit_jump(logical_jump(op), keep_label, &[]);
7409 self.emit(Opcode::Drop, &[]);
7410 self.expr(value)?;
7411 self.emit(Opcode::Insert3, &[]);
7412 self.emit(Opcode::PutArrayEl, &[]);
7413 self.emit_jump(Opcode::Goto, end, &[]);
7414 self.place_label(keep_label);
7415 // Both the object and the index are left over.
7416 self.emit(Opcode::Nip, &[]);
7417 self.emit(Opcode::Nip, &[]);
7418 self.place_label(end);
7419 }
7420 _ => {
7421 self.emit(Opcode::GetArrayEl3, &[]);
7422 self.expr(value)?;
7423 self.emit(compound_opcode(op), &[]);
7424 self.state().no_value = !keep;
7425 if keep {
7426 self.emit(Opcode::Insert3, &[]);
7427 }
7428 self.emit(Opcode::PutArrayEl, &[]);
7429 }
7430 }
7431 }
7432 MemberProp::Private(name) => {
7433 // `obj value` is on the stack, and every private store wants exactly
7434 // that. A top-level private name cannot be assigned (the parser rejects
7435 // `#x = 1`), so the only way here is `this.#x = …` inside the class.
7436 //
7437 // The reference emits `insert2` whether or not the value is wanted,
7438 // so this does too: the copy left behind is the assignment expression's
7439 // value, and a discarded one is simply never read.
7440 let binding = format!("#{}", name.name);
7441 let (kind, setter) = self.private_use(&binding, member.span)?;
7442 match op {
7443 AssignOp::Assign => {
7444 self.expr(value)?;
7445 if keep {
7446 self.emit(Opcode::Insert2, &[]);
7447 }
7448 self.private_store(&binding, kind, setter.as_deref())?;
7449 self.state().no_value = !keep;
7450 }
7451 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7452 let (keep_label, end) = (self.new_label(), self.new_label());
7453 self.emit(Opcode::Dup, &[]);
7454 self.private_load(&binding, kind, member.span)?;
7455 self.emit(Opcode::Dup, &[]);
7456 self.emit_logical_test(op);
7457 self.emit_jump(logical_jump(op), keep_label, &[]);
7458 self.emit(Opcode::Drop, &[]);
7459 self.expr(value)?;
7460 self.emit(Opcode::Insert2, &[]);
7461 self.private_store(&binding, kind, setter.as_deref())?;
7462 self.emit_jump(Opcode::Goto, end, &[]);
7463 self.place_label(keep_label);
7464 self.emit(Opcode::Nip, &[]);
7465 self.place_label(end);
7466 }
7467 _ => {
7468 self.emit(Opcode::Dup, &[]);
7469 self.private_load(&binding, kind, member.span)?;
7470 self.expr(value)?;
7471 self.emit(compound_opcode(op), &[]);
7472 self.emit(Opcode::Insert2, &[]);
7473 self.private_store(&binding, kind, setter.as_deref())?;
7474 }
7475 }
7476 }
7477 }
7478 self.state().cur_pos = saved;
7479 Ok(())
7480 }
7481 // A destructuring assignment: the right-hand side is the expression's own
7482 // value, so it is evaluated once and kept under the pattern's stores.
7483 PatternKind::Array { .. } | PatternKind::Object { .. } => {
7484 self.expr(value)?;
7485 if keep {
7486 self.emit(Opcode::Dup, &[]);
7487 }
7488 self.destructure(target, None)?;
7489 self.state().no_value = !keep;
7490 Ok(())
7491 }
7492 _ => Err(SyntaxError::new(
7493 "this assignment target is not supported by the compiler yet",
7494 target.span,
7495 )),
7496 }
7497 }
7498
7499 /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
7500 ///
7501 /// The stack has to carry four values — receiver, prototype, key, value — because
7502 /// `put_super_value` takes them together; the receiver is what makes a setter found on
7503 /// the prototype run with `this`, and the key has to survive until the store, which is
7504 /// why a compound form converts it to a property key once and `dup3`s rather than
7505 /// evaluating it twice.
7506 fn assign_super(
7507 &mut self,
7508 member: &MemberPattern,
7509 op: AssignOp,
7510 value: &Expr,
7511 ) -> Result<(), SyntaxError> {
7512 let saved = self.cur().cur_pos;
7513 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7514 self.super_base();
7515 match &member.property {
7516 MemberProp::Ident(property) => self.emit(
7517 Opcode::PushAtomValue,
7518 &[Op::Atom(Atom::from_text(&property.name))],
7519 ),
7520 MemberProp::Computed(index) => self.expr(index)?,
7521 MemberProp::Private(_) => {
7522 return Err(SyntaxError::new(
7523 "private fields are not supported by the compiler yet",
7524 member.span,
7525 ));
7526 }
7527 }
7528 match op {
7529 AssignOp::Assign => {
7530 // The key is only converted once, by `put_super_value` itself, so a
7531 // computed key's `toString` runs exactly once.
7532 self.expr(value)?;
7533 self.emit(Opcode::Insert4, &[]);
7534 self.emit(Opcode::PutSuperValue, &[]);
7535 }
7536 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7537 let (keep_label, end) = (self.new_label(), self.new_label());
7538 self.emit(Opcode::ToPropkey, &[]);
7539 self.emit(Opcode::Dup3, &[]);
7540 self.emit(Opcode::GetSuperValue, &[]);
7541 self.emit(Opcode::Dup, &[]);
7542 self.emit_logical_test(op);
7543 self.emit_jump(logical_jump(op), keep_label, &[]);
7544 self.emit(Opcode::Drop, &[]);
7545 self.expr(value)?;
7546 self.emit(Opcode::Insert4, &[]);
7547 self.emit(Opcode::PutSuperValue, &[]);
7548 self.emit_jump(Opcode::Goto, end, &[]);
7549 self.place_label(keep_label);
7550 // The prototype and the key are still under the value that was read.
7551 self.emit(Opcode::Nip, &[]);
7552 self.emit(Opcode::Nip, &[]);
7553 self.emit(Opcode::Nip, &[]);
7554 self.place_label(end);
7555 }
7556 _ => {
7557 self.emit(Opcode::ToPropkey, &[]);
7558 self.emit(Opcode::Dup3, &[]);
7559 self.emit(Opcode::GetSuperValue, &[]);
7560 self.expr(value)?;
7561 self.emit(compound_opcode(op), &[]);
7562 self.emit(Opcode::Insert4, &[]);
7563 self.emit(Opcode::PutSuperValue, &[]);
7564 }
7565 }
7566 // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7567 // is still on the stack when the store finishes, and the expression statement is
7568 // what disposes of it — the same arrangement as `put_field`, reached from the other
7569 // side: there the store consumes the value (`no_value`), here it leaves it
7570 // (`keep` already false, so nothing tells the statement otherwise).
7571 self.state().cur_pos = saved;
7572 Ok(())
7573 }
7574
7575 /// The test a logical assignment applies to the current value.
7576 ///
7577 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7578 /// assign, while `0 ||= b` must not.
7579 fn emit_logical_test(&mut self, op: AssignOp) {
7580 if op == AssignOp::Coalesce {
7581 self.emit(Opcode::IsUndefinedOrNull, &[]);
7582 }
7583 }
7584
7585 /// The private name `#name` this use site resolves against.
7586 ///
7587 /// The parser has already rejected a name no enclosing class declares, so a miss here
7588 /// means the compiler lost track of a class scope — which is worth a real error rather
7589 /// than an `unwrap`.
7590 fn private_use(
7591 &self,
7592 binding: &str,
7593 span: Span,
7594 ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7595 ClassPlan::find(self, binding)
7596 .map(|use_| (use_.kind, use_.setter.clone()))
7597 .ok_or_else(|| {
7598 SyntaxError::new(
7599 format!("the private name '{binding}' is out of scope here"),
7600 span,
7601 )
7602 })
7603 }
7604
7605 /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7606 ///
7607 /// The three readable kinds take three different instructions, because a private name
7608 /// holds three different things — a symbol, a method function, a getter function — and
7609 /// only the first one is a property read at all.
7610 fn private_load(
7611 &mut self,
7612 binding: &str,
7613 kind: PrivateKind,
7614 span: Span,
7615 ) -> Result<(), SyntaxError> {
7616 match kind {
7617 PrivateKind::Field => {
7618 self.emit_var(VarAction::Get, binding);
7619 self.emit(Opcode::GetPrivateField, &[]);
7620 }
7621 PrivateKind::Method => {
7622 self.emit_var(VarAction::Get, binding);
7623 self.emit(Opcode::CheckBrand, &[]);
7624 // `check_brand` reads `obj func` and leaves both; the method itself is what
7625 // `this.#m` evaluates to.
7626 self.emit(Opcode::Nip, &[]);
7627 }
7628 PrivateKind::Getter => {
7629 self.emit_var(VarAction::Get, binding);
7630 self.emit(Opcode::CheckBrand, &[]);
7631 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7632 }
7633 // `#a` is declared but never filled when only a setter exists, so reading it is
7634 // the same refusal as assigning to a `const`. The reference reports it with the
7635 // generic read-only wording and leaves the better message as a `XXX`.
7636 PrivateKind::Setter => self.emit(
7637 Opcode::ThrowError,
7638 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7639 ),
7640 }
7641 let _ = span;
7642 Ok(())
7643 }
7644
7645 /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
7646 fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
7647 match kind {
7648 // A method *is* the callee, so only the check goes in between.
7649 PrivateKind::Method => {
7650 self.emit_var(VarAction::Get, binding);
7651 self.emit(Opcode::CheckBrand, &[]);
7652 }
7653 _ => self.private_load(binding, kind, Span::default())?,
7654 }
7655 Ok(())
7656 }
7657
7658 /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
7659 /// wanted back.
7660 ///
7661 /// A getter/setter pair is a *method call*, not a property store: the reference reads
7662 /// the setter out of its own binding and calls it with the receiver, which is why the
7663 /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
7664 /// keeps the assignment's value for an expression context.
7665 fn private_store(
7666 &mut self,
7667 binding: &str,
7668 kind: PrivateKind,
7669 setter: Option<&str>,
7670 ) -> Result<(), SyntaxError> {
7671 match kind {
7672 PrivateKind::Field => {
7673 self.emit_var(VarAction::Get, binding);
7674 self.emit(Opcode::PutPrivateField, &[]);
7675 }
7676 PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
7677 Some(setter) => {
7678 self.emit_var(VarAction::Get, setter);
7679 // `obj func value` -> `value obj func` for the check, and back again for
7680 // the call, which wants `obj func arg`.
7681 self.emit(Opcode::Swap, &[]);
7682 self.emit(Opcode::Rot3r, &[]);
7683 self.emit(Opcode::CheckBrand, &[]);
7684 self.emit(Opcode::Rot3l, &[]);
7685 self.emit(Opcode::CallMethod, &[Op::Int(1)]);
7686 // The setter's return value is discarded; the assignment's own value is
7687 // whatever the caller left underneath.
7688 self.emit(Opcode::Drop, &[]);
7689 }
7690 None => self.emit(
7691 Opcode::ThrowError,
7692 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7693 ),
7694 },
7695 }
7696 Ok(())
7697 }
7698
7699 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
7700 // `x++` inside a `with` is a read-modify-write of a *property*, so the object is
7701 // resolved once for both halves. See [`Compiler::with_reference`].
7702 let unparened = argument.unparen();
7703 if let ExprKind::Ident(ident) = &unparened.kind {
7704 let name = ident.name.clone();
7705 if !self.visible_with_names(&name).is_empty() {
7706 return self.with_reference(
7707 &name,
7708 &mut |compiler, with_local| compiler.with_update(with_local, ident, op, prefix),
7709 &mut |compiler| compiler.update_plain(op, unparened, prefix),
7710 );
7711 }
7712 }
7713 self.update_plain(op, argument, prefix)
7714 }
7715
7716 fn update_plain(
7717 &mut self,
7718 op: UpdateOp,
7719 argument: &Expr,
7720 prefix: bool,
7721 ) -> Result<(), SyntaxError> {
7722 let instruction = match (op, prefix) {
7723 (UpdateOp::Increment, true) => Opcode::Inc,
7724 (UpdateOp::Increment, false) => Opcode::PostInc,
7725 (UpdateOp::Decrement, true) => Opcode::Dec,
7726 (UpdateOp::Decrement, false) => Opcode::PostDec,
7727 };
7728 // `(y)++` and `((o.x))++` are the same updates as the unparenthesised forms: §13.4
7729 // evaluates the operand as a `LeftHandSideExpression` and the parentheses around a
7730 // reference change nothing — they do not copy the value. Reading `argument.kind`
7731 // directly therefore rejected every parenthesised target with "increment of a
7732 // non-variable", which is not a thing the language has (`target-cover-id`).
7733 let argument = argument.unparen();
7734 if let ExprKind::Member {
7735 object,
7736 property,
7737 optional: _,
7738 } = &argument.kind
7739 {
7740 // `o.x++` needs the receiver twice, so the last link is read with the
7741 // `get_*2`/`get_*3` form that keeps it, and the update is written back
7742 // with `put_field`/`put_array_el`. The reordering in between is what puts
7743 // the old value below the receiver for a postfix update and the new one
7744 // above it for a prefix one:
7745 //
7746 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
7747 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
7748 //
7749 // This mirrors the reference instruction for instruction.
7750 self.expr(object)?;
7751 match property {
7752 MemberProp::Ident(name) => {
7753 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
7754 self.emit(instruction, &[]);
7755 self.emit(
7756 if prefix {
7757 Opcode::Insert2
7758 } else {
7759 Opcode::Perm3
7760 },
7761 &[],
7762 );
7763 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
7764 }
7765 MemberProp::Computed(index) => {
7766 self.expr(index)?;
7767 self.emit(Opcode::GetArrayEl3, &[]);
7768 self.emit(instruction, &[]);
7769 self.emit(
7770 if prefix {
7771 Opcode::Insert3
7772 } else {
7773 Opcode::Perm4
7774 },
7775 &[],
7776 );
7777 self.emit(Opcode::PutArrayEl, &[]);
7778 }
7779 MemberProp::Private(name) => {
7780 // The receiver is duplicated and the read keeps it, exactly as `get_field2`
7781 // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
7782 // `perm3` -> `old obj new` -> store.
7783 let binding = format!("#{}", name.name);
7784 let (kind, setter) = self.private_use(&binding, argument.span)?;
7785 self.emit(Opcode::Dup, &[]);
7786 self.private_load(&binding, kind, argument.span)?;
7787 self.emit(instruction, &[]);
7788 self.emit(
7789 if prefix {
7790 Opcode::Insert2
7791 } else {
7792 Opcode::Perm3
7793 },
7794 &[],
7795 );
7796 self.private_store(&binding, kind, setter.as_deref())?;
7797 }
7798 }
7799 return Ok(());
7800 }
7801 let ExprKind::Ident(name) = &argument.kind else {
7802 return Err(SyntaxError::new(
7803 "increment of a non-variable is not supported by the compiler yet",
7804 argument.span,
7805 ));
7806 };
7807 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
7808 // reference's `inc_loc` folds those three into one, but it does so only in some
7809 // positions (a `for` update and not a bare statement, and never for a lexical
7810 // binding), so emitting it unconditionally would move *away* from its output.
7811 // The instruction is equivalent either way; matching the reference matters more
7812 // than saving two instructions.
7813 let _ = !std::mem::take(&mut self.state().discard_value);
7814 self.emit_var(VarAction::Get, &name.name);
7815 self.emit(instruction, &[]);
7816 if prefix {
7817 self.emit(Opcode::Dup, &[]);
7818 }
7819 self.emit_var(VarAction::Put, &name.name);
7820 Ok(())
7821 }
7822
7823 /// Compile an array literal.
7824 ///
7825 /// The reference splits this into three phases, and the split is load-bearing
7826 /// rather than an optimisation detail:
7827 ///
7828 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
7829 /// the array in one instruction.
7830 /// 2. **Everything up to the first spread** is appended with explicit indices
7831 /// (`define_field <index>`), because a hole has no element to pass to
7832 /// `array_from`. A hole here is what makes `length` need fixing up: an
7833 /// explicit index does not extend the array the way a pushed element does.
7834 /// 3. **From the first spread on** the index lives on the stack, so `append` and
7835 /// `define_array_el` can consume it and `inc` advances it.
7836 ///
7837 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
7838 /// forces phase 2, and `[...a]` forces phase 3.
7839 fn array_literal(
7840 &mut self,
7841 elements: &[Option<ArrayElement>],
7842 span: Span,
7843 ) -> Result<(), SyntaxError> {
7844 let _ = span;
7845 let mut index: u32 = 0;
7846 let mut cursor = 0usize;
7847
7848 // Phase 1: a leading run of plain elements, at most 32 of them.
7849 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
7850 if index >= 32 {
7851 break;
7852 }
7853 self.expr(element)?;
7854 index += 1;
7855 cursor += 1;
7856 }
7857 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
7858
7859 // Phase 2: explicit indices, up to the first spread.
7860 let mut need_length = false;
7861 while let Some(element) = elements.get(cursor) {
7862 if matches!(element, Some(ArrayElement::Spread(_))) {
7863 break;
7864 }
7865 need_length = true;
7866 if let Some(ArrayElement::Expr(expression)) = element {
7867 self.expr(expression)?;
7868 self.emit_define_index(index);
7869 need_length = false;
7870 }
7871 index += 1;
7872 cursor += 1;
7873 }
7874
7875 if cursor >= elements.len() {
7876 if need_length {
7877 // `define_field` cannot set `length`, which is not configurable.
7878 self.emit(Opcode::Dup, &[]);
7879 self.push_number(index as f64);
7880 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7881 }
7882 return Ok(());
7883 }
7884
7885 // Phase 3: the index moves onto the stack for the spreading tail.
7886 //
7887 // `need_length` deliberately carries over from phase 2: a hole before the
7888 // first spread still has to be reflected in `length`, and only the final
7889 // check can do it because the array is not finished until the tail is
7890 // appended.
7891 self.push_number(index as f64);
7892 while let Some(element) = elements.get(cursor) {
7893 match element {
7894 Some(ArrayElement::Spread(expression)) => {
7895 // `append` copies an iterable and leaves the next index behind,
7896 // so no `inc` is needed here.
7897 self.expr(spread_argument(expression))?;
7898 self.emit(Opcode::Append, &[]);
7899 }
7900 None | Some(ArrayElement::Expr(_)) => {
7901 need_length = true;
7902 if let Some(ArrayElement::Expr(expression)) = element {
7903 self.expr(expression)?;
7904 self.emit(Opcode::DefineArrayEl, &[]);
7905 need_length = false;
7906 }
7907 self.emit(Opcode::Inc, &[]);
7908 }
7909 }
7910 cursor += 1;
7911 }
7912 if need_length {
7913 self.emit(Opcode::Dup1, &[]);
7914 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7915 } else {
7916 self.emit(Opcode::Drop, &[]);
7917 }
7918 Ok(())
7919 }
7920
7921 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
7922 fn emit_define_index(&mut self, index: u32) {
7923 self.emit(
7924 Opcode::DefineField,
7925 &[Op::Atom(Atom::from_text(&index.to_string()))],
7926 );
7927 }
7928
7929 // -- functions ---------------------------------------------------------
7930
7931 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
7932 self.compile_function_with_name(func, false)
7933 }
7934
7935 /// Compile a function, recording whether it is a *named function expression*.
7936 ///
7937 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
7938 /// must not leak outside. The reference does that by declaring `g` as a local of
7939 /// the function itself and initialising it with `special_object 2` (the current
7940 /// function), which is why this has to be known at compile time.
7941 fn compile_function_with_name(
7942 &mut self,
7943 func: &ast::Function,
7944 is_expression: bool,
7945 ) -> Result<CompiledFunction, SyntaxError> {
7946 let kind = match (func.is_generator, func.is_async) {
7947 (false, false) => FunctionKind::Normal,
7948 (true, false) => FunctionKind::Generator,
7949 (false, true) => FunctionKind::Async,
7950 (true, true) => FunctionKind::AsyncGenerator,
7951 };
7952 let mut state = FnState::new(
7953 func.name
7954 .as_ref()
7955 .map(|n| n.name.clone())
7956 .unwrap_or_default(),
7957 kind,
7958 );
7959 // The function's own mode, recorded by the parser. Inheriting the enclosing
7960 // function's instead let a nested `"use strict"` directive be ignored, so the
7961 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
7962 state.strict = func.strict;
7963 // A function defined inside a `with` block keeps seeing that object: the guard
7964 // chain names the enclosing `<with>` locals, which resolve outward into closure
7965 // variables exactly like any other captured binding.
7966 state.inherited_with_names = self.cur().with_names.len();
7967 state.with_names = self.cur().with_names.clone();
7968 state.is_arrow = func.is_arrow;
7969 state.created_in_block = self.cur().current_block;
7970 // A default anywhere in the parameter list is what gives the function two
7971 // variable environments. The reference decides this the same way: it scans the
7972 // parenthesis for a top-level `=`, so a destructured name without a default
7973 // stays a plain function-scope binding.
7974 state.in_params = false;
7975 // The reference scans the parenthesis for *any* `=`, including one nested inside
7976 // a pattern, so `function f({a = 1})` has parameter expressions even though the
7977 // parameter itself carries no initialiser.
7978 state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7979 // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
7980 // flag above this looks at the *shape* of each parameter, not just for `=`.
7981 state.simple_parameter_list = func
7982 .params
7983 .iter()
7984 .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
7985 // A function born inside a parameter list inherits the prohibition: it must not
7986 // see the body bindings of the function it was created in.
7987 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
7988 // A class constructor knows what it is only because the class told it.
7989 if let Some(kind) = self.cur().class_ctor_pending {
7990 state.ctor_kind = kind;
7991 }
7992 // A named *expression* binds its own name; a declaration's name is already
7993 // bound in the enclosing scope.
7994 state.self_name = if is_expression && !func.is_arrow {
7995 func.name.as_ref().map(|n| n.name.clone())
7996 } else {
7997 None
7998 };
7999 // Keep the written range so `Function.prototype.toString` can answer with the
8000 // original text rather than `[native code]`.
8001 //
8002 // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
8003 // accessor and generator prefixes, and for a method it must not include the name
8004 // or a leading `static`. `params_span` is exactly that boundary.
8005 // A *method* keeps the old `[native code]` answer: its reported text is defined
8006 // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
8007 // the comments in between kept verbatim), and reconstructing that from a byte
8008 // span got it wrong in more cases than it got right. A plain function and an
8009 // arrow are the shapes libraries actually introspect, and those are exact.
8010 // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
8011 // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
8012 // so the same slice works for every form. (`Params_span` is the boundary that
8013 // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
8014 // `source_span` is set only where the reported text is not the function's own
8015 // range — a class's constructor reports the whole class definition.
8016 let reported = func.source_span.unwrap_or(func.span);
8017 state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
8018 state.line = func.span.start.line;
8019 state.column = func.span.start.column;
8020 // A function body has no hidden `<ret>` local; the value comes back on
8021 // the stack. Only a script keeps one.
8022 // Parameters are positional, so even a pattern occupies one argument slot. A
8023 // simple name is that slot itself; anything else (a pattern, a default, a rest
8024 // parameter) takes an anonymous slot and is unpicked into locals at the top of
8025 // the body, which is the only way one argument can bind several names.
8026 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
8027 // `.length` stops at the first parameter that can be substituted: a default
8028 // fills a missing argument in, and a rest parameter absorbs the rest.
8029 let mut defined_args = func.params.len() as u32;
8030 for (index, param) in func.params.iter().enumerate() {
8031 match simple_parameter(param) {
8032 Some(name) => state.args.push(VarDef::var(name.name.clone())),
8033 None => {
8034 state.args.push(VarDef::var(ANONYMOUS_BINDING));
8035 prologue.push((index, param.clone()));
8036 }
8037 }
8038 }
8039 // A default anywhere before the end also ends the count, which the loop above
8040 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
8041 for (position, param) in func.params.iter().enumerate() {
8042 if matches!(
8043 param.kind,
8044 PatternKind::Assign { .. } | PatternKind::Rest(_)
8045 ) {
8046 defined_args = position as u32;
8047 break;
8048 }
8049 }
8050 state.defined_args = defined_args;
8051 state.param_prologue = prologue;
8052 let depth = self.stack.len();
8053 self.stack.push(state);
8054 let result = self.compile_function_body(func);
8055 if result.is_err() {
8056 // A failed compile must not leave its `FnState` behind. Every caller
8057 // reads `self.state()` as "the function being compiled", so a leftover
8058 // frame silently retargets all later bookkeeping at a dead function.
8059 self.stack.truncate(depth);
8060 }
8061 result
8062 }
8063
8064 /// The body of a function, with its frame already pushed.
8065 fn compile_function_body(
8066 &mut self,
8067 func: &ast::Function,
8068 ) -> Result<CompiledFunction, SyntaxError> {
8069 let body_key = func.params_span.end.offset as u64;
8070 // Where the body begins, in source order. The runtime needs this to tell a
8071 // closure created by a default expression from one the body creates — the two see
8072 // different variable environments — and a bytecode offset would not survive the
8073 // instruction shuffling that building the frame does. Positions are in source
8074 // order, so a comparison answers it.
8075 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
8076 self.push_block(body_key, NO_PARENT);
8077 self.state().body_block = body_key;
8078 // An arrow with an expression body has no statements; the expression is
8079 // its `return`. Building the statement here keeps one code path below, and
8080 // matters for correctness beyond convenience: returning early with the new
8081 // `FnState` still on the stack would leave the compiler looking at the
8082 // wrong function, which surfaces as an unrelated underflow later.
8083 let concise = match &func.body {
8084 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
8085 StmtKind::Return(Some(Box::new((**value).clone()))),
8086 value.span,
8087 )),
8088 js_parse::ast::FunctionBody::Block(_) => None,
8089 };
8090 let body: &[Stmt] = match &concise {
8091 Some(stmt) => std::slice::from_ref(stmt),
8092 None => func
8093 .body
8094 .statements()
8095 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
8096 };
8097 let prologue = std::mem::take(&mut self.state().param_prologue);
8098 let has_param_scope = self.cur().has_parameter_expressions;
8099 // The parameter scope's own bindings, declared in source order.
8100 //
8101 // With parameter expressions the list gets a variable environment of its own, and
8102 // every name it binds is a `let` there. That is what puts the *list* in the
8103 // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
8104 // and `function f(x = y, y){}` does the same, where a single shared environment
8105 // would answer `undefined` to both.
8106 if has_param_scope {
8107 let mut declared: Vec<String> = Vec::new();
8108 for param in &func.params {
8109 let mut names = Vec::new();
8110 param.bound_names(&mut names);
8111 for name in names {
8112 if declared.contains(&name.name) {
8113 continue;
8114 }
8115 declared.push(name.name.clone());
8116 self.declare_param_binding(&name.name);
8117 }
8118 }
8119 }
8120 // A pattern parameter binds its names as function-scope locals, so they have to
8121 // exist — and be unpicked from the argument — before the body runs. With a
8122 // parameter scope these are the *second* environment: the pattern fills the
8123 // parameter's copy, and the body's binding is filled from it afterwards.
8124 for (_, pattern) in &prologue {
8125 let mut names = Vec::new();
8126 pattern.bound_names(&mut names);
8127 for name in names {
8128 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
8129 }
8130 }
8131 self.hoist(body, body_key)?;
8132 // A constructor's prologue is not a parameter unpacking but the `this` binding:
8133 // a base constructor takes the receiver, a derived one starts in the dead zone
8134 // because only `super()` may produce it.
8135 match self.cur().ctor_kind {
8136 CtorKind::None => {}
8137 CtorKind::Base => {
8138 self.begin_this_local();
8139 self.emit(Opcode::CheckCtor, &[]);
8140 // Instance fields are installed at the top of a base constructor's body,
8141 // before any statement — `class C { x = 1; constructor() { this.x } }` sees
8142 // `1`. This used to be emitted at the *tail*, which made every field read
8143 // `undefined` inside the constructor that declared it.
8144 self.call_field_initialiser();
8145 }
8146 CtorKind::Derived => {
8147 self.declare("this", VarDef::lexical("this"));
8148 let slot = self.cur().vars.len() as u32 - 1;
8149 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8150 self.emit(Opcode::CheckCtor, &[]);
8151 }
8152 }
8153 // Entering the parameter list: everything it binds starts in the dead zone.
8154 // The order is the reference's — it walks the scope chain, which is prepended, so
8155 // the bindings come out newest first.
8156 for name in self.param_binding_names().into_iter().rev() {
8157 if let Some(slot) = self.param_binding_slot(&name) {
8158 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8159 }
8160 }
8161 // The whole parameter list is one scope, and nothing in the body exists yet, so
8162 // every name it mentions resolves against the parameter bindings and outward.
8163 self.state().in_params = has_param_scope;
8164 for (index, param) in func.params.iter().enumerate() {
8165 if let Some(pattern) = prologue_pattern(&prologue, index) {
8166 // A destructuring parameter *initialises* its bindings: with a parameter
8167 // scope they are the list's own `let`s, which is why the stores skip the
8168 // dead-zone check, and why the reference reads their properties with
8169 // `get_field2` — a `let` needs no reference.
8170 let kind = if has_param_scope {
8171 VarDeclKind::Let
8172 } else {
8173 VarDeclKind::Var
8174 };
8175 match &pattern.kind {
8176 // `...rest` collects what is left rather than reading one slot.
8177 PatternKind::Rest(inner) => {
8178 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8179 self.destructure(inner, Some(kind))?;
8180 }
8181 _ => {
8182 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8183 self.destructure(pattern, Some(kind))?;
8184 }
8185 }
8186 continue;
8187 }
8188 // A plain name binds straight from its argument slot. With a parameter scope
8189 // the slot is also copied into the parameter binding, which is what a later
8190 // default (or a closure made among the defaults) reads.
8191 let Some(name) = simple_parameter(param) else {
8192 continue;
8193 };
8194 let target = self.param_binding_slot(&name.name);
8195 if matches!(param.kind, PatternKind::Rest(_)) {
8196 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8197 if let Some(slot) = target {
8198 self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
8199 }
8200 // `put_arg` rather than `set_arg`: the array is the last thing on the
8201 // stack and nothing keeps it. Named by hand because a name in the
8202 // parameter list resolves to the parameter binding, and this store has to
8203 // reach the *argument* — that is what the body reads.
8204 self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
8205 continue;
8206 }
8207 if let PatternKind::Assign { default, .. } = ¶m.kind {
8208 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8209 let has_value = self.new_label();
8210 self.emit(Opcode::Dup, &[]);
8211 self.emit(Opcode::IsUndefined, &[]);
8212 self.emit_jump(Opcode::IfFalse, has_value, &[]);
8213 self.emit(Opcode::Drop, &[]);
8214 self.expr(default)?;
8215 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
8216 // The argument slot keeps the substituted value, because the *body* reads
8217 // the slot rather than the parameter binding — so this store is named
8218 // explicitly, like the rest parameter's.
8219 self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8220 self.place_label(has_value);
8221 if let Some(slot) = target {
8222 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8223 }
8224 continue;
8225 }
8226 if let Some(slot) = target {
8227 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8228 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8229 }
8230 }
8231 // Copy the parameter scope into the body. A plain parameter needs nothing: the
8232 // body reads its argument slot, and the list kept the two in step. A name a
8233 // pattern bound has no argument slot of its own, so the body gets a `var` filled
8234 // from the parameter's copy — and *that* is why an assignment inside a default
8235 // does not reach the body.
8236 if has_param_scope {
8237 for (_, pattern) in &prologue {
8238 let mut names = Vec::new();
8239 pattern.bound_names(&mut names);
8240 for name in names {
8241 let Some(slot) = self.param_binding_slot(&name.name) else {
8242 continue;
8243 };
8244 let Some(body) = self.body_var_slot(&name.name) else {
8245 continue;
8246 };
8247 self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
8248 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
8249 }
8250 }
8251 }
8252 // The parameter list is over; from here on a direct `eval` belongs to the body.
8253 self.state().in_params = false;
8254 // Entering the body's own scope comes *after* the parameter list: the body's
8255 // `let`s are not in existence while the defaults run, and the reference emits
8256 // their `set_loc_uninitialized` only once the parameters are bound.
8257 self.emit_scope_enter(body_key);
8258 // A generator starts suspended: `initial_yield` parks the body so that creating one
8259 // runs no body code until the first `next()`.
8260 //
8261 // It comes *after* the parameter unpacking, not before, because a parameter
8262 // initialiser is not body code — `function* g(a = sideEffect())` must run
8263 // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
8264 // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
8265 // until the first `next()` and 29 test262 cases that check for a synchronous throw
8266 // saw none at all.
8267 //
8268 // An async function does **not** get one. Its body runs synchronously up to the
8269 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
8270 // before its caller's next statement — so an `initial_yield` here would park the
8271 // body before it started, which is not fixable at run time: the suspension looks
8272 // exactly like a real `await`.
8273 if self.cur().kind.is_generator() {
8274 self.emit(Opcode::InitialYield, &[]);
8275 }
8276 // Through `stmts`: the body is a block, and a `using` declaration in it is a
8277 // disposal region.
8278 self.stmts(body)?;
8279 // The implicit return only exists if control can actually get here: an
8280 // infinite loop never falls off the end.
8281 if self.end_is_reachable() {
8282 if self.cur().is_suspending() {
8283 // Falling off the end finishes the generator with `undefined`, and the
8284 // value is what tells the resume machinery "completed" rather than
8285 // "suspended".
8286 self.emit(Opcode::Undefined, &[]);
8287 self.emit(Opcode::ReturnAsync, &[]);
8288 } else {
8289 self.emit_class_constructor_tail();
8290 }
8291 }
8292 // Resolution runs while this function is still on the stack: capturing a
8293 // variable from an enclosing function means reaching into that
8294 // function's state, which requires the whole chain to be present.
8295 Ok(self.finish_current())
8296 }
8297
8298 /// Put every binding of a function that contains a direct `eval` into a cell.
8299 ///
8300 /// A direct eval can name any binding in scope, and any closure it creates has to
8301 /// keep sharing that binding after the function returns — `for (let i …)
8302 /// eval("push(() => i)")` collects one closure per iteration and each must read its
8303 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
8304 /// a cell. Doing this unconditionally for such functions is the cheap, honest
8305 /// answer: the alternative is knowing at compile time which names a string will
8306 /// mention.
8307 fn capture_everything_for_eval(&mut self) {
8308 let current = self.stack.len() - 1;
8309 if !self.stack[current].has_direct_eval {
8310 return;
8311 }
8312 for arg in &mut self.stack[current].args {
8313 arg.is_captured = true;
8314 }
8315 for var in &mut self.stack[current].vars {
8316 var.is_captured = true;
8317 }
8318 }
8319
8320 /// Whether the current position in the instruction stream can be reached.
8321 ///
8322 /// A walk over the control-flow graph, using labels as instruction indices.
8323 /// The reference does the same thing to decide whether an implicit
8324 /// `return_undef` is needed.
8325 fn end_is_reachable(&self) -> bool {
8326 let state = self.cur();
8327 reachable_instructions(state, state.insns.len())[state.insns.len()]
8328 }
8329
8330 /// Resolve and assemble the function on top of the compiler stack, then pop
8331 /// it.
8332 fn finish_current(&mut self) -> CompiledFunction {
8333 self.provide_param_arguments();
8334 self.provide_arguments();
8335 self.provide_this_local();
8336 self.provide_new_target_local();
8337 self.provide_home_object_local();
8338 self.provide_active_func_local();
8339 self.provide_self_name();
8340 self.materialize_eval_sites();
8341 self.capture_everything_for_eval();
8342 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
8343 // Captured bindings need a reference cell; the count goes in the header so
8344 // the runtime knows how many cells to allocate on entry.
8345 let current = self.stack.len() - 1;
8346 let captured = self.stack[current]
8347 .args
8348 .iter()
8349 .filter(|a| a.is_captured)
8350 .count()
8351 + self.stack[current]
8352 .vars
8353 .iter()
8354 .filter(|v| v.is_captured)
8355 .count();
8356 self.stack[current].var_ref_count = captured as u32;
8357 // The scope chain is only final now that every binding is known.
8358 rebuild_scope_chain(&mut self.stack[current]);
8359 let (code, stack_size, positions) =
8360 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
8361 let _ = &mut resolved;
8362 let mut state = self.stack.pop().expect("a function is being compiled");
8363 CompiledFunction {
8364 name: state.name,
8365 kind: state.kind,
8366 strict: state.strict,
8367 is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
8368 is_arrow: state.is_arrow,
8369 has_parameter_expressions: state.has_parameter_expressions,
8370 simple_parameter_list: state.simple_parameter_list,
8371 body_start: state.body_start,
8372 args: state.args,
8373 defined_args: state.defined_args,
8374 vars: state.vars,
8375 closure_vars: state.closure_vars,
8376 cpool: state.cpool,
8377 atoms: state.atoms,
8378 code,
8379 stack_size,
8380 var_ref_count: state.var_ref_count,
8381 positions,
8382 source: self.function_source(state.span, state.line, state.column),
8383 line: state.line,
8384 column: state.column,
8385 filename: None,
8386 eval_sites: state.eval_sites,
8387 module: state.module.take().map(Box::new),
8388 }
8389 }
8390}
8391
8392/// Assign each binding a scope level and rebuild the scope chains.
8393///
8394/// Levels are numbered in the order the blocks appear, with 0 reserved for the
8395/// function scope where `var` and hoisted functions live. Every binding outside
8396/// level 0 gets a `scope_next` link to the next binding visible from the same
8397/// point, so walking a block's chain enumerates exactly the bindings live there.
8398///
8399/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
8400/// point at `b`, which is declared later in the source but earlier in the chain.
8401fn rebuild_scope_chain(state: &mut FnState) {
8402 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
8403 // real block that happens to start at offset zero keeps its own level instead of
8404 // being merged into the function scope.
8405 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
8406 for block in &state.blocks {
8407 if !levels.contains(&block.key) {
8408 levels.push(block.key);
8409 }
8410 }
8411 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
8412 let parent_level = |level: usize| -> usize {
8413 if level == 0 {
8414 return 0;
8415 }
8416 let key = levels[level];
8417 let parent = state
8418 .blocks
8419 .iter()
8420 .find(|b| b.key == key)
8421 .map(|b| b.parent)
8422 .unwrap_or(FUNCTION_SCOPE);
8423 level_of(parent)
8424 };
8425
8426 // Own bindings per level, in declaration order.
8427 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
8428 let keys: Vec<u64> = (0..state.vars.len())
8429 .map(|index| {
8430 state
8431 .var_block
8432 .get(index)
8433 .copied()
8434 .unwrap_or(FUNCTION_SCOPE)
8435 })
8436 .collect();
8437 for (index, key) in keys.into_iter().enumerate() {
8438 // The parameter scope is not a block: it is a level of its own with no parent,
8439 // assigned below. Letting it land in level 0 would chain the body's bindings onto
8440 // it, which the reference does not do — the two environments are siblings.
8441 if key == PARAM_SCOPE {
8442 continue;
8443 }
8444 let level = level_of(key);
8445 state.vars[index].scope_level = level as u32;
8446 // A `catch` parameter is part of the runtime scope chain even though it is
8447 // not lexical: the handler's own bindings chain on to it, which is why the
8448 // reference prints `let y [next:1]` with `e` at 1.
8449 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
8450 {
8451 own[level].push(index);
8452 }
8453 }
8454
8455 // A scope's chain is its own bindings in reverse declaration order followed
8456 // by the enclosing scope's chain.
8457 let mut head = vec![-1i32; levels.len()];
8458 for level in 0..levels.len() {
8459 let inherited = if level == 0 {
8460 -1
8461 } else {
8462 head[parent_level(level)]
8463 };
8464 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
8465 head[level] = chain.first().map_or(inherited, |first| *first as i32);
8466 for (position, &index) in chain.iter().enumerate() {
8467 let next = chain
8468 .get(position + 1)
8469 .map_or(inherited, |next| *next as i32);
8470 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
8471 }
8472 }
8473 state.block_heads = head;
8474
8475 // The parameter list is a scope of its own, and it has no parent: the reference pops
8476 // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
8477 // the `-1` a block uses. A level past every real block keeps it out of the walk above
8478 // — nothing but the dump reads it — and the links run newest-to-oldest through the
8479 // bindings themselves, which is the order `set_loc_uninitialized` walks.
8480 let param_level = levels.len() as u32;
8481 let mut previous: Option<usize> = None;
8482 for index in 0..state.vars.len() {
8483 if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
8484 {
8485 continue;
8486 }
8487 state.vars[index].scope_level = param_level;
8488 state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
8489 previous = Some(index);
8490 }
8491}
8492
8493/// This is where names become slots and where the temporal dead zone shows up in
8494/// the instruction stream: a read of a `let`/`const` binding compiles to
8495/// `get_loc_check`, which throws if the binding is still uninitialised.
8496///
8497/// The peephole pass from the reference implementation is applied at the end,
8498/// for the same reason it is applied to resolved bytecode there: the patterns are
8499/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
8500/// resolution. Deleted instructions stay in the list as `None` so that label
8501/// indices remain valid; [`Assembler`] maps them to byte offsets.
8502/// A resolved instruction and the source position it came from.
8503type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
8504
8505/// A resolved instruction paired with its position, which is what `assemble` consumes.
8506type PositionedInsn = (Opcode, Vec<Op>);
8507
8508fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
8509 let current = stack.len() - 1;
8510 // Dead-code elimination, on the symbolic form where labels are still
8511 // instruction indices. A `break` inside a loop leaves the trailing `goto`
8512 // unreachable, and a `return` leaves everything after it unreachable; the
8513 // reference drops both. Doing it here means the emitter never has to think
8514 // about reachability.
8515 strip_empty_gosubs(stack, current);
8516 eliminate_dead_code(stack, current);
8517 let insns = std::mem::take(&mut stack[current].insns);
8518 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
8519 // `insns`, and every arm below pushes exactly one instruction, so the positions
8520 // stay aligned with `out`.
8521 let positions = std::mem::take(&mut stack[current].insn_pos);
8522 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
8523 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8524 for (index, insn) in insns.iter().enumerate() {
8525 let pos = positions.get(index).copied().flatten();
8526 out_pos.push(pos);
8527 match insn {
8528 Insn::Fixed { op, operands } => {
8529 let operands = operands
8530 .iter()
8531 .map(|operand| match operand {
8532 Op::Atom(atom) => {
8533 Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
8534 }
8535 other => other.clone(),
8536 })
8537 .collect();
8538 out.push(Some((*op, operands)));
8539 }
8540 Insn::Var {
8541 action,
8542 name,
8543 block,
8544 in_params,
8545 } => {
8546 // Both reads and writes in the parameter list address the parameter
8547 // scope. That is what puts the list in the temporal dead zone — a read of
8548 // a later parameter is `get_loc_check` on an uninitialised slot — and it
8549 // is also what keeps an assignment made inside a default away from the
8550 // body, which sees a separate environment.
8551 let slot = resolve_slot(stack, current, name, *block, *in_params);
8552 // A store to the name of a named function expression is special: the
8553 // reference drops it in sloppy mode and throws in strict mode, because
8554 // the binding is immutable but only *checked* when the body is strict.
8555 // The same rule applies when the name is reached through a closure:
8556 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8557 // the store in the arrow too, not just in the function that owns the
8558 // binding. Reaching the owner means walking the chain of closure
8559 // entries, which is what `self_name_binding` does.
8560 let self_name = matches!(action, VarAction::Put | VarAction::Set)
8561 .then(|| {
8562 // A local of this function is the common case and needs no
8563 // chain walk; only an access that resolves elsewhere can be
8564 // pointing at an enclosing function's name binding.
8565 if let Slot::Loc(index) = slot {
8566 stack[current]
8567 .vars
8568 .get(index as usize)
8569 .filter(|var| var.kind == VarKind::FunctionName)
8570 .map(|var| var.is_const)
8571 } else {
8572 self_name_binding(stack, current, name, *block)
8573 }
8574 })
8575 .flatten();
8576 if let Some(is_const) = self_name {
8577 out.push(Some(if is_const {
8578 (
8579 Opcode::ThrowError,
8580 vec![
8581 Op::AtomId(intern_atom(&mut stack[current], name)),
8582 Op::Int(0),
8583 ],
8584 )
8585 } else {
8586 (Opcode::Drop, Vec::new())
8587 }));
8588 continue;
8589 }
8590 out.push(Some(variable_instruction(stack, current, *action, slot)));
8591 }
8592 Insn::CloseCaptured { name, block } => {
8593 // The block matters: a loop variable is scoped to the `for` head's own
8594 // block, so resolving it against block 0 would miss it entirely and
8595 // silently emit nothing.
8596 let slot = resolve_slot(stack, current, name, *block, false);
8597 // Only a local with a reference cell has anything to close. A global
8598 // or a never-captured local resolves to no instruction at all, which
8599 // keeps the bytecode identical to the reference's.
8600 if let Slot::Loc(index) = slot
8601 && stack[current]
8602 .vars
8603 .get(index as usize)
8604 .is_some_and(|v| v.is_captured)
8605 {
8606 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
8607 } else {
8608 out.push(None);
8609 }
8610 }
8611 Insn::DeleteVar { name } => {
8612 // A binding — a local, an argument, or a declared global — cannot be
8613 // deleted, and the reference encodes that as a constant `push_false`.
8614 // Only an implicit global needs the runtime lookup.
8615 if matches!(
8616 resolve_slot(stack, current, name, 0, false),
8617 Slot::Global(_)
8618 ) {
8619 let atom = intern_atom(&mut stack[current], name);
8620 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
8621 } else {
8622 out.push(Some((Opcode::PushFalse, Vec::new())));
8623 }
8624 }
8625 Insn::Dead => out.push(None),
8626 }
8627 }
8628 // Which label (if any) sits on each instruction, so the jump patterns can
8629 // tell whether they would cross a jump target.
8630 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
8631 for (id, placed) in stack[current].labels.iter().enumerate() {
8632 if let Some(index) = *placed
8633 && index < label_at.len()
8634 && label_at[index].is_none()
8635 {
8636 label_at[index] = Some(id as u32);
8637 }
8638 }
8639 if std::env::var_os("QJS_DEBUG").is_some() {
8640 eprintln!("--- peephole entry ---");
8641 for (i, e) in out.iter().enumerate() {
8642 eprintln!("{i}: {e:?}");
8643 }
8644 eprintln!("label_at: {label_at:?}");
8645 }
8646 peephole(&mut out, &label_at, &stack[current].labels);
8647 (out, out_pos)
8648}
8649
8650/// Find where `name` lives, capturing it in an enclosing function when needed.
8651///
8652/// The search runs outward through the enclosing functions' states, which are
8653/// still on the compiler stack while a nested function is resolved. Finding the
8654/// name in an enclosing function is what creates a closure reference, and every
8655/// function in between has to forward it — a function can only reach its own
8656/// parent's frame.
8657///
8658/// A name declared nowhere is a global. The reference does *not* look it up by
8659/// name from the inner function: the top-level function gets one `[global]`
8660/// entry and every nested function gets a `[global_ref<n>]` pointing at its
8661/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
8662/// rather than `[global]`.
8663/// The lexical blocks enclosing `block`, innermost first.
8664fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
8665 let mut chain = Vec::new();
8666 let mut current = Some(block);
8667 while let Some(key) = current {
8668 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
8669 // explicitly (rather than on "no block with this key") is what keeps a block
8670 // that happens to sit at offset zero from being mistaken for the terminator.
8671 if key == NO_PARENT || chain.contains(&key) {
8672 break;
8673 }
8674 chain.push(key);
8675 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
8676 }
8677 chain
8678}
8679
8680/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
8681///
8682/// The binding may be several functions away: an arrow nested in `function myfunc`
8683/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
8684/// means following `Ref` entries down and then reading the owning function's var table.
8685fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
8686 let state = stack.get(current)?;
8687 // A parameter shadows everything and is never a function-expression name.
8688 if state.args.iter().any(|arg| arg.name == name) {
8689 return None;
8690 }
8691 // A local of this very function: the answer is in its var table.
8692 if let Some(index) = local_slot_index(state, name, block) {
8693 let var = state.vars.get(index)?;
8694 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8695 }
8696 // Otherwise the name lives further out, and the closure entry says how to get
8697 // there. `Local` names the owner's slot directly; `Ref` names the next level's
8698 // closure entry, so the walk continues downwards.
8699 let mut level = current;
8700 let mut index = state
8701 .closure_vars
8702 .iter()
8703 .position(|closure| closure.name == name)?;
8704 loop {
8705 let state = stack.get(level)?;
8706 let closure = state.closure_vars.get(index)?;
8707 match closure.closure_type {
8708 ClosureType::Local => {
8709 let owner = stack.get(level.checked_sub(1)?)?;
8710 let var = owner.vars.get(closure.var_idx as usize)?;
8711 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8712 }
8713 ClosureType::Arg => return None,
8714 ClosureType::Ref => {
8715 level -= 1;
8716 index = closure.var_idx as usize;
8717 }
8718 // A global is never a function-expression name.
8719 ClosureType::Global
8720 | ClosureType::GlobalDecl
8721 | ClosureType::GlobalRef
8722 | ClosureType::ModuleDecl
8723 | ClosureType::ModuleImport => return None,
8724 }
8725 }
8726}
8727
8728/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
8729fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
8730 block_chain(state, block).into_iter().find_map(|scope| {
8731 state.vars.iter().enumerate().find_map(|(index, var)| {
8732 (var.name == name && state.var_block.get(index).copied() == Some(scope))
8733 .then_some(index)
8734 })
8735 })
8736}
8737
8738/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
8739fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
8740 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
8741 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
8742 }) {
8743 return index as u32;
8744 }
8745 state.var_block.push(PARAM_SCOPE);
8746 state.vars.push(VarDef::var(name));
8747 state.vars.len() as u32 - 1
8748}
8749
8750/// The name a parameter binds straight from its argument slot, if it has one.
8751///
8752/// A plain name does — with or without a default, and with or without `...`. Everything
8753/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
8754/// reference names the argument in the first case and leaves it `<null>` in the second,
8755/// so both the dump and the closures that capture the argument depend on this.
8756fn simple_parameter(param: &Pattern) -> Option<&Ident> {
8757 match ¶m.kind {
8758 PatternKind::Ident(name) => Some(name),
8759 PatternKind::Assign { target, .. } => match &target.kind {
8760 PatternKind::Ident(name) => Some(name),
8761 _ => None,
8762 },
8763 PatternKind::Rest(inner) => match &inner.kind {
8764 PatternKind::Ident(name) => Some(name),
8765 _ => None,
8766 },
8767 _ => None,
8768 }
8769}
8770
8771/// The pattern a parameter list has to unpick, if `index` is one of them.
8772fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
8773 prologue
8774 .iter()
8775 .find(|(at, _)| *at == index)
8776 .map(|(_, pattern)| pattern)
8777}
8778
8779fn pattern_has_default(pattern: &Pattern) -> bool {
8780 match &pattern.kind {
8781 PatternKind::Assign { .. } => true,
8782 PatternKind::Rest(inner) => pattern_has_default(inner),
8783 PatternKind::Array { elements, rest } => {
8784 elements.iter().flatten().any(element_has_default)
8785 || rest.as_deref().is_some_and(rest_has_default)
8786 }
8787 PatternKind::Object { properties, rest } => {
8788 properties.iter().flatten().any(element_has_default)
8789 || rest.as_deref().is_some_and(rest_has_default)
8790 }
8791 _ => false,
8792 }
8793}
8794
8795fn element_has_default(element: &PatternElement) -> bool {
8796 match element {
8797 PatternElement::Pattern(pattern) => pattern_has_default(pattern),
8798 PatternElement::Property { value, .. } => pattern_has_default(value),
8799 }
8800}
8801
8802fn rest_has_default(rest: &RestElement) -> bool {
8803 match rest {
8804 RestElement::Pattern(pattern) => pattern_has_default(pattern),
8805 RestElement::Member(_) => false,
8806 }
8807}
8808
8809/// Whether a function-scope binding is visible to the parameter list.
8810///
8811/// The parameter list runs before the body, so the body's `var`s and function
8812/// declarations do not exist yet — a name that only the body declares has to resolve
8813/// outward instead. What *does* exist by then is the compiler's own prologue: the
8814/// self-name of a named function expression (bound by `special_object 2` before anything
8815/// else), `this` and `new.target`. Those stay visible, which is what makes
8816/// `function f(a = this)` and `var f = function f(a = f)` work.
8817///
8818/// `arguments` is handled separately, as a binding of the parameter scope itself: with
8819/// parameter expressions the reference creates two of them, and the one the parameter
8820/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
8821fn visible_in_params(var: &VarDef) -> bool {
8822 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
8823}
8824
8825fn resolve_slot(
8826 stack: &mut [FnState],
8827 current: usize,
8828 name: &str,
8829 block: u64,
8830 in_params: bool,
8831) -> Slot {
8832 // The parameter list's own bindings. They are consulted first because they shadow
8833 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
8834 // `a` in the parameter scope, so a closure made there reads the parameter even after
8835 // the body assigns to its own `a`.
8836 if in_params
8837 && let Some(index) = stack[current]
8838 .vars
8839 .iter()
8840 .enumerate()
8841 .position(|(index, var)| {
8842 var.name == name
8843 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
8844 })
8845 {
8846 return Slot::Loc(index as u32);
8847 }
8848 // A name can be bound more than once: two `catch` parameters in nested
8849 // handlers are two slots. The binding that wins is the one whose scope encloses
8850 // the access, and among those the innermost — so the blocks are walked outward
8851 // and the first binding found on the way is the one that counts. A binding in
8852 // no block (`var`) is reachable from anywhere, which is why the function scope
8853 // is the end of the walk.
8854 //
8855 // The block walk comes *before* the argument slots, because a block may shadow a
8856 // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
8857 // slot is only the answer once nothing nearer claims the name.
8858 let chain = block_chain(&stack[current], block);
8859 for scope in &chain {
8860 let found = stack[current]
8861 .vars
8862 .iter()
8863 .enumerate()
8864 .find(|(index, var)| {
8865 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
8866 })
8867 .map(|(index, _)| index);
8868 if let Some(index) = found {
8869 return Slot::Loc(index as u32);
8870 }
8871 }
8872 // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
8873 // its own slot, and `var` of the same name in the body is the same binding.
8874 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
8875 return Slot::Arg(index as u32);
8876 }
8877 // Function-scope bindings — `var` and function declarations — are recorded with
8878 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
8879 // them. They are reachable from anywhere in the function, which is exactly what
8880 // the sentinel means.
8881 //
8882 // This pass is *only* for those. A lexical binding has to be found through the
8883 // chain or not at all, and looking a name up without its block is precisely how
8884 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
8885 // block leaked out of it.
8886 let function_scoped = stack[current]
8887 .vars
8888 .iter()
8889 .enumerate()
8890 .find(|(index, var)| {
8891 var.name == name
8892 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
8893 && (!in_params || visible_in_params(var))
8894 })
8895 .map(|(index, _)| index);
8896 if let Some(index) = function_scoped {
8897 return Slot::Loc(index as u32);
8898 }
8899 if let Some(index) = stack[current]
8900 .closure_vars
8901 .iter()
8902 .position(|c| c.name == name)
8903 {
8904 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
8905 }
8906
8907 for owner in (0..current).rev() {
8908 // The nested function was created inside one of this frame's blocks, and the
8909 // outermost visible binding is the innermost block on that chain — not whatever
8910 // comes first in the variable table. `function f(){ class S{} }` has two `S`
8911 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
8912 // the class body is the one a method may see.
8913 let entry = stack
8914 .get(owner + 1)
8915 .map(|s| s.created_in_block)
8916 .unwrap_or(0);
8917 let lexical = block_chain(&stack[owner], entry)
8918 .into_iter()
8919 .find_map(|scope| {
8920 stack[owner]
8921 .vars
8922 .iter()
8923 .enumerate()
8924 .find(|(index, var)| {
8925 var.name == name
8926 && stack[owner].var_block.get(*index).copied() == Some(scope)
8927 })
8928 .map(|(index, _)| index)
8929 });
8930 // A function born in a parameter list sees that list's bindings, not the body's:
8931 // the parameter scope is the environment it was created in.
8932 let in_param_scope = stack
8933 .get(owner + 1)
8934 .is_some_and(|child| child.created_in_params)
8935 .then(|| {
8936 stack[owner]
8937 .vars
8938 .iter()
8939 .enumerate()
8940 .position(|(index, var)| {
8941 var.name == name
8942 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
8943 })
8944 })
8945 .flatten();
8946 let found = if let Some(index) = in_param_scope {
8947 let var = &stack[owner].vars[index];
8948 Some(Found::Local(
8949 ClosureType::Local,
8950 index as u32,
8951 var.is_const,
8952 var.needs_check(),
8953 ))
8954 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
8955 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
8956 } else if let Some(index) = lexical {
8957 let var = &stack[owner].vars[index];
8958 Some(Found::Local(
8959 ClosureType::Local,
8960 index as u32,
8961 var.is_const,
8962 var.needs_check(),
8963 ))
8964 } else if let Some(index) = stack[owner]
8965 .vars
8966 .iter()
8967 .enumerate()
8968 .find_map(|(index, var)| {
8969 // A function created inside a parameter list must not see the body of the
8970 // function it was born in; see [`FnState::created_in_params`].
8971 let hidden = stack
8972 .get(owner + 1)
8973 .is_some_and(|child| child.created_in_params);
8974 (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
8975 })
8976 {
8977 let var = &stack[owner].vars[index];
8978 Some(Found::Local(
8979 ClosureType::Local,
8980 index as u32,
8981 var.is_const,
8982 var.needs_check(),
8983 ))
8984 } else if stack[owner].self_name.as_deref() == Some(name) {
8985 // A named function expression's own name. The reference declares it here,
8986 // on the first lookup that fails, rather than up front — and that is what
8987 // makes it reachable from a *nested* function: the nested lookup is what
8988 // walks out and creates the binding. A direct reference in the body is
8989 // caught the same way, which is why `provide_self_name` only has to add
8990 // the prologue.
8991 let strict = stack[owner].strict;
8992 stack[owner].var_block.push(FUNCTION_SCOPE);
8993 stack[owner].vars.push(VarDef {
8994 kind: VarKind::FunctionName,
8995 // In strict mode the name is immutable, so a store raises; sloppy
8996 // mode drops the store instead (see `variable_instruction`).
8997 is_const: strict,
8998 ..VarDef::var(name)
8999 });
9000 let index = stack[owner].vars.len() as u32 - 1;
9001 Some(Found::Local(ClosureType::Local, index, strict, false))
9002 } else if let Some(index) = stack[owner]
9003 .closure_vars
9004 .iter()
9005 .position(|c| c.name == name)
9006 {
9007 let closure = &stack[owner].closure_vars[index];
9008 Some(match closure.closure_type {
9009 // `GlobalRef` belongs here too: it is a *global* reached through this
9010 // frame's reference table, so treating it as a `Ref` to a local cell makes
9011 // the reader look for a cell no frame ever fills. That is how a second
9012 // function using `eval` in its parameter list read `undefined` after a
9013 // sibling had already made `eval` a closure entry.
9014 ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
9015 Found::Global(index as u32)
9016 }
9017 // A module variable is a cell in the *module's* environment, which is
9018 // the module body's parent as far as a nested function is concerned — so
9019 // it is captured as a plain reference, not looked up as a global.
9020 ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
9021 ClosureType::Ref,
9022 index as u32,
9023 closure.is_const,
9024 closure.is_lexical,
9025 ),
9026 _ => Found::Local(
9027 ClosureType::Ref,
9028 index as u32,
9029 closure.is_const,
9030 closure.is_lexical,
9031 ),
9032 })
9033 } else {
9034 None
9035 };
9036 let Some(found) = found else { continue };
9037
9038 let (is_const, is_lexical) = match found {
9039 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
9040 Found::Global(_) => (false, false),
9041 };
9042 // Mark the owner's binding as captured so it moves into a reference cell.
9043 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
9044 let slot = match found {
9045 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
9046 _ => &mut stack[owner].vars[index as usize],
9047 };
9048 slot.is_captured = true;
9049 }
9050 // Forward the reference through every function in between.
9051 let mut previous = match found {
9052 Found::Local(kind, index, _, _) => (kind, index),
9053 Found::Global(index) => (ClosureType::Global, index),
9054 };
9055 for level in owner + 1..=current {
9056 let kind = match (previous.0, level) {
9057 // A global stays a global at *every* level. Without `GlobalRef` in
9058 // this arm the second nested function over the same global got a
9059 // `Ref` to a cell no frame ever held, so the innermost closure read
9060 // `undefined` — which is how a two-deep getter lost its outer
9061 // variable.
9062 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
9063 ClosureType::GlobalRef
9064 }
9065 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
9066 _ => ClosureType::Ref,
9067 };
9068 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
9069 previous = (kind, index);
9070 }
9071 let index = previous.1;
9072 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
9073 }
9074
9075 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
9076 // creating a property. The top-level function holds the entry.
9077 let mut previous = (
9078 ClosureType::Global,
9079 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
9080 );
9081 for level in 1..=current {
9082 let index = ensure_closure(
9083 stack,
9084 level,
9085 name,
9086 false,
9087 false,
9088 ClosureType::GlobalRef,
9089 previous.1,
9090 );
9091 previous = (ClosureType::GlobalRef, index);
9092 }
9093 Slot::Global(previous.1)
9094}
9095
9096/// What an outward search turned up.
9097#[derive(Debug, Clone, Copy)]
9098enum Found {
9099 /// A binding in an enclosing function, reachable through a closure of this
9100 /// type, with its const/lexical flags.
9101 Local(ClosureType, u32, bool, bool),
9102 /// A global, reached through the enclosing function's closure entry.
9103 Global(u32),
9104}
9105
9106/// Add a closure entry to `level` if it is not there yet.
9107fn ensure_closure(
9108 stack: &mut [FnState],
9109 level: usize,
9110 name: &str,
9111 is_const: bool,
9112 is_lexical: bool,
9113 closure_type: ClosureType,
9114 var_idx: u32,
9115) -> u32 {
9116 if let Some(index) = stack[level]
9117 .closure_vars
9118 .iter()
9119 .position(|c| c.name == name)
9120 {
9121 return index as u32;
9122 }
9123 stack[level].closure_vars.push(ClosureVar {
9124 name: name.to_string(),
9125 is_const,
9126 is_lexical,
9127 closure_type,
9128 var_idx: var_idx as u16,
9129 });
9130 stack[level].closure_vars.len() as u32 - 1
9131}
9132
9133fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
9134 match closure.closure_type {
9135 // A `global_ref` only says *how* the binding is found (through the
9136 // parent's closure table); the access itself is an ordinary global one.
9137 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
9138 ClosureType::GlobalDecl => Slot::GlobalDecl(index),
9139 // A module variable is a real cell in the module's environment, so it is reached
9140 // exactly like a captured local — the host, not the global object, is what fills
9141 // the slot.
9142 ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
9143 _ => Slot::VarRef(index),
9144 }
9145}
9146
9147/// Pick the opcode for one variable access.
9148///
9149/// The `_check` variants are what enforce the temporal dead zone. They are used
9150/// for every access to a `let`/`const` binding except its own initialisation —
9151/// which is exactly the operation that takes the binding out of the dead zone.
9152fn variable_instruction(
9153 stack: &[FnState],
9154 current: usize,
9155 action: VarAction,
9156 slot: Slot,
9157) -> (Opcode, Vec<Op>) {
9158 let lexical = match slot {
9159 Slot::Loc(index) => stack[current]
9160 .vars
9161 .get(index as usize)
9162 .is_some_and(|v| v.needs_check()),
9163 Slot::VarRef(index) => stack[current]
9164 .closure_vars
9165 .get(index as usize)
9166 .is_some_and(|c| c.is_lexical),
9167 _ => false,
9168 };
9169 let operand = vec![Op::Slot(slot)];
9170 match (action, slot) {
9171 (VarAction::Get, Slot::Loc(index)) => (
9172 if lexical {
9173 Opcode::GetLocCheck
9174 } else {
9175 Opcode::GetLoc
9176 },
9177 vec![Op::Slot(Slot::Loc(index))],
9178 ),
9179 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
9180 (VarAction::Get, Slot::VarRef(index)) => (
9181 if lexical {
9182 Opcode::GetVarRefCheck
9183 } else {
9184 Opcode::GetVarRef
9185 },
9186 vec![Op::Slot(Slot::VarRef(index))],
9187 ),
9188 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
9189 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
9190 // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
9191 // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
9192 // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
9193 // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
9194 // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
9195 // `ReferenceError`.
9196 (VarAction::GetUndef, Slot::Loc(index)) => (
9197 if lexical {
9198 Opcode::GetLocCheck
9199 } else {
9200 Opcode::GetLoc
9201 },
9202 vec![Op::Slot(Slot::Loc(index))],
9203 ),
9204 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
9205 (VarAction::GetUndef, Slot::VarRef(index)) => (
9206 if lexical {
9207 Opcode::GetVarRefCheck
9208 } else {
9209 Opcode::GetVarRef
9210 },
9211 vec![Op::Slot(Slot::VarRef(index))],
9212 ),
9213 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9214 (Opcode::GetVarUndef, operand)
9215 }
9216
9217 (VarAction::Put, Slot::Loc(_)) => (
9218 if lexical {
9219 Opcode::PutLocCheck
9220 } else {
9221 Opcode::PutLoc
9222 },
9223 operand,
9224 ),
9225 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
9226 (VarAction::Put, Slot::VarRef(_)) => (
9227 if lexical {
9228 Opcode::PutVarRefCheck
9229 } else {
9230 Opcode::PutVarRef
9231 },
9232 operand,
9233 ),
9234 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
9235 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9236 // Initialisation is what ends the dead zone, so it never checks.
9237 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9238 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
9239 // `this` in a derived constructor is always a local, so these cannot happen;
9240 // routing them to the ordinary forms keeps the match total without inventing
9241 // opcodes the reference does not have.
9242 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
9243 // The captured form of `PutLocCheckInit`: `super()` inside an arrow that closes over
9244 // the constructor's `this` still has to refuse a second initialisation, and the
9245 // plain store accepted it (`fields-run-once-on-double-super`).
9246 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRefCheckInit, operand),
9247 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9248 (Opcode::PutVarInit, operand)
9249 }
9250 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
9251 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9252 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9253 (Opcode::PutVarInit, operand)
9254 }
9255 (VarAction::Set, Slot::Loc(_)) => (
9256 if lexical {
9257 Opcode::SetLocCheck
9258 } else {
9259 Opcode::SetLoc
9260 },
9261 operand,
9262 ),
9263 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
9264 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
9265 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9266 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9267 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
9268 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9269 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
9270 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
9271 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9272 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
9273 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9274 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
9275 }
9276}
9277
9278/// The instruction-rewriting pass.
9279///
9280/// These are the reference implementation's patterns, restricted to the ones the
9281/// constructs this compiler supports can produce. Each entry is a comment on the
9282/// bytecode it removes, because the whole point is that the result is one
9283/// instruction shorter than the literal translation of the AST.
9284fn peephole(
9285 insns: &mut [Option<(Opcode, Vec<Op>)>],
9286 label_at: &[Option<u32>],
9287 placed: &[Option<usize>],
9288) {
9289 fold_dup_patterns(insns, label_at);
9290
9291 // `drop` before `return_undef` is dead: the return discards the whole frame
9292 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
9293 // consumes its own `drop`; removing the drop first would leave the `dup` and
9294 // produce a `set_` where the reference has a `put_`.
9295 for index in 0..insns.len() {
9296 if opcode_at(insns, index) != Some(Opcode::Drop) {
9297 continue;
9298 }
9299 // Skip over a run of drops, but stop at a jump target: removing code on
9300 // one side of a label would silently retarget the jump.
9301 let mut next = index + 1;
9302 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
9303 next += 1;
9304 }
9305 if is_label_at(label_at, next) {
9306 continue;
9307 }
9308 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
9309 for entry in &mut insns[index..next] {
9310 *entry = None;
9311 }
9312 }
9313 }
9314
9315 // The rewrites below all decide against one fixed snapshot, which is what the
9316 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
9317 // the pass, so a rule never observes what an earlier rule removed. Gathering
9318 // every deletion first and applying them together reproduces that.
9319 let snapshot: Vec<Option<Opcode>> = insns
9320 .iter()
9321 .map(|entry| entry.as_ref().map(|(op, _)| *op))
9322 .collect();
9323 // The next instruction that is still there. Holes left by dead-code
9324 // elimination are not instructions, so a rule looks past them.
9325 let next_op = |index: usize| -> Option<usize> {
9326 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
9327 };
9328
9329 let mut doomed = vec![false; insns.len()];
9330 for index in 0..insns.len() {
9331 // A constant pushed only to be dropped does nothing at all. This is what a
9332 // comma expression with a literal left operand compiles to — `(0, f)()` — and
9333 // the reference removes the pair rather than making the reader step over it.
9334 let constant = matches!(
9335 snapshot[index],
9336 Some(
9337 Opcode::Undefined
9338 | Opcode::Null
9339 | Opcode::PushMinus1
9340 | Opcode::Push0
9341 | Opcode::Push1
9342 | Opcode::Push2
9343 | Opcode::Push3
9344 | Opcode::Push4
9345 | Opcode::Push5
9346 | Opcode::Push6
9347 | Opcode::Push7
9348 | Opcode::PushTrue
9349 | Opcode::PushFalse
9350 | Opcode::PushI32
9351 )
9352 );
9353 if constant
9354 && let Some(next) = next_op(index)
9355 && snapshot[next] == Some(Opcode::Drop)
9356 {
9357 doomed[index] = true;
9358 doomed[next] = true;
9359 }
9360 }
9361 for (index, entry) in insns.iter_mut().enumerate() {
9362 if doomed[index] {
9363 *entry = None;
9364 }
9365 }
9366
9367 // A conditional whose destination is the very next instruction just pops its
9368 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
9369 // compiles to.
9370 //
9371 // Order matters, and it is the reference's order: this runs *before* the
9372 // folding below, on the instruction the conditional originally had. Folding
9373 // moves a conditional's destination, and the reference never re-examines it
9374 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
9375 // a conditional even though folding leaves it pointing at the next
9376 // instruction.
9377 for (index, entry) in insns.iter_mut().enumerate() {
9378 let Some((op, operands)) = entry.clone() else {
9379 continue;
9380 };
9381 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
9382 continue;
9383 }
9384 let Some(id) = label_id(&operands) else {
9385 continue;
9386 };
9387 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
9388 *entry = Some((Opcode::Drop, Vec::new()));
9389 }
9390 }
9391
9392 // A constant condition is decided here rather than at run time.
9393 fold_constant_conditions(insns, label_at);
9394 // The conditional folding below is about pairs of *real* branches, so it runs
9395 // before a jump to the next instruction is dropped: `do { … if (c) continue }
9396 // while (t)` puts `continue` exactly on the condition, and the reference inverts
9397 // the branch first and only then notices the jump goes nowhere.
9398 fold_conditional_jumps(insns, label_at, placed);
9399
9400 // A jump whose destination is the very next instruction does nothing, which is
9401 // what constant folding leaves behind for `while (1) { … }`.
9402 remove_jump_to_next(insns, placed);
9403
9404 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
9405 // a use of the same variable boils down to.
9406 for index in 0..insns.len() {
9407 let Some((put_op, _)) = insns[index].clone() else {
9408 continue;
9409 };
9410 if !is_foldable_put(put_op) {
9411 continue;
9412 }
9413 if is_label_at(label_at, index + 1) {
9414 continue;
9415 }
9416 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
9417 continue;
9418 };
9419 if get_op != get_form_of(put_op) {
9420 continue;
9421 }
9422 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
9423 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
9424 continue;
9425 }
9426 insns[index] = Some((set_form_of(put_op), get_operands));
9427 insns[index + 1] = None;
9428 }
9429}
9430
9431/// Drop `gosub`s that call an empty subroutine.
9432///
9433/// A `gosub` whose target starts with `ret` returns immediately, so the reference
9434/// drops the call. This is how `try`/`catch` without a `finally` loses its
9435/// finalizer plumbing: the finalizer block is empty, its first instruction is
9436/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
9437/// [`eliminate_dead_code`] then removes.
9438fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
9439 let state = &stack[current];
9440 let mut targets = Vec::new();
9441 for insn in &state.insns {
9442 if let Insn::Fixed { op, operands } = insn
9443 && *op == Opcode::Gosub
9444 && let Some(id) = label_id(operands)
9445 && let Some(target) = state.labels.get(id as usize).copied().flatten()
9446 {
9447 targets.push(target);
9448 }
9449 }
9450 let empty: Vec<usize> = targets
9451 .into_iter()
9452 .filter(|target| {
9453 stack[current]
9454 .insns
9455 .get(*target)
9456 .map(|insn| {
9457 matches!(
9458 insn,
9459 Insn::Fixed {
9460 op: Opcode::Ret,
9461 ..
9462 }
9463 )
9464 })
9465 .unwrap_or(false)
9466 })
9467 .collect();
9468 if empty.is_empty() {
9469 return;
9470 }
9471 for insn in stack[current].insns.iter_mut() {
9472 if let Insn::Fixed { op, operands } = insn
9473 && *op == Opcode::Gosub
9474 && let Some(id) = label_id(operands)
9475 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
9476 && empty.contains(&target)
9477 {
9478 *insn = Insn::Dead;
9479 }
9480 }
9481}
9482
9483/// Replace unreachable instructions with [`Insn::Dead`].
9484fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
9485 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
9486 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
9487 if !reachable[index] {
9488 *insn = Insn::Dead;
9489 }
9490 }
9491}
9492
9493/// Mark every instruction index reachable from the entry, plus the index one past
9494/// the last instruction.
9495///
9496/// `seen[len]` answers "can control reach the end of this function", and the
9497/// entries before it identify dead code. Both DCE and the implicit-return decision
9498/// read the same result, which keeps them from disagreeing.
9499fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
9500 let mut seen = vec![false; count + 1];
9501 let mut worklist = vec![0usize];
9502 while let Some(index) = worklist.pop() {
9503 if index > count || seen[index] {
9504 continue;
9505 }
9506 seen[index] = true;
9507 if index == count {
9508 continue;
9509 }
9510 let (op, operands) = match &state.insns[index] {
9511 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
9512 // A variable access never transfers control, and a removed
9513 // instruction is only reachable if it is already marked.
9514 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
9515 worklist.push(index + 1);
9516 continue;
9517 }
9518 };
9519 match op {
9520 // A return, a throw and a `ret` all leave this instruction stream: the
9521 // first two give control to the caller or the handler, and `ret`
9522 // returns to a `gosub` elsewhere.
9523 // A tail call leaves the function too: the callee's result becomes this
9524 // function's result, so nothing after it runs.
9525 Opcode::Return
9526 | Opcode::ReturnUndef
9527 | Opcode::ReturnAsync
9528 | Opcode::TailCall
9529 | Opcode::TailCallMethod
9530 | Opcode::Throw
9531 | Opcode::ThrowError
9532 | Opcode::Ret => {}
9533 // A `catch` records where exceptions from the code that follows go.
9534 // That code is not reachable through normal control flow, but it is
9535 // reachable — through the exception edge — so the walk has to follow
9536 // it, or dead-code elimination would delete every handler.
9537 Opcode::Catch => {
9538 if let Some(target) = placed_label(state, operands) {
9539 worklist.push(target);
9540 }
9541 worklist.push(index + 1);
9542 }
9543 // A `gosub` calls a subroutine and then continues, so both edges count.
9544 Opcode::Gosub => {
9545 if let Some(target) = placed_label(state, operands) {
9546 worklist.push(target);
9547 }
9548 worklist.push(index + 1);
9549 }
9550 Opcode::Goto => {
9551 if let Some(target) = placed_label(state, operands) {
9552 worklist.push(target);
9553 }
9554 }
9555 Opcode::IfTrue | Opcode::IfFalse => {
9556 if let Some(target) = placed_label(state, operands) {
9557 worklist.push(target);
9558 }
9559 worklist.push(index + 1);
9560 }
9561 _ => worklist.push(index + 1),
9562 }
9563 }
9564 seen
9565}
9566
9567/// The instruction index a jump operand points at, resolved through the label
9568/// placement table.
9569fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
9570 let id = label_id(operands)?;
9571 state.labels.get(id as usize).copied().flatten()
9572}
9573
9574/// The label an instruction refers to.
9575fn label_id(operands: &[Op]) -> Option<u32> {
9576 operands.iter().find_map(|operand| match operand {
9577 Op::Label(label) => Some(label.0),
9578 _ => None,
9579 })
9580}
9581
9582/// Turn `if_false L; goto M; L:` into `if_true M`.
9583///
9584/// A conditional whose alternate branch is an unconditional jump needs one jump,
9585/// not two. This is the shape `if (c) break;` produces, so folding it removes an
9586/// instruction and a label from every conditional `break`.
9587/// The boolean a constant-push instruction produces, or `None` if it is not one.
9588///
9589/// Only the operators whose truthiness is decided by the opcode are covered; a
9590/// constant that needs the constant pool (a string) is left alone, because reading it
9591/// would mean threading the pool through the peephole for a case the reference also
9592/// skips.
9593fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
9594 match op {
9595 // `push_0` returns -1 for zero, `push_1` 1, and so on.
9596 Opcode::PushMinus1 => Some(true),
9597 Opcode::Push0 => Some(false),
9598 Opcode::Push1
9599 | Opcode::Push2
9600 | Opcode::Push3
9601 | Opcode::Push4
9602 | Opcode::Push5
9603 | Opcode::Push6
9604 | Opcode::Push7 => Some(true),
9605 Opcode::PushTrue => Some(true),
9606 Opcode::PushFalse => Some(false),
9607 Opcode::Undefined | Opcode::Null => Some(false),
9608 Opcode::PushI32 => match operands.first() {
9609 Some(Op::Int(value)) => Some(*value != 0),
9610 _ => None,
9611 },
9612 _ => None,
9613 }
9614}
9615
9616/// Fold a branch on a constant condition.
9617///
9618/// `if (0) a() else b()` must not test anything at run time, and the reference
9619/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
9620/// which is why the bytecode for a `while (1)` loop has no condition at all.
9621///
9622/// Two instructions become one, so the slot the test occupied is left empty rather
9623/// than shifting everything after it: labels have already been resolved to indices.
9624fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9625 for index in 0..insns.len() {
9626 let Some((push_op, push_operands)) = insns[index].clone() else {
9627 continue;
9628 };
9629 let Some(truth) = constant_truth(push_op, &push_operands) else {
9630 continue;
9631 };
9632 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
9633 continue;
9634 };
9635 // A label on the branch means something else jumps *here* — the value is on the
9636 // stack and the conditional is what pops it. Deleting the branch would leave that
9637 // jump with no instruction, and a label whose slot is empty resolves to the next
9638 // one that is not, i.e. to the far side of the branch. That is how
9639 // `if (a && false) then else` jumped to `then`: `&&` ends its chain on a label, and
9640 // the constant `false` sits directly in front of the statement's own conditional.
9641 if is_label_at(label_at, index + 1) {
9642 continue;
9643 }
9644 let (destination, taken) = match branch_op {
9645 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
9646 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
9647 _ => continue,
9648 };
9649 let Some(destination) = destination else {
9650 continue;
9651 };
9652 insns[index] = if taken {
9653 // The branch is always taken, so it becomes an unconditional jump.
9654 Some((Opcode::Goto, vec![destination]))
9655 } else {
9656 // The branch never runs: both instructions disappear and control falls
9657 // through to what came after.
9658 None
9659 };
9660 insns[index + 1] = None;
9661 }
9662}
9663
9664/// Remove a jump whose destination is the instruction right after it.
9665///
9666/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
9667/// its test into nothing, and the loop-end jump then points at the following
9668/// instruction. The reference drops them, so `stack_size` and the listing agree.
9669fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
9670 for index in 0..insns.len() {
9671 let Some((op, operands)) = insns[index].clone() else {
9672 continue;
9673 };
9674 if !is_goto(op) {
9675 continue;
9676 }
9677 let Some(id) = label_id(&operands) else {
9678 continue;
9679 };
9680 // The next instruction that still exists, which is what "the instruction
9681 // after this jump" means once earlier folds have punched holes.
9682 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
9683 if placed.get(id as usize).copied().flatten() == next {
9684 insns[index] = None;
9685 }
9686 }
9687}
9688
9689fn fold_conditional_jumps(
9690 insns: &mut [Option<(Opcode, Vec<Op>)>],
9691 label_at: &[Option<u32>],
9692 placed: &[Option<usize>],
9693) {
9694 for index in 0..insns.len() {
9695 let Some((op, operands)) = insns[index].clone() else {
9696 continue;
9697 };
9698 let inverted = match op {
9699 Opcode::IfFalse => Opcode::IfTrue,
9700 Opcode::IfTrue => Opcode::IfFalse,
9701 _ => continue,
9702 };
9703 // Next must be an unconditional jump that is not itself a target, and the
9704 // instruction after it must be exactly where the conditional goes.
9705 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
9706 continue;
9707 };
9708 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
9709 continue;
9710 }
9711 // The conditional must land on the instruction *after* the jump. Several
9712 // labels can share a position, so this asks where *this* label was put
9713 // rather than what label happens to sit there.
9714 let Some(taken) = label_id(&operands) else {
9715 continue;
9716 };
9717 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
9718 continue;
9719 }
9720 let Some(destination) = next_operands.first().cloned() else {
9721 continue;
9722 };
9723 insns[index] = Some((inverted, vec![destination]));
9724 insns[index + 1] = None;
9725 }
9726}
9727
9728/// Whether a jump target is placed at this instruction index.
9729fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
9730 label_at.get(index).copied().flatten().is_some()
9731}
9732
9733fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9734 // `dup put_x(n)` -> `set_x(n)`
9735 // `dup put_x(n) drop` -> `put_x(n)`
9736 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
9737 for index in 0..insns.len() {
9738 if opcode_at(insns, index) != Some(Opcode::Dup) {
9739 continue;
9740 }
9741 if is_label_at(label_at, index + 1) {
9742 continue;
9743 }
9744 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
9745 continue;
9746 };
9747 if !is_foldable_put(put_op) {
9748 continue;
9749 }
9750 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
9751 continue;
9752 };
9753 let mut new_op = set_form_of(put_op);
9754 let mut end = index + 2;
9755 if is_label_at(label_at, end) {
9756 // The `put` has to stay as it is; only the `dup` can be folded.
9757 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
9758 insns[index + 1] = None;
9759 continue;
9760 }
9761 // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
9762 // Deleting it moves the label's target onto whatever follows, and the code that
9763 // jumps there arrives with a different stack than the fall-through path: that is
9764 // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
9765 // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
9766 // an empty stack. The store had already consumed the value it was supposed to
9767 // leave behind.
9768 if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
9769 new_op = put_op;
9770 end += 1;
9771 if opcode_at(insns, end) == Some(get_form_of(put_op))
9772 && !is_label_at(label_at, end)
9773 && insns[end]
9774 .as_ref()
9775 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
9776 {
9777 new_op = set_form_of(put_op);
9778 end += 1;
9779 }
9780 }
9781 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
9782 for entry in &mut insns[index + 1..end] {
9783 *entry = None;
9784 }
9785 }
9786}
9787
9788fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
9789 insns
9790 .get(index)
9791 .and_then(|entry| entry.as_ref())
9792 .map(|(op, _)| *op)
9793}
9794
9795/// The four `put_` families that have a `set_` twin. Deliberately not including
9796/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
9797/// these, and folding the others would produce instructions that do not exist.
9798fn is_foldable_put(op: Opcode) -> bool {
9799 matches!(
9800 op,
9801 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
9802 )
9803}
9804
9805fn set_form_of(op: Opcode) -> Opcode {
9806 match op {
9807 Opcode::PutLoc => Opcode::SetLoc,
9808 Opcode::PutLocCheck => Opcode::SetLocCheck,
9809 Opcode::PutArg => Opcode::SetArg,
9810 Opcode::PutVarRef => Opcode::SetVarRef,
9811 other => other,
9812 }
9813}
9814
9815fn get_form_of(op: Opcode) -> Opcode {
9816 match op {
9817 Opcode::PutLoc => Opcode::GetLoc,
9818 Opcode::PutLocCheck => Opcode::GetLocCheck,
9819 Opcode::PutArg => Opcode::GetArg,
9820 Opcode::PutVarRef => Opcode::GetVarRef,
9821 other => other,
9822 }
9823}
9824
9825/// Atom interning, per function.
9826///
9827/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
9828/// identifiers, so the array-index rule applies here rather than at the handful of
9829/// call sites that build property keys.
9830fn intern_atom(state: &mut FnState, name: &str) -> u32 {
9831 intern_atom_value(state, Atom::from_text(name))
9832}
9833
9834/// [`intern_atom`] for an operand that is already an [`Atom`].
9835///
9836/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
9837/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
9838/// would have looked up.
9839fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
9840 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
9841 return index as u32;
9842 }
9843 state.atoms.push(atom);
9844 state.atoms.len() as u32 - 1
9845}
9846
9847fn binary_opcode(op: BinaryOp) -> Opcode {
9848 match op {
9849 BinaryOp::Add => Opcode::Add,
9850 BinaryOp::Sub => Opcode::Sub,
9851 BinaryOp::Mul => Opcode::Mul,
9852 BinaryOp::Div => Opcode::Div,
9853 BinaryOp::Mod => Opcode::Mod,
9854 BinaryOp::Pow => Opcode::Pow,
9855 BinaryOp::BitOr => Opcode::Or,
9856 BinaryOp::BitXor => Opcode::Xor,
9857 BinaryOp::BitAnd => Opcode::And,
9858 BinaryOp::Shl => Opcode::Shl,
9859 BinaryOp::Shr => Opcode::Sar,
9860 BinaryOp::UShr => Opcode::Shr,
9861 BinaryOp::Lt => Opcode::Lt,
9862 BinaryOp::LtEq => Opcode::Lte,
9863 BinaryOp::Gt => Opcode::Gt,
9864 BinaryOp::GtEq => Opcode::Gte,
9865 BinaryOp::Eq => Opcode::Eq,
9866 BinaryOp::NotEq => Opcode::Neq,
9867 BinaryOp::StrictEq => Opcode::StrictEq,
9868 BinaryOp::StrictNotEq => Opcode::StrictNeq,
9869 BinaryOp::In => Opcode::In,
9870 BinaryOp::Instanceof => Opcode::Instanceof,
9871 }
9872}
9873
9874fn compound_opcode(op: AssignOp) -> Opcode {
9875 match op {
9876 AssignOp::Add => Opcode::Add,
9877 AssignOp::Sub => Opcode::Sub,
9878 AssignOp::Mul => Opcode::Mul,
9879 AssignOp::Div => Opcode::Div,
9880 AssignOp::Mod => Opcode::Mod,
9881 AssignOp::Pow => Opcode::Pow,
9882 AssignOp::Shl => Opcode::Shl,
9883 AssignOp::Shr => Opcode::Sar,
9884 AssignOp::UShr => Opcode::Shr,
9885 AssignOp::BitOr => Opcode::Or,
9886 AssignOp::BitXor => Opcode::Xor,
9887 AssignOp::BitAnd => Opcode::And,
9888 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
9889 }
9890}
9891
9892/// Encode the resolved instruction stream, choosing short forms where possible.
9893///
9894/// The peephole pass leaves holes in the instruction list so that label indices
9895/// stay valid. A label names an *instruction index*, and an index that was
9896/// deleted has to resolve to the next surviving instruction, which is what
9897/// [`resolve_label`] does before the byte offsets are known.
9898fn assemble(
9899 insns: &mut [Option<(Opcode, Vec<Op>)>],
9900 insn_pos: &[Option<Position>],
9901 state: &mut FnState,
9902) -> (Vec<u8>, u32, Vec<LineCol>) {
9903 // Compaction: surviving instructions in order, plus the index mapping.
9904 //
9905 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
9906 // point below where instructions are removed — otherwise a stack trace would point
9907 // at the wrong source line as soon as dead-code elimination kicked in.
9908 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
9909 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
9910 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
9911 for (original, entry) in insns.iter_mut().enumerate() {
9912 if let Some((op, operands)) = entry.take() {
9913 original_to_kept[original] = Some(kept.len());
9914 kept.push((op, operands));
9915 spans.push(insn_pos.get(original).copied().flatten());
9916 }
9917 }
9918
9919 if std::env::var_os("QJS_DEBUG").is_some() {
9920 eprintln!("--- assemble entry --- {kept:?}");
9921 }
9922 // How many labels are real, as opposed to the per-instruction ones allocated
9923 // just below. Only a real label marks a spot in the source program.
9924 let real_labels = state.labels.len();
9925
9926 // Give every surviving instruction a label of its own. Jump cleanup below
9927 // redirects jumps to arbitrary instructions, and a jump target has to be a
9928 // label; pre-allocating one per index means a redirect never has to invent
9929 // anything.
9930 let existing = state.labels.len();
9931 let base = kept.len();
9932 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
9933 for offset in 0..=kept.len() {
9934 state.labels.push(Some(0));
9935 index_label.push(Label((existing + offset) as u32));
9936 }
9937 // Point each pre-allocated label at its instruction, reusing the count from
9938 // `original_to_kept` so the mapping survives compaction.
9939 let place_index_labels = |state: &mut FnState,
9940 original_to_kept: &[Option<usize>],
9941 kept_len: usize,
9942 index_label: &[Label]| {
9943 for (original, mapped) in original_to_kept.iter().enumerate() {
9944 if let Some(kept_index) = mapped {
9945 let label = index_label[*kept_index].0 as usize;
9946 state.labels[label] = Some(original);
9947 }
9948 }
9949 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
9950 };
9951 place_index_labels(state, &original_to_kept, base, &index_label);
9952
9953 // Resolve every label to a kept index once; the placement table maps labels
9954 // to original indices, so a second hop lands in kept space.
9955 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
9956 for (id, placed) in state.labels.iter().enumerate() {
9957 let Some(original) = placed else { continue };
9958 label_kept[id] = if *original == usize::MAX {
9959 Some(base)
9960 } else {
9961 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
9962 };
9963 }
9964
9965 // Code after an unconditional transfer is unreachable, and the reference drops it
9966 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
9967 // scans forward until it finds a label something still jumps to, so a run of
9968 // dead instructions between a `throw` and the next live target disappears.
9969 //
9970 // The scan repeats because dropping a jump lowers the reference count of the
9971 // label it pointed at, which can strand what follows. Only a real label keeps an
9972 // instruction alive here; the per-instruction labels allocated above belong to
9973 // this pass, not to the program.
9974 loop {
9975 let mut references = vec![false; kept.len() + 1];
9976 for (_, operands) in &kept {
9977 if let Some(target) = target_kept_index(operands, &label_kept)
9978 && target < references.len()
9979 {
9980 references[target] = true;
9981 }
9982 }
9983 let mut doomed = vec![false; kept.len()];
9984 let mut any = false;
9985 for (index, (op, _)) in kept.iter().enumerate() {
9986 if !is_transfer(*op) {
9987 continue;
9988 }
9989 for next in index + 1..kept.len() {
9990 if references[next] {
9991 break;
9992 }
9993 doomed[next] = true;
9994 any = true;
9995 }
9996 }
9997 if !any {
9998 break;
9999 }
10000 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
10001 }
10002
10003 // A label that lands on an unconditional jump stands for wherever that jump
10004 // goes, so retarget it once and every jump to the label follows for free.
10005 // This is what makes `continue` in a `for` head reach the loop top instead of
10006 // stopping at the update's trailing jump.
10007 let folded: Vec<Option<usize>> = label_kept
10008 .iter()
10009 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
10010 .collect();
10011 label_kept = folded;
10012
10013 // Jump cleanup, in compacted index space. Two rewrites the reference also
10014 // applies while it resolves labels:
10015 // * a jump whose destination is the very next instruction does nothing;
10016 // * a jump to a jump is redirected to its final destination.
10017 // The second can expose the first, so this repeats until it settles.
10018 loop {
10019 let mut delete = vec![false; kept.len()];
10020 let mut changed = false;
10021 for index in 0..kept.len() {
10022 let (op, operands) = &kept[index];
10023 if !is_goto(*op) {
10024 continue;
10025 }
10026 let Some(immediate) = target_kept_index(operands, &label_kept) else {
10027 continue;
10028 };
10029 let target = follow_jump_chain(&kept, &label_kept, immediate);
10030 if target == index + 1 {
10031 delete[index] = true;
10032 changed = true;
10033 } else if matches!(
10034 kept.get(target).map(|(op, _)| *op),
10035 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
10036 ) {
10037 // Jumping straight to a return or throw is the same as doing it
10038 // here, so the jump becomes that instruction.
10039 kept[index] = (kept[target].0, Vec::new());
10040 changed = true;
10041 } else if target != immediate {
10042 // Redirect to the end of the chain.
10043 let label = index_label[target];
10044 kept[index].1 = vec![Op::Label(label)];
10045 changed = true;
10046 }
10047 }
10048 if !changed {
10049 break;
10050 }
10051 if !delete.iter().any(|deleted| *deleted) {
10052 break;
10053 }
10054 // Drop the deleted instructions and renumber everything.
10055 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10056 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10057 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10058 for (old, entry) in kept.into_iter().enumerate() {
10059 if delete[old] {
10060 continue;
10061 }
10062 moved[old] = Some(next.len());
10063 next.push(entry);
10064 next_spans.push(spans[old]);
10065 }
10066 for (id, slot) in label_kept.iter_mut().enumerate() {
10067 let Some(old) = *slot else { continue };
10068 *slot = match moved.get(old).copied().flatten() {
10069 Some(new) => Some(new),
10070 // The target was deleted: the jump now lands on whatever follows.
10071 None => (old..moved.len())
10072 .find_map(|i| moved[i])
10073 .or(Some(next.len())),
10074 };
10075 let _ = id;
10076 }
10077 kept = next;
10078 spans = next_spans;
10079 }
10080
10081 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
10082 // jump to the next instruction and is deleted, leaving the label at the end with
10083 // nothing pointing at it. If that also strands the last instruction, it goes
10084 // too — which is how a `try` whose body always returns ends on its `ret` rather
10085 // than an implicit `return_undef`.
10086 // Which instructions something still jumps to. Reading the surviving jumps is
10087 // what the reference's reference counts amount to: once a jump has been folded
10088 // away the label it named is unreferenced, even though the program still has a
10089 // label there.
10090 let mut references = vec![false; kept.len() + 1];
10091 let _ = real_labels;
10092 for (_, operands) in &kept {
10093 if let Some(target) = target_kept_index(operands, &label_kept)
10094 && target < references.len()
10095 {
10096 references[target] = true;
10097 }
10098 }
10099 let mut end = kept.len();
10100 while end > 0 {
10101 let last = end - 1;
10102 let reachable = references[last] || end < kept.len();
10103 if reachable {
10104 break;
10105 }
10106 let after_transfer = last
10107 .checked_sub(1)
10108 .map(|previous| {
10109 matches!(
10110 kept[previous].0,
10111 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
10112 )
10113 })
10114 .unwrap_or(false);
10115 if !after_transfer {
10116 break;
10117 }
10118 end = last;
10119 }
10120 kept.truncate(end);
10121 spans.truncate(end);
10122
10123 // Choose an opcode for each instruction and its size, so label offsets can be
10124 // computed.
10125 let chosen = choose_opcodes(&kept, &label_kept);
10126 let offsets = instruction_offsets(&chosen);
10127 let offset = *offsets.last().unwrap_or(&0);
10128
10129 let mut code = Vec::with_capacity(offset);
10130 for (position, (_, operands)) in kept.iter().enumerate() {
10131 let op = chosen[position];
10132 code.push(op as u8);
10133 let operands = retarget_labels(operands, &label_kept, kept.len());
10134 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
10135 }
10136 let stack_size = compute_stack_size(&code);
10137 // Keep only the offsets where the position actually changes: a run of
10138 // instructions on one line is one table entry, and the runtime binary searches
10139 // the table for the frame's pc.
10140 //
10141 // The table always starts at pc 0 with the *function's own* position, because the
10142 // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
10143 // last_line_num)` from `fd->source_pos`, the token the function definition starts at
10144 // (`function`, `async`, a method's property name). An instruction before the first
10145 // recorded operator therefore reports the function's own start, which is what makes a
10146 // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
10147 let mut positions: Vec<LineCol> = vec![LineCol {
10148 pc: 0,
10149 line: state.line,
10150 column: state.column,
10151 }];
10152 let mut last: Option<Position> = None;
10153 for (index, span) in spans.iter().enumerate() {
10154 let Some(pos) = *span else { continue };
10155 if last == Some(pos) {
10156 continue;
10157 }
10158 last = Some(pos);
10159 if pos.line == state.line && pos.column == state.column {
10160 // Already the seed entry above.
10161 continue;
10162 }
10163 positions.push(LineCol {
10164 pc: offsets[index] as u32,
10165 line: pos.line,
10166 column: pos.column,
10167 });
10168 }
10169 (code, stack_size, positions)
10170}
10171
10172/// Whether an instruction always transfers control away, so anything after it in the
10173/// same stream is unreachable.
10174fn is_transfer(op: Opcode) -> bool {
10175 matches!(
10176 op,
10177 Opcode::Goto
10178 | Opcode::Goto8
10179 | Opcode::Goto16
10180 | Opcode::Return
10181 | Opcode::ReturnUndef
10182 | Opcode::Throw
10183 | Opcode::ThrowError
10184 | Opcode::Ret
10185 )
10186}
10187
10188/// Remove the marked instructions and renumber the label table so it keeps pointing
10189/// at the same instructions. A label whose instruction went away moves to whatever
10190/// follows it, since a jump is never left with nowhere to land.
10191fn drop_instructions(
10192 kept: Vec<(Opcode, Vec<Op>)>,
10193 spans: Vec<Option<Position>>,
10194 label_kept: &mut [Option<usize>],
10195 doomed: &[bool],
10196) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
10197 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10198 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10199 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10200 for (old, entry) in kept.into_iter().enumerate() {
10201 if doomed.get(old).copied().unwrap_or(false) {
10202 continue;
10203 }
10204 moved[old] = Some(result.len());
10205 result.push(entry);
10206 result_spans.push(spans[old]);
10207 }
10208 for slot in label_kept.iter_mut() {
10209 let Some(old) = *slot else { continue };
10210 *slot = match moved.get(old).copied().flatten() {
10211 Some(new) => Some(new),
10212 None => (old..moved.len())
10213 .find_map(|i| moved[i])
10214 .or(Some(result.len())),
10215 };
10216 }
10217 (result, result_spans)
10218}
10219
10220fn is_goto(op: Opcode) -> bool {
10221 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
10222}
10223
10224/// The kept index a jump operand points at.
10225fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
10226 let id = label_id(operands)?;
10227 label_kept.get(id as usize).copied().flatten()
10228}
10229
10230/// Follow a chain of unconditional jumps to its first real destination.
10231fn follow_jump_chain(
10232 kept: &[(Opcode, Vec<Op>)],
10233 label_kept: &[Option<usize>],
10234 start: usize,
10235) -> usize {
10236 let mut current = start;
10237 // `for(;;)` jumps to itself, so the walk has to be bounded.
10238 for _ in 0..kept.len() {
10239 let Some((op, operands)) = kept.get(current) else {
10240 return current;
10241 };
10242 if !is_goto(*op) {
10243 return current;
10244 }
10245 let Some(next) = target_kept_index(operands, label_kept) else {
10246 return current;
10247 };
10248 if next == current {
10249 return current;
10250 }
10251 current = next;
10252 }
10253 current
10254}
10255
10256/// Rewrite label operands from label ids to kept instruction indices.
10257fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
10258 operands
10259 .iter()
10260 .map(|operand| match operand {
10261 Op::Label(label) => {
10262 let target = label_kept
10263 .get(label.0 as usize)
10264 .copied()
10265 .flatten()
10266 .unwrap_or(kept_len);
10267 Op::Label(Label(target as u32))
10268 }
10269 other => other.clone(),
10270 })
10271 .collect()
10272}
10273
10274/// Encode the resolved instruction stream, choosing short forms where possible.
10275///
10276/// Compute the maximum value-stack depth by exploring the control-flow graph.
10277///
10278/// This is a breadth-first walk from the first instruction, tracking the stack
10279/// depth on entry to each instruction. Every instruction has at most two
10280/// successors (fall through, and a jump target), so a worklist over byte offsets
10281/// is enough. The reference does the same thing in `compute_stack_size`, which is
10282/// why the resulting numbers match exactly.
10283///
10284/// Instructions that pop a variable number of values (`call`, `array_from`, …)
10285/// encode that count in their operand, which is added to the static `n_pop`.
10286fn compute_stack_size(code: &[u8]) -> u32 {
10287 let mut depth_at = vec![u16::MAX; code.len()];
10288 // Each entry carries the enclosing `catch` levels, innermost last, because
10289 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
10290 // offset and forgets that level.
10291 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
10292 let mut max_depth = 0u32;
10293
10294 while let Some((pc, depth, catch_levels)) = worklist.pop() {
10295 if pc >= code.len() {
10296 continue;
10297 }
10298 if depth_at[pc] != u16::MAX {
10299 continue;
10300 }
10301 force_depth(&mut depth_at, pc, depth);
10302
10303 let Some(op) = Opcode::from_u8(code[pc]) else {
10304 break;
10305 };
10306 let info = op.info();
10307 let next = pc + info.size as usize;
10308 if next > code.len() {
10309 break;
10310 }
10311 let mut n_pop = info.n_pop as u32;
10312 let mut n_push = info.n_push as u32;
10313 // Variable-length forms carry their count in the operand.
10314 match info.format {
10315 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
10316 n_pop += read_u16(code, pc + 1) as u32;
10317 }
10318 crate::opcode::OpFormat::Npopx => {
10319 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
10320 }
10321 _ => {}
10322 }
10323 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
10324 // are the `set_` variant; the table already records that, so nothing to
10325 // adjust here.
10326 let _ = &mut n_push;
10327
10328 // The depth before this instruction's own push, which is what a `catch`
10329 // records as its level.
10330 let depth_before = depth;
10331 let mut depth = depth.saturating_sub(n_pop) + n_push;
10332 let mut catch_levels = catch_levels;
10333 if op == Opcode::NipCatch {
10334 // Discard everything above the innermost catch offset, keeping the value
10335 // on top: the frame the code after this sees is the same shape it would
10336 // have had if the `try` were not there.
10337 if let Some(base) = catch_levels.pop() {
10338 depth = base + 1;
10339 }
10340 }
10341 max_depth = max_depth.max(depth);
10342
10343 // Successors.
10344 let target = jump_target_of(code, pc, op);
10345 match op {
10346 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10347 if let Some(target) = target {
10348 worklist.push((target, depth, catch_levels));
10349 }
10350 }
10351 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
10352 if let Some(target) = target {
10353 worklist.push((target, depth, catch_levels.clone()));
10354 }
10355 worklist.push((next, depth, catch_levels));
10356 }
10357 // A `catch` records an exception edge to the handler. The handler is
10358 // entered with the thrown value on top of the stack, in the slot the
10359 // catch offset occupies on the normal path — which is why the handler's
10360 // first instruction can `put_loc` the exception away, and why the depth
10361 // is the same on both paths.
10362 Opcode::Catch => {
10363 if let Some(target) = target {
10364 // The handler is protected by the *enclosing* catch, not by this
10365 // one: an error raised inside it is what the handler's own
10366 // `catch` catches.
10367 worklist.push((target, depth, catch_levels.clone()));
10368 }
10369 catch_levels.push(depth_before);
10370 worklist.push((next, depth, catch_levels));
10371 }
10372 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
10373 // rewind past it too. Its level sits one slot higher than a `catch`'s:
10374 // the iterator and next-method slots occupy the offset's place.
10375 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
10376 if let Some(target) = target {
10377 worklist.push((target, depth, catch_levels.clone()));
10378 }
10379 catch_levels.push(depth_before + 1);
10380 worklist.push((next, depth, catch_levels));
10381 }
10382 // `gosub` calls a subroutine with the return address on top. The opcode
10383 // table records no push for it — `ret` is what pops the slot — so the
10384 // extra one is added here, where the depth of the subroutine's first
10385 // instruction is being computed.
10386 Opcode::Gosub => {
10387 if let Some(target) = target {
10388 worklist.push((target, depth + 1, catch_levels.clone()));
10389 }
10390 worklist.push((next, depth, catch_levels));
10391 }
10392 // `ret` goes back to a `gosub`; nothing here follows it.
10393 Opcode::Ret
10394 | Opcode::Return
10395 | Opcode::ReturnUndef
10396 | Opcode::Throw
10397 | Opcode::ThrowError => {}
10398 _ => worklist.push((next, depth, catch_levels)),
10399 }
10400 }
10401 max_depth
10402}
10403
10404/// Record the stack depth on entry to `pc`, keeping the deeper value if the
10405/// instruction is reachable more than once.
10406fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
10407 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
10408 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
10409 depth_at[pc] = clamped;
10410 }
10411}
10412
10413fn read_u16(code: &[u8], at: usize) -> u16 {
10414 let mut value = 0u16;
10415 for i in 0..2 {
10416 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
10417 }
10418 value
10419}
10420
10421/// The absolute target of a jump instruction, if it has one.
10422fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
10423 let info = op.info();
10424 let position = pc + 1;
10425 match info.format {
10426 crate::opcode::OpFormat::Label8 => {
10427 let offset = *code.get(position)? as i8 as i64;
10428 Some((position as i64 + offset) as usize)
10429 }
10430 crate::opcode::OpFormat::Label16 => {
10431 let offset = read_u16(code, position) as i16 as i64;
10432 Some((position as i64 + offset) as usize)
10433 }
10434 crate::opcode::OpFormat::Label => {
10435 let mut offset = 0i32;
10436 for i in 0..4 {
10437 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
10438 }
10439 Some((position as i64 + offset as i64) as usize)
10440 }
10441 _ => None,
10442 }
10443}
10444
10445fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
10446 use Opcode::*;
10447 match (op, operands.first()) {
10448 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
10449 op.short_form(*value as u32).unwrap_or(op)
10450 }
10451 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
10452 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
10453 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
10454 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
10455 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
10456 // A declared global is reached through its reference cell, so it shares
10457 // the `var_ref` encodings, short forms included.
10458 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
10459 op.short_form(*index).unwrap_or(op)
10460 }
10461 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
10462 op.short_form(*count as u32).unwrap_or(op)
10463 }
10464 _ => op,
10465 }
10466}
10467
10468/// The byte offset each instruction will start at, plus the total code size.
10469fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
10470 let mut offsets = Vec::with_capacity(chosen.len() + 1);
10471 let mut offset = 0usize;
10472 for op in chosen {
10473 offsets.push(offset);
10474 offset += op.size() as usize;
10475 }
10476 offsets.push(offset);
10477 offsets
10478}
10479
10480/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
10481/// the offset actually fits.
10482///
10483/// The choice is circular: an instruction's size decides the offsets of everything after
10484/// it, and the offsets decide whether a jump may be short. So this starts with every jump
10485/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
10486/// Shrinking only ever *shortens* distances, so the loop converges.
10487///
10488/// Doing it in one pass instead — which is what this used to do — silently truncated any
10489/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
10490/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
10491/// with four closures in its body simply stopped, with no error and no output past the
10492/// first iteration.
10493fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
10494 let mut chosen: Vec<Opcode> = kept
10495 .iter()
10496 .map(|(op, operands)| choose_short_form(*op, operands))
10497 .collect();
10498 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
10499 let candidates = |op: Opcode| match op {
10500 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
10501 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
10502 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
10503 _ => None,
10504 };
10505 loop {
10506 let offsets = instruction_offsets(&chosen);
10507 let mut changed = false;
10508 for index in 0..kept.len() {
10509 let (op, operands) = &kept[index];
10510 let Some((short, medium, has_medium)) = candidates(*op) else {
10511 continue;
10512 };
10513 if chosen[index] == short {
10514 continue;
10515 }
10516 let Some(target) = target_kept_index(operands, label_kept) else {
10517 continue;
10518 };
10519 let Some(&target_offset) = offsets.get(target) else {
10520 continue;
10521 };
10522 // A jump is relative to the byte after its opcode, which is the convention
10523 // `jump_target_of` decodes with.
10524 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
10525 if (-128..=127).contains(&relative) {
10526 chosen[index] = short;
10527 changed = true;
10528 } else if has_medium
10529 && chosen[index] == Opcode::Goto
10530 && (-32_768..=32_767).contains(&relative)
10531 {
10532 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
10533 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
10534 // the reference encodes them.
10535 chosen[index] = medium;
10536 changed = true;
10537 }
10538 }
10539 if !changed {
10540 return chosen;
10541 }
10542 }
10543}
10544
10545fn encode_operands(
10546 code: &mut Vec<u8>,
10547 op: Opcode,
10548 operands: &[Op],
10549 position: usize,
10550 offsets: &[usize],
10551) {
10552 use crate::opcode::OpFormat::*;
10553 let info = op.info();
10554 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
10555 let index = match slot {
10556 Slot::Arg(i)
10557 | Slot::Loc(i)
10558 | Slot::VarRef(i)
10559 | Slot::Global(i)
10560 | Slot::GlobalDecl(i) => i,
10561 };
10562 code.extend_from_slice(&(index as u16).to_be_bytes());
10563 };
10564 match info.format {
10565 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
10566 U8 | Const8 => {
10567 if let Some(value) = operands.first().and_then(operand_uint) {
10568 code.push(value as u8);
10569 }
10570 }
10571 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
10572 // like their wide counterparts, only one byte wide.
10573 Loc8 => {
10574 if let Some(Op::Slot(slot)) = operands.first() {
10575 let index = match slot {
10576 Slot::Arg(i)
10577 | Slot::Loc(i)
10578 | Slot::VarRef(i)
10579 | Slot::Global(i)
10580 | Slot::GlobalDecl(i) => *i,
10581 };
10582 code.push(index as u8);
10583 }
10584 }
10585 I8 => {
10586 if let Some(value) = operands.first().and_then(operand_int) {
10587 code.push(value as i8 as u8);
10588 }
10589 }
10590 U16 | Npop => {
10591 if let Some(value) = operands.first().and_then(operand_int) {
10592 code.extend_from_slice(&(value as u16).to_be_bytes());
10593 }
10594 }
10595 I16 => {
10596 if let Some(value) = operands.first().and_then(operand_int) {
10597 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
10598 }
10599 }
10600 I32 => {
10601 if let Some(value) = operands.first().and_then(operand_int) {
10602 code.extend_from_slice(&value.to_be_bytes());
10603 }
10604 }
10605 U32 | Const => {
10606 if let Some(value) = operands.first().and_then(operand_uint) {
10607 code.extend_from_slice(&value.to_be_bytes());
10608 }
10609 }
10610 Loc | Arg | VarRef => {
10611 if let Some(Op::Slot(slot)) = operands.first() {
10612 write_slot(code, *slot);
10613 }
10614 }
10615 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
10616 if let Some(Op::AtomId(index)) = operands.first() {
10617 code.extend_from_slice(&index.to_be_bytes());
10618 }
10619 // The trailing immediate means different things per format, and the
10620 // atom forms that carry a *label* have to resolve it like any other
10621 // jump, so they cannot share the `U8`/`U16` arms above.
10622 match info.format {
10623 AtomU8 | AtomLabelU8 => {
10624 if let Some(value) = operands.get(1).and_then(operand_uint) {
10625 code.push(value as u8);
10626 }
10627 }
10628 AtomU16 | AtomLabelU16 => {
10629 if let Some(value) = operands.get(1).and_then(operand_uint) {
10630 code.extend_from_slice(&(value as u16).to_be_bytes());
10631 }
10632 }
10633 _ => {}
10634 }
10635 }
10636 NpopU16 => {
10637 for operand in operands.iter().take(2) {
10638 if let Some(value) = operand_uint(operand) {
10639 code.extend_from_slice(&(value as u16).to_be_bytes());
10640 }
10641 }
10642 }
10643 Label | Label8 | Label16 | LabelU16 => {
10644 if let Some(Op::Label(label)) = operands.first() {
10645 // Labels were already remapped to kept-instruction indices.
10646 let Some(&target) = offsets.get(label.0 as usize) else {
10647 debug_assert!(false, "label {} is past the end", label.0);
10648 return;
10649 };
10650 let relative = target as i64 - (position as i64 + 1);
10651 match info.format {
10652 Label8 => code.push(relative as i8 as u8),
10653 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
10654 // `label_u16` stores the target followed by an unrelated u16.
10655 LabelU16 => {
10656 code.extend_from_slice(&(relative as i32).to_be_bytes());
10657 if let Some(value) = operands.get(1).and_then(operand_uint) {
10658 code.extend_from_slice(&(value as u16).to_be_bytes());
10659 }
10660 }
10661 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
10662 }
10663 }
10664 }
10665 }
10666}
10667
10668fn operand_int(op: &Op) -> Option<i32> {
10669 match op {
10670 Op::Int(value) => Some(*value),
10671 _ => None,
10672 }
10673}
10674
10675fn operand_uint(op: &Op) -> Option<u32> {
10676 match op {
10677 Op::Const(value) | Op::AtomId(value) => Some(*value),
10678 Op::Int(value) => Some(*value as u32),
10679 _ => None,
10680 }
10681}
10682
10683/// Disassemble a compiled function.
10684pub fn disassemble(function: &CompiledFunction) -> String {
10685 disasm::disassemble_program(function)
10686}
10687
10688/// How many of an object pattern's keys are computed.
10689///
10690/// Only the count matters: a rest element needs a run-time key log exactly when at least one
10691/// key is not a literal, and the log is sized by walking the pattern anyway.
10692fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
10693 properties
10694 .iter()
10695 .flatten()
10696 .filter(|element| {
10697 matches!(
10698 element,
10699 PatternElement::Property {
10700 key: PropName::Computed(_),
10701 ..
10702 }
10703 )
10704 })
10705 .count()
10706}