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/// The next template-site identity, process-wide.
84///
85/// A counter rather than something derived from the unit: two compilation units that both
86/// number their sites from zero would collide in the realm's registry, and a collision
87/// there is observable — it would hand the *same* template object to two unrelated sites.
88fn next_template_site() -> u32 {
89 static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
90 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
91}
92
93/// How one field names its property.
94///
95/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
96/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
97/// is fixed when the class is created. Keeping the expression here instead made
98/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
99/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
100/// `{1: "a"}`.
101enum FieldKey<'a> {
102 /// `x`, `"x"`, `0` — the property name is static text.
103 Literal(&'a PropKey),
104 /// `#x`: the class-scope binding that holds the private symbol.
105 Private(String),
106 /// `[expr]`: the class-scope binding that holds the evaluated key.
107 Computed(String),
108}
109
110/// The `var_block` sentinel for a binding that lives at function scope.
111///
112/// It has to be a value a *real* block key can never take. Block keys are source
113/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
114/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
115/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
116/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
117/// sentinel takes the slot below it.
118const FUNCTION_SCOPE: u64 = u64::MAX - 3;
119
120/// The `var_block` sentinel for a binding of the parameter list.
121///
122/// A function whose parameter list contains a default expression gets *two* variable
123/// environments: one for the parameters and one for the body, so a `var` in the body
124/// that shares a name with a parameter is a different binding. The parameter bindings
125/// therefore need a scope key of their own: reachable while the defaults are
126/// evaluated, invisible to the body, and never merged with a body `var` of the same
127/// name.
128///
129/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
130/// the closure and the body shared one slot, when only the parameters were in scope
131/// when it was created.
132const PARAM_SCOPE: u64 = u64::MAX - 4;
133
134/// The name of the hidden local a `using` declaration caches its dispose method in.
135///
136/// It has to be a name no source can produce, because a script may declare anything: the
137/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
138fn using_method_name(name: &str) -> String {
139 format!("<using.method {name}>")
140}
141
142/// The `blocks` parent sentinel for "this block has no enclosing block".
143///
144/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
145/// also the terminator the chain walk from the script body reached the file's
146/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
147/// leaked into the body scope.
148const NO_PARENT: u64 = u64::MAX - 2;
149
150/// The block key for a script body. Distinct from both sentinels and unreachable from
151/// any source offset.
152const SCRIPT_BODY: u64 = u64::MAX - 1;
153
154/// An operand of a symbolic instruction.
155#[derive(Debug, Clone, PartialEq)]
156enum Op {
157 /// An immediate integer.
158 Int(i32),
159 /// A jump target.
160 Label(Label),
161 /// A constant pool index.
162 Const(u32),
163 /// An atom, before interning.
164 Atom(Atom),
165 /// An interned atom, as an index into [`Function::atoms`].
166 AtomId(u32),
167 /// A resolved slot.
168 Slot(Slot),
169}
170
171/// Where a resolved variable lives.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum Slot {
174 Arg(u32),
175 Loc(u32),
176 VarRef(u32),
177 /// A global, by closure-var index.
178 Global(u32),
179 /// A global *declared* in this script. The reference keeps these bindings in
180 /// reference cells so that the script and any closure share one variable, so
181 /// a store goes through `put_var_ref` while a read uses `get_var`.
182 GlobalDecl(u32),
183}
184
185/// What a symbolic variable access does, which decides the final opcode.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187enum VarAction {
188 /// Read the value.
189 Get,
190 /// Read the value, yielding `undefined` for an undeclared global.
191 GetUndef,
192 /// Write, leaving nothing on the stack.
193 Put,
194 /// Write and initialise, leaving the value on the stack.
195 PutInit,
196 /// Write, leaving the value on the stack.
197 Set,
198 /// Initialise a binding that may only be initialised once, such as a derived
199 /// constructor's `this`.
200 PutInitChecked,
201 /// Initialise, leaving the value on the stack and without the `const` check.
202 ///
203 /// A class's own scope binding is a `const` that has to be initialised in the middle
204 /// of the definition — after the constructor exists but before the static fields run
205 /// — and the value has to survive for the outer store to use.
206 SetInit,
207 /// Write a binding that lives in a reference cell.
208 PutRef,
209 /// Read through a reference the caller already pushed: `[ref] -> [ref, value]`.
210 GetRef,
211 /// Push a **Reference** (§6.2.5) to the binding, so the same lvalue can be read and
212 /// written without resolving the name twice.
213 ///
214 /// Only emitted where a direct `eval` may run in between: `x *= (eval("var x = 2"), 4)`
215 /// must read the `x` of §13.15.3 step 2 and store to *that* one at step 7, and by then
216 /// the eval has declared a shadowing binding with the same name.
217 MakeRef,
218}
219
220#[derive(Debug, Clone)]
221enum Insn {
222 /// A fully determined instruction.
223 Fixed { op: Opcode, operands: Vec<Op> },
224 /// A variable access, resolved in the second pass.
225 ///
226 /// `block` is the lexical block the access appears in, which is what makes
227 /// shadowing work: two bindings can share a name, and the one that wins is
228 /// whichever scope encloses the access.
229 Var {
230 action: VarAction,
231 name: String,
232 block: u64,
233 /// Whether the access was written in the parameter list; see
234 /// [`FnState::in_params`].
235 in_params: bool,
236 },
237 /// Close a binding *if* it turned out to be captured.
238 ///
239 /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
240 /// only known once the body has been compiled — a closure created there is the
241 /// thing that makes it necessary. The reference emits `close_loc` exactly in that
242 /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
243 /// of emitted blind.
244 CloseCaptured { name: String, block: u64 },
245 /// `delete name`, which can only answer `false` once the binding is known.
246 ///
247 /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
248 /// looks the name up on the global object, which is what distinguishes an implicit
249 /// global (configurable, deletable) from a declared one (a binding, always `false`).
250 DeleteVar { name: String },
251 /// An instruction that dead-code elimination removed. It keeps its slot so
252 /// that label indices stay valid, and resolves to no bytecode.
253 Dead,
254}
255
256/// Where `break` and `continue` jump to.
257///
258/// Targets are stacked as the compiler enters loops and labelled statements, so a
259/// bare `break` needs no analysis: it is simply the innermost target. A labelled
260/// one searches outward by name.
261#[derive(Debug, Clone)]
262struct JumpTarget {
263 /// The labels attached to this target. `l: for(;;)` gives one name; a bare
264 /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
265 /// same statement and `break a` must reach the same place as `break b`.
266 names: Vec<String>,
267 /// Where `break` lands. `None` for a construct `break` may only leave, not
268 /// target — a `try`, whose entry exists purely to unwind.
269 break_label: Option<Label>,
270 /// Where `continue` lands. `None` for anything that is not a loop.
271 continue_label: Option<Label>,
272 /// Stack slots to discard when control leaves this construct by a jump.
273 ///
274 /// Both `switch` and `try` leave something on the value stack for the duration
275 /// of the construct — the discriminant, or the `catch` offset — and a jump out
276 /// has to take it with it. A loop leaves nothing.
277 drop_count: u32,
278 /// The finalizer to run when control leaves this construct.
279 ///
280 /// Set on a `try` even when it has no `finally`: the label is always emitted and
281 /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
282 /// does not have to know whether a finalizer exists.
283 finally_label: Option<Label>,
284 /// Whether this is a labelled non-loop statement, which an unlabelled `break`
285 /// does not reach.
286 is_regular_stmt: bool,
287 /// Whether leaving this construct has to close an iterator.
288 ///
289 /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
290 /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
291 /// is dropped rather than closed.
292 has_iterator: bool,
293 /// Whether that iterator speaks the *async* protocol.
294 ///
295 /// An async close has to `await` the inner `return`, so it is an inline instruction
296 /// sequence rather than one opcode — the reference's `emit_iterator_close`.
297 is_async_iterator: bool,
298}
299
300/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
301///
302/// Both leave `source value` on the stack, so this is purely which spelling the reference
303/// picked, and it picked it by whether it had to build a *reference* for the target:
304///
305/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
306/// consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
307/// destructures);
308/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
309/// * a `var`, and any assignment target, go through `dup; get_field`, because the
310/// reference builds a reference for them — which is what `with` needs.
311fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
312 nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
313}
314
315/// Whether binding this pattern starts by boxing the value it was handed.
316fn nests_a_pattern(pattern: &Pattern) -> bool {
317 match &pattern.kind {
318 PatternKind::Array { .. } | PatternKind::Object { .. } => true,
319 PatternKind::Assign { target, .. } => nests_a_pattern(target),
320 _ => false,
321 }
322}
323
324/// `copy_data_properties` flags for an object-literal spread.
325///
326/// The byte packs three fields: the low bits are the stack offset of the source,
327/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
328/// as well as string keys. A spread passes a literal `null` exclusion list right
329/// below the source, so that field stays zero and only the source offset and the
330/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
331const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
332
333/// The expression a `...` introduces.
334///
335/// The parser marks the spread in two places — the element/property variant and an
336/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
337/// stepped through before the argument can be compiled.
338fn spread_argument(spread: &Expr) -> &Expr {
339 match &spread.kind {
340 ExprKind::Spread(inner) => inner,
341 _ => spread,
342 }
343}
344
345/// The flag byte `define_method` takes.
346///
347/// The low two bits pick value/getter/setter; bit 2 marks the property
348/// enumerable, which every object-literal method is.
349/// What kind of class constructor a function is being compiled as.
350///
351/// A constructor is not an ordinary method: a base one materialises `this` and refuses
352/// to run without `new`, and a derived one starts with `this` in the dead zone until
353/// `super()` produces it.
354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355enum CtorKind {
356 /// Not a class constructor.
357 None,
358 /// A constructor of a class without `extends`.
359 Base,
360 /// A constructor of a class with `extends`.
361 Derived,
362}
363
364/// The flag byte `define_method` takes for a class member.
365///
366/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
367/// a class method is *not* — that is the whole difference from an object-literal method,
368/// and the reason `Object.keys(C.prototype)` stays empty.
369fn class_method_flags(kind: MethodKind) -> i32 {
370 match kind {
371 MethodKind::Constructor | MethodKind::Method => 0,
372 MethodKind::Get => 1,
373 MethodKind::Set => 2,
374 }
375}
376
377fn define_method_flags(kind: PropertyKind) -> i32 {
378 let base = match kind {
379 PropertyKind::Value | PropertyKind::Method => 0,
380 PropertyKind::Get => 1,
381 PropertyKind::Set => 2,
382 };
383 base | 4
384}
385
386/// Convert a numeric property key to the text an atom would be made from.
387///
388/// `PropertyKey` of a number is `ToString(number)`, the same conversion every other place
389/// uses — so this goes through [`crate::number::number_to_string`] rather than formatting
390/// the value here. It used to accept only `[1e-6, 1e21)` and reject the rest, on the
391/// theory that Rust's `{}` and JavaScript's spelling diverge at the extremes; they do, and
392/// that is exactly why the spec's own algorithm is the thing to call. `get 0.0000001() {}`
393/// binds the key `"1e-7"`, and the rejection made it a `SyntaxError` instead.
394///
395/// The `Result` is kept because the call sites are in a `?` chain, and a key conversion
396/// that could still fail (a non-finite value from a source literal, which the lexer does
397/// not produce) belongs on the same path as the rest of a property name's errors.
398fn numeric_key_text(value: f64, _span: Span) -> Result<String, SyntaxError> {
399 Ok(crate::number::number_to_string(value))
400}
401
402/// Collect the operands of a same-operator logical run, in source order.
403///
404/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
405/// the caller appends `c`. A node with a different operator is one operand.
406fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
407 if let ExprKind::Logical {
408 op: inner_op,
409 left,
410 right,
411 } = &expr.kind
412 && *inner_op == op
413 {
414 collect_same_operator(op, left, out);
415 out.push(right);
416 return;
417 }
418 out.push(expr);
419}
420
421/// The jump a logical assignment or `??` takes when the value is kept.
422///
423/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
424/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
425/// the value when it is *not* null-ish, so it is the `if_false` side.
426fn logical_jump(op: AssignOp) -> Opcode {
427 match op {
428 AssignOp::Or => Opcode::IfTrue,
429 AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
430 _ => Opcode::IfFalse,
431 }
432}
433
434/// Whether a loop enumerates keys or values.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436enum ForLoopKind {
437 /// `for (x in o)` — the keys of an object.
438 In,
439 /// `for (x of o)` — the values of an iterable.
440 Of,
441 /// `for await (x of o)` — the values of an async iterable, or of a sync one.
442 AwaitOf,
443}
444
445/// Which part of a `try` statement a block key refers to.
446#[derive(Debug, Clone, Copy)]
447enum TryPart {
448 /// The guarded block.
449 Block = 0,
450 /// The handler body, excluding the catch parameter.
451 Catch = 1,
452 /// The finalizer block.
453 Finally = 2,
454 /// The catch parameter's own scope.
455 Param = 3,
456}
457
458/// A lexical scope, identified while hoisting and numbered at the end.
459///
460/// Scope identity is needed in two passes that must agree: declarations are
461/// hoisted in source order (so slots come out in source order, as in the
462/// reference), but a binding belongs to the block it was written in, which is only
463/// entered later. Blocks are therefore keyed by the source position of their
464/// opening brace, which is stable across both walks.
465#[derive(Debug, Clone, Copy)]
466struct Block {
467 /// Source position of the block.
468 key: u64,
469 /// The block this one is nested in; `0` for the function scope.
470 parent: u64,
471}
472
473/// One function under construction.
474struct FnState {
475 /// The function's own source range, used to record its text for
476 /// `Function.prototype.toString`.
477 span: Option<(usize, usize)>,
478 name: String,
479 kind: FunctionKind,
480 strict: bool,
481 args: Vec<VarDef>,
482 vars: Vec<VarDef>,
483 closure_vars: Vec<ClosureVar>,
484 cpool: Vec<Constant>,
485 atoms: Vec<Atom>,
486 /// Every lexical scope, in creation order.
487 blocks: Vec<Block>,
488 /// The block currently being parsed or compiled.
489 current_block: u64,
490 /// The block a *nested* function was created in, so a capture made from here can be
491 /// resolved against the enclosing function's lexical scopes rather than against a
492 /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
493 /// function's own `let S` instead of the class body's `const S`.
494 created_in_block: u64,
495 /// The block each local was declared in, parallel to `vars`. `0` means the
496 /// function scope, where `var` bindings live.
497 var_block: Vec<u64>,
498 /// Set when the expression just compiled left no value on the stack.
499 ///
500 /// Only a store can do that: `put_field` consumes the object and the value, so
501 /// an assignment whose result is unused emits nothing extra. The expression
502 /// statement then has nothing to drop.
503 no_value: bool,
504 /// Whether a label was placed since the last instruction was emitted.
505 ///
506 /// The `put`/`get` fold is only valid when the two are adjacent in the final
507 /// stream; a label in between means a jump can land on the read, so the store has
508 /// to keep consuming its value. A flag is enough and avoids having to reason about
509 /// which index a label recorded.
510 label_since_insn: bool,
511 /// Whether the value of the expression being compiled is thrown away.
512 ///
513 /// Only an expression *statement* discards its value, and only the outermost
514 /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
515 /// still has to produce a value. Consumed by [`Compiler::assign`], which is
516 /// the one construct whose bytecode depends on it.
517 discard_value: bool,
518 /// The block that holds the function body.
519 body_block: u64,
520 /// Head of each scope's binding chain, indexed by level. Filled in by
521 /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
522 block_heads: Vec<i32>,
523 /// Enclosing `break`/`continue` targets, innermost last.
524 jump_targets: Vec<JumpTarget>,
525 insns: Vec<Insn>,
526 labels: Vec<Option<usize>>,
527 /// Captured locals, which need a reference cell.
528 var_ref_count: u32,
529 line: u32,
530 column: u32,
531 /// Whether this is a script body. A script's top-level declarations create
532 /// global properties rather than locals, which is why they show up as
533 /// closure variables with `[global_decl]`.
534 is_script: bool,
535 /// Whether this is a module body.
536 ///
537 /// A module body is a script in every respect that matters here — no `arguments`,
538 /// no `this` of its own — but its top-level declarations are *module*-scoped
539 /// instead of global, which is what this flag changes.
540 is_module: bool,
541 /// Whether the function is an arrow, which never gets its own `arguments`.
542 is_arrow: bool,
543 /// The name a *named function expression* binds inside its own body.
544 /// How many parameters count towards `.length`.
545 defined_args: u32,
546 /// Parameters that are not a plain name, with the argument slot each came from.
547 param_prologue: Vec<(usize, Pattern)>,
548 /// What kind of class constructor this function is, if any.
549 ctor_kind: CtorKind,
550 /// Whether the class has instance fields, so the constructor has to run their
551 /// initialiser before it returns.
552 /// What the nested function about to be compiled should be told about its class.
553 class_ctor_pending: Option<CtorKind>,
554 /// Whether this function needs the hidden `this` local, because an arrow inside it
555 /// refers to `this`.
556 ///
557 /// An arrow has no `this` of its own, so the reference materialises the enclosing
558 /// function's receiver into a local and lets the arrow capture it as an ordinary
559 /// closure variable. Declaring the local is not enough on its own: the store that
560 /// fills it has to be prepended to the body, which is what this flag arranges.
561 needs_this_local: bool,
562 /// The same, for `arguments`.
563 needs_arguments_local: bool,
564 /// The same, for `new.target`.
565 needs_new_target_local: bool,
566 /// Whether the body already opens by filling a `this` local, which
567 /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
568 has_this_prologue: bool,
569 /// The same, for `<home_object>`: the object `super` resolves against.
570 ///
571 /// An arrow and a static block have no home object of their own — only the method or
572 /// initialiser they were written in does — so `super.x` inside one is a read of the
573 /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
574 /// by `special_object 4`, the same way `this` is.
575 needs_home_object_local: bool,
576 /// Whether this function has an `arguments` binding of its own.
577 ///
578 /// False for a class field initialiser and a static block: §15.7 puts them outside any
579 /// function, so `arguments` does not exist there and `eval('arguments')` inside one is a
580 /// `SyntaxError` rather than the caller's arguments object. The parser already enforces
581 /// that for written code; this carries the same fact to the `eval` call site, which has
582 /// to compile the eval'd source under the caller's restriction.
583 no_arguments_binding: bool,
584 /// The same, for `this.active_func`: the function `super()` constructs from.
585 ///
586 /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
587 /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
588 /// as a local of the enclosing function; an arrow that escaped the constructor
589 /// (`iter.return = () => super()`) then finds it in its closure even with the
590 /// constructor nowhere on the call stack.
591 needs_active_func_local: bool,
592 /// Hidden locals of the `with` blocks currently open, innermost last.
593 with_names: Vec<String>,
594 /// How many of [`FnState::with_names`] were already open when this function was
595 /// created, i.e. belong to an *enclosing* function.
596 ///
597 /// The distinction decides shadowing, and it is positional rather than lexical. A
598 /// `with` opened **inside** this function's body sits nearer than the function's own
599 /// environment, so it shadows even a `var` of this function:
600 /// `function f(){ with(o){ var v = 1 } }` writes `o.v`. A `with` opened **outside**
601 /// does not: `with(o){ function f(){ var v = 1 } }` writes `f`'s local `v`, because
602 /// `f`'s environment is the inner one. Treating both alike broke one family or the
603 /// other — `S12.10_A1.2` and `S12.10_A1.7` are these two cases.
604 inherited_with_names: usize,
605 /// Set while a with-guard is being emitted, so the guard's own accesses are not
606 /// wrapped in another guard.
607 emitting_with_guard: bool,
608 self_name: Option<String>,
609 /// Where the function body starts, in source order; see [`Function::body_start`].
610 body_start: (u32, u32),
611 /// Whether the body contains a *direct* `eval(...)` call.
612 ///
613 /// A direct eval sees every binding of the function that called it, including ones
614 /// no other code mentions. It also hands those bindings to any closure it creates,
615 /// which can outlive the function. Both need the bindings to live in cells, so this
616 /// flag makes the function treat all of them as captured.
617 has_direct_eval: bool,
618 /// Whether this function's body contains a direct `eval` **anywhere**, known before any
619 /// of it is compiled.
620 ///
621 /// [`Self::has_direct_eval`] is learned as the eval call is compiled, which is too late
622 /// for an lvalue that must be resolved *before* the right-hand side that contains the
623 /// eval. This one is seeded from the AST, so `x *= (eval("var x = 2"), 4)` knows to pin
624 /// the reference before it emits the read.
625 eval_can_declare: bool,
626 /// Whether the parameter list contains a default expression, which is what gives
627 /// the function a second variable environment (see [`PARAM_SCOPE`]).
628 has_parameter_expressions: bool,
629 /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
630 simple_parameter_list: bool,
631 /// Whether the instructions being emitted belong to the parameter list.
632 ///
633 /// References made here must not see the body's `var`s: the body has not run yet,
634 /// and the reference's own model keeps the two scopes apart.
635 in_params: bool,
636 /// Whether an arrow created in this function's parameter list needs the parameter
637 /// scope's `arguments` binding.
638 needs_param_arguments: bool,
639 /// Whether this function was *created* inside a parameter list.
640 ///
641 /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
642 /// arrow too. The name reference is the arrow's, but the scope it must not see
643 /// belongs to the function the arrow was born in.
644 created_in_params: bool,
645 /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
646 ///
647 /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
648 /// final while the body is still being compiled: a named function expression declares
649 /// its own name binding *after* the body, and that binding is exactly what
650 /// `eval("myfunc = 1")` has to find.
651 eval_sites: Vec<EvalSite>,
652 /// Direct `eval` call sites seen so far: where, and the block that was current.
653 pending_eval_sites: Vec<(Span, u64, bool, Vec<EvalPrivate>, bool)>,
654 /// Whether this body contains `await`.
655 ///
656 /// For a *module* this decides whether its body is an async function: top-level
657 /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
658 /// to survive to the compiled function rather than being a local of the compiler.
659 has_await: bool,
660 /// The module tables, when this body is a module.
661 ///
662 /// Only the top-level state ever has one: `export` and `import` are top-level
663 /// statements, so nothing nested can add to these tables.
664 module: Option<ModuleMeta>,
665 /// Whether the self-name prologue (`special_object 2` then the store) has been
666 /// emitted for this function.
667 ///
668 /// A *nested* function's lookup declares the binding early (see
669 /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
670 /// prologue is still needed — the binding existing is not the same as it being
671 /// initialised.
672 self_name_initialized: bool,
673 /// Whether the code emitted so far leaves the program's result on the stack.
674 /// The reference tracks this for the hidden `<ret>` local of an eval script.
675 leaves_value: bool,
676 /// Statement nesting depth, used to tell top-level statements apart.
677 stmt_depth: u32,
678 /// Function declarations waiting to be instantiated at scope entry, as
679 /// (target slot, constant pool index). The reference emits these from
680 /// `instantiate_hoisted_definitions` rather than at the statement, because a
681 /// declaration is visible before it is reached.
682 hoisted: Vec<(u64, HoistTarget, u32)>,
683 /// Function declarations whose bodies are compiled only once the enclosing scope
684 /// has finished hoisting, as (owning block, declaration).
685 ///
686 /// Compiling a body at the declaration makes the result depend on source order: in
687 /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
688 /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
689 /// names first and the bodies second is what removes that dependence.
690 deferred_funcs: Vec<(u64, Box<ast::Function>)>,
691 /// The source position of the node being compiled. Every instruction emitted
692 /// takes it, which is how the position table that feeds stack traces is built.
693 cur_pos: Option<Position>,
694 /// One position per entry in `insns`, index-aligned.
695 insn_pos: Vec<Option<Position>>,
696}
697
698/// Where a hoisted function declaration is stored.
699#[derive(Debug, Clone)]
700enum HoistTarget {
701 Arg(u32),
702 Loc(u32),
703 /// A global, which the resolver looks up by name.
704 Global(String),
705}
706
707impl FnState {
708 /// Whether this function suspends: a generator or an async function.
709 ///
710 /// A suspending function's `return` is a `return_async` and its body starts with an
711 /// `initial_yield`, so almost every statement that touches control flow asks this.
712 fn is_suspending(&self) -> bool {
713 self.kind.is_generator() || self.kind.is_async()
714 }
715
716 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
717 FnState {
718 span: None,
719 name: name.into(),
720 kind,
721 strict: false,
722 args: Vec::new(),
723 vars: Vec::new(),
724 closure_vars: Vec::new(),
725 cpool: Vec::new(),
726 atoms: Vec::new(),
727 blocks: Vec::new(),
728 current_block: 0,
729 created_in_block: NO_PARENT,
730 var_block: Vec::new(),
731 no_value: false,
732 label_since_insn: false,
733 discard_value: false,
734 body_block: 0,
735 block_heads: Vec::new(),
736 jump_targets: Vec::new(),
737 insns: Vec::new(),
738 labels: Vec::new(),
739 var_ref_count: 0,
740 line: 1,
741 column: 1,
742 is_script: false,
743 is_module: false,
744 is_arrow: false,
745 defined_args: 0,
746 param_prologue: Vec::new(),
747 ctor_kind: CtorKind::None,
748 class_ctor_pending: None,
749 needs_this_local: false,
750 needs_arguments_local: false,
751 needs_new_target_local: false,
752 has_this_prologue: false,
753 needs_home_object_local: false,
754 no_arguments_binding: false,
755 needs_active_func_local: false,
756 with_names: Vec::new(),
757 inherited_with_names: 0,
758 emitting_with_guard: false,
759 self_name: None,
760 has_direct_eval: false,
761 eval_can_declare: false,
762 body_start: (0, 0),
763 has_parameter_expressions: false,
764 simple_parameter_list: true,
765 in_params: false,
766 needs_param_arguments: false,
767 created_in_params: false,
768 eval_sites: Vec::new(),
769 pending_eval_sites: Vec::new(),
770 has_await: false,
771 module: None,
772 self_name_initialized: false,
773 leaves_value: false,
774 stmt_depth: 0,
775 hoisted: Vec::new(),
776 deferred_funcs: Vec::new(),
777 cur_pos: None,
778 insn_pos: Vec::new(),
779 }
780 }
781
782 /// The scope a declaration lands in: a script's top-level declarations are
783 /// globals, everything else gets a slot.
784 /// Whether a binding declared *now* becomes a property of the global object.
785 ///
786 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
787 /// The `var` case is decided by the keyword rather than by the cursor position:
788 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
789 /// binding as a `var i` in the body, even though the head has its own block.
790 fn declares_globally(&self, def: &VarDef) -> bool {
791 // A module's top-level declarations are *module*-scoped: they live in the module
792 // record, never on the global object. Two modules can both declare `var x`
793 // without seeing each other, which is the whole point.
794 if self.is_module {
795 return false;
796 }
797 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
798 }
799}
800
801/// The compiler's entry point.
802pub struct Compiler {
803 /// The text being compiled, kept so each function can record its own slice for
804 /// `Function.prototype.toString`.
805 source: Option<String>,
806 module: bool,
807 /// Whether the program itself is the body of an `async` function.
808 ///
809 /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
810 /// completion value is wrapped so a returned promise is not adopted.
811 async_body: bool,
812 /// Enclosing functions, outermost first. The last entry is the current one.
813 stack: Vec<FnState>,
814 /// The private names visible at this point, innermost class body last.
815 ///
816 /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
817 /// to the class body: a method, an arrow inside it and a class nested inside that arrow
818 /// all resolve against the same entries, and the parser accepts exactly that set
819 /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
820 /// class's names the moment a method started.
821 private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
822 /// Whether the expression [`Compiler::expr`] is about to compile is the one its
823 /// statement asked to discard.
824 ///
825 /// `FnState::discard_value` says "the statement's value is thrown away", which is only
826 /// ever true of the statement's own expression — an assignment nested inside it, as in
827 /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
828 /// keeping the answer here is what tells the two apart; without it the nested store
829 /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
830 /// function threw `undefined is not a function`.
831 discard_root: bool,
832}
833
834/// How a use site of a private name compiles.
835///
836/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
837/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
838/// of a setter-only accessor pair.
839#[derive(Clone, Copy, PartialEq, Eq)]
840enum PrivateKind {
841 /// `#x = 1`: an own property keyed by the symbol in the binding.
842 Field,
843 /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
844 Method,
845 /// `get #a() {}`: the binding holds the getter, and a read calls it.
846 Getter,
847 /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
848 /// the same `TypeError` as reading an uninitialised `const`.
849 Setter,
850}
851
852/// What the compiler knows about one `#name` where it is used.
853#[derive(Clone)]
854struct PrivateUse {
855 kind: PrivateKind,
856 /// `#a<set>` when the class defines a setter for this name.
857 ///
858 /// A second binding, not a second field of the first: the reference stores the setter
859 /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
860 setter: Option<String>,
861}
862
863/// The class-scope bindings one class body needs, in declaration order.
864#[derive(Default)]
865struct ClassPlan {
866 /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
867 /// at class entry, in member order.
868 bindings: Vec<String>,
869 /// The private names, for the use sites inside the body.
870 uses: std::collections::HashMap<String, PrivateUse>,
871 /// Computed field keys, by element index, so the emission pass does not have to redo the
872 /// per-half counter that names them.
873 computed: std::collections::HashMap<usize, String>,
874 /// Whether the instance initialiser has to add the brand to `this`.
875 instance_brand: bool,
876 /// Whether the constructor itself has to carry the brand.
877 static_brand: bool,
878}
879
880impl ClassPlan {
881 /// Walk a class body once and decide every class-scope binding it needs.
882 ///
883 /// Order is the reference's: a member's binding is created when the member is parsed, so
884 /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
885 /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
886 /// the disassembly stops matching even when every instruction is right.
887 fn build(class: &Class) -> ClassPlan {
888 let mut plan = ClassPlan::default();
889 let mut instance_keys = 0usize;
890 let mut static_keys = 0usize;
891 for (index, element) in class.elements.iter().enumerate() {
892 match element {
893 ClassElement::Method {
894 key: PropName::Private(ident),
895 kind,
896 is_static,
897 ..
898 } => {
899 let name = format!("#{}", ident.name);
900 let first = !plan.uses.contains_key(&name);
901 if first {
902 plan.bindings.push(name.clone());
903 plan.uses.insert(
904 name.clone(),
905 PrivateUse {
906 kind: match kind {
907 MethodKind::Get => PrivateKind::Getter,
908 MethodKind::Set => PrivateKind::Setter,
909 _ => PrivateKind::Method,
910 },
911 setter: None,
912 },
913 );
914 }
915 match kind {
916 MethodKind::Set => {
917 let binding = format!("{name}<set>");
918 plan.bindings.push(binding.clone());
919 if let Some(use_) = plan.uses.get_mut(&name) {
920 use_.setter = Some(binding);
921 }
922 }
923 // A getter is what makes the name readable, so a pair that started
924 // as a setter becomes readable once the getter arrives.
925 MethodKind::Get => {
926 if let Some(use_) = plan.uses.get_mut(&name) {
927 use_.kind = PrivateKind::Getter;
928 }
929 }
930 _ => {}
931 }
932 if *is_static {
933 plan.static_brand = true;
934 } else {
935 plan.instance_brand = true;
936 }
937 }
938 ClassElement::Method {
939 key: PropName::Computed(_),
940 ..
941 } => {}
942 ClassElement::Method { .. } => {}
943 ClassElement::Field {
944 key: PropName::Private(ident),
945 ..
946 } => {
947 let name = format!("#{}", ident.name);
948 if !plan.uses.contains_key(&name) {
949 plan.bindings.push(name.clone());
950 plan.uses.insert(
951 name,
952 PrivateUse {
953 kind: PrivateKind::Field,
954 setter: None,
955 },
956 );
957 }
958 }
959 ClassElement::Field {
960 key: PropName::Computed(_),
961 is_static,
962 ..
963 } => {
964 let index_in_half = if *is_static {
965 static_keys += 1;
966 static_keys - 1
967 } else {
968 instance_keys += 1;
969 instance_keys - 1
970 };
971 let binding = computed_field_binding(index_in_half, *is_static);
972 plan.bindings.push(binding.clone());
973 plan.computed.insert(index, binding);
974 }
975 ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
976 }
977 }
978 plan
979 }
980
981 /// How a private name used inside the body compiles, or `None` if no enclosing class
982 /// declares it.
983 fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
984 compiler
985 .private_scopes
986 .iter()
987 .rev()
988 .find_map(|scope| scope.get(name))
989 }
990}
991
992impl Compiler {
993 /// The exact source text of a function, for `Function.prototype.toString`.
994 ///
995 /// §20.2.3.5 requires the *original* text: a function must stringify back to what
996 /// was written, comments and odd spacing included. Slicing the recorded span out of
997 /// the whole source is the only way to get that — rebuilding it from the AST would
998 /// normalise the text, and answering `[native code]` for a script function (which is
999 /// what this engine used to do) makes the result useless for feature detection and
1000 /// for libraries that read their own source.
1001 ///
1002 /// Top-level bodies have no single expression span, so their `source` stays `None`
1003 /// and `toString` falls back to the calling convention the spec allows.
1004 fn function_source(
1005 &self,
1006 span: Option<(usize, usize)>,
1007 line: u32,
1008 column: u32,
1009 ) -> Option<String> {
1010 let source = self.source.as_ref()?;
1011 let span = span?;
1012 let bytes = source.as_bytes();
1013 let start = span.0;
1014 let end = span.1;
1015 if start >= bytes.len() || end > bytes.len() || start >= end {
1016 let _ = (line, column);
1017 return None;
1018 }
1019 Some(source.get(start..end)?.to_string())
1020 }
1021}
1022
1023/// Compile a script.
1024pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1025 Compiler::new(false).compile(program)
1026}
1027
1028/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
1029/// the original source.
1030///
1031/// The separate entry point rather than a parameter on [`compile_script`] because the
1032/// tests and the disassembler compile from an AST they built themselves and have no
1033/// source to give; they keep the `None` behaviour they already relied on.
1034pub fn compile_script_with_source(
1035 program: &Program,
1036 source: &str,
1037) -> Result<CompiledFunction, SyntaxError> {
1038 let mut compiler = Compiler::new(false);
1039 compiler.source = Some(source.to_string());
1040 compiler.compile(program)
1041}
1042
1043/// [`compile_script_with_source`] for a module.
1044pub fn compile_module_with_source(
1045 program: &Program,
1046 source: &str,
1047) -> Result<CompiledFunction, SyntaxError> {
1048 let mut compiler = Compiler::new(true);
1049 compiler.source = Some(source.to_string());
1050 compiler.compile(program)
1051}
1052
1053/// Compile a script whose top level is the body of an `async` function.
1054/// The body is an ordinary script in every other way — it still reports a completion value
1055/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1056/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1057/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1058/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1059/// documents.
1060pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1061 Compiler::for_suspensible_script().compile(program)
1062}
1063
1064/// Compile a module.
1065pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1066 Compiler::new(true).compile(program)
1067}
1068
1069/// Compile a direct `eval` body that inherits private names from its caller.
1070///
1071/// `class C { #m = 44; f() { return eval("this.#m") } }` is legal — private names are
1072/// lexically scoped and the eval runs inside the caller's scope — but the names live in the
1073/// *call site's* compilation unit, so they have to be handed over. Seeding them as the
1074/// outermost private scope is what lets the eval resolve `#m` to the caller's binding: the
1075/// read compiles as an ordinary name lookup of `#m`, which at run time finds the caller's
1076/// slot through the same `eval`-scope machinery every other inherited name uses.
1077///
1078/// `suspensible` selects the `{async: true}` form (`std.evalScript(s, {async: true})`), whose
1079/// body may `await`.
1080pub fn compile_eval_with_private(
1081 program: &Program,
1082 private: &[EvalPrivate],
1083 suspensible: bool,
1084) -> Result<CompiledFunction, SyntaxError> {
1085 let mut compiler = if suspensible {
1086 Compiler::for_suspensible_script()
1087 } else {
1088 Compiler::new(false)
1089 };
1090 if !private.is_empty() {
1091 let scope: std::collections::HashMap<String, PrivateUse> = private
1092 .iter()
1093 .map(|entry| {
1094 (
1095 entry.name.clone(),
1096 PrivateUse {
1097 kind: match entry.kind {
1098 EvalPrivateKind::Field => PrivateKind::Field,
1099 EvalPrivateKind::Method => PrivateKind::Method,
1100 EvalPrivateKind::Getter => PrivateKind::Getter,
1101 EvalPrivateKind::Setter => PrivateKind::Setter,
1102 },
1103 setter: entry.setter.clone(),
1104 },
1105 )
1106 })
1107 .collect();
1108 compiler.private_scopes.push(scope);
1109 }
1110 compiler.compile(program)
1111}
1112
1113impl Compiler {
1114 /// Create a compiler.
1115 pub fn new(module: bool) -> Compiler {
1116 Compiler {
1117 source: None,
1118 module,
1119 async_body: false,
1120 stack: Vec::new(),
1121 private_scopes: Vec::new(),
1122 discard_root: false,
1123 }
1124 }
1125
1126 /// Create a compiler for a script whose top level is an `async` function body.
1127 fn for_suspensible_script() -> Compiler {
1128 Compiler {
1129 source: None,
1130 module: false,
1131 async_body: true,
1132 stack: Vec::new(),
1133 private_scopes: Vec::new(),
1134 discard_root: false,
1135 }
1136 }
1137
1138 /// Compile a whole program into its top-level function.
1139 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1140 let mut state = FnState::new("<eval>", FunctionKind::Normal);
1141 // A module body is *not* a script: it has no completion value, so no hidden
1142 // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1143 // is having no `arguments` of its own and no receiver — see `is_module`.
1144 state.is_script = !self.module;
1145 state.is_module = self.module;
1146 if self.module {
1147 state.module = Some(ModuleMeta::default());
1148 }
1149 state.strict = program.strict || self.module;
1150 state.line = program.span.start.line;
1151 state.column = program.span.start.column;
1152 // Locals are numbered in declaration order; `<ret>` is always slot 0.
1153 //
1154 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1155 // slot that only appears in one of the two arrays shifts every later
1156 // binding's block and silently loses the temporal-dead-zone marking for
1157 // the script's own blocks. A function frame has no `<ret>`, which is why
1158 // the misalignment only showed up at the top level.
1159 if !self.module {
1160 state.vars.push(VarDef::var("<ret>"));
1161 state.var_block.push(FUNCTION_SCOPE);
1162 }
1163 self.stack.push(state);
1164 // The body is its own scope, keyed by the position of the program.
1165 // The script body needs a key no statement can produce. Statement keys are
1166 // source offsets, and the program's own start offset is `0` — which is also
1167 // the offset of the first statement, so a top-level `{ let x }` or
1168 // `for (let i …)` used to share the body's block and lose its scope.
1169 let body_key = SCRIPT_BODY;
1170 self.push_block(body_key, NO_PARENT);
1171 self.state().body_block = body_key;
1172 // A module body opens with a re-entry guard. The host evaluates a module exactly
1173 // once, so the guard never fires in practice — but the reference emits it, and a
1174 // module function called a second time (through `eval` of its own source, say)
1175 // must not run its body again.
1176 let module_guard = self.module.then(|| self.new_label());
1177 if let Some(body) = module_guard {
1178 // The guard wraps the *hoisting* too: a second evaluation of the same module
1179 // body must not even re-create its function declarations.
1180 self.emit(Opcode::PushThis, &[]);
1181 self.emit_jump(Opcode::IfFalse, body, &[]);
1182 }
1183 self.hoist(&program.body, body_key)?;
1184 // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1185 // come before the guard's `return_undef`: the reference's jump target sits past
1186 // both, and a second evaluation therefore re-creates nothing.
1187 self.emit_scope_enter(body_key);
1188 if let Some(body) = module_guard {
1189 self.emit(Opcode::ReturnUndef, &[]);
1190 self.place_label(body);
1191 }
1192 // Through `stmts` rather than the loop, so a `using` region at the top level of an
1193 // eval'd body or a module gets its disposal epilogue like any other block.
1194 self.stmts(&program.body)?;
1195 if self.module {
1196 // A module has no completion value; its body simply ends.
1197 self.emit(Opcode::Undefined, &[]);
1198 self.emit(Opcode::ReturnAsync, &[]);
1199 // Top-level `await` makes the body an async function, so the host runs it as
1200 // a coroutine and waits. Without this the `await` opcode would suspend in a
1201 // body that nothing knows how to resume — which is what "a generator body ran
1202 // as an ordinary call" was reporting.
1203 if self.cur().has_await {
1204 self.state().kind = FunctionKind::Async;
1205 }
1206 } else if self.async_body {
1207 // An async body reports its completion value the same way, but through an
1208 // object: the function answers a promise, and resolving that promise *with*
1209 // the completion value would adopt a promise completion instead of reporting
1210 // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1211 // resolve to `{value: <promise>}` rather than to `7`.
1212 //
1213 // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1214 // value in an object so that promises can be safely returned").
1215 self.emit(Opcode::Object, &[]);
1216 self.emit(Opcode::Dup, &[]);
1217 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1218 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1219 self.emit(Opcode::Return, &[]);
1220 self.state().kind = FunctionKind::Async;
1221 } else {
1222 // The program's value is whatever the last expression statement stored in
1223 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1224 // case into a single `set_loc0`.
1225 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1226 self.emit(Opcode::Return, &[]);
1227 }
1228 Ok(self.finish_current())
1229 }
1230
1231 // -- emitting ----------------------------------------------------------
1232
1233 fn state(&mut self) -> &mut FnState {
1234 self.stack.last_mut().expect("a function is being compiled")
1235 }
1236
1237 fn cur(&self) -> &FnState {
1238 self.stack.last().expect("a function is being compiled")
1239 }
1240
1241 fn emit(&mut self, op: Opcode, operands: &[Op]) {
1242 self.state().label_since_insn = false;
1243 let pos = self.cur().cur_pos;
1244 self.state().insns.push(Insn::Fixed {
1245 op,
1246 operands: operands.to_vec(),
1247 });
1248 self.state().insn_pos.push(pos);
1249 }
1250
1251 /// Reset the script's hidden return value to `undefined`.
1252 ///
1253 /// Called at the start of every statement that does not itself produce the
1254 /// program's value, which is how the reference keeps `if`/loop results from
1255 /// leaking into an eval result.
1256 fn reset_value(&mut self) {
1257 if !self.cur().is_script {
1258 return;
1259 }
1260 self.emit(Opcode::Undefined, &[]);
1261 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1262 self.state().leaves_value = false;
1263 }
1264
1265 /// Whether `name` is a local or argument slot rather than a global.
1266 fn is_slot(&self, name: &str) -> bool {
1267 self.cur().vars.iter().any(|v| v.name == name)
1268 || self.cur().args.iter().any(|a| a.name == name)
1269 }
1270
1271 /// `with (object) body`
1272 ///
1273 /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1274 /// what makes the object reachable from a closure created inside the block, and it
1275 /// is also what lets an `eval` find it: the runtime collects the active `With`
1276 /// locals of every frame and resolves names against them before the realm.
1277 ///
1278 /// Inside the block every name reference is spelled as "look in the with objects
1279 /// first", innermost outwards, and falls through to the ordinary access. The test is
1280 /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1281 /// Record asks.
1282 fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1283 // `with (e) s` completes with `UpdateEmpty(s, undefined)` — an *empty* body still
1284 // produces `undefined`, it does not inherit the previous statement's value. So
1285 // `eval("1; with({}){}")` is `undefined` while `eval("1; with({}){2;}")` is `2`.
1286 // Without this the sticky `<ret>` local leaked the `1` through, the same way it
1287 // would for an `if` or a loop.
1288 self.reset_value();
1289 let name = self.next_with_name();
1290 // The object expression is evaluated *outside* the scope it introduces, so no
1291 // wrapper may be emitted for the names it mentions.
1292 let saved = std::mem::take(&mut self.state().with_names);
1293 self.expr(object)?;
1294 self.state().with_names = saved;
1295 self.emit(Opcode::ToObject, &[]);
1296 self.declare_hidden_local(&name, VarKind::With);
1297 // Pushed before the store so the store itself is not guarded by an *outer*
1298 // `with` — the object being stored is the new one, not something to look up.
1299 self.state().with_names.push(name.clone());
1300 self.emit_var(VarAction::Put, &name);
1301 let result = self.stmt(body);
1302 self.state().with_names.pop();
1303 result
1304 }
1305
1306 /// A hidden-local name for one `with` block, distinct from every enclosing one.
1307 fn next_with_name(&self) -> String {
1308 let depth = self.cur().with_names.len();
1309 if depth == 0 {
1310 "<with>".to_string()
1311 } else {
1312 format!("<with{depth}>")
1313 }
1314 }
1315
1316 /// Declare a hidden local that must stay a *local* even in a script.
1317 ///
1318 /// A script's `var` is a property of the global object, but the `with` object is not
1319 /// part of the source program's name space at all — it only exists for the compiler
1320 /// and the runtime — so it goes straight into the frame's slot list.
1321 fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1322 let state = self.state();
1323 if state.vars.iter().any(|v| v.name == name) {
1324 return;
1325 }
1326 state.var_block.push(FUNCTION_SCOPE);
1327 state.vars.push(VarDef {
1328 kind,
1329 ..VarDef::var(name)
1330 });
1331 }
1332
1333 /// Emit a name access, guarded by every active `with` object.
1334 ///
1335 /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1336 /// the read itself; the outer guards and the plain access are what the `if_false`
1337 /// jumps to, so the innermost object wins.
1338 fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1339 let names = self.visible_with_names(name);
1340 let done = self.new_label();
1341 let mut starts = Vec::new();
1342 // Innermost object first: the last `with` opened is the one that shadows the
1343 // others, so its guard has to be the first chance to satisfy the name.
1344 for with_name in names.iter().rev() {
1345 let next = self.new_label();
1346 // `with_has_var` takes the object and carries the name as an atom. It is not
1347 // `in`: an Object Environment Record also consults `Symbol.unscopables`, so
1348 // `globalThis[Symbol.unscopables] = {v: true}` leaves `v` to the outer scope.
1349 self.emit_var(VarAction::Get, with_name);
1350 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1351 self.emit_jump(Opcode::IfFalse, next, &[]);
1352 starts.push(next);
1353 // The operation is `with_get_var`/`with_put_var`, not a plain property access:
1354 // `GetBindingValue`/`SetMutableBinding` ask `HasProperty` **again** before
1355 // getting or setting. That second question is observable — a proxy's `has`
1356 // trap runs one more time (`get-binding-value-call-with-proxy-env` logs
1357 // `has, get unscopables, has, get`) and an `unscopables` getter that deletes
1358 // the property leaves a binding that has gone, which strict code must report
1359 // as a `ReferenceError` rather than write to.
1360 match action {
1361 // A store already has its value on the stack, and `with_put_var` takes the
1362 // pair in `put_field`'s order: object first, then the value.
1363 VarAction::Put | VarAction::PutInit => {
1364 self.emit_var(VarAction::Get, with_name);
1365 self.emit(Opcode::Swap, &[]);
1366 self.emit(Opcode::WithPutVar, &[Op::Atom(Atom::from_text(name))]);
1367 }
1368 _ => {
1369 self.emit_var(VarAction::Get, with_name);
1370 self.emit(Opcode::WithGetVar, &[Op::Atom(Atom::from_text(name))]);
1371 }
1372 }
1373 self.emit_jump(Opcode::Goto, done, &[]);
1374 self.place_label(next);
1375 }
1376 self.emit_var(action, name);
1377 self.place_label(done);
1378 }
1379
1380 /// The `with` blocks that can shadow `name`, innermost last.
1381 ///
1382 /// A parameter or a local of this function is *inside* every `with` this function
1383 /// opened, so those shadow it; a `with` that was already open when this function was
1384 /// created is outside the function's own environment, so the local wins and that
1385 /// block is skipped. See [`FnState::inherited_with_names`].
1386 fn visible_with_names(&self, name: &str) -> Vec<String> {
1387 let state = self.cur();
1388 // The hidden `<with…>` locals are how the guard reaches its own objects, so they
1389 // must never be guarded themselves — not by their own block (which would recurse)
1390 // and not by an enclosing one (which would ask a `with` object whether it has a
1391 // property called `<with>`, always answer no, and waste the chain). Source can
1392 // never spell these names, so exempting all of them changes nothing else.
1393 if state.with_names.iter().any(|hidden| hidden == name) {
1394 return Vec::new();
1395 }
1396 let start = if self.is_slot(name) {
1397 state.inherited_with_names
1398 } else {
1399 0
1400 };
1401 state.with_names[start..]
1402 .iter()
1403 .filter(|hidden| hidden.as_str() != name)
1404 .cloned()
1405 .collect()
1406 }
1407
1408 /// Compile `x` as a **reference** to the with object's property, resolving the object
1409 /// once for the whole read-modify-write.
1410 ///
1411 /// `x += 1`, `x++` and `x ||= v` read and then write the same name. Two independent
1412 /// guards get that wrong the moment the read changes the answer: with
1413 /// `{ get x(){ delete this.x; return 2 } }`, `with (o) { x++ }` reads through the
1414 /// getter — which removes the property — and then the write's own guard no longer
1415 /// finds it, so the store landed on the *global* `x` and `o.x` stayed `undefined`. The
1416 /// reference resolves the base once (`with_make_ref`) and reuses it for both halves.
1417 ///
1418 /// The same shape comes out of compiling the name as a **member** of the with object:
1419 /// `get_field2`/`put_field` already evaluate their receiver once, and the hidden
1420 /// `<with>` local holds exactly the object the guard just tested. So each candidate
1421 /// object gets `if the name is bound here, compile as `this.name`; otherwise fall
1422 /// through to the next object`, and the last fallback is the ordinary name.
1423 fn with_reference(
1424 &mut self,
1425 name: &str,
1426 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1427 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1428 ) -> Result<(), SyntaxError> {
1429 let targets = self.visible_with_names(name);
1430 if targets.is_empty() {
1431 return plain(self);
1432 }
1433 let done = self.new_label();
1434 let result = self.with_reference_inner(name, &targets, guarded, plain, done);
1435 self.place_label(done);
1436 result
1437 }
1438
1439 fn with_reference_inner(
1440 &mut self,
1441 name: &str,
1442 targets: &[String],
1443 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1444 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1445 done: Label,
1446 ) -> Result<(), SyntaxError> {
1447 let Some((innermost, outer)) = targets.split_last() else {
1448 return plain(self);
1449 };
1450 let next = self.new_label();
1451 self.emit_var(VarAction::Get, innermost);
1452 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1453 self.emit_jump(Opcode::IfFalse, next, &[]);
1454 guarded(self, innermost)?;
1455 self.emit_jump(Opcode::Goto, done, &[]);
1456 self.place_label(next);
1457 self.with_reference_inner(name, outer, guarded, plain, done)
1458 }
1459
1460 /// `delete name`, honouring any enclosing `with`.
1461 ///
1462 /// Inside a `with` the name may be a property of the with object, and then `delete`
1463 /// removes *that* property instead of touching the outer binding —
1464 /// `with (o) { delete p }` answers `true` and leaves `o` without `p` even when a
1465 /// global `p` exists. Left to the resolver it deleted the global instead, so the
1466 /// `statements/with/S12.10_A1.*` family then saw a `ReferenceError` on every later
1467 /// `p`.
1468 ///
1469 /// Emitted as a sequence here rather than during resolution because a resolution slot
1470 /// holds one instruction, and this is a loop over the with objects plus a fallback.
1471 fn delete_ident(&mut self, name: &str) {
1472 let names = self.cur().with_names.clone();
1473 let done = self.new_label();
1474 let mut starts = Vec::new();
1475 if !names.is_empty() {
1476 self.state().emitting_with_guard = true;
1477 // Innermost object first, like the read/write guard: the last `with` opened is
1478 // the one that shadows the others.
1479 for with_name in names.iter().rev() {
1480 let next = self.new_label();
1481 self.emit_var(VarAction::Get, with_name);
1482 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1483 self.emit_jump(Opcode::IfFalse, next, &[]);
1484 // `delete` takes the receiver then the key.
1485 self.emit_var(VarAction::Get, with_name);
1486 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1487 self.emit(Opcode::Delete, &[]);
1488 self.emit_jump(Opcode::Goto, done, &[]);
1489 self.place_label(next);
1490 starts.push(next);
1491 }
1492 self.state().emitting_with_guard = false;
1493 }
1494 // The fallback: not a property of any with object, so the ordinary rule applies.
1495 let pos = self.cur().cur_pos;
1496 self.state().insns.push(Insn::DeleteVar {
1497 name: name.to_string(),
1498 });
1499 self.state().insn_pos.push(pos);
1500 if !names.is_empty() {
1501 self.place_label(done);
1502 }
1503 }
1504
1505 fn emit_var(&mut self, action: VarAction, name: &str) {
1506 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1507 // stores and keeps the value in one instruction. The reference does this
1508 // in a post-pass; folding it at emit time keeps instruction indices
1509 // stable, which matters because labels are recorded as indices.
1510 //
1511 // Only slots have a `set_` form: a global is stored with `put_var` and
1512 // read with `get_var`, and the reference does not fold those.
1513 //
1514 // A label between the two cancels the fold. `set_x v` leaves the value on
1515 // the stack, which is only equivalent when the read immediately follows the
1516 // store; when a jump target sits in between, the store must *consume* the
1517 // value and the read must fetch it afresh. A loop head is exactly that
1518 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1519 // condition re-reads it — and folding across the label would make the
1520 // condition compare whatever the previous iteration left on the stack.
1521 if action == VarAction::Get {
1522 let is_slot = self.is_slot(name);
1523 let at_label = std::mem::take(&mut self.state().label_since_insn);
1524 //
1525 // `arguments` is excluded because the reference treats it as a special
1526 // binding: it is initialised once and read many times, and folding its
1527 // initialisation into a `set_` would leave the object on the stack where
1528 // the reference leaves nothing.
1529 if is_slot
1530 && name != "arguments"
1531 && !at_label
1532 && let Some(Insn::Var {
1533 action: previous,
1534 name: previous_name,
1535 ..
1536 }) = self.state().insns.last_mut()
1537 && *previous == VarAction::Put
1538 && previous_name == name
1539 {
1540 *previous = VarAction::Set;
1541 return;
1542 }
1543 }
1544 // Inside a `with`, every name lookup consults the with objects first. Two names
1545 // are exempt:
1546 //
1547 // * the hidden `<with…>` locals themselves, or the guard would recurse;
1548 // * a name this function **declares** — a parameter, a `var`, or a `let` of the
1549 // current body. `with` sits *outside* the function's own environment, so a
1550 // function declared inside a `with` still resolves its own bindings first:
1551 // `with (o) { function f(){ var value = "x" } }` writes `f`'s local `value`, not
1552 // `o.value`. Guarding it anyway wrote through to the with object whenever it
1553 // happened to have the name, which is why
1554 // `statements/with/S12.10_A1.7` saw `myObj.value` change. The runtime's
1555 // `eval_binding_value` already models the same order.
1556 let guarded = !self.visible_with_names(name).is_empty()
1557 && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1558 && !self.state().emitting_with_guard;
1559 if guarded {
1560 self.state().emitting_with_guard = true;
1561 self.emit_with_guarded(action, name);
1562 self.state().emitting_with_guard = false;
1563 return;
1564 }
1565 let block = self.cur().current_block;
1566 self.state().label_since_insn = false;
1567 let pos = self.cur().cur_pos;
1568 let in_params = self.cur().in_params;
1569 self.state().insns.push(Insn::Var {
1570 action,
1571 name: name.to_string(),
1572 block,
1573 in_params,
1574 });
1575 self.state().insn_pos.push(pos);
1576 }
1577
1578 fn new_label(&mut self) -> Label {
1579 let state = self.state();
1580 state.labels.push(None);
1581 Label(state.labels.len() as u32 - 1)
1582 }
1583
1584 fn place_label(&mut self, label: Label) {
1585 let index = self.cur().insns.len();
1586 self.state().label_since_insn = true;
1587 self.state().labels[label.0 as usize] = Some(index);
1588 }
1589
1590 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1591 let mut operands = vec![Op::Label(label)];
1592 operands.extend_from_slice(extra);
1593 self.emit(op, &operands);
1594 }
1595
1596 // -- scopes ------------------------------------------------------------
1597
1598 /// Start a new lexical scope inside `parent`.
1599 fn push_block(&mut self, key: u64, parent: u64) {
1600 let state = self.state();
1601 if !state.blocks.iter().any(|b| b.key == key) {
1602 state.blocks.push(Block { key, parent });
1603 }
1604 state.current_block = key;
1605 }
1606
1607 /// Emit the code that runs when a lexical scope is entered.
1608 ///
1609 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1610 /// so entering its block marks it uninitialised. Hoisted function
1611 /// declarations are created here instead, which is why a call before the
1612 /// declaration still works.
1613 ///
1614 /// The order is not obvious: bindings are emitted in *reverse* declaration
1615 /// order, because the reference walks its scope chain, which is built by
1616 /// prepending.
1617 fn emit_scope_enter(&mut self, block: u64) {
1618 // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1619 // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1620 // so entering an outer scope threw away every nested block's function
1621 // declarations: `function h(){ { function k(){} } return k; }` answered
1622 // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1623 // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1624 // in a block is also a `var` of the enclosing function), and it is what makes the
1625 // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1626 let mut hoisted = std::mem::take(&mut self.state().hoisted);
1627 let mut rest = Vec::with_capacity(hoisted.len());
1628 let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1629 for (owner, target, pool_index) in hoisted.drain(..) {
1630 if owner == block {
1631 mine.push((target, pool_index));
1632 } else {
1633 rest.push((owner, target, pool_index));
1634 }
1635 }
1636 self.state().hoisted = rest;
1637 mine.sort_by_key(|(target, _)| match target {
1638 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1639 HoistTarget::Global(_) => u32::MAX,
1640 });
1641 for (target, pool_index) in mine {
1642 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1643 match target {
1644 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1645 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1646 HoistTarget::Global(name) => {
1647 // A global binding lives in a reference cell, so the store
1648 // goes through `put_var_ref` while reads use `get_var`.
1649 let block = self.cur().current_block;
1650 let pos = self.cur().cur_pos;
1651 let in_params = self.cur().in_params;
1652 self.state().insns.push(Insn::Var {
1653 action: VarAction::PutRef,
1654 name,
1655 block,
1656 in_params,
1657 });
1658 self.state().insn_pos.push(pos);
1659 }
1660 }
1661 }
1662 for index in self.block_vars_reversed(block) {
1663 self.emit(
1664 Opcode::SetLocUninitialized,
1665 &[Op::Slot(Slot::Loc(index as u32))],
1666 );
1667 }
1668 }
1669
1670 /// Emit the code that runs when a lexical scope is exited.
1671 ///
1672 /// A captured binding has to be closed: detaching its reference cell freezes
1673 /// the value the binding had when the block ended, which is what a closure
1674 /// created inside the block must keep seeing.
1675 fn emit_scope_leave(&mut self, block: u64) {
1676 for index in self.block_vars_reversed(block) {
1677 if self.cur().vars[index].is_captured {
1678 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1679 }
1680 }
1681 }
1682
1683 /// Locals declared in `block`, in reverse declaration order.
1684 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1685 let state = self.cur();
1686 let mut out: Vec<usize> = (0..state.vars.len())
1687 .filter(|index| {
1688 state.var_block.get(*index).copied() == Some(block)
1689 && state.vars[*index].is_lexical
1690 // A derived constructor's `this` is lexical but is not initialised by
1691 // entering the scope: `check_ctor` proves it, so its dead-zone marker
1692 // was emitted with the constructor's own prologue.
1693 && state.vars[*index].name != "this"
1694 })
1695 .collect();
1696 out.reverse();
1697 out
1698 }
1699
1700 /// Declare a local, even at the top level of a script.
1701 ///
1702 /// A `catch` parameter is always a local: the reference puts it in the
1703 /// function's own variable list (`1: catch e`), never in the global object,
1704 /// because it only exists while the handler runs.
1705 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1706 let state = self.state();
1707 let index = state.vars.len() as u32;
1708 // A `catch` parameter belongs to a scope even though it is not lexical: the
1709 // runtime instantiates it per handler entry, but it never sits in the
1710 // temporal dead zone.
1711 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1712 state.current_block
1713 } else {
1714 0
1715 };
1716 state.var_block.push(block);
1717 state.vars.push(def);
1718 index
1719 }
1720
1721 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1722 if self.cur().is_module
1723 && self.cur().current_block == self.cur().body_block
1724 && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1725 {
1726 // Only the body's own block: a `let` inside a module-level `{}` is still an
1727 // ordinary local of that block, not a module variable.
1728 //
1729 // A `using` binding is excluded on purpose, and the reference excludes it in
1730 // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1731 // "'using' variables are currently not exported in modules"): a module-level
1732 // `using` is an ordinary *local* of the module body function, not a module
1733 // cell. Two things follow, and both are what the reference does — `export {a}`
1734 // of a `using` binding is "exported variable 'a' does not exist", and
1735 // disposal works, because the disposal epilogue addresses locals by slot.
1736 //
1737 // The hidden dispose-method variable is excluded for a stronger reason: it is
1738 // *always* a local (`add_scope_var` in the reference), and it must sit
1739 // immediately after its value so `using_dispose` can find it at `slot + 1`.
1740 return self.declare_module(name, &def);
1741 }
1742 if self.cur().declares_globally(&def) {
1743 self.declare_global(name, &def);
1744 return 0;
1745 }
1746 let state = self.state();
1747 let index = state.vars.len() as u32;
1748 let block = if def.is_lexical {
1749 state.current_block
1750 } else {
1751 0
1752 };
1753 state.var_block.push(block);
1754 state.vars.push(def);
1755 index
1756 }
1757
1758 /// Declare a `using` binding and its cached dispose method, returning both slots.
1759 ///
1760 /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1761 /// `(value, value + 1)` — the reference does the same and documents the constraint.
1762 fn declare_using(&mut self, name: &str) -> (u32, u32) {
1763 let mut def = VarDef::lexical(name);
1764 def.kind = VarKind::Using;
1765 // A `using` binding is immutable, exactly like a `const`: assigning to one is a
1766 // `TypeError` at run time, which is what `using-invalid-assignment-*-for` assert.
1767 // `VarDef::lexical` leaves `is_const` false, so the store would have landed.
1768 def.is_const = true;
1769 let value = self.declare(name, def);
1770 let mut method = VarDef::lexical(using_method_name(name));
1771 method.kind = VarKind::UsingMethod;
1772 let method_slot = self.declare(&using_method_name(name), method);
1773 (value, method_slot)
1774 }
1775
1776 /// The slot a `using` binding's dispose method lives in.
1777 fn using_method_slot(&self, name: &str) -> Option<u32> {
1778 let hidden = using_method_name(name);
1779 self.cur()
1780 .vars
1781 .iter()
1782 .position(|var| var.name == hidden)
1783 .map(|index| index as u32)
1784 }
1785
1786 // -- statements --------------------------------------------------------
1787
1788 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1789 self.stmt_labelled(stmt, &[])
1790 }
1791
1792 /// Compile a statement that a chain of labels names.
1793 ///
1794 /// Only a loop consumes `labels`; every other statement ignores them (the
1795 /// parser has already rejected a label on a statement that cannot use it).
1796 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1797 // Only a *top-level* expression statement supplies the program's value.
1798 let saved = self.cur().leaves_value;
1799 self.state().leaves_value =
1800 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1801 self.state().stmt_depth += 1;
1802 let result = self.stmt_inner(stmt, labels);
1803 self.state().stmt_depth -= 1;
1804 // A nested statement never contributes the program's value, so the flag
1805 // the wrapper set above is what survives.
1806 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1807 self.state().leaves_value = produced;
1808 let _ = saved;
1809 result
1810 }
1811
1812 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1813 match &stmt.kind {
1814 StmtKind::Empty | StmtKind::Debugger => {}
1815 StmtKind::Expr(expr) => {
1816 // The statement's first token is a position the reference records: an
1817 // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1818 // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1819 // is why an error from a construct with no position of its own (`[...it]`
1820 // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1821 let saved = self.cur().cur_pos;
1822 self.state().cur_pos = Some(expr.span.start);
1823 // An expression statement's value is thrown away — except in a
1824 // script, where it becomes the program's result. `assign` reads this
1825 // and clears it, so a nested assignment still produces a value.
1826 self.state().discard_value = !self.cur().is_script;
1827 let result = self.expr(expr);
1828 self.state().discard_value = false;
1829 result?;
1830 if std::mem::take(&mut self.state().no_value) {
1831 // A store whose value was discarded left nothing to drop.
1832 } else if self.cur().is_script {
1833 // The program's value lands in the hidden `<ret>` local.
1834 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1835 } else {
1836 self.emit(Opcode::Drop, &[]);
1837 }
1838 // Restored last: the trailing `drop` is part of the statement, and in the
1839 // reference it simply inherits whatever the expression last recorded.
1840 self.state().cur_pos = saved;
1841 }
1842 StmtKind::Block(body) => {
1843 // The block's declarations were hoisted with its enclosing
1844 // statement list, so there is nothing left to declare here.
1845 let key = stmt.span.start.offset as u64;
1846 let parent = self.cur().current_block;
1847 self.push_block(key, parent);
1848 self.emit_scope_enter(key);
1849 // A block is where a `using` region lives, so its statements have to go
1850 // through `stmts`: that is what emits the disposal epilogue.
1851 self.stmts(body)?;
1852 self.emit_scope_leave(key);
1853 self.state().current_block = parent;
1854 }
1855 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1856 // A function declaration was already instantiated when its scope was
1857 // entered, so the statement itself emits nothing.
1858 StmtKind::FuncDecl(_) => {}
1859 StmtKind::If { test, cons, alt } => {
1860 self.reset_value();
1861 let else_label = self.new_label();
1862 let end_label = self.new_label();
1863 self.expr(test)?;
1864 self.emit_jump(Opcode::IfFalse, else_label, &[]);
1865 self.stmt(cons)?;
1866 if alt.is_some() {
1867 self.emit_jump(Opcode::Goto, end_label, &[]);
1868 }
1869 self.place_label(else_label);
1870 if let Some(alt) = alt {
1871 self.stmt(alt)?;
1872 self.place_label(end_label);
1873 }
1874 }
1875 StmtKind::While { test, body } => {
1876 self.reset_value();
1877 let top = self.new_label();
1878 let end = self.new_label();
1879 self.place_label(top);
1880 self.expr(test)?;
1881 // The condition's false branch and `break` share one target,
1882 // which is why a `while` loop needs only one end label.
1883 self.emit_jump(Opcode::IfFalse, end, &[]);
1884 self.loop_body(body, labels, top, end)?;
1885 self.emit_jump(Opcode::Goto, top, &[]);
1886 self.place_label(end);
1887 }
1888 StmtKind::DoWhile { body, test } => {
1889 self.reset_value();
1890 let top = self.new_label();
1891 let cont = self.new_label();
1892 let end = self.new_label();
1893 self.place_label(top);
1894 // `continue` in a `do…while` runs the test, so it lands on `cont`
1895 // rather than on the loop head.
1896 self.loop_body(body, labels, cont, end)?;
1897 self.place_label(cont);
1898 self.expr(test)?;
1899 self.emit_jump(Opcode::IfTrue, top, &[]);
1900 self.place_label(end);
1901 }
1902 StmtKind::For {
1903 init,
1904 test,
1905 update,
1906 body,
1907 } => {
1908 self.reset_value();
1909 let for_key = stmt.span.start.offset as u64;
1910 let for_parent = self.cur().current_block;
1911 self.push_block(for_key, for_parent);
1912 self.emit_scope_enter(for_key);
1913 let mut using_head = None;
1914 if let Some(init) = init {
1915 match init {
1916 ForInit::VarDecl(decl) if decl.kind.is_using() => {
1917 // A `using` resource declared in the head lives until the whole
1918 // statement ends, not one iteration, so the disposal region has
1919 // to wrap the loop — and there may be several of them, each
1920 // needing its own region so that a later initialiser that
1921 // throws still disposes the earlier resources
1922 // (`initializer-disposed-if-subsequent-initializer-throws-in-forstatement-head`).
1923 using_head = Some(decl);
1924 }
1925 ForInit::VarDecl(decl) => {
1926 self.var_decl(decl)?;
1927 }
1928 ForInit::Expr(expr) => {
1929 // The head's value is discarded. Saying so lets an
1930 // assignment store with `put` instead of `dup`+`put`, which
1931 // is what the reference emits — and the difference matters:
1932 // a `dup`/`drop` pair around the store gives the peephole a
1933 // chance to fold the store into the *condition's* read.
1934 self.state().discard_value = true;
1935 let result = self.expr(expr);
1936 self.state().discard_value = false;
1937 result?;
1938 if !std::mem::take(&mut self.state().no_value) {
1939 self.emit(Opcode::Drop, &[]);
1940 }
1941 }
1942 }
1943 }
1944 // A `using` head's resource is disposed when the statement ends, on every
1945 // way out: `break`, `return`, an exception, and reaching the end.
1946 let flow = match using_head {
1947 Some(decl) => self.for_using_head(
1948 decl, 0, init, test, update, body, labels, for_key, for_parent,
1949 ),
1950 None => {
1951 self.for_loop_tail(init, test, update, body, labels, for_key, for_parent)
1952 }
1953 };
1954 flow?;
1955 }
1956 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1957 StmtKind::Throw(expr) => {
1958 self.expr(expr)?;
1959 self.emit(Opcode::Throw, &[]);
1960 }
1961 StmtKind::Break(_) | StmtKind::Continue(_) => {
1962 // Labels and loops are wired up in a later milestone; a bare
1963 // break/continue jumps to the innermost enclosing target, which
1964 // the loop helpers register.
1965 self.control_transfer(stmt)?;
1966 }
1967 StmtKind::Labeled { label, body } => {
1968 self.labeled(label, body, stmt)?;
1969 }
1970 StmtKind::Switch {
1971 discriminant,
1972 cases,
1973 } => {
1974 self.switch(discriminant, cases, stmt)?;
1975 }
1976 StmtKind::Try {
1977 block,
1978 handler,
1979 finalizer,
1980 } => {
1981 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1982 }
1983 StmtKind::ForIn { left, right, body } => {
1984 self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1985 }
1986 StmtKind::ForOf {
1987 left,
1988 right,
1989 body,
1990 is_await,
1991 } => {
1992 let kind = if *is_await {
1993 ForLoopKind::AwaitOf
1994 } else {
1995 ForLoopKind::Of
1996 };
1997 self.for_in_of(stmt, left, right, body, kind, labels)?;
1998 }
1999 StmtKind::With { object, body } => self.with_stmt(object, body)?,
2000 StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
2001 // `import` emits nothing: hoisting already bound its names, and the host
2002 // fills their cells before the body runs.
2003 StmtKind::Import(_) => {}
2004 StmtKind::Export(decl) => self.export_stmt(decl)?,
2005 }
2006 Ok(())
2007 }
2008
2009 /// Compile `return`, running every enclosing finalizer on the way out.
2010 ///
2011 /// `nip_catch` is what makes this possible: it discards everything on the stack
2012 /// down to and including the `catch` offset while keeping the return value on
2013 /// top, so the frame the finalizer sees has the same shape as on the normal
2014 /// path.
2015 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
2016 let mut has_value = value.is_some();
2017 if let Some(expr) = value {
2018 // `return f(x)` is a tail call *only* when nothing has to happen to the
2019 // value afterwards. A `finally` or an open iterator in scope forces the
2020 // normal path, because the cleanup has to run after the call returns —
2021 // which is exactly what a tail call refuses to do.
2022 //
2023 // A **generator or async function** never tail-calls either: its `return` is
2024 // not a return to the caller but `return_async`, which reads the value off the
2025 // stack and finishes the coroutine. A tail call replaces the frame and hands
2026 // the callee's result straight to whoever resumed us, so the value vanished and
2027 // `it.next(42)` answered `{done: true, value: undefined}` for
2028 // `function* g(){ return f(yield) }`. The reference emits `call1` plus
2029 // `return_async` there and has no tail form for a suspending body at all.
2030 let plain = !self.cur().is_suspending()
2031 // A derived constructor's return is not just the value: a non-object answer
2032 // becomes `this`, so the frame has to survive to run that.
2033 && self.cur().ctor_kind != CtorKind::Derived
2034 && self
2035 .cur()
2036 .jump_targets
2037 .iter()
2038 .all(|target| target.finally_label.is_none() && !target.has_iterator);
2039 if plain && self.expr_if_tail_call(expr)? {
2040 // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
2041 // happen here as well.
2042 self.note_direct_eval(expr);
2043 return Ok(());
2044 }
2045 self.expr(expr)?;
2046 }
2047 // `return v` in an *async generator* awaits `v` before anything else happens —
2048 // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
2049 // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
2050 // exactly that reason ("the await must be done before handling the finally in case
2051 // it raises an exception").
2052 if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
2053 self.emit(Opcode::Await, &[]);
2054 self.state().has_await = true;
2055 }
2056 has_value = self.emit_unwind_for_return(has_value);
2057 // A generator or async function does not return to its caller: it either
2058 // finishes, and the value becomes `{value, done: true}`, or it suspends.
2059 // `return_async` is the "finished" half, and it reads the value off the stack
2060 // rather than carrying it, which is what the resume machinery expects.
2061 if self.cur().is_suspending() {
2062 if !has_value {
2063 self.emit(Opcode::Undefined, &[]);
2064 }
2065 self.emit(Opcode::ReturnAsync, &[]);
2066 return Ok(());
2067 }
2068 // A derived constructor's result is `this` whenever the body does not answer an
2069 // object, and `this` is a local in the dead zone until `super()` returns — which is
2070 // why reading it here is also what turns `constructor(){ return; }` into the
2071 // ReferenceError the reference reports. The interpreter could not do this on its
2072 // own: by the time it sees `undefined` come back, the frame that held `this` is
2073 // gone, and `construct`'s own idea of `this` is the placeholder it made before the
2074 // body ran (`derived-class-return-override-with-{undefined,empty}`).
2075 if self.cur().ctor_kind == CtorKind::Derived {
2076 if !has_value {
2077 self.emit_var(VarAction::Get, "this");
2078 self.emit(Opcode::Return, &[]);
2079 return Ok(());
2080 }
2081 // `return <expr>` is only *sometimes* `this`: `undefined` is, any other
2082 // primitive is a `TypeError` (raised by `construct`), and an object replaces
2083 // `this` outright. Which one it is can only be known at run time.
2084 let keep = self.new_label();
2085 self.emit(Opcode::Dup, &[]);
2086 self.emit(Opcode::IsUndefined, &[]);
2087 self.emit_jump(Opcode::IfFalse, keep, &[]);
2088 self.emit(Opcode::Drop, &[]);
2089 self.emit_var(VarAction::Get, "this");
2090 self.place_label(keep);
2091 self.emit(Opcode::Return, &[]);
2092 return Ok(());
2093 }
2094 if has_value {
2095 self.emit(Opcode::Return, &[]);
2096 } else {
2097 self.emit(Opcode::ReturnUndef, &[]);
2098 }
2099 Ok(())
2100 }
2101
2102 /// Close an iterator: the reference's `emit_iterator_close`.
2103 ///
2104 /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
2105 /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
2106 /// sequence, and three details in it are load-bearing:
2107 ///
2108 /// * the iterator object is compared against `undefined` first, because a loop that
2109 /// ran to completion clears that slot rather than closing an exhausted iterator;
2110 /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
2111 /// * `preserve_completion` keeps whatever was underneath (the return value of the
2112 /// function being left), which is why one branch ends on `nip` and the other on `drop`.
2113 fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
2114 if !is_async {
2115 if preserve_completion {
2116 self.emit(Opcode::Rot3r, &[]);
2117 self.emit(Opcode::Undefined, &[]);
2118 }
2119 self.emit(Opcode::IteratorClose, &[]);
2120 return;
2121 }
2122 if preserve_completion {
2123 // `iter next completion -> completion iter`
2124 self.emit(Opcode::Nip, &[]);
2125 self.emit(Opcode::Swap, &[]);
2126 } else {
2127 // `iter next catch_offset -> iter`
2128 self.emit(Opcode::Drop, &[]);
2129 self.emit(Opcode::Drop, &[]);
2130 }
2131 let done = self.new_label();
2132 let no_return = self.new_label();
2133 self.emit(Opcode::Dup, &[]);
2134 self.emit(Opcode::IsUndefined, &[]);
2135 self.emit_jump(Opcode::IfTrue, done, &[]);
2136 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
2137 self.emit(Opcode::Dup, &[]);
2138 self.emit(Opcode::IsUndefinedOrNull, &[]);
2139 self.emit_jump(Opcode::IfTrue, no_return, &[]);
2140 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
2141 self.emit(Opcode::Await, &[]);
2142 self.state().has_await = true;
2143 self.emit_jump(Opcode::Goto, done, &[]);
2144 self.place_label(no_return);
2145 self.emit(Opcode::Drop, &[]);
2146 self.place_label(done);
2147 self.emit(Opcode::Drop, &[]);
2148 }
2149
2150 /// Emit the finalizer/iterator cleanup for leaving the current position with a
2151 /// return, and report whether a value is now on the stack for it to carry.
2152 ///
2153 /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
2154 /// enclosing `finally` at once, and the two used to be separate — the `yield` path
2155 /// simply emitted `return_async`, so `it.return()` ended the generator without ever
2156 /// running `finally` blocks the body was sitting inside.
2157 fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
2158 let targets = self.cur().jump_targets.clone();
2159 for target in targets.iter().rev() {
2160 if target.finally_label.is_none() && !target.has_iterator {
2161 continue;
2162 }
2163 if !has_value {
2164 // The cleanup expects a value to pass through; with nothing to
2165 // return, `undefined` stands in.
2166 self.emit(Opcode::Undefined, &[]);
2167 has_value = true;
2168 }
2169 self.emit(Opcode::NipCatch, &[]);
2170 if target.has_iterator {
2171 // Rewind to the loop's own slots and hand the close a dummy catch offset:
2172 // the loop is being abandoned, so there is nothing left to catch.
2173 self.emit_iterator_close(target.is_async_iterator, true);
2174 } else if let Some(finally) = target.finally_label {
2175 self.emit_jump(Opcode::Gosub, finally, &[]);
2176 }
2177 }
2178 has_value
2179 }
2180
2181 /// Compile a statement list, stopping at the first statement that cannot
2182 /// fall through.
2183 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2184 for (index, stmt) in body.iter().enumerate() {
2185 // A `using` declaration is not just a binding: everything after it, to the end
2186 // of the list, runs inside its disposal region. Compiling the rest of the list
2187 // recursively is what gives nested regions their innermost-first order.
2188 if Self::using_declaration(stmt).is_some() {
2189 return self.using_region(stmt, &body[index + 1..]);
2190 }
2191 self.stmt(stmt)?;
2192 if Self::terminates(stmt) {
2193 break;
2194 }
2195 }
2196 Ok(())
2197 }
2198
2199 /// The declaration a `using` statement carries, if it is one.
2200 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2201 match &stmt.kind {
2202 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2203 _ => None,
2204 }
2205 }
2206
2207 /// Compile `decl` and then the rest of its block, disposing when the block ends.
2208 ///
2209 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2210 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2211 /// exception — and this engine already funnels all of those through `catch` plus
2212 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2213 /// `return` and `break` dispose without knowing anything about `using`.
2214 ///
2215 /// ```text
2216 /// <declaration> value -> x, method -> x+1
2217 /// catch CATCH <- an exception in the rest lands here
2218 /// REST:
2219 /// <the rest of the block>
2220 /// drop <- the catch offset, on the fall-through path
2221 /// undefined; gosub DISPOSE; drop
2222 /// goto END
2223 /// CATCH:
2224 /// using_dispose x <- merges the failure into the pending exception
2225 /// throw
2226 /// DISPOSE:
2227 /// using_dispose_init
2228 /// using_dispose x
2229 /// using_dispose_end <- rethrows if a dispose failed
2230 /// ret
2231 /// END:
2232 /// ```
2233 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2234 let Some(decl) = Self::using_declaration(stmt) else {
2235 unreachable!("using_region is only called for a using declaration");
2236 };
2237 self.using_declarator(stmt, decl, 0, rest)
2238 }
2239
2240 /// One declarator of a `using` declaration, plus the region around everything after it.
2241 ///
2242 /// A `using` may list several resources — `using a = x, b = y;` — and each one is
2243 /// disposed when the block ends, in **reverse** order: §14.3.1.4 pushes them onto
2244 /// `DisposableResourceStack` in source order and §9.5.5 disposes from the top. Nesting
2245 /// one region per declarator gives exactly that, because the inner region ends first
2246 /// (`multiple-resources-disposed-in-reverse-order`). Compiling only the first left the
2247 /// rest undisposed.
2248 fn using_declarator(
2249 &mut self,
2250 stmt: &Stmt,
2251 decl: &VarDecl,
2252 index: usize,
2253 rest: &[Stmt],
2254 ) -> Result<(), SyntaxError> {
2255 let Some(declarator) = decl.declarators.get(index) else {
2256 return self.stmts(rest);
2257 };
2258 // `using` binds a plain identifier and has no pattern form, which the parser
2259 // enforces; the region still has to know *which* slot to dispose.
2260 let name = match &declarator.target.kind {
2261 PatternKind::Ident(ident) => Some(ident.name.clone()),
2262 _ => None,
2263 };
2264 let single = Stmt {
2265 kind: StmtKind::VarDecl(VarDecl {
2266 kind: decl.kind,
2267 declarators: vec![declarator.clone()],
2268 span: declarator.span,
2269 }),
2270 span: declarator.span,
2271 };
2272 self.stmt(&single)?;
2273 let Some(name) = name else {
2274 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2275 // must not make the compiler panic.
2276 return self.using_declarator(stmt, decl, index + 1, rest);
2277 };
2278 let Some(value_slot) = self.using_value_slot(&name) else {
2279 // Declared globally, which the parser rules out for a script; a module's
2280 // top level is a scope, and there the disposal stays a known gap.
2281 return self.using_declarator(stmt, decl, index + 1, rest);
2282 };
2283 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2284 // exit path already disposed.
2285 let live = !rest.last().is_some_and(Self::terminates);
2286 let _ = stmt;
2287 self.using_region_around(
2288 value_slot,
2289 live,
2290 decl.kind == VarDeclKind::AwaitUsing,
2291 |compiler| compiler.using_declarator(stmt, decl, index + 1, rest),
2292 )
2293 }
2294
2295 /// One `using` declarator of a `for` head, wrapped in its disposal region, and then the
2296 /// next — so the resources nest inside-out and dispose in reverse order.
2297 #[allow(clippy::too_many_arguments)]
2298 fn for_using_head(
2299 &mut self,
2300 decl: &VarDecl,
2301 index: usize,
2302 init: &Option<ForInit>,
2303 test: &Option<Box<Expr>>,
2304 update: &Option<Box<Expr>>,
2305 body: &Stmt,
2306 labels: &[String],
2307 for_key: u64,
2308 for_parent: u64,
2309 ) -> Result<(), SyntaxError> {
2310 let Some(declarator) = decl.declarators.get(index) else {
2311 return self.for_loop_tail(init, test, update, body, labels, for_key, for_parent);
2312 };
2313 let name = match &declarator.target.kind {
2314 PatternKind::Ident(ident) => Some(ident.name.clone()),
2315 _ => None,
2316 };
2317 self.var_decl(&VarDecl {
2318 kind: decl.kind,
2319 declarators: vec![declarator.clone()],
2320 span: declarator.span,
2321 })?;
2322 let Some(slot) = name.and_then(|name| self.using_value_slot(&name)) else {
2323 return self.for_using_head(
2324 decl,
2325 index + 1,
2326 init,
2327 test,
2328 update,
2329 body,
2330 labels,
2331 for_key,
2332 for_parent,
2333 );
2334 };
2335 self.using_region_around(
2336 slot,
2337 true,
2338 decl.kind == VarDeclKind::AwaitUsing,
2339 |compiler| {
2340 compiler.for_using_head(
2341 decl,
2342 index + 1,
2343 init,
2344 test,
2345 update,
2346 body,
2347 labels,
2348 for_key,
2349 for_parent,
2350 )
2351 },
2352 )
2353 }
2354
2355 /// The half of a `for` statement that runs inside its head's disposal region: the
2356 /// per-iteration bindings, the test, the body and the update.
2357 ///
2358 /// Split out so that a `using` head can wrap exactly this much — see the
2359 /// `StmtKind::For` arm — because the resource lives as long as the statement.
2360 #[allow(clippy::too_many_arguments)]
2361 fn for_loop_tail(
2362 &mut self,
2363 init: &Option<ForInit>,
2364 test: &Option<Box<Expr>>,
2365 update: &Option<Box<Expr>>,
2366 body: &Stmt,
2367 labels: &[String],
2368 for_key: u64,
2369 for_parent: u64,
2370 ) -> Result<(), SyntaxError> {
2371 // A `let`/`const` in the head gets a *fresh binding per iteration*,
2372 // so a closure made in the body captures that iteration's value
2373 // instead of sharing one. The reference expresses this with
2374 // `close_loc`, which swaps in a new reference cell holding the
2375 // current value; the three points below are the ones it uses — after
2376 // the initialiser, before the update, and after the loop.
2377 let loop_bindings = match init {
2378 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
2379 let mut names: Vec<String> = Vec::new();
2380 for declarator in &decl.declarators {
2381 let mut idents = Vec::new();
2382 declarator.target.bound_names(&mut idents);
2383 names.extend(idents.into_iter().map(|ident| ident.name));
2384 }
2385 names
2386 }
2387 _ => Vec::new(),
2388 };
2389 // The reference also closes right after the initialiser, so the first
2390 // iteration's closures get their own cell rather than sharing the one
2391 // the initialiser wrote into.
2392 for name in &loop_bindings {
2393 let pos = self.cur().cur_pos;
2394 self.state().insns.push(Insn::CloseCaptured {
2395 name: name.clone(),
2396 block: for_key,
2397 });
2398 self.state().insn_pos.push(pos);
2399 }
2400 let top = self.new_label();
2401 let cont = self.new_label();
2402 let end = self.new_label();
2403 self.place_label(top);
2404 if let Some(test) = test {
2405 self.expr(test)?;
2406 self.emit_jump(Opcode::IfFalse, end, &[]);
2407 }
2408 // `continue` runs the update expression first, so it lands on
2409 // `cont`, which sits just before the update.
2410 self.loop_body(body, labels, cont, end)?;
2411 self.place_label(cont);
2412 // Each iteration ends with a fresh cell, so the closures the body just
2413 // created keep the cell they captured and the update writes to a new
2414 // one. Without this every closure in the loop shares one binding.
2415 let binding_block = for_key;
2416 for name in &loop_bindings {
2417 let pos = self.cur().cur_pos;
2418 self.state().insns.push(Insn::CloseCaptured {
2419 name: name.clone(),
2420 block: binding_block,
2421 });
2422 self.state().insn_pos.push(pos);
2423 }
2424 if let Some(update) = update {
2425 self.state().discard_value = true;
2426 let result = self.expr(update);
2427 self.state().discard_value = false;
2428 result?;
2429 if !std::mem::take(&mut self.state().no_value) {
2430 self.emit(Opcode::Drop, &[]);
2431 }
2432 }
2433 self.emit_jump(Opcode::Goto, top, &[]);
2434 self.place_label(end);
2435 self.emit_scope_leave(for_key);
2436 self.state().current_block = for_parent;
2437 Ok(())
2438 }
2439
2440 /// The slot a `using` binding's value lives in.
2441 fn using_value_slot(&self, name: &str) -> Option<u32> {
2442 self.cur()
2443 .vars
2444 .iter()
2445 .position(|var| var.name == name && var.kind == VarKind::Using)
2446 .map(|index| index as u32)
2447 }
2448
2449 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2450 ///
2451 /// Shared between a `using` statement — which owns the rest of its block — and a
2452 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2453 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2454 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2455 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2456 /// target with a `finally_label` is what makes `return` and `break` dispose without
2457 /// knowing anything about `using`.
2458 ///
2459 /// ```text
2460 /// catch CATCH <- an exception inside lands here
2461 /// <inside>
2462 /// drop <- the catch offset, on the fall-through path
2463 /// undefined; gosub DISPOSE; drop
2464 /// goto END
2465 /// CATCH:
2466 /// using_dispose slot <- merges the failure into the pending exception
2467 /// throw
2468 /// DISPOSE:
2469 /// using_dispose_init
2470 /// using_dispose slot
2471 /// using_dispose_end <- rethrows if a dispose failed
2472 /// ret
2473 /// END:
2474 /// ```
2475 fn using_region_around(
2476 &mut self,
2477 value_slot: u32,
2478 live: bool,
2479 is_await_using: bool,
2480 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2481 ) -> Result<(), SyntaxError> {
2482 let catch_label = self.new_label();
2483 let end_label = self.new_label();
2484 let dispose_label = self.new_label();
2485
2486 self.emit_jump(Opcode::Catch, catch_label, &[]);
2487 self.push_jump_target(JumpTarget {
2488 names: Vec::new(),
2489 break_label: None,
2490 continue_label: None,
2491 // The catch offset is the one thing on the stack that leaving has to remove.
2492 drop_count: 1,
2493 finally_label: Some(dispose_label),
2494 is_regular_stmt: false,
2495 has_iterator: false,
2496 is_async_iterator: false,
2497 });
2498 inside(self)?;
2499 self.pop_jump_target();
2500
2501 if live {
2502 self.emit(Opcode::Drop, &[]);
2503 self.emit(Opcode::Undefined, &[]);
2504 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2505 self.emit(Opcode::Drop, &[]);
2506 self.emit_jump(Opcode::Goto, end_label, &[]);
2507 }
2508
2509 // An exception unwinds to here with the thrown value on the stack, which is exactly
2510 // the shape `using_dispose` expects as its error state.
2511 self.place_label(catch_label);
2512 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2513 self.emit(Opcode::Throw, &[]);
2514
2515 self.place_label(dispose_label);
2516 // Inside the subroutine the return value and the `gosub` return address are both
2517 // live, and neither an outer finalizer nor another region may run before this one
2518 // has finished.
2519 self.push_jump_target(JumpTarget {
2520 names: Vec::new(),
2521 break_label: None,
2522 continue_label: None,
2523 drop_count: 2,
2524 finally_label: None,
2525 is_regular_stmt: false,
2526 has_iterator: false,
2527 is_async_iterator: false,
2528 });
2529 self.emit(Opcode::UsingDisposeInit, &[]);
2530 if is_await_using {
2531 // `AsyncDisposableStack`'s order: call the method, **await** its result, and
2532 // fold a rejection into the error state. The catch is what turns that
2533 // rejection — which arrives as an exception from `await` — into the merged
2534 // error, so one failure is rethrown as itself and two become a
2535 // `SuppressedError` (§27.1.3.3's `DisposeResources` steps 5–6).
2536 //
2537 // The shape is the reference's `js_emit_dispose_scope`, adapted to this
2538 // engine's error-state protocol: `using_dispose_init` pushed the state and
2539 // `using_dispose_end` will consume it, so both arms have to leave it in place.
2540 let catch_label = self.new_label();
2541 let merged_label = self.new_label();
2542 self.emit_jump(Opcode::Catch, catch_label, &[]);
2543 self.emit(
2544 Opcode::UsingDisposeAsync,
2545 &[Op::Slot(Slot::Loc(value_slot))],
2546 );
2547 self.emit(Opcode::Await, &[]);
2548 // The awaited value, and the catch offset the successful path still holds.
2549 self.emit(Opcode::Drop, &[]);
2550 self.emit(Opcode::Drop, &[]);
2551 self.emit_jump(Opcode::Goto, merged_label, &[]);
2552 self.place_label(catch_label);
2553 self.emit(Opcode::UsingDisposeMerge, &[]);
2554 self.place_label(merged_label);
2555 self.state().has_await = true;
2556 } else {
2557 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2558 }
2559 self.emit(Opcode::UsingDisposeEnd, &[]);
2560 self.pop_jump_target();
2561 self.emit(Opcode::Ret, &[]);
2562 self.place_label(end_label);
2563 Ok(())
2564 }
2565
2566 /// Declare every name a statement list introduces, before compiling any of
2567 /// it, so a reference that appears textually before a declaration still
2568 /// resolves.
2569 ///
2570 /// Declarations are walked in source order because that is the order the
2571 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2572 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2573 /// declarations hoist out to the function scope; lexical names belong to the
2574 /// block they were written in, which `block` records.
2575 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2576 let saved = self.cur().current_block;
2577 self.state().current_block = block;
2578 let result = self.hoist_list(body);
2579 // Only now is every binding of this scope known, so the deferred function
2580 // bodies can be compiled against the finished list. Compiled at its own
2581 // declaration instead, a body that names a `var` written further down would
2582 // have resolved that name as a global.
2583 if result.is_ok() {
2584 let deferred = std::mem::take(&mut self.state().deferred_funcs);
2585 let mut outcome = Ok(());
2586 for (owner, func) in deferred {
2587 let previous = self.cur().current_block;
2588 self.state().current_block = owner;
2589 outcome = self.func_decl(&func);
2590 self.state().current_block = previous;
2591 if outcome.is_err() {
2592 break;
2593 }
2594 }
2595 self.state().current_block = saved;
2596 return outcome;
2597 }
2598 // `current_block` is restored by the caller for a block statement, since
2599 // it needs it set while compiling; only clean up on the hoist path.
2600 self.state().current_block = saved;
2601 result
2602 }
2603
2604 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2605 for stmt in body {
2606 self.hoist_stmt(stmt)?;
2607 }
2608 Ok(())
2609 }
2610
2611 /// Whether a statement always transfers control away, making everything after
2612 /// it in the same list unreachable.
2613 ///
2614 /// The reference drops such statements in `skip_dead_code`, so `return 1;
2615 /// let x = 2;` compiles to the same bytecode as `return 1;`.
2616 fn terminates(stmt: &Stmt) -> bool {
2617 matches!(
2618 stmt.kind,
2619 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2620 )
2621 }
2622
2623 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2624 match &stmt.kind {
2625 StmtKind::VarDecl(decl) => {
2626 for declarator in &decl.declarators {
2627 let mut names = Vec::new();
2628 declarator.target.bound_names(&mut names);
2629 for name in names {
2630 let text = name.name.clone();
2631 if decl.kind == VarDeclKind::Var {
2632 let def = VarDef::var(text.clone());
2633 self.declare_var(&text, def);
2634 } else if decl.kind.is_using() {
2635 // Two adjacent slots: the resource, then the dispose method
2636 // snapshotted at declaration. `using_dispose` reads them as a
2637 // pair `(slot, slot + 1)`, so nothing may be declared between
2638 // them — which is why both are declared here, in one step,
2639 // rather than the method being added at emission time.
2640 self.declare_using(&text);
2641 } else {
2642 let def = if decl.kind == VarDeclKind::Const {
2643 VarDef::constant(text.clone())
2644 } else {
2645 VarDef::lexical(text.clone())
2646 };
2647 self.declare(&text, def);
2648 }
2649 }
2650 }
2651 }
2652 StmtKind::FuncDecl(func) => {
2653 if let Some(name) = &func.name {
2654 // A function declaration is a `var` binding that happens to
2655 // hold a function, not a lexical one.
2656 let def = VarDef::var(name.name.clone());
2657 self.declare_var(&name.name.clone(), def);
2658 }
2659 // The function object is created when the scope is entered, so it
2660 // exists before the declaration is reached. Its body is compiled
2661 // *after* this scope's hoisting finishes, so a name it uses resolves
2662 // even when the `var` that declares it comes later in the source.
2663 let owner = self.cur().current_block;
2664 self.state().deferred_funcs.push((owner, func.clone()));
2665 }
2666 StmtKind::ClassDecl(class) => {
2667 if let Some(name) = &class.name {
2668 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2669 }
2670 }
2671 // A module's imports are bound before any of its code runs, and its exports
2672 // declare the very bindings they export — so both hoist the declarations
2673 // their `StmtKind` arm will later emit code for.
2674 StmtKind::Import(decl) => self.hoist_import(decl)?,
2675 StmtKind::Export(decl) => self.hoist_export(decl)?,
2676 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2677 StmtKind::If { cons, alt, .. } => {
2678 self.hoist_stmt(cons)?;
2679 if let Some(alt) = alt {
2680 self.hoist_stmt(alt)?;
2681 }
2682 }
2683 StmtKind::While { body, .. }
2684 | StmtKind::DoWhile { body, .. }
2685 | StmtKind::Labeled { body, .. }
2686 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2687 StmtKind::For { init, body, .. } => {
2688 // A `for` head gets its own scope even when it declares nothing,
2689 // because `let` in the head is scoped to the loop.
2690 let key = stmt.span.start.offset as u64;
2691 let parent = self.cur().current_block;
2692 self.push_block(key, parent);
2693 if let Some(init) = init
2694 && let ForInit::VarDecl(decl) = init
2695 {
2696 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2697 }
2698 self.hoist_stmt(body)?;
2699 self.state().current_block = parent;
2700 }
2701 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2702 let key = stmt.span.start.offset as u64;
2703 let parent = self.cur().current_block;
2704 self.push_block(key, parent);
2705 if let ForHead::VarDecl(decl) = left {
2706 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2707 }
2708 self.hoist_stmt(body)?;
2709 self.state().current_block = parent;
2710 }
2711 StmtKind::Try {
2712 block,
2713 handler,
2714 finalizer,
2715 } => {
2716 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2717 let try_parent = self.cur().current_block;
2718 if let Some(handler) = handler {
2719 // The catch parameter belongs to the function scope, not to a
2720 // block: it is a `catch` binding rather than a `let`, so it is
2721 // never in the temporal dead zone and `emit_scope_enter` must
2722 // not mark it uninitialised. It still has to be declared before
2723 // the handler body is hoisted, so it takes the slot the
2724 // reference gives it (bindings are numbered in source order).
2725 if let Some(pattern) = &handler.param {
2726 // The parameter gets its own scope, so entering the handler
2727 // does not have to re-declare it. It is not lexical, so it
2728 // is never marked uninitialised.
2729 let key = Self::try_block_key(stmt, TryPart::Param);
2730 let parent = self.cur().current_block;
2731 self.push_block(key, parent);
2732 // A destructuring parameter binds several names, one slot each,
2733 // in the order they are written. The reference declares those as
2734 // `let`s rather than as one `catch` binding — its dump prints
2735 // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2736 // so the kind follows the shape of the parameter.
2737 //
2738 // Neither form is in the dead zone: the stores run as the handler
2739 // is entered, so both use the unchecked `put_loc`.
2740 let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2741 let mut names = Vec::new();
2742 pattern.bound_names(&mut names);
2743 for name in names {
2744 let def = VarDef {
2745 name: name.name.clone(),
2746 is_const: false,
2747 is_lexical: destructures,
2748 kind: if destructures {
2749 crate::bytecode::VarKind::LexicalCatch
2750 } else {
2751 crate::bytecode::VarKind::Catch
2752 },
2753 is_captured: false,
2754 scope_level: 0,
2755 scope_next: None,
2756 };
2757 self.declare_local(&name.name.clone(), def);
2758 }
2759 // The handler body nests inside the parameter's scope, so the
2760 // body's bindings chain on to the parameter (the reference
2761 // prints `let y [next:1]`, pointing at `e`).
2762 self.state().current_block = key;
2763 }
2764 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2765 // Back to the block the `try` itself lives in, so the finalizer
2766 // is a sibling of the handler rather than nested in it.
2767 self.state().current_block = try_parent;
2768 }
2769 if let Some(finalizer) = finalizer {
2770 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2771 }
2772 }
2773 StmtKind::Switch { cases, .. } => {
2774 let key = stmt.span.start.offset as u64;
2775 let parent = self.cur().current_block;
2776 self.push_block(key, parent);
2777 for case in cases {
2778 self.hoist_list(&case.body)?;
2779 }
2780 self.state().current_block = parent;
2781 }
2782 _ => {}
2783 }
2784 Ok(())
2785 }
2786
2787 /// Hoist a nested statement list, which is its own lexical scope.
2788 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2789 let parent = self.cur().current_block;
2790 self.push_block(key, parent);
2791 self.hoist_list(body)?;
2792 self.state().current_block = parent;
2793 Ok(())
2794 }
2795
2796 /// A block key for one part of a `try` statement.
2797 ///
2798 /// The three parts are three separate scopes, so they cannot share the key a
2799 /// statement's own offset would give them: the try block, the handler body and
2800 /// the finalizer would then look like one scope, and their `let` bindings would
2801 /// be marked uninitialised only on entering the first of them.
2802 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2803 (stmt.span.start.offset as u64) * 4 + part as u64
2804 }
2805
2806 /// Declare a `var`: it lives in the function's own scope, not the block's.
2807 fn declare_var(&mut self, name: &str, def: VarDef) {
2808 if self.cur().is_module {
2809 self.declare_module(name, &def);
2810 return;
2811 }
2812 if self.cur().declares_globally(&def) {
2813 self.declare_global(name, &def);
2814 return;
2815 }
2816 let state = self.state();
2817 // A binding of the *parameter* scope does not count: the body's `var` of the
2818 // same name is a different binding and needs a slot of its own.
2819 if state.vars.iter().enumerate().any(|(index, v)| {
2820 v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2821 }) {
2822 return;
2823 }
2824 // A `var` belongs to the function scope, never to the enclosing block.
2825 state.var_block.push(FUNCTION_SCOPE);
2826 state.vars.push(def);
2827 }
2828
2829 /// Declare `name` as a binding of the parameter scope, returning its slot.
2830 fn declare_param_var(&mut self, name: &str) -> u32 {
2831 declare_param_var_at(self.state(), name)
2832 }
2833
2834 /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2835 ///
2836 /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2837 /// so each points at the one declared before it and the oldest ends the chain with
2838 /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2839 /// runtime walks when it instantiates them.
2840 fn declare_param_binding(&mut self, name: &str) -> u32 {
2841 let state = self.state();
2842 let previous = state
2843 .vars
2844 .iter()
2845 .enumerate()
2846 .rev()
2847 .find(|(index, var)| {
2848 state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2849 })
2850 .map(|(index, _)| index as i32);
2851 let index = state.vars.len() as u32;
2852 state.var_block.push(PARAM_SCOPE);
2853 let mut def = VarDef::lexical(name);
2854 // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2855 // the function's, and its bindings are initialised one by one rather than all at
2856 // once — which is exactly what the dead zone needs.
2857 def.scope_level = 1;
2858 def.scope_next = Some(previous.unwrap_or(-2));
2859 state.vars.push(def);
2860 index
2861 }
2862
2863 /// The slot of a parameter-list binding, if the list has one by that name.
2864 fn param_binding_slot(&self, name: &str) -> Option<u32> {
2865 let state = self.cur();
2866 state
2867 .vars
2868 .iter()
2869 .enumerate()
2870 .position(|(index, var)| {
2871 var.name == name
2872 && var.is_lexical
2873 && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2874 })
2875 .map(|index| index as u32)
2876 }
2877
2878 /// Every parameter-list binding, in declaration order.
2879 fn param_binding_names(&self) -> Vec<String> {
2880 let state = self.cur();
2881 state
2882 .vars
2883 .iter()
2884 .enumerate()
2885 .filter(|(index, var)| {
2886 var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2887 })
2888 .map(|(_, var)| var.name.clone())
2889 .collect()
2890 }
2891
2892 /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2893 fn body_var_slot(&self, name: &str) -> Option<u32> {
2894 let state = self.cur();
2895 state
2896 .vars
2897 .iter()
2898 .enumerate()
2899 .find(|(index, var)| {
2900 var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2901 })
2902 .map(|(index, _)| index as u32)
2903 }
2904
2905 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2906 /// one.
2907 ///
2908 /// With parameter expressions the reference creates two: an unmapped one in the
2909 /// argument scope, for the defaults and anything they close over, and the body's own.
2910 /// They are separate bindings, which is what makes
2911 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2912 /// report 1 from `p` and 2 from the body.
2913 fn provide_param_arguments(&mut self) {
2914 if !self.cur().has_parameter_expressions {
2915 return;
2916 }
2917 let mentioned = self.cur().needs_param_arguments
2918 || self
2919 .cur()
2920 .insns
2921 .iter()
2922 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2923 if !mentioned {
2924 return;
2925 }
2926 let slot = self.declare_param_var("arguments");
2927 let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2928 0
2929 } else {
2930 1
2931 };
2932 self.prepend_initialiser_to(
2933 slot,
2934 Insn::Fixed {
2935 op: Opcode::SpecialObject,
2936 operands: vec![Op::Int(magic)],
2937 },
2938 );
2939 }
2940
2941 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2942 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2943 let current = self.stack.len() - 1;
2944 let init = [
2945 producer,
2946 Insn::Fixed {
2947 op: Opcode::PutLoc,
2948 operands: vec![Op::Slot(Slot::Loc(slot))],
2949 },
2950 ];
2951 let inserted = init.len();
2952 for (index, instruction) in init.into_iter().enumerate() {
2953 self.stack[current].insns.insert(index, instruction);
2954 }
2955 for placed in self.stack[current].labels.iter_mut().flatten() {
2956 *placed += inserted;
2957 }
2958 self.state().label_since_insn = false;
2959 }
2960
2961 /// Give the function an `arguments` binding if its body mentions one.
2962 ///
2963 /// The check runs on the *instruction* stream rather than the AST: by this point
2964 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2965 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2966 /// would renumber every later local slot and stop the bytecode matching the
2967 /// reference, which only adds the binding when the body uses it.
2968 ///
2969 /// `arguments` is a local, initialised at the top of the body by
2970 /// `special_object`; that is the reference's shape, so the disassembly agrees.
2971 fn provide_arguments(&mut self) {
2972 let current = self.stack.len() - 1;
2973 if self.stack[current].is_script || self.stack[current].is_module {
2974 // A module has no `arguments` binding; referring to it is a ReferenceError,
2975 // which is exactly what an unbound name produces.
2976 return;
2977 }
2978 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2979 // function, which is why `() => arguments` sees the caller's arguments.
2980 if self.stack[current].is_arrow {
2981 if self.mentions("arguments") {
2982 self.ensure_enclosing_arguments();
2983 }
2984 return;
2985 }
2986 // Only a *body* mention needs the body's binding: the parameter list has one of
2987 // its own (see [`Compiler::provide_param_arguments`]).
2988 //
2989 // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2990 // `Var`, so without this the body got no binding at all — the name resolved to
2991 // the global object and `delete` answered `true` for a binding that cannot be
2992 // deleted. The reference answers `false`.
2993 let mentioned = self.cur().insns.iter().any(|insn| match insn {
2994 Insn::Var {
2995 name, in_params, ..
2996 } => name == "arguments" && !*in_params,
2997 Insn::DeleteVar { name } => name == "arguments",
2998 _ => false,
2999 });
3000 // A mention that resolves to the body's *own* lexical `arguments` is not a request
3001 // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
3002 // implicit binding is not created at all. Providing it anyway was worse than useless:
3003 // its prologue store resolved past the shadowing `let` and landed on the **global**,
3004 // so `function f(p = eval("var arguments")) { let arguments; }` defined
3005 // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
3006 // test262's `fn-body-cntns-arguments-lex-bind` family).
3007 //
3008 // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
3009 // var *is* the binding, and the implicit arguments object is initialised into it at
3010 // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
3011 // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
3012 // `typeof arguments` `"undefined"`.
3013 if self
3014 .cur()
3015 .vars
3016 .iter()
3017 .any(|var| var.name == "arguments" && var.needs_check())
3018 {
3019 return;
3020 }
3021 if !mentioned && !self.cur().needs_arguments_local {
3022 return;
3023 }
3024 // The request may have come only from a parameter-list arrow, in which case the
3025 // parameter scope's binding already answers for it and the body needs none.
3026 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
3027 return;
3028 }
3029 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
3030 //
3031 // With parameter expressions the list and the body are separate environments, so
3032 // an assignment to a parameter cannot be reflected into `arguments` at all — the
3033 // arguments object is unmapped whatever the mode, which is why the reference emits
3034 // `special_object 0` here even in sloppy code.
3035 // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
3036 // object unmapped whatever the mode — §10.4.4 keys the decision on
3037 // `IsSimpleParameterList`, not on strictness alone.
3038 let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
3039 0
3040 } else {
3041 1
3042 };
3043 // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
3044 // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
3045 // The only storage both sides can see is a reference cell, so every parameter the
3046 // object maps gets one — even a parameter no closure captured. Without this the
3047 // slot holds a plain copy and the mapping has nothing to write through.
3048 if magic == 1 {
3049 for arg in &mut self.stack[current].args {
3050 arg.is_captured = true;
3051 }
3052 }
3053 self.prepend_binding("arguments", magic);
3054 }
3055
3056 /// Whether a *body* instruction refers to `arguments`.
3057 fn body_mentions_arguments(&self) -> bool {
3058 self.cur()
3059 .insns
3060 .iter()
3061 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
3062 }
3063
3064 /// Whether the function body's instruction stream refers to `name`.
3065 fn mentions(&self, name: &str) -> bool {
3066 let current = self.stack.len() - 1;
3067 // A binding of the parameter scope does not answer for the body: the body's own
3068 // `arguments` (or self-name) still has to be provided for it.
3069 if self.stack[current]
3070 .vars
3071 .iter()
3072 .enumerate()
3073 .any(|(index, v)| {
3074 v.name == name
3075 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
3076 })
3077 {
3078 return false;
3079 }
3080 self.stack[current]
3081 .insns
3082 .iter()
3083 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
3084 }
3085
3086 /// Bind the name a named function expression uses to refer to itself.
3087 ///
3088 /// The value is `special_object 2`, the function currently running, so the binding
3089 /// is the closure itself and not a copy. It is a local of this function, which is
3090 /// what keeps `g` out of the enclosing scope.
3091 /// Give the function a local `this`, for an arrow inside it to capture.
3092 fn provide_this_local(&mut self) {
3093 let current = self.stack.len() - 1;
3094 if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
3095 return;
3096 }
3097 if !self.stack[current]
3098 .vars
3099 .iter()
3100 .any(|var| var.name == "this")
3101 {
3102 self.declare_hidden_local("this", VarKind::Normal);
3103 }
3104 self.prepend_initialiser(
3105 "this",
3106 Insn::Fixed {
3107 op: Opcode::PushThis,
3108 operands: vec![],
3109 },
3110 );
3111 }
3112
3113 /// Give the function a local `<home_object>`, for an arrow or a static block inside it
3114 /// to read through `super`.
3115 fn provide_home_object_local(&mut self) {
3116 let current = self.stack.len() - 1;
3117 if !self.stack[current].needs_home_object_local {
3118 return;
3119 }
3120 if !self.stack[current]
3121 .vars
3122 .iter()
3123 .any(|var| var.name == HOME_OBJECT)
3124 {
3125 self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
3126 }
3127 self.prepend_initialiser(
3128 HOME_OBJECT,
3129 Insn::Fixed {
3130 op: Opcode::SpecialObject,
3131 operands: vec![Op::Int(4)],
3132 },
3133 );
3134 }
3135
3136 fn provide_self_name(&mut self) {
3137 let current = self.stack.len() - 1;
3138 let Some(name) = self.stack[current].self_name.clone() else {
3139 return;
3140 };
3141 if self.stack[current].self_name_initialized {
3142 return;
3143 }
3144 // Either the body refers to the name, or a nested function already forced the
3145 // binding into existence while being resolved. A direct `eval` can name it
3146 // without mentioning it, so its presence is a third reason: in strict mode
3147 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
3148 // that only happens if the binding exists.
3149 let declared = self.stack[current].vars.iter().any(|v| v.name == name);
3150 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
3151 return;
3152 }
3153 self.stack[current].self_name_initialized = true;
3154 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
3155 }
3156
3157 /// Insert `special_object magic` plus the store to `name` at the top of the body.
3158 ///
3159 /// Prepending shifts every label that has been placed, so they are all moved by
3160 /// the number of instructions inserted.
3161 fn prepend_binding(&mut self, name: &str, magic: i32) {
3162 self.prepend_binding_with(name, magic, VarKind::Normal);
3163 }
3164
3165 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
3166 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
3167 let current = self.stack.len() - 1;
3168 // A function-expression's own name is immutable in strict mode, which is what
3169 // makes `f = 1` inside a strict body throw instead of being dropped.
3170 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
3171 self.declare_var(
3172 name,
3173 VarDef {
3174 kind,
3175 is_const,
3176 ..VarDef::var(name)
3177 },
3178 );
3179 let init = [
3180 Insn::Fixed {
3181 op: Opcode::SpecialObject,
3182 operands: vec![Op::Int(magic)],
3183 },
3184 Insn::Var {
3185 // An initialisation, not an assignment: sloppy mode drops stores to a
3186 // function-expression's own name, and the prologue is what puts the
3187 // value there in the first place.
3188 action: if kind == VarKind::FunctionName {
3189 VarAction::PutInit
3190 } else {
3191 VarAction::Put
3192 },
3193 name: name.to_string(),
3194 block: 0,
3195 in_params: false,
3196 },
3197 ];
3198 let inserted = init.len();
3199 for (index, instruction) in init.into_iter().enumerate() {
3200 self.stack[current].insns.insert(index, instruction);
3201 }
3202 for placed in self.stack[current].labels.iter_mut().flatten() {
3203 *placed += inserted;
3204 }
3205 // A store sits at the insertion point now, so the `put`/`get` fold must not
3206 // reach across it.
3207 self.stack[current].label_since_insn = true;
3208 }
3209
3210 /// Record a top-level script declaration as a global.
3211 ///
3212 /// A script's top-level `var`/`let`/`function` create properties of the
3213 /// global object, not slots in the script's frame, so they show up as closure
3214 /// variables instead.
3215 fn declare_global(&mut self, name: &str, def: &VarDef) {
3216 let state = self.state();
3217 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3218 // The name was already referenced, from a function compiled before this
3219 // declaration was reached — `function a(){ b() } function b(){}` resolves
3220 // `b` while `b` is still unknown, and that guess has to be corrected here.
3221 // Leaving it as a plain global meant the declaration was never registered,
3222 // so the binding did not exist at run time and `a()` threw
3223 // `b is not defined`.
3224 if matches!(existing.closure_type, ClosureType::Global) {
3225 existing.closure_type = ClosureType::GlobalDecl;
3226 existing.is_const = def.is_const;
3227 existing.is_lexical = def.is_lexical;
3228 }
3229 return;
3230 }
3231 state.closure_vars.push(ClosureVar {
3232 name: name.to_string(),
3233 is_const: def.is_const,
3234 is_lexical: def.is_lexical,
3235 closure_type: ClosureType::GlobalDecl,
3236 var_idx: 0,
3237 });
3238 }
3239
3240 /// Record a module-level declaration as a module variable.
3241 ///
3242 /// The binding is a closure variable of the module body, so reads and writes are
3243 /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
3244 /// *who fills the cell*: the module record does, before the body runs, and an import
3245 /// points its cell at the exporting module's, which is what makes bindings live and
3246 /// cycles work.
3247 fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
3248 let state = self.state();
3249 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3250 // The name may have been referenced before this declaration was hoisted,
3251 // which resolved it as a plain global. Correct that here, the way
3252 // `declare_global` does.
3253 if matches!(existing.closure_type, ClosureType::Global) {
3254 existing.closure_type = ClosureType::ModuleDecl;
3255 existing.is_const = def.is_const;
3256 existing.is_lexical = def.is_lexical;
3257 }
3258 return 0;
3259 }
3260 state.closure_vars.push(ClosureVar {
3261 name: name.to_string(),
3262 is_const: def.is_const,
3263 is_lexical: def.is_lexical,
3264 closure_type: ClosureType::ModuleDecl,
3265 var_idx: 0,
3266 });
3267 0
3268 }
3269
3270 /// Declare a module variable and answer its closure-variable index.
3271 ///
3272 /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
3273 /// module variable is not one. The import table needs the real index instead, because
3274 /// that is the position the host writes the cell into.
3275 fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
3276 self.declare_module(name, def);
3277 self.cur()
3278 .closure_vars
3279 .iter()
3280 .position(|c| c.name == name)
3281 .map(|index| index as u32)
3282 .unwrap_or(0)
3283 }
3284
3285 /// Declare one imported binding as a module variable.
3286 ///
3287 /// Returns the closure-variable index, which is what the import table records: the
3288 /// host writes the exporter's cell into that slot before the body runs.
3289 fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
3290 let state = self.state();
3291 if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
3292 // Keep the slot, fix the kind: the name may already have been referenced.
3293 state.closure_vars[index].closure_type = ClosureType::ModuleImport;
3294 state.closure_vars[index].is_const = is_const;
3295 return index as u32;
3296 }
3297 state.closure_vars.push(ClosureVar {
3298 name: name.to_string(),
3299 // An imported binding cannot be assigned: `x = 1` on an import is a
3300 // `TypeError` at run time, which the const flag is what produces.
3301 is_const: true,
3302 // Lexical, so reads go through `get_var_ref_check`: before linking has filled
3303 // the cell an import is in its dead zone, and reading it there must say so
3304 // rather than answer `undefined`.
3305 is_lexical: true,
3306 closure_type: ClosureType::ModuleImport,
3307 var_idx: 0,
3308 });
3309 state.closure_vars.len() as u32 - 1
3310 }
3311
3312 /// Emit the code an `export` needs.
3313 ///
3314 /// Only `export default <expr>` has any: everything else is a table entry whose
3315 /// binding is declared elsewhere. The expression is stored into the hidden
3316 /// `*default*` variable rather than returned, because the module body has no value
3317 /// to speak of.
3318 fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3319 match &decl.kind {
3320 ExportKind::Declaration(stmt) => self.stmt(stmt),
3321 ExportKind::Default(expr) => {
3322 // `export default class Foo {}`: evaluate the declaration (which binds
3323 // `Foo`), then copy its value into the hidden `*default*` binding, because a
3324 // class declaration is a *statement* and `expr` cannot be compiled as one.
3325 if let ExprKind::Class(class) = &expr.kind
3326 && class.name.is_some()
3327 {
3328 self.stmt(&Stmt {
3329 kind: StmtKind::ClassDecl(class.clone()),
3330 span: expr.span,
3331 })?;
3332 let Some(name) = &class.name else {
3333 return Ok(());
3334 };
3335 self.emit_var(VarAction::Get, &name.name);
3336 let index = self.declare_export_default();
3337 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3338 return Ok(());
3339 }
3340 // A named default function/class is already a module binding; the export
3341 // points at it and there is nothing to evaluate.
3342 if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
3343 return Ok(());
3344 }
3345 self.expr(expr)?;
3346 // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
3347 // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
3348 // name is observable — `imported.default.name` — and without this an
3349 // anonymous `export default class {}` arrived with the empty name.
3350 self.set_name_if_anonymous(expr, &Wtf8::new("default"));
3351 let index = self.declare_export_default();
3352 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3353 Ok(())
3354 }
3355 ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
3356 }
3357 }
3358
3359 /// A module name as the string it denotes.
3360 fn module_name_text(name: &ModuleName) -> &str {
3361 match name {
3362 ModuleName::Ident(ident) => &ident.name,
3363 ModuleName::Str(text) => text,
3364 }
3365 }
3366
3367 /// Bind `import`'s local names and record where each one comes from.
3368 ///
3369 /// Nothing is emitted: an import is not an instruction, it is a promise that the
3370 /// binding's cell will be filled before the body runs. The cell lands in the module's
3371 /// environment at a fixed index, and the host fills it from the exporter's cell —
3372 /// which is why a cyclic import can bind before the other module has evaluated.
3373 fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
3374 let request = self.module_request(&decl.source, &decl.attributes);
3375 for specifier in &decl.specifiers {
3376 let (local, name, is_star) = match specifier {
3377 ImportSpecifier::Default(ident) => {
3378 (ident.name.clone(), "default".to_string(), false)
3379 }
3380 ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3381 ImportSpecifier::Named { imported, local } => (
3382 local.name.clone(),
3383 Self::module_name_text(imported).to_string(),
3384 false,
3385 ),
3386 };
3387 // `import * as ns` is *not* a live binding of another module's variable —
3388 // it is a value of its own, which is why the reference declares it like a
3389 // module variable and the host stores the namespace object in that cell.
3390 let var_idx = if is_star {
3391 // `const`: a namespace object is a value, and the binding is immutable.
3392 self.declare_module_var(&local, &VarDef::constant(local.clone()))
3393 } else {
3394 self.declare_import(&local, true)
3395 };
3396 self.module_meta().imports.push(ImportEntry {
3397 module: request,
3398 name,
3399 var_idx,
3400 is_star,
3401 });
3402 }
3403 Ok(())
3404 }
3405
3406 /// Record what an `export` offers, declaring the binding it exports.
3407 ///
3408 /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3409 fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3410 match &decl.kind {
3411 ExportKind::Declaration(stmt) => {
3412 // The inner declaration keeps its own hoisting, then every name it binds
3413 // becomes an export of the same name.
3414 self.hoist_stmt(stmt)?;
3415 let mut names = Vec::new();
3416 Self::declared_names(stmt, &mut names);
3417 for name in names {
3418 let var_idx = self.module_binding_index(&name);
3419 self.exports_local(&name, var_idx);
3420 }
3421 }
3422 ExportKind::Default(expr) => {
3423 // The reference puts a default export in a hidden `*default*` variable,
3424 // so `export default function f(){}` can export a *value* while `f` stays
3425 // a binding of the module.
3426 if let ExprKind::Function(func) = &expr.kind
3427 && let Some(name) = &func.name
3428 {
3429 let text = name.name.clone();
3430 self.hoist_stmt(&Stmt {
3431 kind: StmtKind::FuncDecl(func.clone()),
3432 span: expr.span,
3433 })?;
3434 let var_idx = self.module_binding_index(&text);
3435 self.module_meta().exports.push(ExportEntry::Local {
3436 export_name: "default".to_string(),
3437 var_idx,
3438 });
3439 return Ok(());
3440 }
3441 if let ExprKind::Class(class) = &expr.kind
3442 && class.name.is_some()
3443 {
3444 // `export default class Foo {}` binds `Foo` in the module scope **and**
3445 // stores the class into the hidden `*default*` binding — it is a
3446 // declaration *and* a value, unlike `export default class {}` which is
3447 // only a value.
3448 //
3449 // Pointing the `default` export straight at `Foo` looked simpler and was
3450 // wrong twice over: `module_binding_index` did not find the lexical
3451 // binding the hoist had just made, so it declared a second one that
3452 // nothing ever wrote, and `export_stmt` then had no code to emit for the
3453 // declaration either. `imported.default` came out `undefined` and `Foo`
3454 // was not in scope inside its own module.
3455 self.hoist_stmt(&Stmt {
3456 kind: StmtKind::ClassDecl(class.clone()),
3457 span: expr.span,
3458 })?;
3459 let var_idx = self.declare_export_default();
3460 self.exports_local("default", var_idx);
3461 return Ok(());
3462 }
3463 let var_idx = self.declare_export_default();
3464 self.module_meta().exports.push(ExportEntry::Local {
3465 export_name: "default".to_string(),
3466 var_idx,
3467 });
3468 }
3469 ExportKind::Named {
3470 specifiers,
3471 source,
3472 attributes,
3473 } => match source {
3474 Some(source) => {
3475 let request = self.module_request(source, attributes);
3476 for specifier in specifiers {
3477 self.module_meta().exports.push(ExportEntry::Indirect {
3478 export_name: Self::module_name_text(&specifier.exported).to_string(),
3479 module: request,
3480 import_name: Self::module_name_text(&specifier.local).to_string(),
3481 });
3482 }
3483 }
3484 None => {
3485 for specifier in specifiers {
3486 let local = Self::module_name_text(&specifier.local).to_string();
3487 let export_name = Self::module_name_text(&specifier.exported).to_string();
3488 // `export { x }` where `x` is itself an **import** re-exports the
3489 // binding the import names, not a binding of this module
3490 // (§16.2.1.6.3: a local export whose local name is imported resolves
3491 // through the imported module). Recording it as a local made two
3492 // modules that both forward one import look like two different
3493 // bindings, and the name was reported ambiguous
3494 // (`import-and-export-propagates-binding`;
3495 // `namespace-unambiguous-if-import-star-as-and-export`).
3496 let closure_names: Vec<String> = self
3497 .cur()
3498 .closure_vars
3499 .iter()
3500 .map(|var| var.name.clone())
3501 .collect();
3502 let forwarded = self
3503 .module_meta()
3504 .imports
3505 .iter()
3506 .filter(|entry| {
3507 closure_names
3508 .get(entry.var_idx as usize)
3509 .is_some_and(|name| *name == local)
3510 })
3511 .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3512 .find(|(_, name, is_star)| !is_star || name.is_empty());
3513 if let Some((request, name, is_star)) = forwarded {
3514 // A namespace import has no export *name* of its own; the
3515 // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3516 // which is what the marker below records.
3517 let import_name = if is_star {
3518 "*namespace*".to_string()
3519 } else {
3520 name
3521 };
3522 self.module_meta().exports.push(ExportEntry::Indirect {
3523 export_name,
3524 module: request,
3525 import_name,
3526 });
3527 continue;
3528 }
3529 let var_idx = self.module_binding_index(&local);
3530 self.module_meta().exports.push(ExportEntry::Local {
3531 export_name,
3532 var_idx,
3533 });
3534 }
3535 }
3536 },
3537 ExportKind::All {
3538 source,
3539 exported,
3540 attributes,
3541 } => {
3542 let request = self.module_request(source, attributes);
3543 match exported {
3544 Some(name) => {
3545 self.module_meta().exports.push(ExportEntry::StarAs {
3546 export_name: Self::module_name_text(name).to_string(),
3547 module: request,
3548 });
3549 }
3550 None => {
3551 self.module_meta()
3552 .exports
3553 .push(ExportEntry::Star { module: request });
3554 }
3555 }
3556 }
3557 }
3558 Ok(())
3559 }
3560
3561 /// The names a declaration binds, which is what `export <decl>` exports.
3562 fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3563 match &stmt.kind {
3564 StmtKind::VarDecl(decl) => {
3565 for declarator in &decl.declarators {
3566 let mut names = Vec::new();
3567 declarator.target.bound_names(&mut names);
3568 out.extend(names.into_iter().map(|name| name.name));
3569 }
3570 }
3571 StmtKind::FuncDecl(func) => {
3572 if let Some(name) = &func.name {
3573 out.push(name.name.clone());
3574 }
3575 }
3576 StmtKind::ClassDecl(class) => {
3577 if let Some(name) = &class.name {
3578 out.push(name.name.clone());
3579 }
3580 }
3581 _ => {}
3582 }
3583 }
3584
3585 /// The closure-variable index of a module binding, declaring it if the name was
3586 /// exported without being declared here.
3587 ///
3588 /// `export { x }` where `x` is not declared in the module is a link-time
3589 /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3590 fn module_binding_index(&mut self, name: &str) -> u32 {
3591 if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3592 return index as u32;
3593 }
3594 self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3595 }
3596
3597 fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3598 self.module_meta().exports.push(ExportEntry::Local {
3599 export_name: export_name.to_string(),
3600 var_idx,
3601 });
3602 }
3603
3604 /// The hidden `*default*` binding `export default <expr>` stores into.
3605 fn declare_export_default(&mut self) -> u32 {
3606 const DEFAULT: &str = "*default*";
3607 if let Some(index) = self
3608 .cur()
3609 .closure_vars
3610 .iter()
3611 .position(|c| c.name == DEFAULT)
3612 {
3613 return index as u32;
3614 }
3615 self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3616 }
3617
3618 /// The module tables, which only the top-level state has.
3619 fn module_meta(&mut self) -> &mut ModuleMeta {
3620 self.state()
3621 .module
3622 .as_mut()
3623 .expect("module tables are only touched while compiling a module")
3624 }
3625
3626 /// The index of `specifier`'s request, adding it if it is new.
3627 ///
3628 /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3629 /// JSON and once as text is two modules with two different contents, which is exactly
3630 /// what `hello_module.js` does.
3631 fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3632 let attributes: Vec<(String, String)> = attributes
3633 .iter()
3634 .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3635 .collect();
3636 let meta = self.module_meta();
3637 if let Some(index) = meta
3638 .requests
3639 .iter()
3640 .position(|request| request.specifier == specifier && request.attributes == attributes)
3641 {
3642 return index as u32;
3643 }
3644 meta.requests.push(ModuleRequest {
3645 specifier: specifier.to_string(),
3646 attributes,
3647 });
3648 meta.requests.len() as u32 - 1
3649 }
3650
3651 /// Compile a loop body with a `break`/`continue` target pushed for it.
3652 fn loop_body(
3653 &mut self,
3654 body: &Stmt,
3655 labels: &[String],
3656 continue_label: Label,
3657 break_label: Label,
3658 ) -> Result<(), SyntaxError> {
3659 self.push_jump_target(JumpTarget {
3660 names: labels.to_vec(),
3661 break_label: Some(break_label),
3662 continue_label: Some(continue_label),
3663 // A loop leaves nothing of its own on the value stack.
3664 drop_count: 0,
3665 finally_label: None,
3666 is_regular_stmt: false,
3667 has_iterator: false,
3668 is_async_iterator: false,
3669 });
3670 let result = self.stmt(body);
3671 self.pop_jump_target();
3672 result
3673 }
3674
3675 fn push_jump_target(&mut self, target: JumpTarget) {
3676 self.state().jump_targets.push(target);
3677 }
3678
3679 fn pop_jump_target(&mut self) {
3680 self.state().jump_targets.pop();
3681 }
3682
3683 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3684 let (label, is_break) = match &stmt.kind {
3685 StmtKind::Break(label) => (label.as_ref(), true),
3686 StmtKind::Continue(label) => (label.as_ref(), false),
3687 _ => unreachable!("control_transfer is only called for break and continue"),
3688 };
3689
3690 // Walk outward from the innermost construct. Everything considered before
3691 // the match is a construct control is leaving, and leaving it has a cost:
3692 // its stack slots go, and its finalizer runs.
3693 let targets = self.cur().jump_targets.clone();
3694 for target in targets.iter().rev() {
3695 let destination = match (label, is_break) {
3696 // An unlabelled `break` skips a labelled non-loop statement: `break`
3697 // may name one, but the bare form only means "leave the loop".
3698 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3699 (None, false) => target.continue_label,
3700 (Some(name), true) => target
3701 .break_label
3702 .filter(|_| target.names.contains(&name.name)),
3703 (Some(name), false) => target
3704 .continue_label
3705 .filter(|_| target.names.contains(&name.name)),
3706 };
3707
3708 if let Some(destination) = destination {
3709 self.emit_jump(Opcode::Goto, destination, &[]);
3710 return Ok(());
3711 }
3712
3713 // Closing the iterator consumes the three slots the loop keeps on the
3714 // stack (iterator, next method, catch offset), so those are not dropped
3715 // again below.
3716 let mut remaining = target.drop_count;
3717 if target.has_iterator {
3718 self.emit_iterator_close(target.is_async_iterator, false);
3719 remaining = remaining.saturating_sub(3);
3720 }
3721 for _ in 0..remaining {
3722 self.emit(Opcode::Drop, &[]);
3723 }
3724 if let Some(finally) = target.finally_label {
3725 // The finalizer runs as a subroutine and is handed a dummy return
3726 // value, which is dropped afterwards to keep the stack the depth it
3727 // had before.
3728 self.emit(Opcode::Undefined, &[]);
3729 self.emit_jump(Opcode::Gosub, finally, &[]);
3730 self.emit(Opcode::Drop, &[]);
3731 }
3732 }
3733
3734 // The parser rejects a break/continue with no target, so reaching here
3735 // means the compiler's own bookkeeping is wrong.
3736 Err(SyntaxError::new(
3737 if is_break {
3738 "break has no enclosing loop or switch"
3739 } else {
3740 "continue has no enclosing loop"
3741 },
3742 stmt.span,
3743 ))
3744 }
3745
3746 /// Compile a labelled statement.
3747 ///
3748 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3749 /// that loop's targets, so the chain is collected and handed to the loop. A
3750 /// label on a non-loop statement only provides a `break` target, because
3751 /// `continue` may not target it.
3752 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3753 let mut names = vec![label.name.clone()];
3754 let mut inner = body;
3755 while let StmtKind::Labeled {
3756 label: next,
3757 body: deeper,
3758 } = &inner.kind
3759 {
3760 names.push(next.name.clone());
3761 inner = deeper;
3762 }
3763 if Self::is_loop(inner) {
3764 return self.stmt_labelled(inner, &names);
3765 }
3766 let end = self.new_label();
3767 self.push_jump_target(JumpTarget {
3768 names,
3769 break_label: Some(end),
3770 continue_label: None,
3771 drop_count: 0,
3772 finally_label: None,
3773 is_regular_stmt: true,
3774 has_iterator: false,
3775 is_async_iterator: false,
3776 });
3777 let result = self.stmt(inner);
3778 self.pop_jump_target();
3779 result?;
3780 self.place_label(end);
3781 let _ = stmt;
3782 Ok(())
3783 }
3784
3785 /// Whether a statement is a loop, i.e. a valid target for `continue`.
3786 fn is_loop(stmt: &Stmt) -> bool {
3787 matches!(
3788 stmt.kind,
3789 StmtKind::While { .. }
3790 | StmtKind::DoWhile { .. }
3791 | StmtKind::For { .. }
3792 | StmtKind::ForIn { .. }
3793 | StmtKind::ForOf { .. }
3794 )
3795 }
3796
3797 /// Compile `switch`.
3798 ///
3799 /// The discriminant is evaluated once and stays on the value stack while the
3800 /// clauses compare against copies of it, so it is dropped at the end — which is
3801 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3802 /// clause's body jumps over the *next* clause's tests straight into its body.
3803 ///
3804 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3805 /// the next run's tests. Only the last run's miss reaches the `default` body, or
3806 /// the end of the switch when there is no `default`. That failure path can point
3807 /// backwards (`default` written first), so the runs and their labels are worked
3808 /// out before any code is emitted.
3809 fn switch(
3810 &mut self,
3811 discriminant: &Expr,
3812 cases: &[SwitchCase],
3813 stmt: &Stmt,
3814 ) -> Result<(), SyntaxError> {
3815 self.reset_value();
3816 // The discriminant is evaluated outside the switch's block scope, before
3817 // any `case` clause exists.
3818 self.expr(discriminant)?;
3819
3820 let switch_key = stmt.span.start.offset as u64;
3821 let switch_parent = self.cur().current_block;
3822 self.push_block(switch_key, switch_parent);
3823 self.emit_scope_enter(switch_key);
3824
3825 let break_label = self.new_label();
3826 self.push_jump_target(JumpTarget {
3827 names: Vec::new(),
3828 break_label: Some(break_label),
3829 // `switch` is a valid `break` target but not a `continue` target.
3830 continue_label: None,
3831 // The discriminant stays on the value stack for the whole statement, so
3832 // a `break` aimed further out has to discard it.
3833 drop_count: 1,
3834 finally_label: None,
3835 is_regular_stmt: false,
3836 has_iterator: false,
3837 is_async_iterator: false,
3838 });
3839
3840 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3841 // its label to the clause after it, so both tests reach the same body.
3842 let mut runs: Vec<(usize, usize)> = Vec::new();
3843 let mut scan = 0;
3844 while scan < cases.len() {
3845 if cases[scan].test.is_some() {
3846 let mut last = scan;
3847 while last + 1 < cases.len()
3848 && cases[last].test.is_some()
3849 && cases[last].body.is_empty()
3850 && cases[last + 1].test.is_some()
3851 {
3852 last += 1;
3853 }
3854 runs.push((scan, last));
3855 scan = last + 1;
3856 } else {
3857 scan += 1;
3858 }
3859 }
3860
3861 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3862 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3863 let default_at = cases.iter().position(|case| case.test.is_none());
3864 // Where the last run sends control when nothing matched.
3865 let miss_target = match default_at {
3866 Some(index) => body_labels[index],
3867 None => break_label,
3868 };
3869
3870 // When `default` comes first, control has to jump over it to reach the
3871 // tests. It only needs to when some clause actually has a test; otherwise
3872 // the default body is the entry point.
3873 let mut entry = None;
3874 if default_at == Some(0) && !runs.is_empty() {
3875 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3876 entry = Some(run_labels[0]);
3877 }
3878
3879 let mut index = 0;
3880 let mut run = 0;
3881 let result = (|| -> Result<(), SyntaxError> {
3882 while index < cases.len() {
3883 if cases[index].test.is_some() {
3884 let (first, last) = runs[run];
3885 // Reaching these tests from the preceding body is a
3886 // fallthrough, which continues inside the body and skips them.
3887 if index > 0 {
3888 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3889 }
3890 if let Some(label) = entry.take() {
3891 self.place_label(label);
3892 }
3893 self.place_label(run_labels[run]);
3894
3895 for (offset, case) in cases[first..=last].iter().enumerate() {
3896 let test = case.test.as_ref().unwrap();
3897 self.emit(Opcode::Dup, &[]);
3898 self.expr(test)?;
3899 self.emit(Opcode::StrictEq, &[]);
3900 if first + offset < last {
3901 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3902 } else {
3903 // Hand over to the next run's tests, or give up.
3904 let next = match runs.get(run + 1) {
3905 Some(_) => run_labels[run + 1],
3906 None => miss_target,
3907 };
3908 self.emit_jump(Opcode::IfFalse, next, &[]);
3909 }
3910 }
3911
3912 self.place_label(body_labels[index]);
3913 for case in &cases[first..=last] {
3914 self.stmts(&case.body)?;
3915 }
3916 index = last + 1;
3917 run += 1;
3918 } else {
3919 // `default`: control arrives here either by falling through or
3920 // because every test missed.
3921 self.place_label(body_labels[index]);
3922 self.stmts(&cases[index].body)?;
3923 index += 1;
3924 }
3925 }
3926 Ok(())
3927 })();
3928
3929 if result.is_ok() {
3930 self.place_label(break_label);
3931 // Discard the discriminant now that no test needs it.
3932 self.emit(Opcode::Drop, &[]);
3933 }
3934
3935 self.pop_jump_target();
3936 self.emit_scope_leave(switch_key);
3937 self.state().current_block = switch_parent;
3938 result
3939 }
3940
3941 /// Compile `try`/`catch`/`finally`.
3942 ///
3943 /// The shape is an exception table built out of `catch` instructions, each of
3944 /// which records where control goes if the instructions that follow raise:
3945 ///
3946 /// ```text
3947 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
3948 /// <guarded block>
3949 /// drop <- discard the catch offset
3950 /// undefined; gosub FINALLY; drop
3951 /// goto END
3952 /// HANDLER:
3953 /// <bind the catch parameter>
3954 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
3955 /// <handler body>
3956 /// drop; undefined; gosub FINALLY; drop; goto END
3957 /// CATCH2:
3958 /// gosub FINALLY; throw <- run the finalizer, then let the error out
3959 /// FINALLY:
3960 /// <finalizer>
3961 /// ret <- return to the `gosub`
3962 /// END:
3963 /// ```
3964 ///
3965 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3966 /// of the finalizer serves the normal path, the handler path and the
3967 /// propagating-exception path.
3968 ///
3969 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3970 /// runs with `ret_value` on the stack, and the normal path has no value to
3971 /// keep, so it pushes one to keep the stack depth identical on every path.
3972 fn try_stmt(
3973 &mut self,
3974 stmt: &Stmt,
3975 block: &[Stmt],
3976 handler: &Option<CatchClause>,
3977 finalizer: Option<&[Stmt]>,
3978 ) -> Result<(), SyntaxError> {
3979 self.reset_value();
3980
3981 let catch_label = self.new_label();
3982 let catch2_label = self.new_label();
3983 let finally_label = self.new_label();
3984 let end_label = self.new_label();
3985
3986 self.emit_jump(Opcode::Catch, catch_label, &[]);
3987
3988 // The guarded block. `break` may not target it, so its entry exists purely
3989 // to unwind: a jump out has to discard the catch offset and run the
3990 // finalizer.
3991 self.push_jump_target(JumpTarget {
3992 names: Vec::new(),
3993 break_label: None,
3994 continue_label: None,
3995 drop_count: 1,
3996 finally_label: Some(finally_label),
3997 is_regular_stmt: false,
3998 has_iterator: false,
3999 is_async_iterator: false,
4000 });
4001
4002 let block_key = Self::try_block_key(stmt, TryPart::Block);
4003 let block_parent = self.cur().current_block;
4004 self.push_block(block_key, block_parent);
4005 self.emit_scope_enter(block_key);
4006 self.stmts(block)?;
4007 self.emit_scope_leave(block_key);
4008 self.state().current_block = block_parent;
4009 // A guarded block that ends in a `return`/`throw` never reaches the
4010 // epilogue, so the reference does not emit one.
4011 self.pop_jump_target();
4012 let block_live = !block.last().is_some_and(Self::terminates);
4013
4014 if block_live {
4015 self.emit(Opcode::Drop, &[]);
4016 self.emit(Opcode::Undefined, &[]);
4017 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4018 self.emit(Opcode::Drop, &[]);
4019 self.emit_jump(Opcode::Goto, end_label, &[]);
4020 }
4021
4022 if let Some(handler) = handler {
4023 self.place_label(catch_label);
4024 // The thrown value is on top of the stack: bind it, or discard it for
4025 // `catch { }`.
4026 match &handler.param {
4027 Some(pattern) => {
4028 // The stores resolve the names, so they have to run inside the
4029 // parameter's own scope; otherwise a same-named `catch` further out
4030 // could win. A `catch` binding is never in the dead zone, so the store
4031 // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
4032 let param_key = Self::try_block_key(stmt, TryPart::Param);
4033 let param_parent = self.cur().current_block;
4034 self.push_block(param_key, param_parent);
4035 self.destructure(pattern, Some(VarDeclKind::Var))?;
4036 self.state().current_block = param_parent;
4037 }
4038 None => self.emit(Opcode::Drop, &[]),
4039 }
4040 self.emit_jump(Opcode::Catch, catch2_label, &[]);
4041
4042 self.push_jump_target(JumpTarget {
4043 names: Vec::new(),
4044 break_label: None,
4045 continue_label: None,
4046 drop_count: 1,
4047 finally_label: Some(finally_label),
4048 is_regular_stmt: false,
4049 has_iterator: false,
4050 is_async_iterator: false,
4051 });
4052 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
4053 let catch_parent = self.cur().current_block;
4054 self.push_block(catch_key, catch_parent);
4055 self.emit_scope_enter(catch_key);
4056 self.stmts(&handler.body)?;
4057 self.emit_scope_leave(catch_key);
4058 self.state().current_block = catch_parent;
4059 self.pop_jump_target();
4060 let handler_live = !handler.body.last().is_some_and(Self::terminates);
4061
4062 if handler_live {
4063 self.emit(Opcode::Drop, &[]);
4064 self.emit(Opcode::Undefined, &[]);
4065 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4066 self.emit(Opcode::Drop, &[]);
4067 self.emit_jump(Opcode::Goto, end_label, &[]);
4068 }
4069
4070 // An error raised inside the handler still has to run the finalizer.
4071 self.place_label(catch2_label);
4072 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4073 self.emit(Opcode::Throw, &[]);
4074 } else {
4075 // `try`/`finally` with no handler: the finalizer runs, then the error
4076 // keeps propagating.
4077 self.place_label(catch_label);
4078 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4079 self.emit(Opcode::Throw, &[]);
4080 }
4081
4082 self.place_label(finally_label);
4083 // Inside the finalizer, leaving has a different cost: the return value and
4084 // the `gosub` return address are both on the stack, and neither finalizer nor
4085 // any outer one may run before the block has finished.
4086 self.push_jump_target(JumpTarget {
4087 names: Vec::new(),
4088 break_label: None,
4089 continue_label: None,
4090 drop_count: 2,
4091 finally_label: None,
4092 is_regular_stmt: false,
4093 has_iterator: false,
4094 is_async_iterator: false,
4095 });
4096 // §14.15.3 step 7: a finalizer that completes **normally** is discarded — the
4097 // `try` block's completion is what the statement answers. Only an abrupt exit from
4098 // the finalizer (`break`, `return`, a throw) replaces it, and that path jumps out
4099 // before the restore below.
4100 //
4101 // Without this the finalizer's last expression statement won: `eval('4; try { }
4102 // catch { } finally { 5; }')` answered `5` where the spec says `undefined`
4103 // (`cptn-finally-skip-catch`, `completion-values`).
4104 let saved_completion = if finalizer.is_some() && self.completion_slot().is_some() {
4105 self.declare_hidden_local("<finally.ret>", VarKind::Normal);
4106 self.emit_var(VarAction::Get, "<ret>");
4107 self.emit_var(VarAction::Put, "<finally.ret>");
4108 // And the body starts from *empty*, because an abrupt exit from the finalizer
4109 // keeps whatever the finalizer itself produced: `finally { break; }` answers
4110 // `undefined`, not the `try` block's value, while `finally { 42; break; }`
4111 // answers `42`. §14.15.3's `UpdateEmpty(F, undefined)` is what fills the empty
4112 // one in.
4113 self.emit(Opcode::Undefined, &[]);
4114 self.emit_var(VarAction::Put, "<ret>");
4115 true
4116 } else {
4117 false
4118 };
4119 if let Some(finalizer) = finalizer {
4120 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
4121 let finally_parent = self.cur().current_block;
4122 self.push_block(finally_key, finally_parent);
4123 self.emit_scope_enter(finally_key);
4124 self.stmts(finalizer)?;
4125 self.emit_scope_leave(finally_key);
4126 self.state().current_block = finally_parent;
4127 }
4128 if saved_completion {
4129 // The finalizer's own statements have already run, so restoring now is what
4130 // discards a normal completion.
4131 self.emit_var(VarAction::Get, "<finally.ret>");
4132 self.emit_var(VarAction::Put, "<ret>");
4133 }
4134 self.pop_jump_target();
4135 self.emit(Opcode::Ret, &[]);
4136 self.place_label(end_label);
4137 Ok(())
4138 }
4139
4140 /// The slot of the completion-value local, when this body has one.
4141 ///
4142 /// Only a script or `eval` body has `<ret>`: a function's completion value is not
4143 /// observable, so there is nothing to keep.
4144 fn completion_slot(&self) -> Option<u32> {
4145 self.cur()
4146 .vars
4147 .iter()
4148 .position(|var| var.name == "<ret>")
4149 .map(|index| index as u32)
4150 }
4151
4152 /// Compile `for`/`in` and `for`/`of`.
4153 ///
4154 /// Both keep an enumeration record on the value stack for the whole loop, which
4155 /// is what makes leaving early expensive: the record has to be dropped, or the
4156 /// iterator closed. The layout is
4157 ///
4158 /// ```text
4159 /// <iterated expression>
4160 /// for_in_start | for_of_start <- pushes the record
4161 /// goto TEST
4162 /// NEXT:
4163 /// <bind the loop variable>
4164 /// <body>
4165 /// TEST:
4166 /// for_in_next | for_of_next 0
4167 /// if_false NEXT <- not finished: next iteration
4168 /// drop <- finished: discard the leftover value
4169 /// BREAK:
4170 /// drop | iterator_close <- the one cleanup `break` also uses
4171 /// ```
4172 ///
4173 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
4174 /// normal exit share one copy — which is why `break` inside the loop emits nothing
4175 /// of its own, and only a jump that passes *through* the loop pays for its record.
4176 fn for_in_of(
4177 &mut self,
4178 stmt: &Stmt,
4179 left: &ForHead,
4180 right: &Expr,
4181 body: &Stmt,
4182 kind: ForLoopKind,
4183 labels: &[String],
4184 ) -> Result<(), SyntaxError> {
4185 self.reset_value();
4186
4187 let loop_key = stmt.span.start.offset as u64;
4188 let loop_parent = self.cur().current_block;
4189 self.push_block(loop_key, loop_parent);
4190 self.emit_scope_enter(loop_key);
4191
4192 // The iterated expression is evaluated inside the loop's scope, after the
4193 // bindings exist in the temporal dead zone.
4194 self.expr(right)?;
4195
4196 let next = self.new_label();
4197 let test = self.new_label();
4198 let break_target = self.new_label();
4199
4200 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
4201 match kind {
4202 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
4203 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
4204 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
4205 }
4206 self.emit_jump(Opcode::Goto, test, &[]);
4207
4208 self.push_jump_target(JumpTarget {
4209 // `outer: for (x of xs) … break outer` needs the name here. Without it the
4210 // loop had no label to break to, and the compiler reported "break has no
4211 // enclosing loop" for a loop that was plainly enclosing it.
4212 names: labels.to_vec(),
4213 break_label: Some(break_target),
4214 continue_label: Some(test),
4215 // Passing through the loop has to dispose of its record. A `for`/`of`
4216 // record is three slots, and closing the iterator consumes all of them.
4217 drop_count: if has_iterator { 3 } else { 1 },
4218 finally_label: None,
4219 is_regular_stmt: false,
4220 has_iterator,
4221 is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
4222 });
4223
4224 self.place_label(next);
4225 self.bind_loop_variable(left)?;
4226
4227 // The reference marks the body with its own label here. Nothing jumps to it
4228 // once the loop is laid out, but it is not decoration: a label between the
4229 // store and the body is why `put_loc v; get_loc v` does *not* fold into
4230 // `set_loc v` when the body starts by reading the loop variable.
4231 let body_label = self.new_label();
4232 self.place_label(body_label);
4233 // `for (using x of …)` disposes once per iteration, so the body is a disposal
4234 // region rather than the whole loop: the resource is the element that this
4235 // iteration produced.
4236 let using_head = match left {
4237 ForHead::VarDecl(decl) if decl.kind.is_using() => {
4238 let slot =
4239 decl.declarators
4240 .first()
4241 .and_then(|declarator| match &declarator.target.kind {
4242 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
4243 _ => None,
4244 });
4245 slot.map(|slot| (slot, decl.kind == VarDeclKind::AwaitUsing))
4246 }
4247 _ => None,
4248 };
4249 match using_head {
4250 Some((slot, awaited)) => {
4251 let live = !Self::terminates(body);
4252 self.using_region_around(slot, live, awaited, |compiler| compiler.stmt(body))?;
4253 }
4254 None => self.stmt(body)?,
4255 }
4256
4257 // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
4258 // binding each iteration**, so a closure the body creates keeps that iteration's
4259 // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
4260 // a new reference cell holding the current value.
4261 //
4262 // The position is the *end* of the body, not the start: closing before the body
4263 // would leave the closures pointing at the cell the next `put_loc` overwrites, and
4264 // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
4265 for name in Self::loop_binding_names(left) {
4266 let pos = self.cur().cur_pos;
4267 self.state().insns.push(Insn::CloseCaptured {
4268 name,
4269 block: loop_key,
4270 });
4271 self.state().insn_pos.push(pos);
4272 }
4273 self.place_label(test);
4274 match kind {
4275 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
4276 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
4277 ForLoopKind::AwaitOf => {
4278 // The reference's shape: step, `await` the result, then unpack it.
4279 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
4280 self.emit(Opcode::Await, &[]);
4281 self.state().has_await = true;
4282 self.emit(Opcode::IteratorGetValueDone, &[]);
4283 }
4284 }
4285 self.emit_jump(Opcode::IfFalse, next, &[]);
4286 // The loop is finished; `for_xx_next` left an `undefined` behind.
4287 self.emit(Opcode::Drop, &[]);
4288
4289 self.pop_jump_target();
4290 self.place_label(break_target);
4291 if has_iterator {
4292 // A loop that ran to completion finds its iterator slot already cleared (see
4293 // `iterator_get_value_done`), so this closes only an iterator abandoned by a
4294 // `break` that jumped here.
4295 self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
4296 } else {
4297 self.emit(Opcode::Drop, &[]);
4298 }
4299
4300 self.emit_scope_leave(loop_key);
4301 self.state().current_block = loop_parent;
4302 Ok(())
4303 }
4304
4305 /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
4306 /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
4307 fn loop_binding_names(left: &ForHead) -> Vec<String> {
4308 let ForHead::VarDecl(decl) = left else {
4309 return Vec::new();
4310 };
4311 if decl.kind == VarDeclKind::Var {
4312 return Vec::new();
4313 }
4314 let mut names = Vec::new();
4315 for declarator in &decl.declarators {
4316 let mut idents = Vec::new();
4317 declarator.target.bound_names(&mut idents);
4318 names.extend(idents.into_iter().map(|ident| ident.name));
4319 }
4320 names
4321 }
4322
4323 /// Store the value `for_xx_next` left on the stack into the loop variable.
4324 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
4325 // A declaration *initialises* the binding, which is what takes a `let` out of
4326 // the temporal dead zone, so the store is the unchecked form. Assigning to a
4327 // binding declared elsewhere is an ordinary write and keeps its check.
4328 let (pattern, action) = match left {
4329 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
4330 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
4331 };
4332 match &pattern.kind {
4333 PatternKind::Ident(name) => {
4334 // `for (using x of …)` validates and snapshots each iteration's value
4335 // before the body runs, which is what makes a non-disposable element fail
4336 // on the iteration that produced it rather than at the end of the loop.
4337 if let ForHead::VarDecl(decl) = left
4338 && decl.kind.is_using()
4339 {
4340 let method_slot = self
4341 .using_method_slot(&name.name)
4342 .expect("a using binding was declared during hoisting");
4343 self.emit(
4344 Opcode::UsingCheck,
4345 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4346 );
4347 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4348 }
4349 self.emit_var(action, &name.name);
4350 Ok(())
4351 }
4352 // Every other target stores through the same path an assignment pattern
4353 // uses, which is what makes `for (a[0] in obj)` write each key into the
4354 // property instead of refusing the loop outright.
4355 _ => self.destructure(
4356 pattern,
4357 match left {
4358 ForHead::VarDecl(decl) => Some(decl.kind),
4359 ForHead::Assign(_) => None,
4360 },
4361 ),
4362 }
4363 }
4364
4365 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
4366 for declarator in &decl.declarators {
4367 let Some(init) = &declarator.init else {
4368 // `var x;` stays `undefined`. A lexical binding is different: it
4369 // has to be *initialised* to leave the temporal dead zone, so the
4370 // compiler supplies an explicit `undefined`.
4371 if decl.kind.is_lexical() {
4372 // A lexical binding has to be *initialised* to leave the temporal
4373 // dead zone, and a destructuring one is no different — `let {a}`
4374 // with no initialiser is a syntax error, but `let [a] = []` still
4375 // needs `a` to be initialised from an empty source, which the
4376 // pattern does on its own.
4377 self.emit(Opcode::Undefined, &[]);
4378 self.destructure(&declarator.target, Some(decl.kind))?;
4379 }
4380 continue;
4381 };
4382 match &declarator.target.kind {
4383 PatternKind::Ident(name) => {
4384 self.expr(init)?;
4385 self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
4386 if decl.kind.is_using() {
4387 // `using_check` validates the value and snapshots its dispose
4388 // method: `value -> value, method`. The snapshot is what makes a
4389 // later change to `Symbol.dispose` irrelevant, and validating here
4390 // is what keeps the body from running at all when the value is not
4391 // disposable.
4392 let method_slot = self
4393 .using_method_slot(&name.name)
4394 .expect("a using binding was declared during hoisting");
4395 self.emit(
4396 Opcode::UsingCheck,
4397 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4398 );
4399 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4400 self.emit_var(VarAction::PutInit, &name.name);
4401 continue;
4402 }
4403 // A declaration statement produces no value, so nothing is
4404 // duplicated onto the stack.
4405 match decl.kind {
4406 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
4407 _ => self.emit_var(VarAction::PutInit, &name.name),
4408 }
4409 }
4410 _ => {
4411 // A destructuring declaration keeps nothing on the stack: the
4412 // pattern consumes the initialiser.
4413 self.expr(init)?;
4414 self.destructure(&declarator.target, Some(decl.kind))?;
4415 }
4416 }
4417 }
4418 Ok(())
4419 }
4420
4421 /// Bind a destructuring pattern from the value on top of the stack.
4422 ///
4423 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4424 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4425 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4426 /// *assignment*, where a member expression is a legal target and the store is an
4427 /// ordinary property write.
4428 ///
4429 /// The value is consumed. An assignment expression's own result is the right-hand
4430 /// side, which the caller keeps separately — the spec does not make the pattern's
4431 /// last store produce it.
4432 fn destructure(
4433 &mut self,
4434 pattern: &Pattern,
4435 decl: Option<VarDeclKind>,
4436 ) -> Result<(), SyntaxError> {
4437 match &pattern.kind {
4438 PatternKind::Ident(name) => {
4439 match decl {
4440 Some(VarDeclKind::Var) | None => {
4441 self.emit_var(VarAction::Put, &name.name);
4442 }
4443 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4444 }
4445 Ok(())
4446 }
4447 PatternKind::Assign { target, default } => {
4448 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4449 // keeps `null`.
4450 //
4451 // The shape is the reference's: test for `undefined`, and when the value is
4452 // present fall **through** to a single store both paths share. The
4453 // alternatives — branching to the store on each side — need a second store
4454 // and a jump between them, which is what the dump used to show.
4455 let has_value = self.new_label();
4456 self.emit(Opcode::Dup, &[]);
4457 self.emit(Opcode::IsUndefined, &[]);
4458 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4459 self.emit(Opcode::Drop, &[]);
4460 self.expr(default)?;
4461 // `var {f = function(){}} = {}` names the function `f`, like a plain
4462 // `var f = function(){}` does. Both pattern forms do it:
4463 // `BindingInitialization` names the value for a *binding* target, and since
4464 // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4465 // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4466 // no name to give, which is why only an identifier qualifies.
4467 if let PatternKind::Ident(name) = &target.kind {
4468 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4469 }
4470 self.place_label(has_value);
4471 self.destructure(target, decl)
4472 }
4473 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4474 PatternKind::Object { properties, rest } => {
4475 self.destructure_object(properties, rest, decl, pattern)
4476 }
4477 PatternKind::Member(member) if decl.is_none() => {
4478 // An assignment pattern may store into a property. The value is on the
4479 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4480 // put the three in the order `put_array_el`/`put_field` expect.
4481 self.expr(&member.object)?;
4482 match &member.property {
4483 MemberProp::Ident(name) => {
4484 // `value obj` -> `obj value`, the order `put_field` takes.
4485 // Nothing needs to be left behind: a pattern element's value is
4486 // consumed by its own store.
4487 self.emit(Opcode::Swap, &[]);
4488 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4489 }
4490 MemberProp::Computed(index) => {
4491 self.expr(index)?;
4492 // `value obj key` -> `obj key value`.
4493 self.emit(Opcode::Rot3l, &[]);
4494 self.emit(Opcode::PutArrayEl, &[]);
4495 }
4496 MemberProp::Private(name) => {
4497 // `value obj` -> `obj value`, and the store half of the assignment is
4498 // the same one `obj.#x = value` uses — only without `insert2`,
4499 // because a pattern element's value is not wanted back.
4500 let binding = format!("#{}", name.name);
4501 let (kind, setter) = self.private_use(&binding, member.span)?;
4502 self.emit(Opcode::Swap, &[]);
4503 self.private_store(&binding, kind, setter.as_deref())?;
4504 }
4505 }
4506 Ok(())
4507 }
4508 PatternKind::Rest(inner) => self.destructure(inner, decl),
4509 PatternKind::Invalid(expr) => {
4510 Err(SyntaxError::new("invalid assignment target", expr.span))
4511 }
4512 _ => Err(SyntaxError::new(
4513 "this destructuring target is not supported by the compiler yet",
4514 pattern.span,
4515 )),
4516 }
4517 }
4518
4519 /// `[…]` on the left: drain an iterator, binding one target per element.
4520 ///
4521 /// A target that stores into a **property** — `[o.p] = it` — has its reference worked
4522 /// out *before* the value is pulled. That ordering is observable twice over
4523 /// (`array-elem-iter-thrw-close`):
4524 ///
4525 /// * `next` must not have been called yet when the reference throws, so
4526 /// `[ {}[thrower()] ] = iterable` reports `nextCount === 0`;
4527 /// * the iterator must still be closed, because the throw happens while the record is
4528 /// live — which is `catch_here`'s `catch_offset 0` doing its work.
4529 ///
4530 /// Doing it the other way round — pull the value, then evaluate the reference — got
4531 /// both wrong: an extra `next` call, and, when the reference threw, an iterator that had
4532 /// already been drained past.
4533 fn destructure_array(
4534 &mut self,
4535 elements: &[Option<PatternElement>],
4536 rest: &Option<Box<RestElement>>,
4537 decl: Option<VarDeclKind>,
4538 ) -> Result<(), SyntaxError> {
4539 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4540 // pattern accepts any iterable and closes the iterator when the pattern ends
4541 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4542 // first because it is on top.
4543 //
4544 // It also counts as an open iterator for `return` and `break`: a pattern is not a
4545 // loop, but the record is live across everything the pattern evaluates, so
4546 // `function* g(){ [ {} = yield ] = it }` resumed with `return()` has to close it
4547 // (`array-elem-iter-rtrn-close`). `emit_unwind_for_return` finds it by this entry
4548 // and `nip_catch` uncovers exactly the `iter next` pairs it left behind.
4549 //
4550 // A `break`/`continue` cannot occur inside a pattern, so `names` and both labels
4551 // are empty and `drop_count` — read only by that unreachable path — keeps the
4552 // reference's 2.
4553 self.push_jump_target(JumpTarget {
4554 names: Vec::new(),
4555 break_label: None,
4556 continue_label: None,
4557 drop_count: 2,
4558 finally_label: None,
4559 is_regular_stmt: false,
4560 has_iterator: true,
4561 is_async_iterator: false,
4562 });
4563 self.emit(Opcode::ForOfStart, &[]);
4564 for element in elements {
4565 match element {
4566 Some(PatternElement::Pattern(pattern)) => {
4567 match Self::member_element_target(pattern, decl) {
4568 // A prepared reference sits above the record, so `for_of_next` is
4569 // told how many values are in the way.
4570 Some(member) => {
4571 let extra = self.prepare_member_target(member)?;
4572 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4573 self.emit(Opcode::Drop, &[]);
4574 self.destructure_prepared(pattern, member)?;
4575 }
4576 None => {
4577 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4578 self.emit(Opcode::Drop, &[]);
4579 self.destructure(pattern, decl)?;
4580 }
4581 }
4582 }
4583 Some(PatternElement::Property { span, .. }) => {
4584 return Err(SyntaxError::new(
4585 "a property pattern is not a valid array element",
4586 *span,
4587 ));
4588 }
4589 // An elision skips the value, which is already on the stack.
4590 None => {
4591 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4592 self.emit(Opcode::Drop, &[]);
4593 self.emit(Opcode::Drop, &[]);
4594 }
4595 }
4596 }
4597 if let Some(rest) = rest {
4598 // The remaining values go into a fresh array. The target and its running
4599 // index stay on the stack above the iterator, which is what the operand of
4600 // `for_of_next` accounts for: two values sit above the iterator triple.
4601 let prepared = match decl {
4602 None => Self::member_rest_target(rest),
4603 // A binding pattern cannot store into a property.
4604 Some(_) => None,
4605 };
4606 let extra = match prepared {
4607 Some(member) => 2 + self.prepare_member_target(member)?,
4608 None => 2,
4609 };
4610 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4611 self.emit(Opcode::Push0, &[]);
4612 let top = self.new_label();
4613 self.place_label(top);
4614 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4615 let done = self.new_label();
4616 self.emit_jump(Opcode::IfTrue, done, &[]);
4617 self.emit(Opcode::DefineArrayEl, &[]);
4618 self.emit(Opcode::Inc, &[]);
4619 self.emit_jump(Opcode::Goto, top, &[]);
4620 self.place_label(done);
4621 self.emit(Opcode::Drop, &[]);
4622 self.emit(Opcode::Drop, &[]);
4623 match prepared {
4624 Some(member) => self.store_member_value(member)?,
4625 None => self.destructure_rest(rest, decl)?,
4626 }
4627 }
4628 self.emit(Opcode::IteratorClose, &[]);
4629 self.pop_jump_target();
4630 Ok(())
4631 }
4632
4633 /// The property an array element stores into, when it stores into one at all.
4634 ///
4635 /// `Assign` is peeled because `[o.p = d] = it` evaluates `o.p`'s reference at the same
4636 /// point `[o.p] = it` does; the default value is applied afterwards, on the pulled
4637 /// value. Nothing deeper is: a nested pattern's own targets are reached by recursing
4638 /// into `destructure`, and those never straddle a `for_of_next`.
4639 fn member_element_target(
4640 pattern: &Pattern,
4641 decl: Option<VarDeclKind>,
4642 ) -> Option<&ast::MemberPattern> {
4643 if decl.is_some() {
4644 return None;
4645 }
4646 match &pattern.kind {
4647 PatternKind::Member(member) => Some(member),
4648 PatternKind::Assign { target, .. } => Self::member_element_target(target, decl),
4649 _ => None,
4650 }
4651 }
4652
4653 /// The same, for a rest element.
4654 fn member_rest_target(rest: &RestElement) -> Option<&ast::MemberPattern> {
4655 match rest {
4656 RestElement::Member(member) => Some(member),
4657 RestElement::Pattern(pattern) => match &pattern.kind {
4658 PatternKind::Member(member) => Some(member),
4659 _ => None,
4660 },
4661 }
4662 }
4663
4664 /// Push a member target's reference — the object, and the key when the property is
4665 /// computed — and answer how many values that put above the iterator record.
4666 fn prepare_member_target(&mut self, member: &ast::MemberPattern) -> Result<i32, SyntaxError> {
4667 self.expr(&member.object)?;
4668 match &member.property {
4669 MemberProp::Ident(_) | MemberProp::Private(_) => Ok(1),
4670 MemberProp::Computed(index) => {
4671 self.expr(index)?;
4672 Ok(2)
4673 }
4674 }
4675 }
4676
4677 /// Store the value on top of the stack through a prepared member reference.
4678 ///
4679 /// `obj value` for a named property, `obj key value` for a computed one — the orders
4680 /// `put_field` and `put_array_el` take, so no reordering is needed here. The `swap` and
4681 /// `rot3l` in [`Compiler::destructure`]'s member case exist only because *it* starts
4682 /// with the value already on the stack.
4683 fn store_member_value(&mut self, member: &ast::MemberPattern) -> Result<(), SyntaxError> {
4684 match &member.property {
4685 MemberProp::Ident(name) => {
4686 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4687 }
4688 MemberProp::Computed(_) => self.emit(Opcode::PutArrayEl, &[]),
4689 MemberProp::Private(name) => {
4690 let binding = format!("#{}", name.name);
4691 let (kind, setter) = self.private_use(&binding, member.span)?;
4692 self.private_store(&binding, kind, setter.as_deref())?;
4693 }
4694 }
4695 Ok(())
4696 }
4697
4698 /// The value of an array element whose member reference is already prepared.
4699 ///
4700 /// Only the default-value test differs from [`Compiler::destructure`]: the reference
4701 /// and the value are both on the stack while the test runs, which is why the object is
4702 /// evaluated before the default rather than after it.
4703 fn destructure_prepared(
4704 &mut self,
4705 pattern: &Pattern,
4706 member: &ast::MemberPattern,
4707 ) -> Result<(), SyntaxError> {
4708 if let PatternKind::Assign { default, .. } = &pattern.kind {
4709 let has_value = self.new_label();
4710 self.emit(Opcode::Dup, &[]);
4711 self.emit(Opcode::IsUndefined, &[]);
4712 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4713 self.emit(Opcode::Drop, &[]);
4714 self.expr(default)?;
4715 self.place_label(has_value);
4716 }
4717 self.store_member_value(member)
4718 }
4719
4720 /// `{…}` on the left: read properties off one boxed source object.
4721 fn destructure_object(
4722 &mut self,
4723 properties: &[Option<PatternElement>],
4724 rest: &Option<Box<RestElement>>,
4725 decl: Option<VarDeclKind>,
4726 pattern: &Pattern,
4727 ) -> Result<(), SyntaxError> {
4728 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4729 // aside for the rest element below.
4730 self.emit(Opcode::ToObject, &[]);
4731 let mut taken: Vec<Wtf8> = Vec::new();
4732 // A computed key's *value* is only known at run time, so with a rest element the
4733 // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4734 // local array that every key is written into as the pattern is walked — literal
4735 // keys by name, computed ones by the value the expression produced. Without this,
4736 // `let { [k]: a, ...rest } = o` was refused outright.
4737 let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4738 let key_log = if needs_key_log {
4739 let name = "<rest_exclude>";
4740 self.declare_hidden_local(name, VarKind::Normal);
4741 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4742 self.emit_var(VarAction::Put, name);
4743 Some(name)
4744 } else {
4745 None
4746 };
4747 for property in properties {
4748 let Some(PatternElement::Property {
4749 key, value, span, ..
4750 }) = property
4751 else {
4752 return Err(SyntaxError::new(
4753 "a bare pattern is not a valid object property",
4754 properties
4755 .iter()
4756 .flatten()
4757 .map(|element| match element {
4758 PatternElement::Pattern(pattern) => pattern.span,
4759 PatternElement::Property { span, .. } => *span,
4760 })
4761 .next()
4762 .unwrap_or(pattern.span),
4763 ));
4764 };
4765 // Every read needs the source twice: to read from, and to keep for the next
4766 // property. `get_field2` is that duplicate-and-read in one instruction, but it
4767 // leaves the copy *under* the value, so it is only usable when whatever
4768 // consumes the value tolerates that. See [`reads_with_get_field2`].
4769 let nested = reads_with_get_field2(decl, value);
4770 if !nested {
4771 self.emit(Opcode::Dup, &[]);
4772 }
4773 let slot = taken.len();
4774 match key {
4775 PropName::Literal(literal) => {
4776 let name = self.property_key_text(literal, *span)?;
4777 taken.push(name.clone());
4778 if let Some(log) = &key_log {
4779 // `arr index key -> arr`: the key is written into the log before
4780 // the read, so the order of observable operations is unchanged.
4781 self.emit_var(VarAction::Get, log);
4782 self.push_number(slot as f64);
4783 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4784 self.emit(Opcode::PutArrayEl, &[]);
4785 }
4786 self.emit(
4787 if nested {
4788 Opcode::GetField2
4789 } else {
4790 Opcode::GetField
4791 },
4792 &[Op::Atom(Atom::from_wtf8(&name))],
4793 );
4794 }
4795 PropName::Computed(index) => {
4796 self.expr(index)?;
4797 // `key key`: one stays on the stack for the read, the other goes into
4798 // the exclusion log. The index is a compile-time constant, so no counter
4799 // local is needed.
4800 if let Some(log) = &key_log {
4801 taken.push(Wtf8::default());
4802 self.emit(Opcode::Dup, &[]);
4803 self.emit_var(VarAction::Get, log);
4804 self.emit(Opcode::Swap, &[]);
4805 self.push_number(slot as f64);
4806 self.emit(Opcode::Swap, &[]);
4807 self.emit(Opcode::PutArrayEl, &[]);
4808 }
4809 self.emit(Opcode::GetArrayEl, &[]);
4810 }
4811 PropName::Private(_) => {
4812 return Err(SyntaxError::new(
4813 "private fields are not supported by the compiler yet",
4814 value.span,
4815 ));
4816 }
4817 }
4818 self.destructure(value, decl)?;
4819 }
4820 match rest {
4821 Some(rest) => {
4822 // `target src exclude`: the exclusion list is an array of the keys the
4823 // literal part already took, so the rest object gets only the others.
4824 self.emit(Opcode::Object, &[]);
4825 self.emit(Opcode::Swap, &[]);
4826 match &key_log {
4827 // Built while walking the pattern; see `needs_key_log`.
4828 Some(log) => {
4829 self.emit_var(VarAction::Get, log);
4830 }
4831 None => {
4832 for name in &taken {
4833 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4834 }
4835 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4836 }
4837 }
4838 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4839 self.emit(Opcode::Drop, &[]);
4840 self.emit(Opcode::Drop, &[]);
4841 self.destructure_rest(rest, decl)?;
4842 }
4843 // The source was only kept for a rest element.
4844 None => self.emit(Opcode::Drop, &[]),
4845 }
4846 Ok(())
4847 }
4848
4849 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4850 fn destructure_rest(
4851 &mut self,
4852 rest: &RestElement,
4853 decl: Option<VarDeclKind>,
4854 ) -> Result<(), SyntaxError> {
4855 match rest {
4856 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4857 // `[...a.b] = c` stores into a property.
4858 RestElement::Member(member) => {
4859 let pattern = Pattern {
4860 kind: PatternKind::Member(member.clone()),
4861 span: member.span,
4862 };
4863 self.destructure(&pattern, decl)
4864 }
4865 }
4866 }
4867
4868 /// Compile a function declaration and queue it for instantiation at scope
4869 /// entry.
4870 ///
4871 /// A declaration is visible before the statement that declares it, so the
4872 /// code that creates the function object belongs at the top of the enclosing
4873 /// scope, not at the declaration.
4874 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4875 let name = func.name.as_ref().expect("a declaration has a name");
4876 let function = self.compile_function(func)?;
4877 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4878 let target = self.hoist_target(&name.name);
4879 let block = self.cur().current_block;
4880 self.state().hoisted.push((block, target, pool_index));
4881 Ok(())
4882 }
4883
4884 /// Where a name lives, for a hoisted declaration.
4885 fn hoist_target(&self, name: &str) -> HoistTarget {
4886 let state = self.cur();
4887 if let Some(index) = state.args.iter().position(|a| a.name == name) {
4888 return HoistTarget::Arg(index as u32);
4889 }
4890 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4891 return HoistTarget::Loc(index as u32);
4892 }
4893 // A global function declaration is not a slot at all.
4894 HoistTarget::Global(name.to_string())
4895 }
4896
4897 // -- expressions -------------------------------------------------------
4898
4899 /// Compile one expression, recording where its instructions sit.
4900 ///
4901 /// The position is the node's operator when it has one and its first token
4902 /// otherwise, and it is restored on the way out so a parent's own instructions —
4903 /// which are emitted *after* its children — are blamed on the parent. Without the
4904 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4905 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4906 // `discard_value` belongs to the *statement* that is about to be compiled, so it
4907 // may only be honoured by that statement's own top-level expression. Taking it here
4908 // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4909 // the argument list is a different expression — it must still leave its value on the
4910 // stack. Without this the argument vanished, and `call` then consumed the callee as
4911 // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4912 // function).
4913 self.discard_root = std::mem::take(&mut self.state().discard_value);
4914 let saved = self.cur().cur_pos;
4915 // Only the node kinds the reference calls `emit_source_pos` for record a position:
4916 // the operator a node exists for, and a variable *read*, which the reference
4917 // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4918 // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4919 // start, a parenthesised group, an anonymous function expression — leaves the
4920 // previous position in place, because a table entry the reference never writes is
4921 // one we must not write either: the instruction that inherits a position (the
4922 // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4923 // report a more recent token than the reference does.
4924 let pos = expr.op_pos.or(match &expr.kind {
4925 ExprKind::Ident(ident) => Some(ident.span.start),
4926 _ => None,
4927 });
4928 match pos {
4929 Some(pos) => self.state().cur_pos = Some(pos),
4930 // A node the reference records nothing for: its own instructions stay
4931 // unpositioned, so they inherit whatever was written last — which is what an
4932 // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4933 // enclosing position instead would blame them on a token the reference has not
4934 // reached yet: a spread's `iterator_open` reports the expression it follows, and
4935 // a template's `to_propkey` the interpolation.
4936 None => self.state().cur_pos = None,
4937 }
4938 // Note a direct `eval` call before compiling it, because the *whole* function
4939 // is affected: an eval can name any binding the function declares, so every one
4940 // of them has to live in a cell for a closure it creates to capture it.
4941 self.note_direct_eval(expr);
4942 let result = self.expr_inner(expr);
4943 self.discard_root = false;
4944 self.state().cur_pos = saved;
4945 result
4946 }
4947
4948 /// Record which bindings are in scope at a direct `eval` call.
4949 ///
4950 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4951 /// resolves names from a string at run time, so the only chance to pin down *which*
4952 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4953 /// its block is the current block, an enclosing one, or the function scope.
4954 fn materialize_eval_sites(&mut self) {
4955 let pending = std::mem::take(&mut self.state().pending_eval_sites);
4956 for (span, site_block, in_params, private, arguments_allowed) in pending {
4957 self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
4958 }
4959 }
4960
4961 /// Resolve the bindings visible at one `eval` call.
4962 fn resolve_eval_site(
4963 &mut self,
4964 span: Span,
4965 site_block: u64,
4966 site_in_params: bool,
4967 private_names: Vec<EvalPrivate>,
4968 arguments_allowed: bool,
4969 ) {
4970 /// How near a binding is: function distance first, then block depth, then the
4971 /// later declaration (which shadows the earlier one in the same block).
4972 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4973
4974 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4975 // walked, innermost function first: a direct `eval` sees every enclosing
4976 // function's bindings, and none of them can be resolved at run time because the
4977 // runtime only has names to go on.
4978 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4979 let deepest = self.stack.len() - 1;
4980 for (level, state) in self.stack.iter().enumerate().rev() {
4981 let owner = (deepest - level) as u32;
4982 // The innermost function's block is the one the call sat in, which is not
4983 // the block the compiler is in now; the enclosing functions are still at
4984 // the point where this one was created.
4985 let here = if level == deepest {
4986 site_block
4987 } else {
4988 state.current_block
4989 };
4990 // The chain of live blocks, innermost first, with a depth for each. The walk
4991 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4992 // block can start at source offset zero.
4993 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4994 let mut block = here;
4995 while let Some(parent) = state
4996 .blocks
4997 .iter()
4998 .find(|candidate| candidate.key == block)
4999 .map(|candidate| candidate.parent)
5000 .filter(|parent| *parent != NO_PARENT)
5001 .filter(|parent| parent != &block)
5002 {
5003 live.push((parent, live.len()));
5004 block = parent;
5005 }
5006 let depth_of = |key: u64| {
5007 live.iter()
5008 .find(|(candidate, _)| *candidate == key)
5009 .map(|(_, depth)| *depth)
5010 // The function scope is the outermost depth there is. A binding of a
5011 // block this site is not inside lands here too, which pushes it
5012 // behind every live one — the right answer: it is out of scope.
5013 .unwrap_or(live.len())
5014 };
5015 for (index, arg) in state.args.iter().enumerate() {
5016 bindings.push((
5017 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
5018 EvalVisible {
5019 name: arg.name.clone(),
5020 is_arg: true,
5021 index: index as u32,
5022 owner,
5023 },
5024 ));
5025 }
5026 // A parameter list cannot see the body, so a body `var` is not a binding the
5027 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
5028 // not let that eval write the body's `c`.
5029 let hides_body = if level == deepest {
5030 site_in_params
5031 } else {
5032 state.created_in_params
5033 };
5034 for (index, var) in state.vars.iter().enumerate() {
5035 let block = state
5036 .var_block
5037 .get(index)
5038 .copied()
5039 .unwrap_or(FUNCTION_SCOPE);
5040 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
5041 continue;
5042 }
5043 bindings.push((
5044 (
5045 owner as usize,
5046 depth_of(block),
5047 std::cmp::Reverse(index as u32),
5048 ),
5049 EvalVisible {
5050 name: var.name.clone(),
5051 is_arg: false,
5052 index: index as u32,
5053 owner,
5054 },
5055 ));
5056 }
5057 }
5058 // Innermost function first, then innermost block, then the later declaration
5059 // (which shadows the earlier one within a block).
5060 bindings.sort_by_key(|(priority, _)| *priority);
5061 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
5062 self.state().eval_sites.push(EvalSite {
5063 line: span.start.line,
5064 column: span.start.column,
5065 bindings,
5066 private_names,
5067 arguments_allowed,
5068 });
5069 }
5070
5071 /// The private names visible from the compiler's current position, innermost last.
5072 ///
5073 /// A direct `eval` inherits these because private names are lexically scoped
5074 /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
5075 /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
5076 /// shadowing `ClassPlan::find` gives a use site inside the body.
5077 fn visible_private_names(&self) -> Vec<EvalPrivate> {
5078 let mut out: Vec<EvalPrivate> = Vec::new();
5079 for scope in &self.private_scopes {
5080 for (name, use_) in scope {
5081 if out.iter().any(|entry| &entry.name == name) {
5082 continue;
5083 }
5084 out.push(EvalPrivate {
5085 name: name.clone(),
5086 kind: match use_.kind {
5087 PrivateKind::Field => EvalPrivateKind::Field,
5088 PrivateKind::Method => EvalPrivateKind::Method,
5089 PrivateKind::Getter => EvalPrivateKind::Getter,
5090 PrivateKind::Setter => EvalPrivateKind::Setter,
5091 },
5092 setter: use_.setter.clone(),
5093 });
5094 }
5095 }
5096 out
5097 }
5098
5099 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
5100 ///
5101 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
5102 /// a bare identifier callee counts.
5103 /// Record everything a direct `eval` call site has to tell the runtime.
5104 ///
5105 /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
5106 /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
5107 /// entirely. Missing the tail-call path is not hypothetical — it is why
5108 /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
5109 /// names were otherwise wired through.
5110 fn note_direct_eval(&mut self, expr: &Expr) {
5111 if !Self::is_direct_eval(expr) {
5112 return;
5113 }
5114 // Every enclosing function is affected too: the eval sees the whole scope chain,
5115 // and a closure it creates can capture a binding of any of them.
5116 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
5117 // because the closure the eval builds outlives the loop iteration.
5118 for state in &mut self.stack {
5119 state.has_direct_eval = true;
5120 }
5121 let block = self.cur().current_block;
5122 let in_params = self.cur().in_params;
5123 // The private names are snapshotted **here**, at the call site, not when the sites
5124 // are materialised: materialisation happens once the whole function is compiled, by
5125 // which point every class scope has been popped and the answer would always be
5126 // empty.
5127 let private = self.visible_private_names();
5128 // An arrow has no `arguments` of its own and inherits the restriction from the
5129 // nearest real function: `x = () => { () => eval('arguments') }` is still a
5130 // class field initializer's arrow, and still has no `arguments` to see.
5131 let arguments_allowed = !self
5132 .stack
5133 .iter()
5134 .rev()
5135 .find(|state| !state.is_arrow)
5136 .is_some_and(|state| state.no_arguments_binding);
5137 self.state().pending_eval_sites.push((
5138 expr.span,
5139 block,
5140 in_params,
5141 private,
5142 arguments_allowed,
5143 ));
5144 }
5145
5146 fn is_direct_eval(expr: &Expr) -> bool {
5147 matches!(
5148 &expr.kind,
5149 ExprKind::Call { callee, .. }
5150 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
5151 )
5152 }
5153
5154 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5155 match &expr.kind {
5156 ExprKind::Number(value) => self.push_number(*value),
5157 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
5158 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
5159 ExprKind::Null => self.emit(Opcode::Null, &[]),
5160 ExprKind::String(text) => self.push_string(text),
5161 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
5162 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
5163 ExprKind::This => self.this_expression(),
5164 ExprKind::NewTarget => self.new_target_expression(),
5165 ExprKind::Paren(inner) => self.expr(inner)?,
5166 ExprKind::Binary { op, left, right } => {
5167 self.expr(left)?;
5168 self.expr(right)?;
5169 self.emit(binary_opcode(*op), &[]);
5170 }
5171 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
5172 ExprKind::Unary {
5173 op: UnaryOp::Minus,
5174 argument,
5175 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
5176 let ExprKind::Number(value) = argument.unparen().kind else {
5177 unreachable!("matched above")
5178 };
5179 // The reference folds a negative literal only when the negation is
5180 // exact in the integer range: `-1` becomes `push_minus1` and
5181 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
5182 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
5183 // `-Infinity`, not `Infinity` — and folding a fraction would change
5184 // which instruction the reference emits.
5185 let negated = -value;
5186 // `-2147483648` is deliberately excluded: its magnitude is one past
5187 // `i32::MAX`, so the reference sends it through the constant pool and
5188 // negates at run time instead.
5189 if value > 0.0
5190 && negated == negated.trunc()
5191 && negated >= -(i32::MAX as f64)
5192 && negated < 0.0
5193 {
5194 self.push_number(negated);
5195 } else {
5196 self.push_number(value);
5197 self.emit(Opcode::Neg, &[]);
5198 }
5199 }
5200 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
5201 ExprKind::Conditional { test, cons, alt } => {
5202 let else_label = self.new_label();
5203 let end_label = self.new_label();
5204 self.expr(test)?;
5205 self.emit_jump(Opcode::IfFalse, else_label, &[]);
5206 self.expr(cons)?;
5207 self.emit_jump(Opcode::Goto, end_label, &[]);
5208 self.place_label(else_label);
5209 self.expr(alt)?;
5210 self.place_label(end_label);
5211 }
5212 ExprKind::Assign { op, target, value } => {
5213 let discard = std::mem::take(&mut self.discard_root);
5214 self.assign(*op, target, value, discard)?
5215 }
5216 ExprKind::Update {
5217 op,
5218 argument,
5219 prefix,
5220 } => self.update(*op, argument, *prefix)?,
5221 ExprKind::Sequence(items) => {
5222 for (index, item) in items.iter().enumerate() {
5223 self.expr(item)?;
5224 if index + 1 != items.len() {
5225 self.emit(Opcode::Drop, &[]);
5226 }
5227 }
5228 }
5229 ExprKind::Call { .. } => self.chain_link_top(expr)?,
5230 ExprKind::Member { .. } => self.chain_link_top(expr)?,
5231 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
5232 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
5233 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
5234 ExprKind::Template(template) => self.template_literal(template)?,
5235 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
5236 ExprKind::New { callee, arguments } => {
5237 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
5238 // The `dup` is not redundant: `call_constructor` takes the
5239 // constructor twice, once as the target and once as `new.target`,
5240 // which is what makes `new.target === C` inside the body.
5241 self.expr(callee)?;
5242 self.emit(Opcode::Dup, &[]);
5243 let args = arguments.as_deref().unwrap_or(&[]);
5244 if Self::has_spread(args) {
5245 // `C C array`: the duplicated callee is already both the target
5246 // and `new.target`, so no reordering is needed before `apply 1`.
5247 self.argument_array(args)?;
5248 self.emit(Opcode::Apply, &[Op::Int(1)]);
5249 return Ok(());
5250 }
5251 for argument in args {
5252 self.expr(argument)?;
5253 }
5254 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
5255 }
5256 ExprKind::Class(class) => self.class_definition(class, true)?,
5257 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
5258 ExprKind::Yield { argument, delegate } => {
5259 self.yield_expression(argument.as_deref(), *delegate)?
5260 }
5261 ExprKind::Await(argument) => self.await_expression(argument)?,
5262 ExprKind::RegExp { pattern, flags } => {
5263 // A literal is compiled *here*, at parse time, not when the line runs. The
5264 // spec is explicit that an invalid pattern is an early error (§12.9.4:
5265 // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
5266 // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
5267 // also validates `\p{…}` names: 163 conformance cases are patterns that have
5268 // to be rejected before any code runs.
5269 //
5270 // This is the whole reason the engine lives in its own crate rather than
5271 // inside `quickjs-pure`: the compiler could not depend on the interpreter
5272 // (`pure` depends on `compile`), but both need this.
5273 // The lexer already rejected an unknown or repeated flag, so an unparsable
5274 // flag string here would be a bug in the lexer rather than in the script;
5275 // fall back to the default flags instead of inventing a second message.
5276 let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
5277 let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
5278 SyntaxError::new(
5279 format!("invalid regular expression: {}", error.message),
5280 expr.span,
5281 )
5282 })?;
5283 // The tree is thrown away and rebuilt when the literal first runs: keeping it
5284 // would mean serialising the syntax tree into the function's constant pool,
5285 // and a literal is created once per evaluation of its expression anyway.
5286 let _ = parsed;
5287 // The pattern and its flags travel as two string constants; `regexp` builds
5288 // the object. A dedicated opcode (rather than a call to the constructor) is
5289 // what the reference does too, so that a literal never goes through the
5290 // public `RegExp` function and its string-coercion rules.
5291 self.push_string(&Wtf8::new(pattern));
5292 self.push_string(&Wtf8::new(flags));
5293 self.emit(Opcode::Regexp, &[]);
5294 }
5295 ExprKind::Arrow(func) => {
5296 let function = self.compile_function(func)?;
5297 let index = self.push_constant(Constant::Function(Box::new(function)));
5298 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5299 }
5300 ExprKind::Function(func) => {
5301 let function = self.compile_function_with_name(func, true)?;
5302 let index = self.push_constant(Constant::Function(Box::new(function)));
5303 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5304 }
5305 // `import.meta`: the host fills a per-module object at link time.
5306 ExprKind::ImportMeta => {
5307 self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
5308 }
5309 // `import("x")` compiles to a two-slot push followed by one opcode: the
5310 // specifier, then the options object. Both are evaluated, in that order, because
5311 // §13.3.10.1 numbers them that way and their side effects are observable — the
5312 // absent second argument is a literal `undefined`, which evaluates to nothing.
5313 ExprKind::ImportCall(specifier, options) => {
5314 self.expr(specifier)?;
5315 match options {
5316 Some(options) => self.expr(options)?,
5317 None => {
5318 self.emit(Opcode::Undefined, &[]);
5319 }
5320 }
5321 self.emit(Opcode::Import, &[]);
5322 }
5323 ExprKind::PrivateIn { name, object } => {
5324 // `#x in o`: the object, then the binding, then one opcode which decides what
5325 // to do with the second operand. A field's binding holds a symbol and the
5326 // answer is an own-property test; a method's holds a function and the answer
5327 // is a brand check — both live in `private_in`, so the compiler emits the
5328 // same instruction for either.
5329 self.expr(object)?;
5330 self.emit_var(VarAction::Get, &format!("#{}", name.name));
5331 self.emit(Opcode::PrivateIn, &[]);
5332 }
5333 _ => {
5334 return Err(SyntaxError::new(
5335 "this expression form is not supported by the compiler yet",
5336 expr.span,
5337 ));
5338 }
5339 }
5340 Ok(())
5341 }
5342
5343 /// Build one array holding the evaluated call arguments, which is how a call
5344 /// containing a spread is compiled: the reference does the same, building the
5345 /// list on the stack and handing it to `apply`.
5346 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5347 let elements: Vec<Option<ArrayElement>> = arguments
5348 .iter()
5349 .map(|argument| match &argument.unparen().kind {
5350 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
5351 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
5352 })
5353 .collect();
5354 self.array_literal(&elements, Span::default())
5355 }
5356
5357 /// Whether any argument is a spread, which is what selects the `apply` form.
5358 fn has_spread(arguments: &[Expr]) -> bool {
5359 arguments
5360 .iter()
5361 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
5362 }
5363
5364 /// Compile `a${x}b`.
5365 ///
5366 /// A template is a `+` chain built left to right: the leading chunk (or an empty
5367 /// string when the template starts with a substitution), then for each
5368 /// substitution its value, `to_propkey` and `add`, then the following chunk when
5369 /// it is not empty. `to_propkey` is what makes a number or object substitute the
5370 /// way `ToString` would while leaving the result a string for `add` to
5371 /// concatenate.
5372 ///
5373 /// The chunk is an atom rather than a constant-pool string, because a non-empty
5374 /// chunk always lands where a value is pushed and `push_atom_value` is the
5375 /// instruction the reference uses for it; the empty first chunk has its own
5376 /// zero-byte form.
5377 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
5378 let first = template.quasis.first();
5379 match first.and_then(|quasi| quasi.cooked.clone()) {
5380 Some(text) if !text.is_empty() => {
5381 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5382 }
5383 // Either the template begins with a substitution, or the chunk is
5384 // empty — in both cases the chain needs a string to start from.
5385 _ => self.emit(Opcode::PushEmptyString, &[]),
5386 }
5387 for (index, expression) in template.expressions.iter().enumerate() {
5388 self.expr(expression)?;
5389 self.emit(Opcode::ToPropkey, &[]);
5390 self.emit(Opcode::Add, &[]);
5391 if let Some(text) = template
5392 .quasis
5393 .get(index + 1)
5394 .and_then(|quasi| quasi.cooked.clone())
5395 && !text.is_empty()
5396 {
5397 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5398 self.emit(Opcode::Add, &[]);
5399 }
5400 }
5401 Ok(())
5402 }
5403
5404 /// Compile an object literal.
5405 ///
5406 /// The object is built in place: `object` pushes it, and each property leaves it
5407 /// on the stack with one field more, so no temporary is needed and later
5408 /// properties can overwrite earlier ones.
5409 ///
5410 /// The instruction depends on *how* the property was written, not on what kind
5411 /// of value it holds:
5412 ///
5413 /// | source | instruction |
5414 /// |---|---|
5415 /// | `{ a: v }` | `define_field a` |
5416 /// | `{ __proto__: v }` | `set_proto` |
5417 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
5418 /// | `{ m() {} }` | `define_method m,4` |
5419 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
5420 /// | `{ [k]() {} }` | `define_method_computed 4` |
5421 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
5422 ///
5423 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
5424 /// key itself, which is why the trailing `drop` is absent there too.
5425 /// `tag`…``: a call whose first argument is the call site's template object.
5426 ///
5427 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
5428 /// array beside it, so `String.raw` can read the source text back. It is a constant
5429 /// because its contents never change; the reference builds one per call site and
5430 /// reuses it, while this builds one per evaluation, which only `tag` code that
5431 /// compares template objects across calls could tell apart.
5432 /// A fresh template site id. See [`Constant::Template`].
5433 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
5434 let cooked = quasi
5435 .quasis
5436 .iter()
5437 .map(|chunk| chunk.cooked.clone())
5438 .collect();
5439 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
5440 let index = self.push_constant(Constant::Template {
5441 site: next_template_site(),
5442 cooked,
5443 raw,
5444 });
5445 let count = quasi.expressions.len() + 1;
5446 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
5447 if let ExprKind::Member {
5448 object, property, ..
5449 } = &tag.unparen().kind
5450 {
5451 self.expr(object)?;
5452 match property {
5453 MemberProp::Ident(name) => {
5454 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5455 }
5456 MemberProp::Computed(key) => {
5457 self.expr(key)?;
5458 self.emit(Opcode::GetArrayEl2, &[]);
5459 }
5460 MemberProp::Private(name) => {
5461 let binding = format!("#{}", name.name);
5462 let (kind, _) = self.private_use(&binding, tag.span)?;
5463 self.private_callee(&binding, kind)?;
5464 }
5465 }
5466 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5467 for expression in &quasi.expressions {
5468 self.expr(expression)?;
5469 }
5470 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
5471 return Ok(());
5472 }
5473 self.expr(tag)?;
5474 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5475 for expression in &quasi.expressions {
5476 self.expr(expression)?;
5477 }
5478 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
5479 Ok(())
5480 }
5481
5482 fn object_literal(
5483 &mut self,
5484 properties: &[ObjectProperty],
5485 span: Span,
5486 ) -> Result<(), SyntaxError> {
5487 self.emit(Opcode::Object, &[]);
5488 for property in properties {
5489 match property {
5490 ObjectProperty::Spread(value) => {
5491 // `copy_data_properties` takes the target, the source and an
5492 // exclusion list; a literal `null` means "exclude nothing".
5493 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
5494 // exclusion list by stack offset.
5495 self.expr(spread_argument(value))?;
5496 self.emit(Opcode::Null, &[]);
5497 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
5498 self.emit(Opcode::Drop, &[]);
5499 self.emit(Opcode::Drop, &[]);
5500 }
5501 ObjectProperty::Property {
5502 key,
5503 value,
5504 kind,
5505 shorthand,
5506 span: property_span,
5507 } => match key {
5508 PropName::Computed(key_expr) => {
5509 self.expr(key_expr)?;
5510 match kind {
5511 PropertyKind::Value => {
5512 self.emit(Opcode::ToPropkey, &[]);
5513 self.expr(value)?;
5514 self.set_name_if_anonymous_computed(value);
5515 self.emit(Opcode::DefineArrayEl, &[]);
5516 // `define_array_el` leaves the object and the key;
5517 // the key is no longer needed.
5518 self.emit(Opcode::Drop, &[]);
5519 }
5520 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5521 self.emit_method_function(value)?;
5522 self.emit(
5523 Opcode::DefineMethodComputed,
5524 &[Op::Int(define_method_flags(*kind))],
5525 );
5526 }
5527 }
5528 }
5529 PropName::Literal(key) => {
5530 let name = self.property_key_text(key, *property_span)?;
5531 match kind {
5532 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5533 self.emit_method_function(value)?;
5534 self.emit(
5535 Opcode::DefineMethod,
5536 &[
5537 Op::Atom(Atom::from_wtf8(&name)),
5538 Op::Int(define_method_flags(*kind)),
5539 ],
5540 );
5541 }
5542 PropertyKind::Value => {
5543 self.expr(value)?;
5544 // `{__proto__: x}` sets the prototype instead of
5545 // creating a property; the shorthand `{__proto__}`
5546 // is an ordinary property and does not.
5547 if name == "__proto__" && !shorthand {
5548 self.emit(Opcode::SetProto, &[]);
5549 } else {
5550 self.set_name_if_anonymous(value, &name);
5551 self.emit(
5552 Opcode::DefineField,
5553 &[Op::Atom(Atom::from_wtf8(&name))],
5554 );
5555 }
5556 }
5557 }
5558 }
5559 PropName::Private(_) => {
5560 return Err(SyntaxError::new(
5561 "private names are not valid in object literals",
5562 *property_span,
5563 ));
5564 }
5565 },
5566 }
5567 }
5568 let _ = span;
5569 Ok(())
5570 }
5571
5572 /// Emit the function a method/accessor property defines.
5573 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
5574 self.expr(value)
5575 }
5576
5577 /// The name a literal property key contributes.
5578 ///
5579 /// String keys are used as written. A numeric key is converted the way
5580 /// `ToString` would convert it, because the atom is made from that spelling:
5581 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5582 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5583 match key {
5584 PropKey::Str(text) => Ok(text.clone()),
5585 PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5586 }
5587 }
5588
5589 /// Compile an optional chain.
5590 ///
5591 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5592 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5593 /// `undefined`. So the chain is compiled with one end label and every guard
5594 /// jumps to it. The parser hands us the extent of that spine as an
5595 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5596 /// exactly the scope the label has to cover.
5597 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5598 let end = self.new_label();
5599 self.chain_link(inner, end)?;
5600 self.place_label(end);
5601 Ok(())
5602 }
5603
5604 /// A member access or call reached from outside any optional chain.
5605 ///
5606 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5607 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5608 /// still created because [`Self::chain_link`] takes it, and placing it at the
5609 /// end is a no-op that keeps a single code path.
5610 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5611 let end = self.new_label();
5612 self.chain_link(expr, end)?;
5613 self.place_label(end);
5614 Ok(())
5615 }
5616
5617 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5618 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5619 match &expr.kind {
5620 ExprKind::Member {
5621 object,
5622 property,
5623 optional,
5624 } => {
5625 // `super.x` is not a lookup on a value: it starts at the home object's
5626 // prototype and keeps `this` as the receiver, so it cannot go through
5627 // `chain_link` and the ordinary field read.
5628 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5629 self.super_base();
5630 match property {
5631 MemberProp::Ident(name) => self.emit(
5632 Opcode::PushAtomValue,
5633 &[Op::Atom(Atom::from_text(&name.name))],
5634 ),
5635 MemberProp::Computed(index) => self.expr(index)?,
5636 MemberProp::Private(_) => {
5637 return Err(SyntaxError::new(
5638 "private fields are not supported by the compiler yet",
5639 expr.span,
5640 ));
5641 }
5642 }
5643 self.emit(Opcode::GetSuperValue, &[]);
5644 return Ok(());
5645 }
5646 self.chain_link(object, end)?;
5647 if *optional {
5648 self.optional_guard(end);
5649 }
5650 match property {
5651 // `.length` has its own opcode. The reference emits it for every
5652 // object, not just arrays, so a name-based rule is right and
5653 // cheaper than the generic field read.
5654 MemberProp::Ident(name) if name.name == "length" => {
5655 self.emit(Opcode::GetLength, &[]);
5656 }
5657 MemberProp::Ident(name) => {
5658 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5659 }
5660 MemberProp::Computed(index) => {
5661 self.expr(index)?;
5662 self.emit(Opcode::GetArrayEl, &[]);
5663 }
5664 MemberProp::Private(name) => {
5665 // The binding comes from the class scope, so a read from outside the
5666 // class cannot name it at all. `?.` checks the object, not the field:
5667 // `o?.#x` guards on `o` being nullish.
5668 let binding = format!("#{}", name.name);
5669 let (kind, _) = self.private_use(&binding, expr.span)?;
5670 self.private_load(&binding, kind, expr.span)?;
5671 }
5672 }
5673 Ok(())
5674 }
5675 ExprKind::Call {
5676 callee,
5677 arguments,
5678 optional,
5679 } => {
5680 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5681 // cannot: it reads the function and then calls it with no
5682 // receiver at all. The reference's answer is to keep the object
5683 // under the function value — `get_field2` reads a field and leaves
5684 // its base in place — and to use `call_method`, which takes the
5685 // receiver from the stack. Missing this does not just cost an
5686 // instruction, it loses the `this` binding.
5687 if let ExprKind::Member {
5688 object,
5689 property,
5690 optional: member_optional,
5691 } = &callee.unparen().kind
5692 {
5693 // `super.m()` reads the method off the home object's prototype but
5694 // calls it with `this`, so the receiver goes under the read instead of
5695 // being replaced by it.
5696 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5697 self.super_base();
5698 match property {
5699 MemberProp::Ident(name) => self.emit(
5700 Opcode::PushAtomValue,
5701 &[Op::Atom(Atom::from_text(&name.name))],
5702 ),
5703 MemberProp::Computed(index) => self.expr(index)?,
5704 MemberProp::Private(_) => {
5705 return Err(SyntaxError::new(
5706 "private fields are not supported by the compiler yet",
5707 expr.span,
5708 ));
5709 }
5710 }
5711 // The two-output form would drop the receiver; this one replaces
5712 // the prototype and the key, leaving `this` underneath.
5713 self.emit(Opcode::GetArrayEl, &[]);
5714 if Self::has_spread(arguments) {
5715 self.argument_array(arguments)?;
5716 self.emit(Opcode::Perm3, &[]);
5717 self.emit(Opcode::Apply, &[Op::Int(0)]);
5718 return Ok(());
5719 }
5720 for argument in arguments {
5721 self.expr(argument)?;
5722 }
5723 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5724 return Ok(());
5725 }
5726 self.chain_link(object, end)?;
5727 if *member_optional {
5728 self.optional_guard(end);
5729 }
5730 match property {
5731 MemberProp::Ident(name) => {
5732 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5733 }
5734 MemberProp::Computed(index) => {
5735 self.expr(index)?;
5736 // The key is not needed after the read, so this is the
5737 // two-output form: object, value.
5738 self.emit(Opcode::GetArrayEl2, &[]);
5739 }
5740 MemberProp::Private(name) => {
5741 // The receiver is already under the callee, which is exactly the
5742 // shape `call_method` and `apply` want — so nothing is dropped.
5743 let binding = format!("#{}", name.name);
5744 let (kind, _) = self.private_use(&binding, expr.span)?;
5745 self.private_callee(&binding, kind)?;
5746 }
5747 }
5748 if Self::has_spread(arguments) {
5749 // Stack is `obj func`; the array goes on top, then `perm3`
5750 // reorders to the `func this array` that `apply` wants.
5751 self.argument_array(arguments)?;
5752 self.emit(Opcode::Perm3, &[]);
5753 self.emit(Opcode::Apply, &[Op::Int(0)]);
5754 return Ok(());
5755 }
5756 for argument in arguments {
5757 self.expr(argument)?;
5758 }
5759 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5760 return Ok(());
5761 }
5762 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5763 // with `get_field2` so the base stays under it, and on the short-circuit
5764 // path pushes an extra `undefined` as a placeholder receiver — the call
5765 // then throws, which is what calling a missing optional chain should do.
5766 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5767 && let ExprKind::Member {
5768 object,
5769 property,
5770 optional: member_optional,
5771 } = &inner.unparen().kind
5772 {
5773 let call = self.new_label();
5774 // A guard target of its own: the outer `end` skips the whole
5775 // expression, and a short-circuited receiver still has to reach the
5776 // call so that calling it throws.
5777 let short = self.new_label();
5778 self.chain_link(object, end)?;
5779 if *member_optional {
5780 self.optional_guard(short);
5781 }
5782 match property {
5783 MemberProp::Ident(name) => {
5784 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5785 }
5786 MemberProp::Computed(index) => {
5787 self.expr(index)?;
5788 self.emit(Opcode::GetArrayEl2, &[]);
5789 }
5790 MemberProp::Private(name) => {
5791 let binding = format!("#{}", name.name);
5792 let (kind, _) = self.private_use(&binding, expr.span)?;
5793 self.private_callee(&binding, kind)?;
5794 }
5795 }
5796 self.emit_jump(Opcode::Goto, call, &[]);
5797 self.place_label(short);
5798 self.emit(Opcode::Undefined, &[]);
5799 self.place_label(call);
5800 if Self::has_spread(arguments) {
5801 self.argument_array(arguments)?;
5802 self.emit(Opcode::Perm3, &[]);
5803 self.emit(Opcode::Apply, &[Op::Int(0)]);
5804 return Ok(());
5805 }
5806 for argument in arguments {
5807 self.expr(argument)?;
5808 }
5809 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5810 return Ok(());
5811 }
5812 self.chain_link(callee, end)?;
5813 if *optional {
5814 self.optional_guard(end);
5815 }
5816 if Self::has_spread(arguments) {
5817 // `func array -> func undefined array`, which is the plain-call
5818 // form of `apply`: the receiver is `undefined`.
5819 self.argument_array(arguments)?;
5820 self.emit(Opcode::Undefined, &[]);
5821 self.emit(Opcode::Swap, &[]);
5822 self.emit(Opcode::Apply, &[Op::Int(0)]);
5823 return Ok(());
5824 }
5825 for argument in arguments {
5826 self.expr(argument)?;
5827 }
5828 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5829 Ok(())
5830 }
5831 _ => self.expr(expr),
5832 }
5833 }
5834
5835 /// Compile `expr` as a tail call when it is one, reporting whether it was.
5836 ///
5837 /// `tail_call` reuses the current frame instead of pushing a new one, so a
5838 /// tail-recursive function runs in constant stack space. It also has to be the
5839 /// *last* thing the function does, which is why only a `return` reaches here.
5840 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5841 let ExprKind::Call {
5842 callee,
5843 arguments,
5844 optional: false,
5845 } = &expr.unparen().kind
5846 else {
5847 return Ok(false);
5848 };
5849 // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5850 // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5851 // as an ordinary call costs the one frame the optimisation was saving and keeps the
5852 // semantics — the alternative was reaching the spread expression below and failing
5853 // with "this expression form is not supported", which is how `return super.m(...a)`
5854 // stopped compiling. Checked before anything is emitted, because the decision cannot
5855 // be taken back once `super_base` or a `get_field2` is on the stack.
5856 if Self::has_spread(arguments) {
5857 return Ok(false);
5858 }
5859 let end = self.new_label();
5860 if let ExprKind::Member {
5861 object,
5862 property,
5863 optional: false,
5864 } = &callee.unparen().kind
5865 {
5866 // `super.m()` in tail position is still an ordinary method call with `this`
5867 // as the receiver; only the read of the method differs.
5868 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5869 self.super_base();
5870 match property {
5871 MemberProp::Ident(name) => self.emit(
5872 Opcode::PushAtomValue,
5873 &[Op::Atom(Atom::from_text(&name.name))],
5874 ),
5875 MemberProp::Computed(index) => self.expr(index)?,
5876 MemberProp::Private(_) => return Ok(false),
5877 }
5878 self.emit(Opcode::GetArrayEl, &[]);
5879 for argument in arguments {
5880 self.expr(argument)?;
5881 }
5882 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5883 self.place_label(end);
5884 return Ok(true);
5885 }
5886 self.chain_link(object, end)?;
5887 match property {
5888 MemberProp::Ident(name) => {
5889 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5890 }
5891 MemberProp::Computed(index) => {
5892 self.expr(index)?;
5893 self.emit(Opcode::GetArrayEl2, &[]);
5894 }
5895 MemberProp::Private(_) => return Ok(false),
5896 }
5897 for argument in arguments {
5898 self.expr(argument)?;
5899 }
5900 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5901 self.place_label(end);
5902 return Ok(true);
5903 }
5904 self.chain_link(callee, end)?;
5905 for argument in arguments {
5906 self.expr(argument)?;
5907 }
5908 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5909 self.place_label(end);
5910 Ok(true)
5911 }
5912
5913 /// The `?.` guard: keep the value if it is neither null nor undefined,
5914 /// otherwise replace it with `undefined` and leave the whole chain.
5915 fn optional_guard(&mut self, end: Label) {
5916 let cont = self.new_label();
5917 self.emit(Opcode::Dup, &[]);
5918 self.emit(Opcode::IsUndefinedOrNull, &[]);
5919 self.emit_jump(Opcode::IfFalse, cont, &[]);
5920 self.emit(Opcode::Drop, &[]);
5921 self.emit(Opcode::Undefined, &[]);
5922 self.emit_jump(Opcode::Goto, end, &[]);
5923 self.place_label(cont);
5924 }
5925
5926 fn push_number(&mut self, value: f64) {
5927 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5928 // goes into the constant pool.
5929 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5930 let int = value as i32;
5931 if (-1..=7).contains(&int) {
5932 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5933 return;
5934 }
5935 if (-128..=127).contains(&int) {
5936 self.emit(Opcode::PushI8, &[Op::Int(int)]);
5937 return;
5938 }
5939 if (-32768..=32767).contains(&int) {
5940 self.emit(Opcode::PushI16, &[Op::Int(int)]);
5941 return;
5942 }
5943 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5944 return;
5945 }
5946 let index = self.push_constant(Constant::Number(value));
5947 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5948 }
5949
5950 /// Push a `BigInt` literal.
5951 ///
5952 /// A value that fits an `i32` uses the immediate form, which is what the reference
5953 /// emits too; anything larger goes into the constant pool, because the operand of
5954 /// `push_bigint` is only four bytes wide.
5955 fn push_bigint(&mut self, digits: &str, radix: u32) {
5956 if radix == 10
5957 && let Ok(value) = digits.parse::<i64>()
5958 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5959 {
5960 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5961 return;
5962 }
5963 let index = self.push_constant(Constant::BigInt {
5964 digits: digits.to_string(),
5965 radix,
5966 });
5967 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5968 }
5969
5970 fn push_string(&mut self, text: &Wtf8) {
5971 if text.is_empty() {
5972 self.emit(Opcode::PushEmptyString, &[]);
5973 return;
5974 }
5975 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5976 }
5977
5978 /// Name an anonymous function from the binding it is assigned to.
5979 ///
5980 /// `var f = function(){}` produces a function whose `name` is `f`, which the
5981 /// runtime cannot know without being told: the function object is created
5982 /// before the store. `set_name` carries the name across.
5983 fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5984 if !value.is_anonymous_function_definition() {
5985 return;
5986 }
5987 // A class cannot use `set_name`, because its static field initialisers have already
5988 // run by the time the store happens and they can see `this.name`:
5989 // `var E = class { static f = this.name }` has to answer `"E"`. The reference patches
5990 // the `define_class` instruction's name operand instead, which is why
5991 // `set_class_name` is a compile-time marker with no runtime effect
5992 // (`class-name-static-initializer-anonymous`).
5993 if matches!(value.unparen().kind, ExprKind::Class(_)) {
5994 if let Some(index) = self.last_define_class() {
5995 let atom = Atom::from_wtf8(name);
5996 if let Some(Insn::Fixed { operands, .. }) = self.state().insns.get_mut(index) {
5997 // `define_class <atom> <flags>`: the name is operand 0.
5998 operands[0] = Op::Atom(atom);
5999 }
6000 }
6001 return;
6002 }
6003 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
6004 }
6005
6006 /// The index of the most recent `define_class` in this function's instruction stream.
6007 ///
6008 /// A backwards scan, because everything the class body emitted for the *enclosing*
6009 /// function is still there after it — the static initialiser's call, the class
6010 /// binding's store, `leave_scope` — and only the `define_class` carries the name.
6011 fn last_define_class(&self) -> Option<usize> {
6012 self.cur().insns.iter().rposition(|insn| {
6013 matches!(
6014 insn,
6015 Insn::Fixed {
6016 op: Opcode::DefineClass,
6017 ..
6018 }
6019 )
6020 })
6021 }
6022
6023 /// The same, for a computed key: the name comes from the value on the stack
6024 /// rather than from an atom, so a different instruction carries it.
6025 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
6026 if value.is_anonymous_function_definition() {
6027 self.emit(Opcode::SetNameComputed, &[]);
6028 }
6029 }
6030
6031 /// Compile a function body that exists only in the compiler's head — a class's
6032 /// implicit constructor or its field initialiser.
6033 ///
6034 /// Everything structural is the same as a written function: a fresh `FnState`, its
6035 /// own body block, and resolution while the frame is still on the stack. Only the
6036 /// statements differ.
6037 fn compile_synthetic_function(
6038 &mut self,
6039 name: &str,
6040 strict: bool,
6041 span: Span,
6042 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
6043 ) -> Result<CompiledFunction, SyntaxError> {
6044 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
6045 state.span = Some((span.start.offset as usize, span.end.offset as usize));
6046 state.strict = strict;
6047 state.created_in_block = self.cur().current_block;
6048 state.with_names = self.cur().with_names.clone();
6049 state.line = span.start.line;
6050 state.column = span.start.column;
6051 let depth = self.stack.len();
6052 self.stack.push(state);
6053 let body_key = span.start.offset as u64;
6054 self.push_block(body_key, NO_PARENT);
6055 self.state().body_block = body_key;
6056 let result = (|| {
6057 self.emit_scope_enter(body_key);
6058 body(self)?;
6059 if self.end_is_reachable() {
6060 self.emit(Opcode::ReturnUndef, &[]);
6061 }
6062 Ok(())
6063 })();
6064 if result.is_err() {
6065 self.stack.truncate(depth);
6066 return result.map(|()| unreachable!());
6067 }
6068 Ok(self.finish_current())
6069 }
6070
6071 /// The implicit return of a class constructor.
6072 ///
6073 /// A constructor that falls off the end initialises its instance fields first, and a
6074 /// derived one returns `this` — which is what makes `new D()` the object `super()`
6075 /// built rather than `undefined`.
6076 fn emit_class_constructor_tail(&mut self) {
6077 match self.cur().ctor_kind {
6078 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
6079 // Nothing to install: a base constructor did it in its prologue and a derived
6080 // one at each `super()` site, which is where `this` first exists.
6081 CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
6082 CtorKind::Derived => {
6083 // `get_loc_check` rather than `get_loc`: reaching the end without ever
6084 // running `super()` is a ReferenceError, not `undefined`.
6085 self.emit_var(VarAction::Get, "this");
6086 self.emit(Opcode::Return, &[]);
6087 }
6088 }
6089 }
6090
6091 /// `yield expr` / `yield* expr`.
6092 ///
6093 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
6094 /// it to the caller and parks the frame. On resume the stack holds the value the
6095 /// caller passed *and* a "magic" number saying which method resumed it — `next`
6096 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
6097 /// `if_false <continue>` asks whether this was an ordinary `next`:
6098 ///
6099 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
6100 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
6101 /// and uses the value sitting under the magic number.
6102 ///
6103 /// A `throw` never reaches here: the interpreter unwinds instead (see
6104 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
6105 fn yield_expression(
6106 &mut self,
6107 argument: Option<&Expr>,
6108 delegate: bool,
6109 ) -> Result<(), SyntaxError> {
6110 if delegate {
6111 return self.yield_star(argument);
6112 }
6113 // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
6114 // does the same for the `return(v)` that can resume it — which is why an async
6115 // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
6116 // generator's is just `yield`.
6117 let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
6118 match argument {
6119 Some(value) => self.expr(value)?,
6120 None => self.emit(Opcode::Undefined, &[]),
6121 }
6122 if is_async {
6123 self.emit(Opcode::Await, &[]);
6124 self.state().has_await = true;
6125 }
6126 self.emit(Opcode::Yield, &[]);
6127 let resume = self.new_label();
6128 self.emit_jump(Opcode::IfFalse, resume, &[]);
6129 // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
6130 // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
6131 // finished the generator and never ran the `finally`.
6132 if is_async {
6133 self.emit(Opcode::Await, &[]);
6134 }
6135 self.emit_unwind_for_return(true);
6136 self.emit(Opcode::ReturnAsync, &[]);
6137 self.place_label(resume);
6138 // Nothing is emitted here: the value the caller passed to `next` *is* the value
6139 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
6140 // it through the ordinary expression-statement discard.
6141 Ok(())
6142 }
6143
6144 /// `yield* iterable`.
6145 ///
6146 /// The shape is the reference's, and it is a fall-through chain rather than a
6147 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
6148 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
6149 /// the inner iterator and finishes, `throw` forwards the exception into it and
6150 /// continues only if it has a `throw` method.
6151 ///
6152 /// The stack is `iter next catch value` throughout, `catch` being the offset
6153 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
6154 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
6155 match argument {
6156 Some(value) => self.expr(value)?,
6157 // The parser rejects a bare `yield*`, so this is unreachable in practice.
6158 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
6159 }
6160 // `for await of` is the same protocol as `for of` with two differences that matter
6161 // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
6162 // every `next()` result is a promise the delegate has to await.
6163 let is_async = self.cur().kind.is_async();
6164 self.emit(
6165 if is_async {
6166 Opcode::ForAwaitOfStart
6167 } else {
6168 Opcode::ForOfStart
6169 },
6170 &[],
6171 );
6172 self.emit(Opcode::Drop, &[]);
6173 self.emit(Opcode::Undefined, &[]);
6174 self.emit(Opcode::Undefined, &[]);
6175 let next = self.new_label();
6176 let resume = self.new_label();
6177 let finished = self.new_label();
6178 let rethrow = self.new_label();
6179 let throw_no_method = self.new_label();
6180 let done = self.new_label();
6181 self.place_label(next);
6182 self.emit(Opcode::IteratorNext, &[]);
6183 if is_async {
6184 self.emit(Opcode::Await, &[]);
6185 self.state().has_await = true;
6186 }
6187 self.emit(Opcode::IteratorCheckObject, &[]);
6188 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6189 self.emit_jump(Opcode::IfTrue, done, &[]);
6190 // The suspension. `resume` is both the label the return path jumps back to in order
6191 // to yield one more value and where the caller's answer arrives, as the value
6192 // followed by the magic number.
6193 //
6194 // The two forms differ in what they hand the suspension: `yield_star` takes the
6195 // result object itself, `async_yield_star` takes `.value`, because an async
6196 // generator awaits and re-wraps whatever it yields.
6197 self.place_label(resume);
6198 if is_async {
6199 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6200 self.emit(Opcode::AsyncYieldStar, &[]);
6201 } else {
6202 self.emit(Opcode::YieldStar, &[]);
6203 }
6204 self.emit(Opcode::Dup, &[]);
6205 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
6206 self.emit(Opcode::Drop, &[]);
6207 self.emit_jump(Opcode::Goto, next, &[]);
6208
6209 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
6210 self.place_label(rethrow);
6211 self.emit(Opcode::PushI32, &[Op::Int(2)]);
6212 self.emit(Opcode::StrictEq, &[]);
6213 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
6214 // A `return` closes the inner iterator; if it had none, the delegate simply
6215 // finishes with the requested value. In an async generator both the call and its
6216 // result are awaited, because the inner `return` may itself be async.
6217 if is_async {
6218 self.emit(Opcode::Await, &[]);
6219 }
6220 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
6221 self.emit_jump(Opcode::IfTrue, finished, &[]);
6222 if is_async {
6223 self.emit(Opcode::Await, &[]);
6224 }
6225 self.emit(Opcode::IteratorCheckObject, &[]);
6226 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6227 self.emit_jump(Opcode::IfFalse, resume, &[]);
6228 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6229 self.place_label(finished);
6230 self.emit(Opcode::Nip, &[]);
6231 self.emit(Opcode::Nip, &[]);
6232 self.emit(Opcode::Nip, &[]);
6233 // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
6234 // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
6235 // awaits the value in an async generator and then runs the same `finally`/iterator
6236 // unwinding a written `return` would. Skipping the unwinding made
6237 // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
6238 if is_async {
6239 self.emit(Opcode::Await, &[]);
6240 }
6241 self.emit_unwind_for_return(true);
6242 self.emit(Opcode::ReturnAsync, &[]);
6243
6244 // `throw(e)`: forward it into the inner iterator.
6245 self.place_label(throw_no_method);
6246 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
6247 let no_throw = self.new_label();
6248 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
6249 if is_async {
6250 self.emit(Opcode::Await, &[]);
6251 }
6252 self.emit(Opcode::IteratorCheckObject, &[]);
6253 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6254 self.emit_jump(Opcode::IfFalse, resume, &[]);
6255 self.emit_jump(Opcode::Goto, done, &[]);
6256 // No `throw` method: close the iterator, then report the spec's TypeError. The
6257 // `if_true` before the `await` is the reference's shape — the flag it consumes is
6258 // what `iterator_call` leaves behind, and a close that *did* find no `return`
6259 // method has nothing to await.
6260 self.place_label(no_throw);
6261 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
6262 let no_close = self.new_label();
6263 self.emit_jump(Opcode::IfTrue, no_close, &[]);
6264 if is_async {
6265 self.emit(Opcode::Await, &[]);
6266 }
6267 self.place_label(no_close);
6268 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
6269
6270 // The inner iterator finished: the delegate's value is the `yield*` expression's
6271 // value, so it is left on the stack for whatever consumes it.
6272 self.place_label(done);
6273 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6274 self.emit(Opcode::Nip, &[]);
6275 self.emit(Opcode::Nip, &[]);
6276 self.emit(Opcode::Nip, &[]);
6277 Ok(())
6278 }
6279
6280 /// `await expr`: exactly one instruction.
6281 ///
6282 /// No resume-magic branch follows it. The reference's `await` leaves a single value
6283 /// on the stack and completion is signalled by the `return_async` at the end of the
6284 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
6285 /// reference never emits, and a `for await` loop — which reaches `await` through the
6286 /// same opcode — would then spill a value the loop's unpacking does not expect.
6287 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
6288 self.expr(argument)?;
6289 self.emit(Opcode::Await, &[]);
6290 self.state().has_await = true;
6291 Ok(())
6292 }
6293
6294 /// The `super` base: the receiver followed by the home object's prototype.
6295 ///
6296 /// Everything `super` does needs both. A *read* starts at the prototype but reports
6297 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
6298 /// prototype but calls it with the receiver.
6299 fn super_base(&mut self) {
6300 self.this_expression();
6301 self.home_object();
6302 self.emit(Opcode::GetSuper, &[]);
6303 }
6304
6305 /// `[[HomeObject]]` as `super` sees it.
6306 ///
6307 /// A method, a constructor and a field initialiser each carry one — `set_home_object`
6308 /// put it there — so for them the special object *is* the answer. An arrow and a
6309 /// static block have none: they read the enclosing function's, which has to be
6310 /// materialised into a local, exactly as `this` is for an arrow.
6311 ///
6312 /// The name matches what the reference stores, so the disassembly agrees; it is not a
6313 /// name any program can write.
6314 fn home_object(&mut self) {
6315 if !self.cur().is_arrow {
6316 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
6317 return;
6318 }
6319 if let Some(target) = self.enclosing_function() {
6320 self.state_at(target).needs_home_object_local = true;
6321 self.declare_at(target, HOME_OBJECT);
6322 }
6323 self.emit_var(VarAction::Get, HOME_OBJECT);
6324 }
6325
6326 /// `super(args)`: construct the parent class and adopt the result as `this`.
6327 ///
6328 /// The parent is the prototype of the constructor that is running, which is exactly
6329 /// what `extends` set up. `new.target` is passed through unchanged so that
6330 /// `new.target` inside the parent is the class actually being constructed.
6331 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
6332 self.active_func_expression();
6333 self.emit(Opcode::GetSuper, &[]);
6334 self.new_target_expression();
6335 if Self::has_spread(arguments) {
6336 self.argument_array(arguments)?;
6337 self.emit(Opcode::Apply, &[Op::Int(1)]);
6338 } else {
6339 for argument in arguments {
6340 self.expr(argument)?;
6341 }
6342 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
6343 }
6344 // The value stays on the stack: `super()` is an expression, and a derived
6345 // constructor's `this` may only be initialised once.
6346 self.emit(Opcode::Dup, &[]);
6347 self.emit_var(VarAction::PutInitChecked, "this");
6348 // Instance fields are installed here, not at the top of the body: a derived
6349 // constructor has no `this` to install them on until `super()` returns. The
6350 // reference emits the same call at every `super()` site.
6351 self.call_field_initialiser();
6352 Ok(())
6353 }
6354
6355 /// `this` as a local, which every class constructor and field initialiser needs.
6356 ///
6357 /// The reference materialises the receiver into a local rather than reading
6358 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
6359 /// and a field initialiser has to see the final value.
6360 fn begin_this_local(&mut self) {
6361 self.declare_hidden_local("this", VarKind::Normal);
6362 self.emit(Opcode::PushThis, &[]);
6363 self.emit_var(VarAction::Put, "this");
6364 // The store is already at the top of the body, so `provide_this_local` has
6365 // nothing left to prepend. Without this the initialiser ended up with
6366 // `push_this; put_loc0 this` twice whenever the class also held a field
6367 // initialiser whose body read `this` through an arrow.
6368 self.state().has_this_prologue = true;
6369 }
6370
6371 /// Compile a constructor the class wrote.
6372 ///
6373 /// The flags have to be in place before the body is compiled, but
6374 /// `compile_function_with_name` creates its own state — so the caller's state is
6375 /// marked instead and the new one inherits it. That is the same trick the parameter
6376 /// prologue uses, and it keeps one code path for both.
6377 fn compile_class_constructor(
6378 &mut self,
6379 func: &ast::Function,
6380 has_heritage: bool,
6381 ) -> Result<CompiledFunction, SyntaxError> {
6382 let saved = self.cur().ctor_kind;
6383 self.state().class_ctor_pending = Some(if has_heritage {
6384 CtorKind::Derived
6385 } else {
6386 CtorKind::Base
6387 });
6388 let result = self.compile_function_with_name(func, false);
6389 self.state().ctor_kind = saved;
6390 self.state().class_ctor_pending = None;
6391 result
6392 }
6393
6394 /// The constructor a class gets when it does not declare one.
6395 ///
6396 /// A base class's is empty; a derived class's forwards every argument to the parent
6397 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
6398 /// instance field initialiser afterwards when the class has fields, which is why the
6399 /// initialiser is captured rather than inlined.
6400 fn compile_implicit_constructor(
6401 &mut self,
6402 class: &Class,
6403 has_heritage: bool,
6404 ) -> Result<CompiledFunction, SyntaxError> {
6405 self.compile_synthetic_function(
6406 "",
6407 true,
6408 Span::new(class.body_end, class.body_end),
6409 |compiler| {
6410 if has_heritage {
6411 // A derived constructor's `this` does not exist until `super()` returns,
6412 // so it starts in the dead zone and `init_ctor` fills it.
6413 compiler.declare("this", VarDef::lexical("this"));
6414 compiler.emit(
6415 Opcode::SetLocUninitialized,
6416 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6417 );
6418 compiler.emit(Opcode::InitCtor, &[]);
6419 compiler.emit(
6420 Opcode::PutLocCheckInit,
6421 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6422 );
6423 } else {
6424 compiler.begin_this_local();
6425 compiler.emit(Opcode::CheckCtor, &[]);
6426 }
6427 compiler.call_field_initialiser();
6428 // A derived constructor returns `this`, the object `super()` built. Without
6429 // this the implicit constructor fell through to `return_undef`, and `new B()`
6430 // handed back the empty object `construct` had made instead of the one the
6431 // parent constructor initialised.
6432 if has_heritage {
6433 compiler.emit_var(VarAction::Get, "this");
6434 compiler.emit(Opcode::Return, &[]);
6435 }
6436 Ok(())
6437 },
6438 )
6439 }
6440
6441 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
6442 ///
6443 /// A class with no instance fields leaves the binding `undefined`, and calling it
6444 /// would throw; the reference emits the same guard rather than branching at compile
6445 /// time because a class can be extended by a subclass whose fields still have to run.
6446 fn call_field_initialiser(&mut self) {
6447 let skip = self.new_label();
6448 self.emit_var(VarAction::Get, "<class_fields_init>");
6449 self.emit(Opcode::Dup, &[]);
6450 self.emit_jump(Opcode::IfFalse, skip, &[]);
6451 self.emit_var(VarAction::Get, "this");
6452 self.emit(Opcode::Swap, &[]);
6453 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6454 self.place_label(skip);
6455 self.emit(Opcode::Drop, &[]);
6456 }
6457
6458 /// The function that defines one class's fields on `this`, and runs its static blocks.
6459 ///
6460 /// `define_field` rather than `put_field`: a field is an own property created
6461 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
6462 /// `x = 1` field must not call the setter.
6463 ///
6464 /// One function serves the whole class: it is called once per instance (or once, for
6465 /// the static half) and walks the members in source order. Static blocks are compiled
6466 /// into the same function because they *are* part of the same sequence — `static a =
6467 /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
6468 /// different values, so the two kinds cannot be split apart.
6469 fn compile_field_initialiser(
6470 &mut self,
6471 items: &[StaticInitItem<'_>],
6472 span: Span,
6473 instance: bool,
6474 add_brand: bool,
6475 ) -> Result<CompiledFunction, SyntaxError> {
6476 self.compile_synthetic_function("", true, span, |compiler| {
6477 // A field initialiser and a static block are not functions, so neither has an
6478 // `arguments` of its own; see `FnState::no_arguments_binding`.
6479 let current = compiler.stack.len() - 1;
6480 compiler.stack[current].no_arguments_binding = true;
6481 if instance {
6482 // An instance initialiser always carries a `<home_object>` local, because the
6483 // brand block below reads it — even when that block turns out to be dead. The
6484 // reference has the same artefact, and the store is visible in its dump.
6485 let current = compiler.stack.len() - 1;
6486 compiler.stack[current].needs_home_object_local = true;
6487 }
6488 compiler.begin_this_local();
6489 if instance {
6490 // `this` gets the brand the prototype created, before any field is defined —
6491 // which is what makes `#m()` usable from inside a field initialiser.
6492 //
6493 // The reference always emits `push_false; if_false L; this; home; add_brand;
6494 // L:` and patches the `push_false` to `push_true` from the class parse when
6495 // the class has private methods; either way the branch folds, but the *mark*
6496 // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
6497 // `this` local from being fused into a `set_loc`.
6498 let skip = compiler.new_label();
6499 if add_brand {
6500 compiler.emit(Opcode::PushTrue, &[]);
6501 } else {
6502 compiler.emit(Opcode::PushFalse, &[]);
6503 }
6504 compiler.emit_jump(Opcode::IfFalse, skip, &[]);
6505 compiler.emit_var(VarAction::Get, "this");
6506 compiler.emit_var(VarAction::Get, HOME_OBJECT);
6507 compiler.emit(Opcode::AddBrand, &[]);
6508 compiler.place_label(skip);
6509 }
6510 for item in items {
6511 match item {
6512 StaticInitItem::Field(key, value) => {
6513 // A private field is *defined*, not assigned: `define_private_field`
6514 // reads `obj symbol value`, and its point is that it fails on a
6515 // receiver that is not this class's — which `put_field` would not.
6516 //
6517 // The three shapes are the reference's: `define_field <atom>` for a
6518 // static name, `define_array_el` for a key that is only known at run
6519 // time (`obj key value`), `define_private_field` for `#x`, and a
6520 // computed key is read from its binding rather than recomputed.
6521 compiler.emit_var(VarAction::Get, "this");
6522 match key {
6523 FieldKey::Private(binding) | FieldKey::Computed(binding) => {
6524 compiler.emit_var(VarAction::Get, binding);
6525 }
6526 FieldKey::Literal(_) => {}
6527 }
6528 match value {
6529 Some(value) => {
6530 compiler.expr(value)?;
6531 // A field initialiser is a `NamedEvaluation` target:
6532 // `x = function(){}` names the function `"x"`, and a private
6533 // field keeps its `#` (`static #f = () => 1` is named
6534 // `"#f"` (elements/static-field-anonymous-function-name).
6535 match key {
6536 FieldKey::Literal(literal) => {
6537 let text = compiler.property_key_text(literal, span)?;
6538 compiler.set_name_if_anonymous(value, &text);
6539 }
6540 FieldKey::Private(binding) => {
6541 compiler.set_name_if_anonymous(value, &Wtf8::new(binding));
6542 }
6543 // The key is a value on the stack, and `set_name_computed`
6544 // is exactly the instruction for that.
6545 FieldKey::Computed(_) => {
6546 compiler.set_name_if_anonymous_computed(value);
6547 }
6548 }
6549 }
6550 None => compiler.emit(Opcode::Undefined, &[]),
6551 }
6552 match key {
6553 FieldKey::Literal(literal) => {
6554 let text = compiler.property_key_text(literal, span)?;
6555 compiler
6556 .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
6557 }
6558 FieldKey::Computed(_) => {
6559 compiler.emit(Opcode::DefineArrayEl, &[]);
6560 // `define_array_el` leaves `obj key`; the key is consumed by
6561 // the copy the pattern machinery wants, so both go.
6562 compiler.emit(Opcode::Drop, &[]);
6563 }
6564 FieldKey::Private(_) => {
6565 compiler.emit(Opcode::DefinePrivateField, &[]);
6566 }
6567 }
6568 compiler.emit(Opcode::Drop, &[]);
6569 }
6570 StaticInitItem::Block { body, body_start } => {
6571 let block = compiler.compile_static_block(body, *body_start)?;
6572 let index = compiler.push_constant(Constant::Function(Box::new(block)));
6573 // `this fclosure`, so `call_method` finds the receiver below the
6574 // callee: the block runs with `this` bound to the class.
6575 compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
6576 compiler.emit_var(VarAction::Get, "this");
6577 compiler.emit(Opcode::Swap, &[]);
6578 compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
6579 // Nothing the block evaluates is wanted; its effects are the point.
6580 compiler.emit(Opcode::Drop, &[]);
6581 }
6582 }
6583 }
6584 Ok(())
6585 })
6586 }
6587
6588 /// Compile a `static { … }` body into the function the class calls for it.
6589 ///
6590 /// Shaped like an arrow, because that is the one function form with no `this`,
6591 /// `new.target` or `arguments` of its own: all three reach the enclosing static
6592 /// initialiser, and through it the class. `arguments` never gets that far — the parser
6593 /// rejects the reference — but `this` and `super` both depend on it.
6594 ///
6595 /// The body is hoisted like a function body's, because the reference parses it as one:
6596 /// `var` inside a block is a local of the block's function, not of whatever encloses
6597 /// the class.
6598 fn compile_static_block(
6599 &mut self,
6600 body: &[Stmt],
6601 body_start: Position,
6602 ) -> Result<CompiledFunction, SyntaxError> {
6603 let mut state = FnState::new(String::new(), FunctionKind::Normal);
6604 // Class bodies are strict, so a static block is too.
6605 state.strict = true;
6606 // The one property that makes this an arrow: nothing of its own to bind `this` to,
6607 // so `this` and `super` come from the initialiser that calls it.
6608 state.is_arrow = true;
6609 state.created_in_block = self.cur().current_block;
6610 state.with_names = self.cur().with_names.clone();
6611 state.line = body_start.line;
6612 state.column = body_start.column;
6613 let depth = self.stack.len();
6614 self.stack.push(state);
6615 let body_key = body_start.offset as u64;
6616 self.push_block(body_key, NO_PARENT);
6617 self.state().body_block = body_key;
6618 let result = (|| {
6619 self.hoist(body, body_key)?;
6620 self.emit_scope_enter(body_key);
6621 for statement in body {
6622 self.stmt(statement)?;
6623 }
6624 if self.end_is_reachable() {
6625 self.emit(Opcode::ReturnUndef, &[]);
6626 }
6627 Ok(())
6628 })();
6629 if result.is_err() {
6630 self.stack.truncate(depth);
6631 return result.map(|()| unreachable!());
6632 }
6633 Ok(self.finish_current())
6634 }
6635
6636 /// Compile a class, leaving the constructor on the stack when `keep`.
6637 ///
6638 /// The shape follows the reference: the class body is its own scope holding the
6639 /// class's *inner* name as a `const` — which is what lets a method refer to the
6640 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6641 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6642 /// on the top of the stack: the prototype for instance members, the constructor
6643 /// itself for `static` ones, which is why a static member costs an extra `swap`.
6644 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6645 let parent_block = self.cur().current_block;
6646 let key = class.span.start.offset as u64;
6647 self.push_block(key, parent_block);
6648 let name = class.name.as_ref().map(|ident| ident.name.clone());
6649 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6650 // resolves `E` without a global lookup. An *unnamed* class expression has no such
6651 // binding, and `define_class` is handed the empty name.
6652 if let Some(name) = &name {
6653 self.declare(name, VarDef::constant(name.clone()));
6654 }
6655 self.emit_scope_enter(key);
6656
6657 // The heritage clause is evaluated outside the class's own scope: it cannot see
6658 // the class binding it is about to initialise.
6659 let saved_block = self.cur().current_block;
6660 self.state().current_block = parent_block;
6661 match &class.super_class {
6662 Some(parent) => self.expr(parent)?,
6663 None => self.emit(Opcode::Undefined, &[]),
6664 }
6665 self.state().current_block = saved_block;
6666 let has_heritage = class.super_class.is_some();
6667
6668 // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6669 // lands after the heritage's code — which is where the reference puts it, because it
6670 // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6671 // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6672 // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6673 // came out in the opposite order from the reference's.
6674 //
6675 // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6676 // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6677 // a const accepts — so the old comment's worry ("a const would refuse the second
6678 // store") did not apply: there is no second store.
6679 // Every `#name` the class declares gets a `const` binding in the class scope, and so
6680 // does every computed field key. That is how the reference does it
6681 // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6682 // what makes a private name resolve like any other class-scope variable — including
6683 // through a nested function's closure — while remaining invisible outside.
6684 //
6685 // All of them are declared *before* `<class_fields_init>`, in member order, because
6686 // that is when the reference's parser creates them.
6687 let plan = ClassPlan::build(class);
6688 // The body's private names are visible from here to the end of the class, and shadow
6689 // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6690 // — it is compiled first because `define_class` consumes it, but its body can name
6691 // `#x` like any other member's.
6692 self.private_scopes.push(plan.uses.clone());
6693 let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6694 for binding in &plan.bindings {
6695 class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6696 }
6697 let fci = self.declare(
6698 "<class_fields_init>",
6699 VarDef::constant("<class_fields_init>"),
6700 );
6701 // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6702 // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6703 // members' bindings follow in reverse.
6704 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6705 for slot in class_slots.iter().rev() {
6706 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6707 }
6708
6709 // The constructor is compiled before `define_class` because that instruction
6710 // consumes it; a class without one gets the implicit version.
6711 let constructor = class.elements.iter().find_map(|element| match element {
6712 ClassElement::Method {
6713 kind: MethodKind::Constructor,
6714 func,
6715 ..
6716 } => Some(&**func),
6717 _ => None,
6718 });
6719 // A constructor is compiled differently from a method: it owns `this`. The flags
6720 // go on the *enclosing* state because a constructor is a nested function and
6721 // `compile_function_with_name` starts a fresh one.
6722 let ctor = match constructor {
6723 Some(func) => self.compile_class_constructor(func, has_heritage)?,
6724 None => self.compile_implicit_constructor(class, has_heritage)?,
6725 };
6726 // A closure, not the bare constant: the constructor captures
6727 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6728 // has to hold the cell rather than a copy of its value.
6729 //
6730 // The pool slot is left unassigned for now, because the reference gives the
6731 // constructor the *last* index of the members' range: `js_parse_class` emits a
6732 // `push_const` whose operand is patched at the end of the class parse, after every
6733 // method has taken a slot. Emitting the members first and the constant second is how
6734 // the numbering comes out the same; the instruction itself stays where it is.
6735 let ctor_insn = self.cur().insns.len();
6736 self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6737 let flags = if has_heritage { 1 } else { 0 };
6738 self.emit(
6739 Opcode::DefineClass,
6740 &[
6741 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6742 Op::Int(flags),
6743 ],
6744 );
6745
6746 // Instance fields and static fields are two different functions: the first runs
6747 // per instance from the constructor, the second runs once, here.
6748 let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6749 let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6750 for (index, element) in class.elements.iter().enumerate() {
6751 match element {
6752 ClassElement::Method {
6753 key: member_key,
6754 is_static,
6755 kind,
6756 func,
6757 span,
6758 } => {
6759 if *kind == MethodKind::Constructor {
6760 continue;
6761 }
6762 // `static(x)` is a *method* named `static`, not a static method; the
6763 // parser already decided which by putting it in `kind`.
6764 if *is_static {
6765 self.emit(Opcode::Swap, &[]);
6766 }
6767 // A computed key is evaluated *here*, before the method's closure
6768 // exists, and stays under it: `define_method_computed` pops
6769 // `function, key, object`, so the stack has to read
6770 // `[class, prototype, key, function]`. Evaluating the key after the
6771 // `fclosure` and swapping the two put the prototype *below* the
6772 // closure, which defined the method on the function and lost the
6773 // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6774 // also the spec's — a class body evaluates every element's name before
6775 // that element's function.
6776 if let PropName::Computed(key) = member_key {
6777 self.expr(key)?;
6778 }
6779 let function = self.compile_function_with_name(func, true)?;
6780 let index = self.push_constant(Constant::Function(Box::new(function)));
6781 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6782 match member_key {
6783 // A private method is not a property of the prototype: it is a
6784 // closure in the class scope, which is why nothing outside can reach
6785 // it and why a use site has to brand-check. `set_name` gives the
6786 // function its `name` (`#m`), which an accessor does not get — the
6787 // reference leaves that commented out.
6788 PropName::Private(ident) => {
6789 let name = format!("#{}", ident.name);
6790 // `set_home_object` first: the brand check reads the function's
6791 // home object, and for a method that is the prototype.
6792 self.emit(Opcode::SetHomeObject, &[]);
6793 let binding = if *kind == MethodKind::Set {
6794 format!("{name}<set>")
6795 } else {
6796 name.clone()
6797 };
6798 if *kind == MethodKind::Method {
6799 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6800 }
6801 self.emit_var(VarAction::PutInit, &binding);
6802 }
6803 PropName::Computed(_) => {
6804 self.emit(
6805 Opcode::DefineMethodComputed,
6806 &[Op::Int(class_method_flags(*kind))],
6807 );
6808 }
6809 PropName::Literal(literal) => {
6810 let text = self.property_key_text(literal, *span)?;
6811 self.emit(
6812 Opcode::DefineMethod,
6813 &[
6814 Op::Atom(Atom::from_wtf8(&text)),
6815 Op::Int(class_method_flags(*kind)),
6816 ],
6817 );
6818 }
6819 }
6820 if *is_static {
6821 self.emit(Opcode::Swap, &[]);
6822 }
6823 }
6824 ClassElement::Field {
6825 key: field_key,
6826 is_static,
6827 value,
6828 ..
6829 } => {
6830 // A private field's *symbol* is created here, at the member, and stored
6831 // in its binding: the field's property is keyed by it, so it has to exist
6832 // before any initialiser runs, and a fresh one per class body is what
6833 // makes two classes that both write `#x` independent.
6834 //
6835 // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6836 // whose `toString` has a side effect must not run again per instance.
6837 let key = match field_key {
6838 PropName::Private(ident) => {
6839 let binding = format!("#{}", ident.name);
6840 if *is_static {
6841 self.emit(Opcode::Swap, &[]);
6842 }
6843 self.emit(
6844 Opcode::PrivateSymbol,
6845 &[Op::Atom(Atom::from_text(&binding))],
6846 );
6847 self.emit_var(VarAction::PutInit, &binding);
6848 if *is_static {
6849 self.emit(Opcode::Swap, &[]);
6850 }
6851 FieldKey::Private(binding)
6852 }
6853 PropName::Computed(expression) => {
6854 let binding = plan
6855 .computed
6856 .get(&index)
6857 .cloned()
6858 .expect("every computed key got a binding");
6859 if *is_static {
6860 self.emit(Opcode::Swap, &[]);
6861 }
6862 self.expr(expression)?;
6863 self.emit(Opcode::ToPropkey, &[]);
6864 self.emit_var(VarAction::PutInit, &binding);
6865 if *is_static {
6866 self.emit(Opcode::Swap, &[]);
6867 }
6868 FieldKey::Computed(binding)
6869 }
6870 PropName::Literal(literal) => FieldKey::Literal(literal),
6871 };
6872 if *is_static {
6873 static_items.push(StaticInitItem::Field(key, value.as_deref()));
6874 } else {
6875 instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6876 }
6877 }
6878 ClassElement::StaticBlock {
6879 body, body_start, ..
6880 } => static_items.push(StaticInitItem::Block {
6881 body,
6882 body_start: *body_start,
6883 }),
6884 }
6885 }
6886
6887 // Now that every member has its slot, the constructor can have the next one and the
6888 // `fclosure` above can name it.
6889 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6890 match self.state().insns.get_mut(ctor_insn) {
6891 Some(Insn::Fixed { operands, .. }) => {
6892 operands[0] = Op::Const(ctor_index);
6893 }
6894 // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6895 // loudly beats emitting a `fclosure` of slot 4294967295.
6896 _ => {
6897 return Err(SyntaxError::new(
6898 "the class constructor's fclosure went missing",
6899 class.span,
6900 ));
6901 }
6902 }
6903
6904 // The instance brand: a symbol created once on the prototype, which every instance
6905 // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6906 // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6907 // copy is created. The prototype is on top of the stack at this point.
6908 if plan.instance_brand {
6909 self.emit(Opcode::Dup, &[]);
6910 self.emit(Opcode::Null, &[]);
6911 self.emit(Opcode::Swap, &[]);
6912 self.emit(Opcode::AddBrand, &[]);
6913 }
6914
6915 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6916 // class has no instance fields. The constructor calls it only when it is defined.
6917 //
6918 // A class with private *methods* but no fields still needs one, because adding the
6919 // brand to each new instance is the initialiser's job.
6920 if instance_fields.is_empty() && !plan.instance_brand {
6921 self.emit(Opcode::Undefined, &[]);
6922 } else {
6923 let initialiser = self.compile_field_initialiser(
6924 &instance_fields,
6925 class.span,
6926 true,
6927 plan.instance_brand,
6928 )?;
6929 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6930 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6931 // `set_home_object` reads `obj func`, so the prototype stays where it is.
6932 self.emit(Opcode::SetHomeObject, &[]);
6933 }
6934 self.emit_var(VarAction::PutInit, "<class_fields_init>");
6935 // The prototype has done its job: every instance member is defined on it. What
6936 // is left under it is the constructor.
6937 self.emit(Opcode::Drop, &[]);
6938
6939 // The static brand, for `static #m() {}`: same opcode, but the home object is the
6940 // constructor itself, so the symbol lands on the class and the class carries it.
6941 if plan.static_brand {
6942 self.emit(Opcode::Dup, &[]);
6943 self.emit(Opcode::Dup, &[]);
6944 self.emit(Opcode::AddBrand, &[]);
6945 }
6946
6947 // The class binding is initialised *before* static fields run, so a static field
6948 // can refer to the class by name (`static y = S.x`).
6949 // `set_loc` leaves the constructor on the stack, which is what the static field
6950 // call and the outer store both consume.
6951 //
6952 // Only when there *is* such a binding: an anonymous class expression declares no
6953 // class-scope name, and asking for one by the empty string resolved to nothing —
6954 // which made `var x = class {}` assign `undefined` and put a bogus global store in
6955 // the instruction stream.
6956 if let Some(name) = &name {
6957 self.emit_var(VarAction::SetInit, name);
6958 }
6959 if !static_items.is_empty() {
6960 // The static half has no brand prologue of its own: the constructor got its
6961 // brand above, before this runs.
6962 let initialiser =
6963 self.compile_field_initialiser(&static_items, class.span, false, false)?;
6964 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6965 self.emit(Opcode::Dup, &[]);
6966 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6967 self.emit(Opcode::SetHomeObject, &[]);
6968 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6969 self.emit(Opcode::Drop, &[]);
6970 }
6971 // The body is over, and with it this class's private names.
6972 let _ = self.private_scopes.pop();
6973 self.emit_scope_leave(key);
6974 self.state().current_block = parent_block;
6975 if keep {
6976 // A class *expression* is its own value; the class-scope binding was only
6977 // ever an alias for it.
6978 return Ok(());
6979 }
6980 // A declaration stores into the binding the enclosing statement declared.
6981 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6982 Ok(())
6983 }
6984
6985 fn push_this(&mut self) {
6986 self.emit(Opcode::PushThis, &[]);
6987 }
6988
6989 /// `this`, which an arrow does not have of its own.
6990 ///
6991 /// The reference gives the enclosing function a local named `this`, initialised from
6992 /// `push_this` at the top of its body, and the arrow then reads it as a captured
6993 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6994 /// the arrow is called with none.
6995 fn this_expression(&mut self) {
6996 // In a class constructor `this` is a local: a derived constructor only gets one
6997 // when `super()` returns, and reading the raw receiver would give the *outer*
6998 // one instead.
6999 if self.cur().ctor_kind != CtorKind::None {
7000 self.emit_var(VarAction::Get, "this");
7001 return;
7002 }
7003 if !self.cur().is_arrow {
7004 self.push_this();
7005 return;
7006 }
7007 // An arrow at the **top level** of a script or module has no enclosing function,
7008 // but it still inherits `this` — the script's or module's own. Falling through to
7009 // `emit_var(Get, "this")` without a target made that a *global* lookup, so
7010 // `var f = () => typeof this` at top level reported
7011 // `ReferenceError: 'this' is not defined` instead of `"object"`
7012 // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
7013 // is the test262 case that reaches it, through a native `forEach`).
7014 //
7015 // The script state is the bottom of the stack, so it is the fallback target. Its
7016 // own `provide_this_local` then prepends the `push_this` the arrow reads.
7017 let target = self.enclosing_function().unwrap_or(0);
7018 self.state_at(target).needs_this_local = true;
7019 self.declare_at(target, "this");
7020 self.emit_var(VarAction::Get, "this");
7021 }
7022
7023 /// `new.target`, which an arrow likewise does not own.
7024 fn new_target_expression(&mut self) {
7025 if !self.cur().is_arrow {
7026 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
7027 return;
7028 }
7029 if let Some(target) = self.enclosing_function() {
7030 self.state_at(target).needs_new_target_local = true;
7031 self.declare_at(target, NEW_TARGET);
7032 }
7033 self.emit_var(VarAction::Get, NEW_TARGET);
7034 }
7035
7036 /// `this.active_func`: the function `super()` resolves against.
7037 ///
7038 /// In a constructor or a method that is the function being run, so the special object
7039 /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
7040 /// a closure variable — see [`FnState::needs_active_func_local`].
7041 fn active_func_expression(&mut self) {
7042 if !self.cur().is_arrow {
7043 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
7044 return;
7045 }
7046 if let Some(target) = self.enclosing_function() {
7047 self.state_at(target).needs_active_func_local = true;
7048 self.declare_at(target, ACTIVE_FUNC);
7049 }
7050 self.emit_var(VarAction::Get, ACTIVE_FUNC);
7051 }
7052
7053 /// Give the function a local `<active_func>`, for an arrow inside it to capture.
7054 fn provide_active_func_local(&mut self) {
7055 let current = self.stack.len() - 1;
7056 if !self.stack[current].needs_active_func_local {
7057 return;
7058 }
7059 if !self.stack[current]
7060 .vars
7061 .iter()
7062 .any(|var| var.name == ACTIVE_FUNC)
7063 {
7064 self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
7065 }
7066 self.prepend_initialiser(
7067 ACTIVE_FUNC,
7068 Insn::Fixed {
7069 op: Opcode::SpecialObject,
7070 operands: vec![Op::Int(2)],
7071 },
7072 );
7073 }
7074
7075 /// Give the function a local `new.target`, for an arrow inside it to capture.
7076 fn provide_new_target_local(&mut self) {
7077 let current = self.stack.len() - 1;
7078 if !self.stack[current].needs_new_target_local {
7079 return;
7080 }
7081 if !self.stack[current]
7082 .vars
7083 .iter()
7084 .any(|var| var.name == NEW_TARGET)
7085 {
7086 self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
7087 }
7088 self.prepend_initialiser(
7089 NEW_TARGET,
7090 Insn::Fixed {
7091 op: Opcode::SpecialObject,
7092 operands: vec![Op::Int(3)],
7093 },
7094 );
7095 }
7096
7097 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
7098 /// function.
7099 fn ensure_enclosing_arguments(&mut self) {
7100 // An arrow created in a parameter list needs the *parameter* scope's
7101 // `arguments`, not the body's: the two are separate bindings and the arrow was
7102 // born before the body existed.
7103 let from_params = self.cur().created_in_params;
7104 if let Some(target) = self.enclosing_function() {
7105 self.state_at(target).needs_arguments_local = true;
7106 if from_params {
7107 self.state_at(target).needs_param_arguments = true;
7108 // Declare it now, not at the enclosing function's `finish_current`: the
7109 // arrow resolves its own `arguments` before that runs, and a binding that
7110 // does not exist yet resolves as a global.
7111 declare_param_var_at(&mut self.stack[target], "arguments");
7112 }
7113 self.declare_at(target, "arguments");
7114 }
7115 }
7116
7117 /// The innermost enclosing frame that is a real function — an arrow inherits from it
7118 /// rather than starting a scope of its own.
7119 /// The innermost enclosing frame that can own a lexical binding an arrow reads —
7120 /// a real function, or a **script** top level.
7121 ///
7122 /// A script is in the list because an `eval` body is compiled as one and an arrow
7123 /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
7124 /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
7125 /// a *global* lookup of `new.target`, which no frame provides — so it raised
7126 /// `ReferenceError` instead of answering the caller's value
7127 /// (`arrow-body-direct-eval-err-contains-newtarget`).
7128 fn enclosing_function(&self) -> Option<usize> {
7129 (0..self.stack.len())
7130 .rev()
7131 .find(|index| !self.stack[*index].is_arrow)
7132 }
7133
7134 fn state_at(&mut self, index: usize) -> &mut FnState {
7135 &mut self.stack[index]
7136 }
7137
7138 /// Declare a `var` binding directly in a specific frame.
7139 fn declare_at(&mut self, index: usize, name: &str) {
7140 let state = &mut self.stack[index];
7141 if state.vars.iter().any(|var| var.name == name) {
7142 return;
7143 }
7144 state.var_block.push(FUNCTION_SCOPE);
7145 state.vars.push(VarDef::var(name));
7146 }
7147
7148 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
7149 /// the reference calls a `special_object` gets initialised on entry.
7150 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
7151 let current = self.stack.len() - 1;
7152 let init = [
7153 producer,
7154 Insn::Var {
7155 action: VarAction::Put,
7156 name: name.to_string(),
7157 block: 0,
7158 // A prologue initialiser runs before the body proper, but it is body
7159 // code: `this` and `arguments` are provided for it, not by it.
7160 in_params: false,
7161 },
7162 ];
7163 let inserted = init.len();
7164 for (index, instruction) in init.into_iter().enumerate() {
7165 self.stack[current].insns.insert(index, instruction);
7166 }
7167 for placed in self.stack[current].labels.iter_mut().flatten() {
7168 *placed += inserted;
7169 }
7170 self.stack[current].label_since_insn = true;
7171 }
7172
7173 fn push_constant(&mut self, constant: Constant) -> u32 {
7174 let state = self.state();
7175 let index = state.cpool.len() as u32;
7176 state.cpool.push(constant);
7177 index
7178 }
7179
7180 /// Compile `a && b`, `a || b`, `a ?? b`.
7181 ///
7182 /// A run of the *same* operator shares one end label, so `a || b || c` tests
7183 /// `a` once and jumps past everything when it is truthy, instead of falling
7184 /// into `b`'s test. The parser builds such a run left-associated —
7185 /// `((a || b) || c)` — so the operands are collected off the left spine.
7186 ///
7187 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
7188 /// `||`'s label, because the inner chain really does end before `&&` begins.
7189 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
7190 let mut operands = Vec::new();
7191 collect_same_operator(op, left, &mut operands);
7192 operands.push(right);
7193
7194 let end = self.new_label();
7195 // Every operand but the last decides whether the chain stops here.
7196 let last = operands.pop().expect("the right operand is always present");
7197 for operand in operands {
7198 self.expr(operand)?;
7199 self.emit(Opcode::Dup, &[]);
7200 match op {
7201 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
7202 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
7203 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
7204 // `0 || b` is `b`. The dedicated test keeps the value unless it is
7205 // null-ish, so the jump is taken on `false`.
7206 LogicalOp::Coalesce => {
7207 self.emit(Opcode::IsUndefinedOrNull, &[]);
7208 self.emit_jump(Opcode::IfFalse, end, &[]);
7209 }
7210 }
7211 self.emit(Opcode::Drop, &[]);
7212 }
7213 self.expr(last)?;
7214 self.place_label(end);
7215 Ok(())
7216 }
7217
7218 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
7219 match op {
7220 UnaryOp::Typeof => {
7221 // `typeof x` must not throw on an undeclared name.
7222 if let ExprKind::Ident(name) = &argument.kind {
7223 self.emit_var(VarAction::GetUndef, &name.name);
7224 } else {
7225 self.expr(argument)?;
7226 }
7227 self.emit(Opcode::Typeof, &[]);
7228 }
7229 UnaryOp::Delete => {
7230 // `delete obj.prop` really deletes, and answers whether it could.
7231 // Deleting a *binding* is always `false`: a local, an argument and a
7232 // declared global are all non-configurable, which the reference encodes
7233 // as a constant `push_false` rather than a runtime check. Only a
7234 // property access has anything to do at run time.
7235 // `delete super.x` is not a delete at all: the spec refuses it, and the
7236 // reference encodes the refusal as a `throw_error`. The receiver and the
7237 // key are still evaluated first, which is what keeps the evaluation order
7238 // of the operand intact.
7239 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
7240 // nothing to delete, and a failed delete is not the same as a skipped
7241 // one. The reference emits the guards so they land on a `drop; push_true`
7242 // tail, which is what this reproduces.
7243 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
7244 && let ExprKind::Member {
7245 object, property, ..
7246 } = &inner.unparen().kind
7247 {
7248 let end = self.new_label();
7249 let done = self.new_label();
7250 self.chain_link(object, end)?;
7251 match property {
7252 MemberProp::Ident(name) => self.emit(
7253 Opcode::PushAtomValue,
7254 &[Op::Atom(Atom::from_text(&name.name))],
7255 ),
7256 MemberProp::Computed(index) => self.expr(index)?,
7257 MemberProp::Private(_) => {
7258 return Err(SyntaxError::new(
7259 "deleting a private field is not allowed",
7260 argument.span,
7261 ));
7262 }
7263 }
7264 self.emit(Opcode::Delete, &[]);
7265 self.emit_jump(Opcode::Goto, done, &[]);
7266 self.place_label(end);
7267 self.emit(Opcode::Drop, &[]);
7268 self.emit(Opcode::PushTrue, &[]);
7269 self.place_label(done);
7270 return Ok(());
7271 }
7272 if let ExprKind::Member { object, .. } = &argument.unparen().kind
7273 && matches!(object.unparen().kind, ExprKind::SuperProp)
7274 {
7275 self.super_base();
7276 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
7277 return Ok(());
7278 }
7279 // Parentheses are transparent to `delete`: `(x)` is still a Reference to
7280 // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
7281 // does, and `delete (a().b)` still evaluates `a()`. Matching on the
7282 // unparenthesised operand is what keeps both — matching on `argument.kind`
7283 // sent every parenthesised form to the "not a Reference" arm, which cost
7284 // `delete(__variable) === false` in test262's `S12.2_A2`.
7285 match &argument.unparen().kind {
7286 ExprKind::Member {
7287 object, property, ..
7288 } => {
7289 self.expr(object)?;
7290 match property {
7291 MemberProp::Ident(name) => {
7292 self.emit(
7293 Opcode::PushAtomValue,
7294 &[Op::Atom(Atom::from_text(&name.name))],
7295 );
7296 }
7297 MemberProp::Computed(index) => self.expr(index)?,
7298 MemberProp::Private(_) => {
7299 return Err(SyntaxError::new(
7300 "deleting a private field is not allowed",
7301 argument.span,
7302 ));
7303 }
7304 }
7305 self.emit(Opcode::Delete, &[]);
7306 }
7307 ExprKind::Ident(name) => {
7308 self.delete_ident(&name.name);
7309 }
7310 // §13.5.1.2 step 2: an operand that is **not** a Reference Record
7311 // answers `true` — there is nothing to delete, and "nothing needed
7312 // deleting" is success. `delete !0`, `delete (1 + 2)` and
7313 // `delete typeof 0` are all `true`, and the operand is still evaluated
7314 // (which is why it is `Drop`ed rather than skipped:
7315 // `delete f()` must call `f`).
7316 //
7317 // Answering `false` here is the C reference's old behaviour and was
7318 // wrong in an observable way: test262's
7319 // `dynamic-import/assignment-expression/logical-and-expr` builds a
7320 // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
7321 // half turned the whole `&&` into `false`, so the import asked for a
7322 // module named "false".
7323 _ => {
7324 self.expr(argument)?;
7325 self.emit(Opcode::Drop, &[]);
7326 self.emit(Opcode::PushTrue, &[]);
7327 }
7328 }
7329 }
7330 UnaryOp::Void => {
7331 self.expr(argument)?;
7332 self.emit(Opcode::Drop, &[]);
7333 self.emit(Opcode::Undefined, &[]);
7334 }
7335 UnaryOp::Minus => {
7336 self.expr(argument)?;
7337 self.emit(Opcode::Neg, &[]);
7338 }
7339 UnaryOp::Plus => {
7340 self.expr(argument)?;
7341 self.emit(Opcode::Plus, &[]);
7342 }
7343 UnaryOp::Not => {
7344 self.expr(argument)?;
7345 self.emit(Opcode::Lnot, &[]);
7346 }
7347 UnaryOp::BitNot => {
7348 self.expr(argument)?;
7349 self.emit(Opcode::Not, &[]);
7350 }
7351 }
7352 Ok(())
7353 }
7354
7355 /// A store to `name` while a `with` may capture it.
7356 ///
7357 /// The reference is resolved **first**, before the right-hand side runs. That order is
7358 /// the whole point: in `x = (delete env.x, 0)` the resolution has already decided that
7359 /// `x` is `env`'s property, so `PutValue` then finds it gone and strict code throws
7360 /// `ReferenceError` (`set-mutable-binding-binding-deleted-with-typed-array-in-
7361 /// proto-chain-strict-mode`). The ordinary path evaluates the right-hand side before
7362 /// the guard runs, which put the guard *after* the mutation.
7363 ///
7364 /// Shapes mirror [`Compiler::assign_ident_plain`] and the member arms of
7365 /// [`Compiler::assign`], with `dup; with_get_var` in place of `get_field2` and
7366 /// `with_put_var` in place of `put_field` — the same stack effects, but each half also
7367 /// asks the `HasProperty` that `GetBindingValue`/`SetMutableBinding` require.
7368 fn with_assign(
7369 &mut self,
7370 with_local: &str,
7371 name: &Ident,
7372 op: AssignOp,
7373 value: &Expr,
7374 keep: bool,
7375 ) -> Result<(), SyntaxError> {
7376 let atom = Atom::from_text(&name.name);
7377 self.state().cur_pos = Some(name.span.start);
7378 match op {
7379 AssignOp::Assign => {
7380 self.expr(value)?;
7381 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7382 if keep {
7383 self.emit(Opcode::Dup, &[]);
7384 }
7385 self.state().no_value = !keep;
7386 self.emit_var(VarAction::Get, with_local);
7387 self.emit(Opcode::Swap, &[]);
7388 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7389 }
7390 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7391 let (keep_label, end) = (self.new_label(), self.new_label());
7392 self.emit_var(VarAction::Get, with_local);
7393 self.emit(Opcode::Dup, &[]);
7394 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7395 // `obj value` — the object stays underneath for the store.
7396 self.emit(Opcode::Dup, &[]);
7397 self.emit_logical_test(op);
7398 self.emit_jump(logical_jump(op), keep_label, &[]);
7399 self.emit(Opcode::Drop, &[]);
7400 self.expr(value)?;
7401 self.emit(Opcode::Insert2, &[]);
7402 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7403 self.emit_jump(Opcode::Goto, end, &[]);
7404 self.place_label(keep_label);
7405 self.emit(Opcode::Nip, &[]);
7406 self.place_label(end);
7407 }
7408 _ => {
7409 self.emit_var(VarAction::Get, with_local);
7410 self.emit(Opcode::Dup, &[]);
7411 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7412 self.expr(value)?;
7413 self.state().cur_pos = Some(name.span.start);
7414 self.emit(compound_opcode(op), &[]);
7415 self.state().no_value = !keep;
7416 if keep {
7417 self.emit(Opcode::Insert2, &[]);
7418 }
7419 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7420 }
7421 }
7422 Ok(())
7423 }
7424
7425 /// `x++` / `++x` while a `with` may capture `x`, with one resolution for both halves.
7426 fn with_update(
7427 &mut self,
7428 with_local: &str,
7429 name: &Ident,
7430 op: UpdateOp,
7431 prefix: bool,
7432 ) -> Result<(), SyntaxError> {
7433 let instruction = match (op, prefix) {
7434 (UpdateOp::Increment, true) => Opcode::Inc,
7435 (UpdateOp::Increment, false) => Opcode::PostInc,
7436 (UpdateOp::Decrement, true) => Opcode::Dec,
7437 (UpdateOp::Decrement, false) => Opcode::PostDec,
7438 };
7439 let atom = Atom::from_text(&name.name);
7440 self.state().cur_pos = Some(name.span.start);
7441 self.emit_var(VarAction::Get, with_local);
7442 self.emit(Opcode::Dup, &[]);
7443 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7444 self.emit(instruction, &[]);
7445 self.emit(
7446 if prefix {
7447 Opcode::Insert2
7448 } else {
7449 Opcode::Perm3
7450 },
7451 &[],
7452 );
7453 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7454 Ok(())
7455 }
7456
7457 /// A store to a plain identifier, with no `with` in the way.
7458 fn assign_ident_plain(
7459 &mut self,
7460 op: AssignOp,
7461 name: &Ident,
7462 value: &Expr,
7463 discard: bool,
7464 ) -> Result<(), SyntaxError> {
7465 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7466 // about, so it is set only when this assignment *is* that expression.
7467 let keep = !discard;
7468 // A *simple* store is blamed on the identifier, not on the `=`: a
7469 // strict-mode `not_def = 1` raises when the name is written, which the
7470 // reference reports at the name's column. A compound store is blamed on
7471 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
7472 // which the reference reports at the `+=`), so only the simple case
7473 // moves the position.
7474 let saved = self.cur().cur_pos;
7475 let name_pos = Some(name.span.start);
7476 if matches!(op, AssignOp::Assign) {
7477 self.state().cur_pos = name_pos;
7478 }
7479 // A *compound* store reads the binding before it combines, and that read
7480 // is blamed on the identifier: `not_def += 2` fails while reading
7481 // `not_def`, so the position is the name's, not the `+=`'s. The
7482 // combination that follows is blamed on the operator, which is why
7483 // `cur_pos` is put back to the operator position before it is emitted.
7484 self.state().cur_pos = name_pos;
7485 // A direct `eval` in the right-hand side can declare a `var` with this name in the
7486 // *caller's* variable environment, and from then on the name means that binding.
7487 // §13.15.3 resolves the lvalue once, at step 1, and stores through it at step 7 —
7488 // so the binding has to be pinned before the right-hand side runs.
7489 // `compound-assignment/S11.13.2_A6.*` and `assignment/S11.13.1_A6_*` are entirely
7490 // about this. One `__proto__`-shaped corner costs a reference object; every other
7491 // assignment is byte-for-byte what it was.
7492 let pinned = self.cur().eval_can_declare;
7493 if pinned {
7494 self.emit_var(VarAction::MakeRef, &name.name);
7495 }
7496 match op {
7497 AssignOp::Assign => {
7498 self.expr(value)?;
7499 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7500 if pinned {
7501 // `[ref, v] -> [v, ref, v] -> [v]`, the same `insert2` fold the
7502 // member stores use.
7503 if keep {
7504 self.emit(Opcode::Insert2, &[]);
7505 }
7506 self.emit(Opcode::PutRefValue, &[]);
7507 self.state().no_value = !keep;
7508 self.state().cur_pos = saved;
7509 return Ok(());
7510 }
7511 // A discarded store to a *slot* consumes its value, so no copy
7512 // is needed. A global store goes through `put_var`, which the
7513 // reference always pairs with a `dup` — matching it keeps the
7514 // bytecode identical. Getting this wrong is not only an extra
7515 // instruction: a stray copy gives the peephole a chance to fold
7516 // the store into an unrelated later read.
7517 let slot = self.is_slot(&name.name);
7518 if keep || !slot {
7519 self.emit(Opcode::Dup, &[]);
7520 }
7521 self.state().no_value = !keep && slot;
7522 self.emit_var(VarAction::Put, &name.name);
7523 }
7524 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7525 let end = self.new_label();
7526 // The pinned read leaves `[ref, v]`, so the branch that skips the store has
7527 // to `nip` the reference away; the branch that stores consumes it.
7528 self.emit_var(
7529 if pinned {
7530 VarAction::GetRef
7531 } else {
7532 VarAction::Get
7533 },
7534 &name.name,
7535 );
7536 self.state().cur_pos = saved;
7537 self.emit(Opcode::Dup, &[]);
7538 self.emit_logical_test(op);
7539 self.emit_jump(logical_jump(op), end, &[]);
7540 self.emit(Opcode::Drop, &[]);
7541 self.expr(value)?;
7542 // `x ||= function(){}` is a `NamedEvaluation` of the right-hand side, so the
7543 // function is named `x` — the same rule plain assignment follows
7544 // (`lgcl-*-namedevaluation-function`).
7545 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7546 if pinned {
7547 self.emit(Opcode::Insert2, &[]);
7548 self.emit(Opcode::PutRefValue, &[]);
7549 } else {
7550 self.emit(Opcode::Dup, &[]);
7551 self.emit_var(VarAction::Put, &name.name);
7552 }
7553 self.place_label(end);
7554 if pinned {
7555 self.emit(Opcode::Nip, &[]);
7556 }
7557 }
7558 _ => {
7559 self.emit_var(
7560 if pinned {
7561 VarAction::GetRef
7562 } else {
7563 VarAction::Get
7564 },
7565 &name.name,
7566 );
7567 self.expr(value)?;
7568 self.state().cur_pos = saved;
7569 self.emit(compound_opcode(op), &[]);
7570 if pinned {
7571 self.emit(Opcode::Insert2, &[]);
7572 self.emit(Opcode::PutRefValue, &[]);
7573 } else {
7574 self.emit(Opcode::Dup, &[]);
7575 self.emit_var(VarAction::Put, &name.name);
7576 }
7577 }
7578 }
7579 self.state().cur_pos = saved;
7580 Ok(())
7581 }
7582
7583 /// Compile an assignment.
7584 ///
7585 /// Three operator families, three shapes:
7586 ///
7587 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
7588 /// the value is kept, because `put_field`/`put_array_el` consume both the
7589 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
7590 /// the pair it wants and leaves a copy on top.
7591 /// * **compound** `+=` … — read the place, apply the operator, store. A member
7592 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
7593 /// index) underneath the value precisely so the store can follow.
7594 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
7595 /// right-hand side. The test *keeps* the current value and skips the store
7596 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
7597 /// `a` is already truthy.
7598 fn assign(
7599 &mut self,
7600 op: AssignOp,
7601 target: &Pattern,
7602 value: &Expr,
7603 discard: bool,
7604 ) -> Result<(), SyntaxError> {
7605 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7606 // about, so it is set only when this assignment *is* that expression.
7607 let keep = !discard;
7608 match &target.kind {
7609 PatternKind::Ident(name) => {
7610 // Any store to a name a `with` may capture resolves the reference first and
7611 // keeps that resolution for both halves — see [`Compiler::with_assign`].
7612 // Plain `=` needs it just as much as `+=`: `x = (delete env.x, 0)` must
7613 // resolve `x` before the right-hand side deletes it.
7614 let plain_name = name.name.clone();
7615 if !self.visible_with_names(&plain_name).is_empty() {
7616 return self.with_reference(
7617 &plain_name,
7618 &mut |compiler, with_local| {
7619 compiler.with_assign(with_local, name, op, value, !discard)
7620 },
7621 &mut |compiler| compiler.assign_ident_plain(op, name, value, discard),
7622 );
7623 }
7624 self.assign_ident_plain(op, name, value, discard)
7625 }
7626 PatternKind::Member(member) => {
7627 // `super.x = v` is not a store through a value: it starts at the home
7628 // object's prototype but writes to `this`, so it goes through
7629 // `put_super_value` rather than `put_field`. The receiver, prototype, key
7630 // and value are handed over together.
7631 if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
7632 return self.assign_super(member, op, value);
7633 }
7634 // A store is blamed on the selector punctuator (`.` or `[`), the same
7635 // token a load is blamed on — the reference records `put_field obj.a`
7636 // at the `.`, so a setter that throws reports that column and not the
7637 // `=` of the assignment it sits in. The inner expressions restore their
7638 // own positions, so the selector's sticks for the store instructions.
7639 let saved = self.cur().cur_pos;
7640 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7641 self.expr(&member.object)?;
7642 match &member.property {
7643 MemberProp::Ident(property) => {
7644 let atom = Atom::from_text(&property.name);
7645 match op {
7646 AssignOp::Assign => {
7647 self.expr(value)?;
7648 // `put_field` consumes the object and the value, so
7649 // without `insert2` nothing is left over for the
7650 // statement to drop.
7651 self.state().no_value = !keep;
7652 if keep {
7653 self.emit(Opcode::Insert2, &[]);
7654 }
7655 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7656 }
7657 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7658 // `get_field2` leaves the object under the value, so
7659 // the keep path has an object to dispose of. The store
7660 // path must jump *over* that cleanup: falling into it
7661 // would `nip` a stack that only holds the value.
7662 let (keep_label, end) = (self.new_label(), self.new_label());
7663 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7664 self.emit(Opcode::Dup, &[]);
7665 self.emit_logical_test(op);
7666 self.emit_jump(logical_jump(op), keep_label, &[]);
7667 self.emit(Opcode::Drop, &[]);
7668 self.expr(value)?;
7669 self.emit(Opcode::Insert2, &[]);
7670 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7671 self.emit_jump(Opcode::Goto, end, &[]);
7672 self.place_label(keep_label);
7673 self.emit(Opcode::Nip, &[]);
7674 self.place_label(end);
7675 }
7676 _ => {
7677 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7678 self.expr(value)?;
7679 self.emit(compound_opcode(op), &[]);
7680 self.state().no_value = !keep;
7681 if keep {
7682 self.emit(Opcode::Insert2, &[]);
7683 }
7684 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7685 }
7686 }
7687 }
7688 MemberProp::Computed(index) => {
7689 self.expr(index)?;
7690 match op {
7691 AssignOp::Assign => {
7692 self.expr(value)?;
7693 self.state().no_value = !keep;
7694 if keep {
7695 self.emit(Opcode::Insert3, &[]);
7696 }
7697 self.emit(Opcode::PutArrayEl, &[]);
7698 }
7699 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7700 let (keep_label, end) = (self.new_label(), self.new_label());
7701 self.emit(Opcode::GetArrayEl3, &[]);
7702 self.emit(Opcode::Dup, &[]);
7703 self.emit_logical_test(op);
7704 self.emit_jump(logical_jump(op), keep_label, &[]);
7705 self.emit(Opcode::Drop, &[]);
7706 self.expr(value)?;
7707 self.emit(Opcode::Insert3, &[]);
7708 self.emit(Opcode::PutArrayEl, &[]);
7709 self.emit_jump(Opcode::Goto, end, &[]);
7710 self.place_label(keep_label);
7711 // Both the object and the index are left over.
7712 self.emit(Opcode::Nip, &[]);
7713 self.emit(Opcode::Nip, &[]);
7714 self.place_label(end);
7715 }
7716 _ => {
7717 self.emit(Opcode::GetArrayEl3, &[]);
7718 self.expr(value)?;
7719 self.emit(compound_opcode(op), &[]);
7720 self.state().no_value = !keep;
7721 if keep {
7722 self.emit(Opcode::Insert3, &[]);
7723 }
7724 self.emit(Opcode::PutArrayEl, &[]);
7725 }
7726 }
7727 }
7728 MemberProp::Private(name) => {
7729 // `obj value` is on the stack, and every private store wants exactly
7730 // that. A top-level private name cannot be assigned (the parser rejects
7731 // `#x = 1`), so the only way here is `this.#x = …` inside the class.
7732 //
7733 // The reference emits `insert2` whether or not the value is wanted,
7734 // so this does too: the copy left behind is the assignment expression's
7735 // value, and a discarded one is simply never read.
7736 let binding = format!("#{}", name.name);
7737 let (kind, setter) = self.private_use(&binding, member.span)?;
7738 match op {
7739 AssignOp::Assign => {
7740 self.expr(value)?;
7741 if keep {
7742 self.emit(Opcode::Insert2, &[]);
7743 }
7744 self.private_store(&binding, kind, setter.as_deref())?;
7745 self.state().no_value = !keep;
7746 }
7747 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7748 let (keep_label, end) = (self.new_label(), self.new_label());
7749 self.emit(Opcode::Dup, &[]);
7750 self.private_load(&binding, kind, member.span)?;
7751 self.emit(Opcode::Dup, &[]);
7752 self.emit_logical_test(op);
7753 self.emit_jump(logical_jump(op), keep_label, &[]);
7754 self.emit(Opcode::Drop, &[]);
7755 self.expr(value)?;
7756 self.emit(Opcode::Insert2, &[]);
7757 self.private_store(&binding, kind, setter.as_deref())?;
7758 self.emit_jump(Opcode::Goto, end, &[]);
7759 self.place_label(keep_label);
7760 self.emit(Opcode::Nip, &[]);
7761 self.place_label(end);
7762 }
7763 _ => {
7764 self.emit(Opcode::Dup, &[]);
7765 self.private_load(&binding, kind, member.span)?;
7766 self.expr(value)?;
7767 self.emit(compound_opcode(op), &[]);
7768 self.emit(Opcode::Insert2, &[]);
7769 self.private_store(&binding, kind, setter.as_deref())?;
7770 }
7771 }
7772 }
7773 }
7774 self.state().cur_pos = saved;
7775 Ok(())
7776 }
7777 // A destructuring assignment: the right-hand side is the expression's own
7778 // value, so it is evaluated once and kept under the pattern's stores.
7779 PatternKind::Array { .. } | PatternKind::Object { .. } => {
7780 self.expr(value)?;
7781 if keep {
7782 self.emit(Opcode::Dup, &[]);
7783 }
7784 self.destructure(target, None)?;
7785 self.state().no_value = !keep;
7786 Ok(())
7787 }
7788 _ => Err(SyntaxError::new(
7789 "this assignment target is not supported by the compiler yet",
7790 target.span,
7791 )),
7792 }
7793 }
7794
7795 /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
7796 ///
7797 /// The stack has to carry four values — receiver, prototype, key, value — because
7798 /// `put_super_value` takes them together; the receiver is what makes a setter found on
7799 /// the prototype run with `this`, and the key has to survive until the store, which is
7800 /// why a compound form converts it to a property key once and `dup3`s rather than
7801 /// evaluating it twice.
7802 fn assign_super(
7803 &mut self,
7804 member: &MemberPattern,
7805 op: AssignOp,
7806 value: &Expr,
7807 ) -> Result<(), SyntaxError> {
7808 let saved = self.cur().cur_pos;
7809 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7810 self.super_base();
7811 match &member.property {
7812 MemberProp::Ident(property) => self.emit(
7813 Opcode::PushAtomValue,
7814 &[Op::Atom(Atom::from_text(&property.name))],
7815 ),
7816 MemberProp::Computed(index) => self.expr(index)?,
7817 MemberProp::Private(_) => {
7818 return Err(SyntaxError::new(
7819 "private fields are not supported by the compiler yet",
7820 member.span,
7821 ));
7822 }
7823 }
7824 match op {
7825 AssignOp::Assign => {
7826 // The key is only converted once, by `put_super_value` itself, so a
7827 // computed key's `toString` runs exactly once.
7828 self.expr(value)?;
7829 self.emit(Opcode::Insert4, &[]);
7830 self.emit(Opcode::PutSuperValue, &[]);
7831 }
7832 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7833 let (keep_label, end) = (self.new_label(), self.new_label());
7834 self.emit(Opcode::ToPropkey, &[]);
7835 self.emit(Opcode::Dup3, &[]);
7836 self.emit(Opcode::GetSuperValue, &[]);
7837 self.emit(Opcode::Dup, &[]);
7838 self.emit_logical_test(op);
7839 self.emit_jump(logical_jump(op), keep_label, &[]);
7840 self.emit(Opcode::Drop, &[]);
7841 self.expr(value)?;
7842 self.emit(Opcode::Insert4, &[]);
7843 self.emit(Opcode::PutSuperValue, &[]);
7844 self.emit_jump(Opcode::Goto, end, &[]);
7845 self.place_label(keep_label);
7846 // The prototype and the key are still under the value that was read.
7847 self.emit(Opcode::Nip, &[]);
7848 self.emit(Opcode::Nip, &[]);
7849 self.emit(Opcode::Nip, &[]);
7850 self.place_label(end);
7851 }
7852 _ => {
7853 self.emit(Opcode::ToPropkey, &[]);
7854 self.emit(Opcode::Dup3, &[]);
7855 self.emit(Opcode::GetSuperValue, &[]);
7856 self.expr(value)?;
7857 self.emit(compound_opcode(op), &[]);
7858 self.emit(Opcode::Insert4, &[]);
7859 self.emit(Opcode::PutSuperValue, &[]);
7860 }
7861 }
7862 // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7863 // is still on the stack when the store finishes, and the expression statement is
7864 // what disposes of it — the same arrangement as `put_field`, reached from the other
7865 // side: there the store consumes the value (`no_value`), here it leaves it
7866 // (`keep` already false, so nothing tells the statement otherwise).
7867 self.state().cur_pos = saved;
7868 Ok(())
7869 }
7870
7871 /// The test a logical assignment applies to the current value.
7872 ///
7873 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7874 /// assign, while `0 ||= b` must not.
7875 fn emit_logical_test(&mut self, op: AssignOp) {
7876 if op == AssignOp::Coalesce {
7877 self.emit(Opcode::IsUndefinedOrNull, &[]);
7878 }
7879 }
7880
7881 /// The private name `#name` this use site resolves against.
7882 ///
7883 /// The parser has already rejected a name no enclosing class declares, so a miss here
7884 /// means the compiler lost track of a class scope — which is worth a real error rather
7885 /// than an `unwrap`.
7886 fn private_use(
7887 &self,
7888 binding: &str,
7889 span: Span,
7890 ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7891 ClassPlan::find(self, binding)
7892 .map(|use_| (use_.kind, use_.setter.clone()))
7893 .ok_or_else(|| {
7894 SyntaxError::new(
7895 format!("the private name '{binding}' is out of scope here"),
7896 span,
7897 )
7898 })
7899 }
7900
7901 /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7902 ///
7903 /// The three readable kinds take three different instructions, because a private name
7904 /// holds three different things — a symbol, a method function, a getter function — and
7905 /// only the first one is a property read at all.
7906 fn private_load(
7907 &mut self,
7908 binding: &str,
7909 kind: PrivateKind,
7910 span: Span,
7911 ) -> Result<(), SyntaxError> {
7912 match kind {
7913 PrivateKind::Field => {
7914 self.emit_var(VarAction::Get, binding);
7915 self.emit(Opcode::GetPrivateField, &[]);
7916 }
7917 PrivateKind::Method => {
7918 self.emit_var(VarAction::Get, binding);
7919 self.emit(Opcode::CheckBrand, &[]);
7920 // `check_brand` reads `obj func` and leaves both; the method itself is what
7921 // `this.#m` evaluates to.
7922 self.emit(Opcode::Nip, &[]);
7923 }
7924 PrivateKind::Getter => {
7925 self.emit_var(VarAction::Get, binding);
7926 self.emit(Opcode::CheckBrand, &[]);
7927 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7928 }
7929 // `#a` is declared but never filled when only a setter exists, so reading it is
7930 // the same refusal as assigning to a `const`. The reference reports it with the
7931 // generic read-only wording and leaves the better message as a `XXX`.
7932 PrivateKind::Setter => self.emit(
7933 Opcode::ThrowError,
7934 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7935 ),
7936 }
7937 let _ = span;
7938 Ok(())
7939 }
7940
7941 /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
7942 fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
7943 match kind {
7944 // A method *is* the callee, so only the check goes in between.
7945 PrivateKind::Method => {
7946 self.emit_var(VarAction::Get, binding);
7947 self.emit(Opcode::CheckBrand, &[]);
7948 }
7949 _ => self.private_load(binding, kind, Span::default())?,
7950 }
7951 Ok(())
7952 }
7953
7954 /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
7955 /// wanted back.
7956 ///
7957 /// A getter/setter pair is a *method call*, not a property store: the reference reads
7958 /// the setter out of its own binding and calls it with the receiver, which is why the
7959 /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
7960 /// keeps the assignment's value for an expression context.
7961 fn private_store(
7962 &mut self,
7963 binding: &str,
7964 kind: PrivateKind,
7965 setter: Option<&str>,
7966 ) -> Result<(), SyntaxError> {
7967 match kind {
7968 PrivateKind::Field => {
7969 self.emit_var(VarAction::Get, binding);
7970 self.emit(Opcode::PutPrivateField, &[]);
7971 }
7972 PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
7973 Some(setter) => {
7974 self.emit_var(VarAction::Get, setter);
7975 // `obj func value` -> `value obj func` for the check, and back again for
7976 // the call, which wants `obj func arg`.
7977 self.emit(Opcode::Swap, &[]);
7978 self.emit(Opcode::Rot3r, &[]);
7979 self.emit(Opcode::CheckBrand, &[]);
7980 self.emit(Opcode::Rot3l, &[]);
7981 self.emit(Opcode::CallMethod, &[Op::Int(1)]);
7982 // The setter's return value is discarded; the assignment's own value is
7983 // whatever the caller left underneath.
7984 self.emit(Opcode::Drop, &[]);
7985 }
7986 None => self.emit(
7987 Opcode::ThrowError,
7988 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7989 ),
7990 },
7991 }
7992 Ok(())
7993 }
7994
7995 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
7996 // `x++` inside a `with` is a read-modify-write of a *property*, so the object is
7997 // resolved once for both halves. See [`Compiler::with_reference`].
7998 let unparened = argument.unparen();
7999 if let ExprKind::Ident(ident) = &unparened.kind {
8000 let name = ident.name.clone();
8001 if !self.visible_with_names(&name).is_empty() {
8002 return self.with_reference(
8003 &name,
8004 &mut |compiler, with_local| compiler.with_update(with_local, ident, op, prefix),
8005 &mut |compiler| compiler.update_plain(op, unparened, prefix),
8006 );
8007 }
8008 }
8009 self.update_plain(op, argument, prefix)
8010 }
8011
8012 fn update_plain(
8013 &mut self,
8014 op: UpdateOp,
8015 argument: &Expr,
8016 prefix: bool,
8017 ) -> Result<(), SyntaxError> {
8018 let instruction = match (op, prefix) {
8019 (UpdateOp::Increment, true) => Opcode::Inc,
8020 (UpdateOp::Increment, false) => Opcode::PostInc,
8021 (UpdateOp::Decrement, true) => Opcode::Dec,
8022 (UpdateOp::Decrement, false) => Opcode::PostDec,
8023 };
8024 // `(y)++` and `((o.x))++` are the same updates as the unparenthesised forms: §13.4
8025 // evaluates the operand as a `LeftHandSideExpression` and the parentheses around a
8026 // reference change nothing — they do not copy the value. Reading `argument.kind`
8027 // directly therefore rejected every parenthesised target with "increment of a
8028 // non-variable", which is not a thing the language has (`target-cover-id`).
8029 let argument = argument.unparen();
8030 if let ExprKind::Member {
8031 object,
8032 property,
8033 optional: _,
8034 } = &argument.kind
8035 {
8036 // `o.x++` needs the receiver twice, so the last link is read with the
8037 // `get_*2`/`get_*3` form that keeps it, and the update is written back
8038 // with `put_field`/`put_array_el`. The reordering in between is what puts
8039 // the old value below the receiver for a postfix update and the new one
8040 // above it for a prefix one:
8041 //
8042 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
8043 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
8044 //
8045 // This mirrors the reference instruction for instruction.
8046 self.expr(object)?;
8047 match property {
8048 MemberProp::Ident(name) => {
8049 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
8050 self.emit(instruction, &[]);
8051 self.emit(
8052 if prefix {
8053 Opcode::Insert2
8054 } else {
8055 Opcode::Perm3
8056 },
8057 &[],
8058 );
8059 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
8060 }
8061 MemberProp::Computed(index) => {
8062 self.expr(index)?;
8063 self.emit(Opcode::GetArrayEl3, &[]);
8064 self.emit(instruction, &[]);
8065 self.emit(
8066 if prefix {
8067 Opcode::Insert3
8068 } else {
8069 Opcode::Perm4
8070 },
8071 &[],
8072 );
8073 self.emit(Opcode::PutArrayEl, &[]);
8074 }
8075 MemberProp::Private(name) => {
8076 // The receiver is duplicated and the read keeps it, exactly as `get_field2`
8077 // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
8078 // `perm3` -> `old obj new` -> store.
8079 let binding = format!("#{}", name.name);
8080 let (kind, setter) = self.private_use(&binding, argument.span)?;
8081 self.emit(Opcode::Dup, &[]);
8082 self.private_load(&binding, kind, argument.span)?;
8083 self.emit(instruction, &[]);
8084 self.emit(
8085 if prefix {
8086 Opcode::Insert2
8087 } else {
8088 Opcode::Perm3
8089 },
8090 &[],
8091 );
8092 self.private_store(&binding, kind, setter.as_deref())?;
8093 }
8094 }
8095 return Ok(());
8096 }
8097 let ExprKind::Ident(name) = &argument.kind else {
8098 return Err(SyntaxError::new(
8099 "increment of a non-variable is not supported by the compiler yet",
8100 argument.span,
8101 ));
8102 };
8103 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
8104 // reference's `inc_loc` folds those three into one, but it does so only in some
8105 // positions (a `for` update and not a bare statement, and never for a lexical
8106 // binding), so emitting it unconditionally would move *away* from its output.
8107 // The instruction is equivalent either way; matching the reference matters more
8108 // than saving two instructions.
8109 let _ = !std::mem::take(&mut self.state().discard_value);
8110 self.emit_var(VarAction::Get, &name.name);
8111 self.emit(instruction, &[]);
8112 if prefix {
8113 self.emit(Opcode::Dup, &[]);
8114 }
8115 self.emit_var(VarAction::Put, &name.name);
8116 Ok(())
8117 }
8118
8119 /// Compile an array literal.
8120 ///
8121 /// The reference splits this into three phases, and the split is load-bearing
8122 /// rather than an optimisation detail:
8123 ///
8124 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
8125 /// the array in one instruction.
8126 /// 2. **Everything up to the first spread** is appended with explicit indices
8127 /// (`define_field <index>`), because a hole has no element to pass to
8128 /// `array_from`. A hole here is what makes `length` need fixing up: an
8129 /// explicit index does not extend the array the way a pushed element does.
8130 /// 3. **From the first spread on** the index lives on the stack, so `append` and
8131 /// `define_array_el` can consume it and `inc` advances it.
8132 ///
8133 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
8134 /// forces phase 2, and `[...a]` forces phase 3.
8135 fn array_literal(
8136 &mut self,
8137 elements: &[Option<ArrayElement>],
8138 span: Span,
8139 ) -> Result<(), SyntaxError> {
8140 let _ = span;
8141 let mut index: u32 = 0;
8142 let mut cursor = 0usize;
8143
8144 // Phase 1: a leading run of plain elements, at most 32 of them.
8145 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
8146 if index >= 32 {
8147 break;
8148 }
8149 self.expr(element)?;
8150 index += 1;
8151 cursor += 1;
8152 }
8153 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
8154
8155 // Phase 2: explicit indices, up to the first spread.
8156 let mut need_length = false;
8157 while let Some(element) = elements.get(cursor) {
8158 if matches!(element, Some(ArrayElement::Spread(_))) {
8159 break;
8160 }
8161 need_length = true;
8162 if let Some(ArrayElement::Expr(expression)) = element {
8163 self.expr(expression)?;
8164 self.emit_define_index(index);
8165 need_length = false;
8166 }
8167 index += 1;
8168 cursor += 1;
8169 }
8170
8171 if cursor >= elements.len() {
8172 if need_length {
8173 // `define_field` cannot set `length`, which is not configurable.
8174 self.emit(Opcode::Dup, &[]);
8175 self.push_number(index as f64);
8176 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8177 }
8178 return Ok(());
8179 }
8180
8181 // Phase 3: the index moves onto the stack for the spreading tail.
8182 //
8183 // `need_length` deliberately carries over from phase 2: a hole before the
8184 // first spread still has to be reflected in `length`, and only the final
8185 // check can do it because the array is not finished until the tail is
8186 // appended.
8187 self.push_number(index as f64);
8188 while let Some(element) = elements.get(cursor) {
8189 match element {
8190 Some(ArrayElement::Spread(expression)) => {
8191 // `append` copies an iterable and leaves the next index behind,
8192 // so no `inc` is needed here.
8193 self.expr(spread_argument(expression))?;
8194 self.emit(Opcode::Append, &[]);
8195 }
8196 None | Some(ArrayElement::Expr(_)) => {
8197 need_length = true;
8198 if let Some(ArrayElement::Expr(expression)) = element {
8199 self.expr(expression)?;
8200 self.emit(Opcode::DefineArrayEl, &[]);
8201 need_length = false;
8202 }
8203 self.emit(Opcode::Inc, &[]);
8204 }
8205 }
8206 cursor += 1;
8207 }
8208 if need_length {
8209 self.emit(Opcode::Dup1, &[]);
8210 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8211 } else {
8212 self.emit(Opcode::Drop, &[]);
8213 }
8214 Ok(())
8215 }
8216
8217 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
8218 fn emit_define_index(&mut self, index: u32) {
8219 self.emit(
8220 Opcode::DefineField,
8221 &[Op::Atom(Atom::from_text(&index.to_string()))],
8222 );
8223 }
8224
8225 // -- functions ---------------------------------------------------------
8226
8227 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
8228 self.compile_function_with_name(func, false)
8229 }
8230
8231 /// Compile a function, recording whether it is a *named function expression*.
8232 ///
8233 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
8234 /// must not leak outside. The reference does that by declaring `g` as a local of
8235 /// the function itself and initialising it with `special_object 2` (the current
8236 /// function), which is why this has to be known at compile time.
8237 fn compile_function_with_name(
8238 &mut self,
8239 func: &ast::Function,
8240 is_expression: bool,
8241 ) -> Result<CompiledFunction, SyntaxError> {
8242 let kind = match (func.is_generator, func.is_async) {
8243 (false, false) => FunctionKind::Normal,
8244 (true, false) => FunctionKind::Generator,
8245 (false, true) => FunctionKind::Async,
8246 (true, true) => FunctionKind::AsyncGenerator,
8247 };
8248 let mut state = FnState::new(
8249 func.name
8250 .as_ref()
8251 .map(|n| n.name.clone())
8252 .unwrap_or_default(),
8253 kind,
8254 );
8255 // The function's own mode, recorded by the parser. Inheriting the enclosing
8256 // function's instead let a nested `"use strict"` directive be ignored, so the
8257 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
8258 state.strict = func.strict;
8259 // A function defined inside a `with` block keeps seeing that object: the guard
8260 // chain names the enclosing `<with>` locals, which resolve outward into closure
8261 // variables exactly like any other captured binding.
8262 state.inherited_with_names = self.cur().with_names.len();
8263 state.with_names = self.cur().with_names.clone();
8264 state.is_arrow = func.is_arrow;
8265 // Known before the body is compiled, so an lvalue can decide whether to pin its
8266 // reference before emitting the read. See [`FnState::eval_can_declare`].
8267 state.eval_can_declare = func.has_direct_eval;
8268 state.created_in_block = self.cur().current_block;
8269 // A default anywhere in the parameter list is what gives the function two
8270 // variable environments. The reference decides this the same way: it scans the
8271 // parenthesis for a top-level `=`, so a destructured name without a default
8272 // stays a plain function-scope binding.
8273 state.in_params = false;
8274 // The reference scans the parenthesis for *any* `=`, including one nested inside
8275 // a pattern, so `function f({a = 1})` has parameter expressions even though the
8276 // parameter itself carries no initialiser.
8277 state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
8278 // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
8279 // flag above this looks at the *shape* of each parameter, not just for `=`.
8280 state.simple_parameter_list = func
8281 .params
8282 .iter()
8283 .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
8284 // A function born inside a parameter list inherits the prohibition: it must not
8285 // see the body bindings of the function it was created in.
8286 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
8287 // A class constructor knows what it is only because the class told it.
8288 if let Some(kind) = self.cur().class_ctor_pending {
8289 state.ctor_kind = kind;
8290 }
8291 // A named *expression* binds its own name; a declaration's name is already
8292 // bound in the enclosing scope.
8293 state.self_name = if is_expression && !func.is_arrow {
8294 func.name.as_ref().map(|n| n.name.clone())
8295 } else {
8296 None
8297 };
8298 // Keep the written range so `Function.prototype.toString` can answer with the
8299 // original text rather than `[native code]`.
8300 //
8301 // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
8302 // accessor and generator prefixes, and for a method it must not include the name
8303 // or a leading `static`. `params_span` is exactly that boundary.
8304 // A *method* keeps the old `[native code]` answer: its reported text is defined
8305 // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
8306 // the comments in between kept verbatim), and reconstructing that from a byte
8307 // span got it wrong in more cases than it got right. A plain function and an
8308 // arrow are the shapes libraries actually introspect, and those are exact.
8309 // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
8310 // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
8311 // so the same slice works for every form. (`Params_span` is the boundary that
8312 // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
8313 // `source_span` is set only where the reported text is not the function's own
8314 // range — a class's constructor reports the whole class definition.
8315 let reported = func.source_span.unwrap_or(func.span);
8316 state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
8317 state.line = func.span.start.line;
8318 state.column = func.span.start.column;
8319 // A function body has no hidden `<ret>` local; the value comes back on
8320 // the stack. Only a script keeps one.
8321 // Parameters are positional, so even a pattern occupies one argument slot. A
8322 // simple name is that slot itself; anything else (a pattern, a default, a rest
8323 // parameter) takes an anonymous slot and is unpicked into locals at the top of
8324 // the body, which is the only way one argument can bind several names.
8325 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
8326 // `.length` stops at the first parameter that can be substituted: a default
8327 // fills a missing argument in, and a rest parameter absorbs the rest.
8328 let mut defined_args = func.params.len() as u32;
8329 for (index, param) in func.params.iter().enumerate() {
8330 match simple_parameter(param) {
8331 Some(name) => state.args.push(VarDef::var(name.name.clone())),
8332 None => {
8333 state.args.push(VarDef::var(ANONYMOUS_BINDING));
8334 prologue.push((index, param.clone()));
8335 }
8336 }
8337 }
8338 // A default anywhere before the end also ends the count, which the loop above
8339 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
8340 for (position, param) in func.params.iter().enumerate() {
8341 if matches!(
8342 param.kind,
8343 PatternKind::Assign { .. } | PatternKind::Rest(_)
8344 ) {
8345 defined_args = position as u32;
8346 break;
8347 }
8348 }
8349 state.defined_args = defined_args;
8350 state.param_prologue = prologue;
8351 let depth = self.stack.len();
8352 self.stack.push(state);
8353 let result = self.compile_function_body(func);
8354 if result.is_err() {
8355 // A failed compile must not leave its `FnState` behind. Every caller
8356 // reads `self.state()` as "the function being compiled", so a leftover
8357 // frame silently retargets all later bookkeeping at a dead function.
8358 self.stack.truncate(depth);
8359 }
8360 result
8361 }
8362
8363 /// The body of a function, with its frame already pushed.
8364 fn compile_function_body(
8365 &mut self,
8366 func: &ast::Function,
8367 ) -> Result<CompiledFunction, SyntaxError> {
8368 let body_key = func.params_span.end.offset as u64;
8369 // Where the body begins, in source order. The runtime needs this to tell a
8370 // closure created by a default expression from one the body creates — the two see
8371 // different variable environments — and a bytecode offset would not survive the
8372 // instruction shuffling that building the frame does. Positions are in source
8373 // order, so a comparison answers it.
8374 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
8375 self.push_block(body_key, NO_PARENT);
8376 self.state().body_block = body_key;
8377 // An arrow with an expression body has no statements; the expression is
8378 // its `return`. Building the statement here keeps one code path below, and
8379 // matters for correctness beyond convenience: returning early with the new
8380 // `FnState` still on the stack would leave the compiler looking at the
8381 // wrong function, which surfaces as an unrelated underflow later.
8382 let concise = match &func.body {
8383 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
8384 StmtKind::Return(Some(Box::new((**value).clone()))),
8385 value.span,
8386 )),
8387 js_parse::ast::FunctionBody::Block(_) => None,
8388 };
8389 let body: &[Stmt] = match &concise {
8390 Some(stmt) => std::slice::from_ref(stmt),
8391 None => func
8392 .body
8393 .statements()
8394 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
8395 };
8396 let prologue = std::mem::take(&mut self.state().param_prologue);
8397 let has_param_scope = self.cur().has_parameter_expressions;
8398 // The parameter scope's own bindings, declared in source order.
8399 //
8400 // With parameter expressions the list gets a variable environment of its own, and
8401 // every name it binds is a `let` there. That is what puts the *list* in the
8402 // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
8403 // and `function f(x = y, y){}` does the same, where a single shared environment
8404 // would answer `undefined` to both.
8405 if has_param_scope {
8406 let mut declared: Vec<String> = Vec::new();
8407 for param in &func.params {
8408 let mut names = Vec::new();
8409 param.bound_names(&mut names);
8410 for name in names {
8411 if declared.contains(&name.name) {
8412 continue;
8413 }
8414 declared.push(name.name.clone());
8415 self.declare_param_binding(&name.name);
8416 }
8417 }
8418 }
8419 // A pattern parameter binds its names as function-scope locals, so they have to
8420 // exist — and be unpicked from the argument — before the body runs. With a
8421 // parameter scope these are the *second* environment: the pattern fills the
8422 // parameter's copy, and the body's binding is filled from it afterwards.
8423 for (_, pattern) in &prologue {
8424 let mut names = Vec::new();
8425 pattern.bound_names(&mut names);
8426 for name in names {
8427 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
8428 }
8429 }
8430 self.hoist(body, body_key)?;
8431 // A constructor's prologue is not a parameter unpacking but the `this` binding:
8432 // a base constructor takes the receiver, a derived one starts in the dead zone
8433 // because only `super()` may produce it.
8434 match self.cur().ctor_kind {
8435 CtorKind::None => {}
8436 CtorKind::Base => {
8437 self.begin_this_local();
8438 self.emit(Opcode::CheckCtor, &[]);
8439 // Instance fields are installed at the top of a base constructor's body,
8440 // before any statement — `class C { x = 1; constructor() { this.x } }` sees
8441 // `1`. This used to be emitted at the *tail*, which made every field read
8442 // `undefined` inside the constructor that declared it.
8443 self.call_field_initialiser();
8444 }
8445 CtorKind::Derived => {
8446 self.declare("this", VarDef::lexical("this"));
8447 let slot = self.cur().vars.len() as u32 - 1;
8448 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8449 self.emit(Opcode::CheckCtor, &[]);
8450 }
8451 }
8452 // Entering the parameter list: everything it binds starts in the dead zone.
8453 // The order is the reference's — it walks the scope chain, which is prepended, so
8454 // the bindings come out newest first.
8455 for name in self.param_binding_names().into_iter().rev() {
8456 if let Some(slot) = self.param_binding_slot(&name) {
8457 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8458 }
8459 }
8460 // The whole parameter list is one scope, and nothing in the body exists yet, so
8461 // every name it mentions resolves against the parameter bindings and outward.
8462 self.state().in_params = has_param_scope;
8463 for (index, param) in func.params.iter().enumerate() {
8464 if let Some(pattern) = prologue_pattern(&prologue, index) {
8465 // A destructuring parameter *initialises* its bindings: with a parameter
8466 // scope they are the list's own `let`s, which is why the stores skip the
8467 // dead-zone check, and why the reference reads their properties with
8468 // `get_field2` — a `let` needs no reference.
8469 let kind = if has_param_scope {
8470 VarDeclKind::Let
8471 } else {
8472 VarDeclKind::Var
8473 };
8474 match &pattern.kind {
8475 // `...rest` collects what is left rather than reading one slot.
8476 PatternKind::Rest(inner) => {
8477 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8478 self.destructure(inner, Some(kind))?;
8479 }
8480 _ => {
8481 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8482 self.destructure(pattern, Some(kind))?;
8483 }
8484 }
8485 continue;
8486 }
8487 // A plain name binds straight from its argument slot. With a parameter scope
8488 // the slot is also copied into the parameter binding, which is what a later
8489 // default (or a closure made among the defaults) reads.
8490 let Some(name) = simple_parameter(param) else {
8491 continue;
8492 };
8493 let target = self.param_binding_slot(&name.name);
8494 if matches!(param.kind, PatternKind::Rest(_)) {
8495 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8496 if let Some(slot) = target {
8497 self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
8498 }
8499 // `put_arg` rather than `set_arg`: the array is the last thing on the
8500 // stack and nothing keeps it. Named by hand because a name in the
8501 // parameter list resolves to the parameter binding, and this store has to
8502 // reach the *argument* — that is what the body reads.
8503 self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
8504 continue;
8505 }
8506 if let PatternKind::Assign { default, .. } = ¶m.kind {
8507 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8508 let has_value = self.new_label();
8509 self.emit(Opcode::Dup, &[]);
8510 self.emit(Opcode::IsUndefined, &[]);
8511 self.emit_jump(Opcode::IfFalse, has_value, &[]);
8512 self.emit(Opcode::Drop, &[]);
8513 self.expr(default)?;
8514 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
8515 // The argument slot keeps the substituted value, because the *body* reads
8516 // the slot rather than the parameter binding — so this store is named
8517 // explicitly, like the rest parameter's.
8518 self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8519 self.place_label(has_value);
8520 if let Some(slot) = target {
8521 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8522 }
8523 continue;
8524 }
8525 if let Some(slot) = target {
8526 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8527 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8528 }
8529 }
8530 // Copy the parameter scope into the body. A plain parameter needs nothing: the
8531 // body reads its argument slot, and the list kept the two in step. A name a
8532 // pattern bound has no argument slot of its own, so the body gets a `var` filled
8533 // from the parameter's copy — and *that* is why an assignment inside a default
8534 // does not reach the body.
8535 if has_param_scope {
8536 for (_, pattern) in &prologue {
8537 let mut names = Vec::new();
8538 pattern.bound_names(&mut names);
8539 for name in names {
8540 let Some(slot) = self.param_binding_slot(&name.name) else {
8541 continue;
8542 };
8543 let Some(body) = self.body_var_slot(&name.name) else {
8544 continue;
8545 };
8546 self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
8547 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
8548 }
8549 }
8550 }
8551 // The parameter list is over; from here on a direct `eval` belongs to the body.
8552 self.state().in_params = false;
8553 // Entering the body's own scope comes *after* the parameter list: the body's
8554 // `let`s are not in existence while the defaults run, and the reference emits
8555 // their `set_loc_uninitialized` only once the parameters are bound.
8556 self.emit_scope_enter(body_key);
8557 // A generator starts suspended: `initial_yield` parks the body so that creating one
8558 // runs no body code until the first `next()`.
8559 //
8560 // It comes *after* the parameter unpacking, not before, because a parameter
8561 // initialiser is not body code — `function* g(a = sideEffect())` must run
8562 // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
8563 // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
8564 // until the first `next()` and 29 test262 cases that check for a synchronous throw
8565 // saw none at all.
8566 //
8567 // An async function does **not** get one. Its body runs synchronously up to the
8568 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
8569 // before its caller's next statement — so an `initial_yield` here would park the
8570 // body before it started, which is not fixable at run time: the suspension looks
8571 // exactly like a real `await`.
8572 if self.cur().kind.is_generator() {
8573 self.emit(Opcode::InitialYield, &[]);
8574 }
8575 // Through `stmts`: the body is a block, and a `using` declaration in it is a
8576 // disposal region.
8577 self.stmts(body)?;
8578 // The implicit return only exists if control can actually get here: an
8579 // infinite loop never falls off the end.
8580 if self.end_is_reachable() {
8581 if self.cur().is_suspending() {
8582 // Falling off the end finishes the generator with `undefined`, and the
8583 // value is what tells the resume machinery "completed" rather than
8584 // "suspended".
8585 self.emit(Opcode::Undefined, &[]);
8586 self.emit(Opcode::ReturnAsync, &[]);
8587 } else {
8588 self.emit_class_constructor_tail();
8589 }
8590 }
8591 // Resolution runs while this function is still on the stack: capturing a
8592 // variable from an enclosing function means reaching into that
8593 // function's state, which requires the whole chain to be present.
8594 Ok(self.finish_current())
8595 }
8596
8597 /// Put every binding of a function that contains a direct `eval` into a cell.
8598 ///
8599 /// A direct eval can name any binding in scope, and any closure it creates has to
8600 /// keep sharing that binding after the function returns — `for (let i …)
8601 /// eval("push(() => i)")` collects one closure per iteration and each must read its
8602 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
8603 /// a cell. Doing this unconditionally for such functions is the cheap, honest
8604 /// answer: the alternative is knowing at compile time which names a string will
8605 /// mention.
8606 fn capture_everything_for_eval(&mut self) {
8607 let current = self.stack.len() - 1;
8608 if !self.stack[current].has_direct_eval {
8609 return;
8610 }
8611 for arg in &mut self.stack[current].args {
8612 arg.is_captured = true;
8613 }
8614 for var in &mut self.stack[current].vars {
8615 var.is_captured = true;
8616 }
8617 }
8618
8619 /// Whether the current position in the instruction stream can be reached.
8620 ///
8621 /// A walk over the control-flow graph, using labels as instruction indices.
8622 /// The reference does the same thing to decide whether an implicit
8623 /// `return_undef` is needed.
8624 fn end_is_reachable(&self) -> bool {
8625 let state = self.cur();
8626 reachable_instructions(state, state.insns.len())[state.insns.len()]
8627 }
8628
8629 /// Resolve and assemble the function on top of the compiler stack, then pop
8630 /// it.
8631 fn finish_current(&mut self) -> CompiledFunction {
8632 self.provide_param_arguments();
8633 self.provide_arguments();
8634 self.provide_this_local();
8635 self.provide_new_target_local();
8636 self.provide_home_object_local();
8637 self.provide_active_func_local();
8638 self.provide_self_name();
8639 self.materialize_eval_sites();
8640 self.capture_everything_for_eval();
8641 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
8642 // Captured bindings need a reference cell; the count goes in the header so
8643 // the runtime knows how many cells to allocate on entry.
8644 let current = self.stack.len() - 1;
8645 let captured = self.stack[current]
8646 .args
8647 .iter()
8648 .filter(|a| a.is_captured)
8649 .count()
8650 + self.stack[current]
8651 .vars
8652 .iter()
8653 .filter(|v| v.is_captured)
8654 .count();
8655 self.stack[current].var_ref_count = captured as u32;
8656 // The scope chain is only final now that every binding is known.
8657 rebuild_scope_chain(&mut self.stack[current]);
8658 let (code, stack_size, positions) =
8659 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
8660 let _ = &mut resolved;
8661 let mut state = self.stack.pop().expect("a function is being compiled");
8662 CompiledFunction {
8663 name: state.name,
8664 kind: state.kind,
8665 strict: state.strict,
8666 is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
8667 is_arrow: state.is_arrow,
8668 has_parameter_expressions: state.has_parameter_expressions,
8669 simple_parameter_list: state.simple_parameter_list,
8670 body_start: state.body_start,
8671 args: state.args,
8672 defined_args: state.defined_args,
8673 vars: state.vars,
8674 closure_vars: state.closure_vars,
8675 cpool: state.cpool,
8676 atoms: state.atoms,
8677 code,
8678 stack_size,
8679 var_ref_count: state.var_ref_count,
8680 positions,
8681 source: self.function_source(state.span, state.line, state.column),
8682 line: state.line,
8683 column: state.column,
8684 filename: None,
8685 eval_sites: state.eval_sites,
8686 module: state.module.take().map(Box::new),
8687 }
8688 }
8689}
8690
8691/// Assign each binding a scope level and rebuild the scope chains.
8692///
8693/// Levels are numbered in the order the blocks appear, with 0 reserved for the
8694/// function scope where `var` and hoisted functions live. Every binding outside
8695/// level 0 gets a `scope_next` link to the next binding visible from the same
8696/// point, so walking a block's chain enumerates exactly the bindings live there.
8697///
8698/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
8699/// point at `b`, which is declared later in the source but earlier in the chain.
8700fn rebuild_scope_chain(state: &mut FnState) {
8701 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
8702 // real block that happens to start at offset zero keeps its own level instead of
8703 // being merged into the function scope.
8704 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
8705 for block in &state.blocks {
8706 if !levels.contains(&block.key) {
8707 levels.push(block.key);
8708 }
8709 }
8710 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
8711 let parent_level = |level: usize| -> usize {
8712 if level == 0 {
8713 return 0;
8714 }
8715 let key = levels[level];
8716 let parent = state
8717 .blocks
8718 .iter()
8719 .find(|b| b.key == key)
8720 .map(|b| b.parent)
8721 .unwrap_or(FUNCTION_SCOPE);
8722 level_of(parent)
8723 };
8724
8725 // Own bindings per level, in declaration order.
8726 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
8727 let keys: Vec<u64> = (0..state.vars.len())
8728 .map(|index| {
8729 state
8730 .var_block
8731 .get(index)
8732 .copied()
8733 .unwrap_or(FUNCTION_SCOPE)
8734 })
8735 .collect();
8736 for (index, key) in keys.into_iter().enumerate() {
8737 // The parameter scope is not a block: it is a level of its own with no parent,
8738 // assigned below. Letting it land in level 0 would chain the body's bindings onto
8739 // it, which the reference does not do — the two environments are siblings.
8740 if key == PARAM_SCOPE {
8741 continue;
8742 }
8743 let level = level_of(key);
8744 state.vars[index].scope_level = level as u32;
8745 // A `catch` parameter is part of the runtime scope chain even though it is
8746 // not lexical: the handler's own bindings chain on to it, which is why the
8747 // reference prints `let y [next:1]` with `e` at 1.
8748 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
8749 {
8750 own[level].push(index);
8751 }
8752 }
8753
8754 // A scope's chain is its own bindings in reverse declaration order followed
8755 // by the enclosing scope's chain.
8756 let mut head = vec![-1i32; levels.len()];
8757 for level in 0..levels.len() {
8758 let inherited = if level == 0 {
8759 -1
8760 } else {
8761 head[parent_level(level)]
8762 };
8763 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
8764 head[level] = chain.first().map_or(inherited, |first| *first as i32);
8765 for (position, &index) in chain.iter().enumerate() {
8766 let next = chain
8767 .get(position + 1)
8768 .map_or(inherited, |next| *next as i32);
8769 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
8770 }
8771 }
8772 state.block_heads = head;
8773
8774 // The parameter list is a scope of its own, and it has no parent: the reference pops
8775 // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
8776 // the `-1` a block uses. A level past every real block keeps it out of the walk above
8777 // — nothing but the dump reads it — and the links run newest-to-oldest through the
8778 // bindings themselves, which is the order `set_loc_uninitialized` walks.
8779 let param_level = levels.len() as u32;
8780 let mut previous: Option<usize> = None;
8781 for index in 0..state.vars.len() {
8782 if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
8783 {
8784 continue;
8785 }
8786 state.vars[index].scope_level = param_level;
8787 state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
8788 previous = Some(index);
8789 }
8790}
8791
8792/// This is where names become slots and where the temporal dead zone shows up in
8793/// the instruction stream: a read of a `let`/`const` binding compiles to
8794/// `get_loc_check`, which throws if the binding is still uninitialised.
8795///
8796/// The peephole pass from the reference implementation is applied at the end,
8797/// for the same reason it is applied to resolved bytecode there: the patterns are
8798/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
8799/// resolution. Deleted instructions stay in the list as `None` so that label
8800/// indices remain valid; [`Assembler`] maps them to byte offsets.
8801/// A resolved instruction and the source position it came from.
8802type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
8803
8804/// A resolved instruction paired with its position, which is what `assemble` consumes.
8805type PositionedInsn = (Opcode, Vec<Op>);
8806
8807fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
8808 let current = stack.len() - 1;
8809 // Dead-code elimination, on the symbolic form where labels are still
8810 // instruction indices. A `break` inside a loop leaves the trailing `goto`
8811 // unreachable, and a `return` leaves everything after it unreachable; the
8812 // reference drops both. Doing it here means the emitter never has to think
8813 // about reachability.
8814 strip_empty_gosubs(stack, current);
8815 eliminate_dead_code(stack, current);
8816 let insns = std::mem::take(&mut stack[current].insns);
8817 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
8818 // `insns`, and every arm below pushes exactly one instruction, so the positions
8819 // stay aligned with `out`.
8820 let positions = std::mem::take(&mut stack[current].insn_pos);
8821 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
8822 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8823 for (index, insn) in insns.iter().enumerate() {
8824 let pos = positions.get(index).copied().flatten();
8825 out_pos.push(pos);
8826 match insn {
8827 Insn::Fixed { op, operands } => {
8828 let operands = operands
8829 .iter()
8830 .map(|operand| match operand {
8831 Op::Atom(atom) => {
8832 Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
8833 }
8834 other => other.clone(),
8835 })
8836 .collect();
8837 out.push(Some((*op, operands)));
8838 }
8839 Insn::Var {
8840 action,
8841 name,
8842 block,
8843 in_params,
8844 } => {
8845 // Both reads and writes in the parameter list address the parameter
8846 // scope. That is what puts the list in the temporal dead zone — a read of
8847 // a later parameter is `get_loc_check` on an uninitialised slot — and it
8848 // is also what keeps an assignment made inside a default away from the
8849 // body, which sees a separate environment.
8850 let slot = resolve_slot(stack, current, name, *block, *in_params);
8851 // A store to the name of a named function expression is special: the
8852 // reference drops it in sloppy mode and throws in strict mode, because
8853 // the binding is immutable but only *checked* when the body is strict.
8854 // The same rule applies when the name is reached through a closure:
8855 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8856 // the store in the arrow too, not just in the function that owns the
8857 // binding. Reaching the owner means walking the chain of closure
8858 // entries, which is what `self_name_binding` does.
8859 let self_name = matches!(action, VarAction::Put | VarAction::Set)
8860 .then(|| {
8861 // A local of this function is the common case and needs no
8862 // chain walk; only an access that resolves elsewhere can be
8863 // pointing at an enclosing function's name binding.
8864 if let Slot::Loc(index) = slot {
8865 stack[current]
8866 .vars
8867 .get(index as usize)
8868 .filter(|var| var.kind == VarKind::FunctionName)
8869 .map(|var| var.is_const)
8870 } else {
8871 self_name_binding(stack, current, name, *block)
8872 }
8873 })
8874 .flatten();
8875 if let Some(is_const) = self_name {
8876 out.push(Some(if is_const {
8877 (
8878 Opcode::ThrowError,
8879 vec![
8880 Op::AtomId(intern_atom(&mut stack[current], name)),
8881 Op::Int(0),
8882 ],
8883 )
8884 } else {
8885 (Opcode::Drop, Vec::new())
8886 }));
8887 continue;
8888 }
8889 if *action == VarAction::MakeRef {
8890 // A reference to a *local* has to keep working after the enclosing
8891 // frame is gone, and `get_ref_value` reads a cell — so the binding is
8892 // forced into one, exactly as the reference implementation's
8893 // `capture_var` does. Only an access that a direct `eval` in the same
8894 // function can shadow ever asks for this, so the cost is confined to
8895 // functions that contain one.
8896 match slot {
8897 Slot::Loc(index) => {
8898 if let Some(var) = stack[current].vars.get_mut(index as usize) {
8899 var.is_captured = true;
8900 }
8901 }
8902 Slot::Arg(index) => {
8903 if let Some(arg) = stack[current].args.get_mut(index as usize) {
8904 arg.is_captured = true;
8905 }
8906 }
8907 _ => {}
8908 }
8909 }
8910 let (opcode, mut operands) = variable_instruction(stack, current, *action, slot);
8911 if *action == VarAction::MakeRef {
8912 // Operand 0 is the placeholder `variable_instruction` could not fill
8913 // in; the name is in hand here, and it has to be *interned* — this arm
8914 // bypasses `Insn::Fixed`, which is where `Op::Atom` normally becomes an
8915 // `Op::AtomId`.
8916 operands[0] = Op::AtomId(intern_atom(&mut stack[current], name));
8917 }
8918 out.push(Some((opcode, operands)));
8919 }
8920 Insn::CloseCaptured { name, block } => {
8921 // The block matters: a loop variable is scoped to the `for` head's own
8922 // block, so resolving it against block 0 would miss it entirely and
8923 // silently emit nothing.
8924 let slot = resolve_slot(stack, current, name, *block, false);
8925 // Only a local with a reference cell has anything to close. A global
8926 // or a never-captured local resolves to no instruction at all, which
8927 // keeps the bytecode identical to the reference's.
8928 if let Slot::Loc(index) = slot
8929 && stack[current]
8930 .vars
8931 .get(index as usize)
8932 .is_some_and(|v| v.is_captured)
8933 {
8934 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
8935 } else {
8936 out.push(None);
8937 }
8938 }
8939 Insn::DeleteVar { name } => {
8940 // A binding — a local, an argument, or a declared global — cannot be
8941 // deleted, and the reference encodes that as a constant `push_false`.
8942 // Only an implicit global needs the runtime lookup.
8943 if matches!(
8944 resolve_slot(stack, current, name, 0, false),
8945 Slot::Global(_)
8946 ) {
8947 let atom = intern_atom(&mut stack[current], name);
8948 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
8949 } else {
8950 out.push(Some((Opcode::PushFalse, Vec::new())));
8951 }
8952 }
8953 Insn::Dead => out.push(None),
8954 }
8955 }
8956 // Which label (if any) sits on each instruction, so the jump patterns can
8957 // tell whether they would cross a jump target.
8958 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
8959 for (id, placed) in stack[current].labels.iter().enumerate() {
8960 if let Some(index) = *placed
8961 && index < label_at.len()
8962 && label_at[index].is_none()
8963 {
8964 label_at[index] = Some(id as u32);
8965 }
8966 }
8967 if std::env::var_os("QJS_DEBUG").is_some() {
8968 eprintln!("--- peephole entry ---");
8969 for (i, e) in out.iter().enumerate() {
8970 eprintln!("{i}: {e:?}");
8971 }
8972 eprintln!("label_at: {label_at:?}");
8973 }
8974 peephole(&mut out, &label_at, &stack[current].labels);
8975 (out, out_pos)
8976}
8977
8978/// Find where `name` lives, capturing it in an enclosing function when needed.
8979///
8980/// The search runs outward through the enclosing functions' states, which are
8981/// still on the compiler stack while a nested function is resolved. Finding the
8982/// name in an enclosing function is what creates a closure reference, and every
8983/// function in between has to forward it — a function can only reach its own
8984/// parent's frame.
8985///
8986/// A name declared nowhere is a global. The reference does *not* look it up by
8987/// name from the inner function: the top-level function gets one `[global]`
8988/// entry and every nested function gets a `[global_ref<n>]` pointing at its
8989/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
8990/// rather than `[global]`.
8991/// The lexical blocks enclosing `block`, innermost first.
8992fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
8993 let mut chain = Vec::new();
8994 let mut current = Some(block);
8995 while let Some(key) = current {
8996 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
8997 // explicitly (rather than on "no block with this key") is what keeps a block
8998 // that happens to sit at offset zero from being mistaken for the terminator.
8999 if key == NO_PARENT || chain.contains(&key) {
9000 break;
9001 }
9002 chain.push(key);
9003 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
9004 }
9005 chain
9006}
9007
9008/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
9009///
9010/// The binding may be several functions away: an arrow nested in `function myfunc`
9011/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
9012/// means following `Ref` entries down and then reading the owning function's var table.
9013fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
9014 let state = stack.get(current)?;
9015 // A parameter shadows everything and is never a function-expression name.
9016 if state.args.iter().any(|arg| arg.name == name) {
9017 return None;
9018 }
9019 // A local of this very function: the answer is in its var table.
9020 if let Some(index) = local_slot_index(state, name, block) {
9021 let var = state.vars.get(index)?;
9022 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
9023 }
9024 // Otherwise the name lives further out, and the closure entry says how to get
9025 // there. `Local` names the owner's slot directly; `Ref` names the next level's
9026 // closure entry, so the walk continues downwards.
9027 let mut level = current;
9028 let mut index = state
9029 .closure_vars
9030 .iter()
9031 .position(|closure| closure.name == name)?;
9032 loop {
9033 let state = stack.get(level)?;
9034 let closure = state.closure_vars.get(index)?;
9035 match closure.closure_type {
9036 ClosureType::Local => {
9037 let owner = stack.get(level.checked_sub(1)?)?;
9038 let var = owner.vars.get(closure.var_idx as usize)?;
9039 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
9040 }
9041 ClosureType::Arg => return None,
9042 ClosureType::Ref => {
9043 level -= 1;
9044 index = closure.var_idx as usize;
9045 }
9046 // A global is never a function-expression name.
9047 ClosureType::Global
9048 | ClosureType::GlobalDecl
9049 | ClosureType::GlobalRef
9050 | ClosureType::ModuleDecl
9051 | ClosureType::ModuleImport => return None,
9052 }
9053 }
9054}
9055
9056/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
9057fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
9058 block_chain(state, block).into_iter().find_map(|scope| {
9059 state.vars.iter().enumerate().find_map(|(index, var)| {
9060 (var.name == name && state.var_block.get(index).copied() == Some(scope))
9061 .then_some(index)
9062 })
9063 })
9064}
9065
9066/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
9067fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
9068 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
9069 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
9070 }) {
9071 return index as u32;
9072 }
9073 state.var_block.push(PARAM_SCOPE);
9074 state.vars.push(VarDef::var(name));
9075 state.vars.len() as u32 - 1
9076}
9077
9078/// The name a parameter binds straight from its argument slot, if it has one.
9079///
9080/// A plain name does — with or without a default, and with or without `...`. Everything
9081/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
9082/// reference names the argument in the first case and leaves it `<null>` in the second,
9083/// so both the dump and the closures that capture the argument depend on this.
9084fn simple_parameter(param: &Pattern) -> Option<&Ident> {
9085 match ¶m.kind {
9086 PatternKind::Ident(name) => Some(name),
9087 PatternKind::Assign { target, .. } => match &target.kind {
9088 PatternKind::Ident(name) => Some(name),
9089 _ => None,
9090 },
9091 PatternKind::Rest(inner) => match &inner.kind {
9092 PatternKind::Ident(name) => Some(name),
9093 _ => None,
9094 },
9095 _ => None,
9096 }
9097}
9098
9099/// The pattern a parameter list has to unpick, if `index` is one of them.
9100fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
9101 prologue
9102 .iter()
9103 .find(|(at, _)| *at == index)
9104 .map(|(_, pattern)| pattern)
9105}
9106
9107fn pattern_has_default(pattern: &Pattern) -> bool {
9108 match &pattern.kind {
9109 PatternKind::Assign { .. } => true,
9110 PatternKind::Rest(inner) => pattern_has_default(inner),
9111 PatternKind::Array { elements, rest } => {
9112 elements.iter().flatten().any(element_has_default)
9113 || rest.as_deref().is_some_and(rest_has_default)
9114 }
9115 PatternKind::Object { properties, rest } => {
9116 properties.iter().flatten().any(element_has_default)
9117 || rest.as_deref().is_some_and(rest_has_default)
9118 }
9119 _ => false,
9120 }
9121}
9122
9123fn element_has_default(element: &PatternElement) -> bool {
9124 match element {
9125 PatternElement::Pattern(pattern) => pattern_has_default(pattern),
9126 PatternElement::Property { value, .. } => pattern_has_default(value),
9127 }
9128}
9129
9130fn rest_has_default(rest: &RestElement) -> bool {
9131 match rest {
9132 RestElement::Pattern(pattern) => pattern_has_default(pattern),
9133 RestElement::Member(_) => false,
9134 }
9135}
9136
9137/// Whether a function-scope binding is visible to the parameter list.
9138///
9139/// The parameter list runs before the body, so the body's `var`s and function
9140/// declarations do not exist yet — a name that only the body declares has to resolve
9141/// outward instead. What *does* exist by then is the compiler's own prologue: the
9142/// self-name of a named function expression (bound by `special_object 2` before anything
9143/// else), `this` and `new.target`. Those stay visible, which is what makes
9144/// `function f(a = this)` and `var f = function f(a = f)` work.
9145///
9146/// `arguments` is handled separately, as a binding of the parameter scope itself: with
9147/// parameter expressions the reference creates two of them, and the one the parameter
9148/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
9149fn visible_in_params(var: &VarDef) -> bool {
9150 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
9151}
9152
9153fn resolve_slot(
9154 stack: &mut [FnState],
9155 current: usize,
9156 name: &str,
9157 block: u64,
9158 in_params: bool,
9159) -> Slot {
9160 // The parameter list's own bindings. They are consulted first because they shadow
9161 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
9162 // `a` in the parameter scope, so a closure made there reads the parameter even after
9163 // the body assigns to its own `a`.
9164 if in_params
9165 && let Some(index) = stack[current]
9166 .vars
9167 .iter()
9168 .enumerate()
9169 .position(|(index, var)| {
9170 var.name == name
9171 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
9172 })
9173 {
9174 return Slot::Loc(index as u32);
9175 }
9176 // A name can be bound more than once: two `catch` parameters in nested
9177 // handlers are two slots. The binding that wins is the one whose scope encloses
9178 // the access, and among those the innermost — so the blocks are walked outward
9179 // and the first binding found on the way is the one that counts. A binding in
9180 // no block (`var`) is reachable from anywhere, which is why the function scope
9181 // is the end of the walk.
9182 //
9183 // The block walk comes *before* the argument slots, because a block may shadow a
9184 // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
9185 // slot is only the answer once nothing nearer claims the name.
9186 let chain = block_chain(&stack[current], block);
9187 for scope in &chain {
9188 let found = stack[current]
9189 .vars
9190 .iter()
9191 .enumerate()
9192 .find(|(index, var)| {
9193 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
9194 })
9195 .map(|(index, _)| index);
9196 if let Some(index) = found {
9197 return Slot::Loc(index as u32);
9198 }
9199 }
9200 // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
9201 // its own slot, and `var` of the same name in the body is the same binding.
9202 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
9203 return Slot::Arg(index as u32);
9204 }
9205 // Function-scope bindings — `var` and function declarations — are recorded with
9206 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
9207 // them. They are reachable from anywhere in the function, which is exactly what
9208 // the sentinel means.
9209 //
9210 // This pass is *only* for those. A lexical binding has to be found through the
9211 // chain or not at all, and looking a name up without its block is precisely how
9212 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
9213 // block leaked out of it.
9214 let function_scoped = stack[current]
9215 .vars
9216 .iter()
9217 .enumerate()
9218 .find(|(index, var)| {
9219 var.name == name
9220 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
9221 && (!in_params || visible_in_params(var))
9222 })
9223 .map(|(index, _)| index);
9224 if let Some(index) = function_scoped {
9225 return Slot::Loc(index as u32);
9226 }
9227 if let Some(index) = stack[current]
9228 .closure_vars
9229 .iter()
9230 .position(|c| c.name == name)
9231 {
9232 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
9233 }
9234
9235 for owner in (0..current).rev() {
9236 // The nested function was created inside one of this frame's blocks, and the
9237 // outermost visible binding is the innermost block on that chain — not whatever
9238 // comes first in the variable table. `function f(){ class S{} }` has two `S`
9239 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
9240 // the class body is the one a method may see.
9241 let entry = stack
9242 .get(owner + 1)
9243 .map(|s| s.created_in_block)
9244 .unwrap_or(0);
9245 let lexical = block_chain(&stack[owner], entry)
9246 .into_iter()
9247 .find_map(|scope| {
9248 stack[owner]
9249 .vars
9250 .iter()
9251 .enumerate()
9252 .find(|(index, var)| {
9253 var.name == name
9254 && stack[owner].var_block.get(*index).copied() == Some(scope)
9255 })
9256 .map(|(index, _)| index)
9257 });
9258 // A function born in a parameter list sees that list's bindings, not the body's:
9259 // the parameter scope is the environment it was created in.
9260 let in_param_scope = stack
9261 .get(owner + 1)
9262 .is_some_and(|child| child.created_in_params)
9263 .then(|| {
9264 stack[owner]
9265 .vars
9266 .iter()
9267 .enumerate()
9268 .position(|(index, var)| {
9269 var.name == name
9270 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
9271 })
9272 })
9273 .flatten();
9274 let found = if let Some(index) = in_param_scope {
9275 let var = &stack[owner].vars[index];
9276 Some(Found::Local(
9277 ClosureType::Local,
9278 index as u32,
9279 var.is_const,
9280 var.needs_check(),
9281 ))
9282 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
9283 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
9284 } else if let Some(index) = lexical {
9285 let var = &stack[owner].vars[index];
9286 Some(Found::Local(
9287 ClosureType::Local,
9288 index as u32,
9289 var.is_const,
9290 var.needs_check(),
9291 ))
9292 } else if let Some(index) = stack[owner]
9293 .vars
9294 .iter()
9295 .enumerate()
9296 .find_map(|(index, var)| {
9297 // A function created inside a parameter list must not see the body of the
9298 // function it was born in; see [`FnState::created_in_params`].
9299 let hidden = stack
9300 .get(owner + 1)
9301 .is_some_and(|child| child.created_in_params);
9302 (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
9303 })
9304 {
9305 let var = &stack[owner].vars[index];
9306 Some(Found::Local(
9307 ClosureType::Local,
9308 index as u32,
9309 var.is_const,
9310 var.needs_check(),
9311 ))
9312 } else if stack[owner].self_name.as_deref() == Some(name) {
9313 // A named function expression's own name. The reference declares it here,
9314 // on the first lookup that fails, rather than up front — and that is what
9315 // makes it reachable from a *nested* function: the nested lookup is what
9316 // walks out and creates the binding. A direct reference in the body is
9317 // caught the same way, which is why `provide_self_name` only has to add
9318 // the prologue.
9319 let strict = stack[owner].strict;
9320 stack[owner].var_block.push(FUNCTION_SCOPE);
9321 stack[owner].vars.push(VarDef {
9322 kind: VarKind::FunctionName,
9323 // In strict mode the name is immutable, so a store raises; sloppy
9324 // mode drops the store instead (see `variable_instruction`).
9325 is_const: strict,
9326 ..VarDef::var(name)
9327 });
9328 let index = stack[owner].vars.len() as u32 - 1;
9329 Some(Found::Local(ClosureType::Local, index, strict, false))
9330 } else if let Some(index) = stack[owner]
9331 .closure_vars
9332 .iter()
9333 .position(|c| c.name == name)
9334 {
9335 let closure = &stack[owner].closure_vars[index];
9336 Some(match closure.closure_type {
9337 // `GlobalRef` belongs here too: it is a *global* reached through this
9338 // frame's reference table, so treating it as a `Ref` to a local cell makes
9339 // the reader look for a cell no frame ever fills. That is how a second
9340 // function using `eval` in its parameter list read `undefined` after a
9341 // sibling had already made `eval` a closure entry.
9342 ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
9343 Found::Global(index as u32)
9344 }
9345 // A module variable is a cell in the *module's* environment, which is
9346 // the module body's parent as far as a nested function is concerned — so
9347 // it is captured as a plain reference, not looked up as a global.
9348 ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
9349 ClosureType::Ref,
9350 index as u32,
9351 closure.is_const,
9352 closure.is_lexical,
9353 ),
9354 _ => Found::Local(
9355 ClosureType::Ref,
9356 index as u32,
9357 closure.is_const,
9358 closure.is_lexical,
9359 ),
9360 })
9361 } else {
9362 None
9363 };
9364 let Some(found) = found else { continue };
9365
9366 let (is_const, is_lexical) = match found {
9367 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
9368 Found::Global(_) => (false, false),
9369 };
9370 // Mark the owner's binding as captured so it moves into a reference cell.
9371 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
9372 let slot = match found {
9373 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
9374 _ => &mut stack[owner].vars[index as usize],
9375 };
9376 slot.is_captured = true;
9377 }
9378 // Forward the reference through every function in between.
9379 let mut previous = match found {
9380 Found::Local(kind, index, _, _) => (kind, index),
9381 Found::Global(index) => (ClosureType::Global, index),
9382 };
9383 for level in owner + 1..=current {
9384 let kind = match (previous.0, level) {
9385 // A global stays a global at *every* level. Without `GlobalRef` in
9386 // this arm the second nested function over the same global got a
9387 // `Ref` to a cell no frame ever held, so the innermost closure read
9388 // `undefined` — which is how a two-deep getter lost its outer
9389 // variable.
9390 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
9391 ClosureType::GlobalRef
9392 }
9393 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
9394 _ => ClosureType::Ref,
9395 };
9396 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
9397 previous = (kind, index);
9398 }
9399 let index = previous.1;
9400 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
9401 }
9402
9403 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
9404 // creating a property. The top-level function holds the entry.
9405 let mut previous = (
9406 ClosureType::Global,
9407 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
9408 );
9409 for level in 1..=current {
9410 let index = ensure_closure(
9411 stack,
9412 level,
9413 name,
9414 false,
9415 false,
9416 ClosureType::GlobalRef,
9417 previous.1,
9418 );
9419 previous = (ClosureType::GlobalRef, index);
9420 }
9421 Slot::Global(previous.1)
9422}
9423
9424/// What an outward search turned up.
9425#[derive(Debug, Clone, Copy)]
9426enum Found {
9427 /// A binding in an enclosing function, reachable through a closure of this
9428 /// type, with its const/lexical flags.
9429 Local(ClosureType, u32, bool, bool),
9430 /// A global, reached through the enclosing function's closure entry.
9431 Global(u32),
9432}
9433
9434/// Add a closure entry to `level` if it is not there yet.
9435fn ensure_closure(
9436 stack: &mut [FnState],
9437 level: usize,
9438 name: &str,
9439 is_const: bool,
9440 is_lexical: bool,
9441 closure_type: ClosureType,
9442 var_idx: u32,
9443) -> u32 {
9444 if let Some(index) = stack[level]
9445 .closure_vars
9446 .iter()
9447 .position(|c| c.name == name)
9448 {
9449 return index as u32;
9450 }
9451 stack[level].closure_vars.push(ClosureVar {
9452 name: name.to_string(),
9453 is_const,
9454 is_lexical,
9455 closure_type,
9456 var_idx: var_idx as u16,
9457 });
9458 stack[level].closure_vars.len() as u32 - 1
9459}
9460
9461fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
9462 match closure.closure_type {
9463 // A `global_ref` only says *how* the binding is found (through the
9464 // parent's closure table); the access itself is an ordinary global one.
9465 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
9466 ClosureType::GlobalDecl => Slot::GlobalDecl(index),
9467 // A module variable is a real cell in the module's environment, so it is reached
9468 // exactly like a captured local — the host, not the global object, is what fills
9469 // the slot.
9470 ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
9471 _ => Slot::VarRef(index),
9472 }
9473}
9474
9475/// Pick the opcode for one variable access.
9476///
9477/// The `_check` variants are what enforce the temporal dead zone. They are used
9478/// for every access to a `let`/`const` binding except its own initialisation —
9479/// which is exactly the operation that takes the binding out of the dead zone.
9480fn variable_instruction(
9481 stack: &[FnState],
9482 current: usize,
9483 action: VarAction,
9484 slot: Slot,
9485) -> (Opcode, Vec<Op>) {
9486 let lexical = match slot {
9487 Slot::Loc(index) => stack[current]
9488 .vars
9489 .get(index as usize)
9490 .is_some_and(|v| v.needs_check()),
9491 Slot::VarRef(index) => stack[current]
9492 .closure_vars
9493 .get(index as usize)
9494 .is_some_and(|c| c.is_lexical),
9495 _ => false,
9496 };
9497 let operand = vec![Op::Slot(slot)];
9498 // `make_*_ref` carries the name as well as the slot: the reference's runtime resolution
9499 // consults the names a direct `eval` has declared in this frame, which is a by-name
9500 // question, so the atom cannot be dropped. `variable_instruction` never sees the name, so
9501 // the caller patches operand 0 in (see `Compiler::emit_var`).
9502 //
9503 // Operand 1 is a *bare* slot index, not an `Op::Slot`: the opcode already says which
9504 // table it counts in, and `OpFormat::AtomU16`'s second operand is written by the plain
9505 // `u16` encoder, which an `Op::Slot` would silently skip — leaving the instruction two
9506 // bytes short and the whole stream desynchronised.
9507 let ref_slot = match slot {
9508 Slot::Arg(index)
9509 | Slot::Loc(index)
9510 | Slot::VarRef(index)
9511 | Slot::Global(index)
9512 | Slot::GlobalDecl(index) => index,
9513 };
9514 let ref_operand = vec![Op::AtomId(0), Op::Int(ref_slot as i32)];
9515 match (action, slot) {
9516 (VarAction::Get, Slot::Loc(index)) => (
9517 if lexical {
9518 Opcode::GetLocCheck
9519 } else {
9520 Opcode::GetLoc
9521 },
9522 vec![Op::Slot(Slot::Loc(index))],
9523 ),
9524 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
9525 (VarAction::Get, Slot::VarRef(index)) => (
9526 if lexical {
9527 Opcode::GetVarRefCheck
9528 } else {
9529 Opcode::GetVarRef
9530 },
9531 vec![Op::Slot(Slot::VarRef(index))],
9532 ),
9533 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
9534 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
9535 // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
9536 // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
9537 // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
9538 // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
9539 // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
9540 // `ReferenceError`.
9541 (VarAction::GetUndef, Slot::Loc(index)) => (
9542 if lexical {
9543 Opcode::GetLocCheck
9544 } else {
9545 Opcode::GetLoc
9546 },
9547 vec![Op::Slot(Slot::Loc(index))],
9548 ),
9549 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
9550 (VarAction::GetUndef, Slot::VarRef(index)) => (
9551 if lexical {
9552 Opcode::GetVarRefCheck
9553 } else {
9554 Opcode::GetVarRef
9555 },
9556 vec![Op::Slot(Slot::VarRef(index))],
9557 ),
9558 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9559 (Opcode::GetVarUndef, operand)
9560 }
9561
9562 (VarAction::Put, Slot::Loc(_)) => (
9563 if lexical {
9564 Opcode::PutLocCheck
9565 } else {
9566 Opcode::PutLoc
9567 },
9568 operand,
9569 ),
9570 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
9571 (VarAction::Put, Slot::VarRef(_)) => (
9572 if lexical {
9573 Opcode::PutVarRefCheck
9574 } else {
9575 Opcode::PutVarRef
9576 },
9577 operand,
9578 ),
9579 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
9580 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9581 // Initialisation is what ends the dead zone, so it never checks.
9582 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9583 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
9584 // `this` in a derived constructor is always a local, so these cannot happen;
9585 // routing them to the ordinary forms keeps the match total without inventing
9586 // opcodes the reference does not have.
9587 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
9588 // The captured form of `PutLocCheckInit`: `super()` inside an arrow that closes over
9589 // the constructor's `this` still has to refuse a second initialisation, and the
9590 // plain store accepted it (`fields-run-once-on-double-super`).
9591 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRefCheckInit, operand),
9592 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9593 (Opcode::PutVarInit, operand)
9594 }
9595 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
9596 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9597 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9598 (Opcode::PutVarInit, operand)
9599 }
9600 (VarAction::Set, Slot::Loc(_)) => (
9601 if lexical {
9602 Opcode::SetLocCheck
9603 } else {
9604 Opcode::SetLoc
9605 },
9606 operand,
9607 ),
9608 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
9609 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
9610 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9611 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9612 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
9613 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9614 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
9615 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
9616 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9617 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
9618 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9619 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
9620 // A reference pins the binding so that one lvalue can be read and stored without
9621 // resolving the name in between. Which opcode builds it depends on where the
9622 // binding lives; the atom rides along because the *runtime* resolution can still
9623 // override the static answer — see `Interp::make_var_ref`.
9624 (VarAction::MakeRef, Slot::Loc(_)) => (Opcode::MakeLocRef, ref_operand),
9625 (VarAction::MakeRef, Slot::Arg(_)) => (Opcode::MakeArgRef, ref_operand),
9626 (VarAction::MakeRef, Slot::VarRef(_)) => (Opcode::MakeVarRefRef, ref_operand),
9627 (VarAction::MakeRef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9628 (Opcode::MakeVarRef, vec![ref_operand[0].clone()])
9629 }
9630 // Reading through a reference does not consult the binding at all — the reference
9631 // already points at it — so the slot plays no part.
9632 (VarAction::GetRef, _) => (Opcode::GetRefValue, Vec::new()),
9633 }
9634}
9635
9636/// The instruction-rewriting pass.
9637///
9638/// These are the reference implementation's patterns, restricted to the ones the
9639/// constructs this compiler supports can produce. Each entry is a comment on the
9640/// bytecode it removes, because the whole point is that the result is one
9641/// instruction shorter than the literal translation of the AST.
9642fn peephole(
9643 insns: &mut [Option<(Opcode, Vec<Op>)>],
9644 label_at: &[Option<u32>],
9645 placed: &[Option<usize>],
9646) {
9647 fold_dup_patterns(insns, label_at);
9648
9649 // `drop` before `return_undef` is dead: the return discards the whole frame
9650 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
9651 // consumes its own `drop`; removing the drop first would leave the `dup` and
9652 // produce a `set_` where the reference has a `put_`.
9653 for index in 0..insns.len() {
9654 if opcode_at(insns, index) != Some(Opcode::Drop) {
9655 continue;
9656 }
9657 // Skip over a run of drops, but stop at a jump target: removing code on
9658 // one side of a label would silently retarget the jump.
9659 let mut next = index + 1;
9660 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
9661 next += 1;
9662 }
9663 if is_label_at(label_at, next) {
9664 continue;
9665 }
9666 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
9667 for entry in &mut insns[index..next] {
9668 *entry = None;
9669 }
9670 }
9671 }
9672
9673 // The rewrites below all decide against one fixed snapshot, which is what the
9674 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
9675 // the pass, so a rule never observes what an earlier rule removed. Gathering
9676 // every deletion first and applying them together reproduces that.
9677 let snapshot: Vec<Option<Opcode>> = insns
9678 .iter()
9679 .map(|entry| entry.as_ref().map(|(op, _)| *op))
9680 .collect();
9681 // The next instruction that is still there. Holes left by dead-code
9682 // elimination are not instructions, so a rule looks past them.
9683 let next_op = |index: usize| -> Option<usize> {
9684 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
9685 };
9686
9687 let mut doomed = vec![false; insns.len()];
9688 for index in 0..insns.len() {
9689 // A constant pushed only to be dropped does nothing at all. This is what a
9690 // comma expression with a literal left operand compiles to — `(0, f)()` — and
9691 // the reference removes the pair rather than making the reader step over it.
9692 let constant = matches!(
9693 snapshot[index],
9694 Some(
9695 Opcode::Undefined
9696 | Opcode::Null
9697 | Opcode::PushMinus1
9698 | Opcode::Push0
9699 | Opcode::Push1
9700 | Opcode::Push2
9701 | Opcode::Push3
9702 | Opcode::Push4
9703 | Opcode::Push5
9704 | Opcode::Push6
9705 | Opcode::Push7
9706 | Opcode::PushTrue
9707 | Opcode::PushFalse
9708 | Opcode::PushI32
9709 )
9710 );
9711 if constant
9712 && let Some(next) = next_op(index)
9713 && snapshot[next] == Some(Opcode::Drop)
9714 {
9715 doomed[index] = true;
9716 doomed[next] = true;
9717 }
9718 }
9719 for (index, entry) in insns.iter_mut().enumerate() {
9720 if doomed[index] {
9721 *entry = None;
9722 }
9723 }
9724
9725 // A conditional whose destination is the very next instruction just pops its
9726 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
9727 // compiles to.
9728 //
9729 // Order matters, and it is the reference's order: this runs *before* the
9730 // folding below, on the instruction the conditional originally had. Folding
9731 // moves a conditional's destination, and the reference never re-examines it
9732 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
9733 // a conditional even though folding leaves it pointing at the next
9734 // instruction.
9735 for (index, entry) in insns.iter_mut().enumerate() {
9736 let Some((op, operands)) = entry.clone() else {
9737 continue;
9738 };
9739 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
9740 continue;
9741 }
9742 let Some(id) = label_id(&operands) else {
9743 continue;
9744 };
9745 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
9746 *entry = Some((Opcode::Drop, Vec::new()));
9747 }
9748 }
9749
9750 // A constant condition is decided here rather than at run time.
9751 fold_constant_conditions(insns, label_at);
9752 // The conditional folding below is about pairs of *real* branches, so it runs
9753 // before a jump to the next instruction is dropped: `do { … if (c) continue }
9754 // while (t)` puts `continue` exactly on the condition, and the reference inverts
9755 // the branch first and only then notices the jump goes nowhere.
9756 fold_conditional_jumps(insns, label_at, placed);
9757
9758 // A jump whose destination is the very next instruction does nothing, which is
9759 // what constant folding leaves behind for `while (1) { … }`.
9760 remove_jump_to_next(insns, placed);
9761
9762 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
9763 // a use of the same variable boils down to.
9764 for index in 0..insns.len() {
9765 let Some((put_op, _)) = insns[index].clone() else {
9766 continue;
9767 };
9768 if !is_foldable_put(put_op) {
9769 continue;
9770 }
9771 if is_label_at(label_at, index + 1) {
9772 continue;
9773 }
9774 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
9775 continue;
9776 };
9777 if get_op != get_form_of(put_op) {
9778 continue;
9779 }
9780 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
9781 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
9782 continue;
9783 }
9784 insns[index] = Some((set_form_of(put_op), get_operands));
9785 insns[index + 1] = None;
9786 }
9787}
9788
9789/// Drop `gosub`s that call an empty subroutine.
9790///
9791/// A `gosub` whose target starts with `ret` returns immediately, so the reference
9792/// drops the call. This is how `try`/`catch` without a `finally` loses its
9793/// finalizer plumbing: the finalizer block is empty, its first instruction is
9794/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
9795/// [`eliminate_dead_code`] then removes.
9796fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
9797 let state = &stack[current];
9798 let mut targets = Vec::new();
9799 for insn in &state.insns {
9800 if let Insn::Fixed { op, operands } = insn
9801 && *op == Opcode::Gosub
9802 && let Some(id) = label_id(operands)
9803 && let Some(target) = state.labels.get(id as usize).copied().flatten()
9804 {
9805 targets.push(target);
9806 }
9807 }
9808 let empty: Vec<usize> = targets
9809 .into_iter()
9810 .filter(|target| {
9811 stack[current]
9812 .insns
9813 .get(*target)
9814 .map(|insn| {
9815 matches!(
9816 insn,
9817 Insn::Fixed {
9818 op: Opcode::Ret,
9819 ..
9820 }
9821 )
9822 })
9823 .unwrap_or(false)
9824 })
9825 .collect();
9826 if empty.is_empty() {
9827 return;
9828 }
9829 for insn in stack[current].insns.iter_mut() {
9830 if let Insn::Fixed { op, operands } = insn
9831 && *op == Opcode::Gosub
9832 && let Some(id) = label_id(operands)
9833 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
9834 && empty.contains(&target)
9835 {
9836 *insn = Insn::Dead;
9837 }
9838 }
9839}
9840
9841/// Replace unreachable instructions with [`Insn::Dead`].
9842fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
9843 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
9844 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
9845 if !reachable[index] {
9846 *insn = Insn::Dead;
9847 }
9848 }
9849}
9850
9851/// Mark every instruction index reachable from the entry, plus the index one past
9852/// the last instruction.
9853///
9854/// `seen[len]` answers "can control reach the end of this function", and the
9855/// entries before it identify dead code. Both DCE and the implicit-return decision
9856/// read the same result, which keeps them from disagreeing.
9857fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
9858 let mut seen = vec![false; count + 1];
9859 let mut worklist = vec![0usize];
9860 while let Some(index) = worklist.pop() {
9861 if index > count || seen[index] {
9862 continue;
9863 }
9864 seen[index] = true;
9865 if index == count {
9866 continue;
9867 }
9868 let (op, operands) = match &state.insns[index] {
9869 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
9870 // A variable access never transfers control, and a removed
9871 // instruction is only reachable if it is already marked.
9872 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
9873 worklist.push(index + 1);
9874 continue;
9875 }
9876 };
9877 match op {
9878 // A return, a throw and a `ret` all leave this instruction stream: the
9879 // first two give control to the caller or the handler, and `ret`
9880 // returns to a `gosub` elsewhere.
9881 // A tail call leaves the function too: the callee's result becomes this
9882 // function's result, so nothing after it runs.
9883 Opcode::Return
9884 | Opcode::ReturnUndef
9885 | Opcode::ReturnAsync
9886 | Opcode::TailCall
9887 | Opcode::TailCallMethod
9888 | Opcode::Throw
9889 | Opcode::ThrowError
9890 | Opcode::Ret => {}
9891 // A `catch` records where exceptions from the code that follows go.
9892 // That code is not reachable through normal control flow, but it is
9893 // reachable — through the exception edge — so the walk has to follow
9894 // it, or dead-code elimination would delete every handler.
9895 Opcode::Catch => {
9896 if let Some(target) = placed_label(state, operands) {
9897 worklist.push(target);
9898 }
9899 worklist.push(index + 1);
9900 }
9901 // A `gosub` calls a subroutine and then continues, so both edges count.
9902 Opcode::Gosub => {
9903 if let Some(target) = placed_label(state, operands) {
9904 worklist.push(target);
9905 }
9906 worklist.push(index + 1);
9907 }
9908 Opcode::Goto => {
9909 if let Some(target) = placed_label(state, operands) {
9910 worklist.push(target);
9911 }
9912 }
9913 Opcode::IfTrue | Opcode::IfFalse => {
9914 if let Some(target) = placed_label(state, operands) {
9915 worklist.push(target);
9916 }
9917 worklist.push(index + 1);
9918 }
9919 _ => worklist.push(index + 1),
9920 }
9921 }
9922 seen
9923}
9924
9925/// The instruction index a jump operand points at, resolved through the label
9926/// placement table.
9927fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
9928 let id = label_id(operands)?;
9929 state.labels.get(id as usize).copied().flatten()
9930}
9931
9932/// The label an instruction refers to.
9933fn label_id(operands: &[Op]) -> Option<u32> {
9934 operands.iter().find_map(|operand| match operand {
9935 Op::Label(label) => Some(label.0),
9936 _ => None,
9937 })
9938}
9939
9940/// Turn `if_false L; goto M; L:` into `if_true M`.
9941///
9942/// A conditional whose alternate branch is an unconditional jump needs one jump,
9943/// not two. This is the shape `if (c) break;` produces, so folding it removes an
9944/// instruction and a label from every conditional `break`.
9945/// The boolean a constant-push instruction produces, or `None` if it is not one.
9946///
9947/// Only the operators whose truthiness is decided by the opcode are covered; a
9948/// constant that needs the constant pool (a string) is left alone, because reading it
9949/// would mean threading the pool through the peephole for a case the reference also
9950/// skips.
9951fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
9952 match op {
9953 // `push_0` returns -1 for zero, `push_1` 1, and so on.
9954 Opcode::PushMinus1 => Some(true),
9955 Opcode::Push0 => Some(false),
9956 Opcode::Push1
9957 | Opcode::Push2
9958 | Opcode::Push3
9959 | Opcode::Push4
9960 | Opcode::Push5
9961 | Opcode::Push6
9962 | Opcode::Push7 => Some(true),
9963 Opcode::PushTrue => Some(true),
9964 Opcode::PushFalse => Some(false),
9965 Opcode::Undefined | Opcode::Null => Some(false),
9966 Opcode::PushI32 => match operands.first() {
9967 Some(Op::Int(value)) => Some(*value != 0),
9968 _ => None,
9969 },
9970 _ => None,
9971 }
9972}
9973
9974/// Fold a branch on a constant condition.
9975///
9976/// `if (0) a() else b()` must not test anything at run time, and the reference
9977/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
9978/// which is why the bytecode for a `while (1)` loop has no condition at all.
9979///
9980/// Two instructions become one, so the slot the test occupied is left empty rather
9981/// than shifting everything after it: labels have already been resolved to indices.
9982fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9983 for index in 0..insns.len() {
9984 let Some((push_op, push_operands)) = insns[index].clone() else {
9985 continue;
9986 };
9987 let Some(truth) = constant_truth(push_op, &push_operands) else {
9988 continue;
9989 };
9990 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
9991 continue;
9992 };
9993 // A label on the branch means something else jumps *here* — the value is on the
9994 // stack and the conditional is what pops it. Deleting the branch would leave that
9995 // jump with no instruction, and a label whose slot is empty resolves to the next
9996 // one that is not, i.e. to the far side of the branch. That is how
9997 // `if (a && false) then else` jumped to `then`: `&&` ends its chain on a label, and
9998 // the constant `false` sits directly in front of the statement's own conditional.
9999 if is_label_at(label_at, index + 1) {
10000 continue;
10001 }
10002 let (destination, taken) = match branch_op {
10003 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
10004 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
10005 _ => continue,
10006 };
10007 let Some(destination) = destination else {
10008 continue;
10009 };
10010 insns[index] = if taken {
10011 // The branch is always taken, so it becomes an unconditional jump.
10012 Some((Opcode::Goto, vec![destination]))
10013 } else {
10014 // The branch never runs: both instructions disappear and control falls
10015 // through to what came after.
10016 None
10017 };
10018 insns[index + 1] = None;
10019 }
10020}
10021
10022/// Remove a jump whose destination is the instruction right after it.
10023///
10024/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
10025/// its test into nothing, and the loop-end jump then points at the following
10026/// instruction. The reference drops them, so `stack_size` and the listing agree.
10027fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
10028 for index in 0..insns.len() {
10029 let Some((op, operands)) = insns[index].clone() else {
10030 continue;
10031 };
10032 if !is_goto(op) {
10033 continue;
10034 }
10035 let Some(id) = label_id(&operands) else {
10036 continue;
10037 };
10038 // The next instruction that still exists, which is what "the instruction
10039 // after this jump" means once earlier folds have punched holes.
10040 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
10041 if placed.get(id as usize).copied().flatten() == next {
10042 insns[index] = None;
10043 }
10044 }
10045}
10046
10047fn fold_conditional_jumps(
10048 insns: &mut [Option<(Opcode, Vec<Op>)>],
10049 label_at: &[Option<u32>],
10050 placed: &[Option<usize>],
10051) {
10052 for index in 0..insns.len() {
10053 let Some((op, operands)) = insns[index].clone() else {
10054 continue;
10055 };
10056 let inverted = match op {
10057 Opcode::IfFalse => Opcode::IfTrue,
10058 Opcode::IfTrue => Opcode::IfFalse,
10059 _ => continue,
10060 };
10061 // Next must be an unconditional jump that is not itself a target, and the
10062 // instruction after it must be exactly where the conditional goes.
10063 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
10064 continue;
10065 };
10066 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
10067 continue;
10068 }
10069 // The conditional must land on the instruction *after* the jump. Several
10070 // labels can share a position, so this asks where *this* label was put
10071 // rather than what label happens to sit there.
10072 let Some(taken) = label_id(&operands) else {
10073 continue;
10074 };
10075 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
10076 continue;
10077 }
10078 let Some(destination) = next_operands.first().cloned() else {
10079 continue;
10080 };
10081 insns[index] = Some((inverted, vec![destination]));
10082 insns[index + 1] = None;
10083 }
10084}
10085
10086/// Whether a jump target is placed at this instruction index.
10087fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
10088 label_at.get(index).copied().flatten().is_some()
10089}
10090
10091fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
10092 // `dup put_x(n)` -> `set_x(n)`
10093 // `dup put_x(n) drop` -> `put_x(n)`
10094 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
10095 for index in 0..insns.len() {
10096 if opcode_at(insns, index) != Some(Opcode::Dup) {
10097 continue;
10098 }
10099 if is_label_at(label_at, index + 1) {
10100 continue;
10101 }
10102 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
10103 continue;
10104 };
10105 if !is_foldable_put(put_op) {
10106 continue;
10107 }
10108 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
10109 continue;
10110 };
10111 let mut new_op = set_form_of(put_op);
10112 let mut end = index + 2;
10113 if is_label_at(label_at, end) {
10114 // The `put` has to stay as it is; only the `dup` can be folded.
10115 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
10116 insns[index + 1] = None;
10117 continue;
10118 }
10119 // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
10120 // Deleting it moves the label's target onto whatever follows, and the code that
10121 // jumps there arrives with a different stack than the fall-through path: that is
10122 // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
10123 // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
10124 // an empty stack. The store had already consumed the value it was supposed to
10125 // leave behind.
10126 if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
10127 new_op = put_op;
10128 end += 1;
10129 if opcode_at(insns, end) == Some(get_form_of(put_op))
10130 && !is_label_at(label_at, end)
10131 && insns[end]
10132 .as_ref()
10133 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
10134 {
10135 new_op = set_form_of(put_op);
10136 end += 1;
10137 }
10138 }
10139 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
10140 for entry in &mut insns[index + 1..end] {
10141 *entry = None;
10142 }
10143 }
10144}
10145
10146fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
10147 insns
10148 .get(index)
10149 .and_then(|entry| entry.as_ref())
10150 .map(|(op, _)| *op)
10151}
10152
10153/// The four `put_` families that have a `set_` twin. Deliberately not including
10154/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
10155/// these, and folding the others would produce instructions that do not exist.
10156fn is_foldable_put(op: Opcode) -> bool {
10157 matches!(
10158 op,
10159 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
10160 )
10161}
10162
10163fn set_form_of(op: Opcode) -> Opcode {
10164 match op {
10165 Opcode::PutLoc => Opcode::SetLoc,
10166 Opcode::PutLocCheck => Opcode::SetLocCheck,
10167 Opcode::PutArg => Opcode::SetArg,
10168 Opcode::PutVarRef => Opcode::SetVarRef,
10169 other => other,
10170 }
10171}
10172
10173fn get_form_of(op: Opcode) -> Opcode {
10174 match op {
10175 Opcode::PutLoc => Opcode::GetLoc,
10176 Opcode::PutLocCheck => Opcode::GetLocCheck,
10177 Opcode::PutArg => Opcode::GetArg,
10178 Opcode::PutVarRef => Opcode::GetVarRef,
10179 other => other,
10180 }
10181}
10182
10183/// Atom interning, per function.
10184///
10185/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
10186/// identifiers, so the array-index rule applies here rather than at the handful of
10187/// call sites that build property keys.
10188fn intern_atom(state: &mut FnState, name: &str) -> u32 {
10189 intern_atom_value(state, Atom::from_text(name))
10190}
10191
10192/// [`intern_atom`] for an operand that is already an [`Atom`].
10193///
10194/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
10195/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
10196/// would have looked up.
10197fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
10198 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
10199 return index as u32;
10200 }
10201 state.atoms.push(atom);
10202 state.atoms.len() as u32 - 1
10203}
10204
10205fn binary_opcode(op: BinaryOp) -> Opcode {
10206 match op {
10207 BinaryOp::Add => Opcode::Add,
10208 BinaryOp::Sub => Opcode::Sub,
10209 BinaryOp::Mul => Opcode::Mul,
10210 BinaryOp::Div => Opcode::Div,
10211 BinaryOp::Mod => Opcode::Mod,
10212 BinaryOp::Pow => Opcode::Pow,
10213 BinaryOp::BitOr => Opcode::Or,
10214 BinaryOp::BitXor => Opcode::Xor,
10215 BinaryOp::BitAnd => Opcode::And,
10216 BinaryOp::Shl => Opcode::Shl,
10217 BinaryOp::Shr => Opcode::Sar,
10218 BinaryOp::UShr => Opcode::Shr,
10219 BinaryOp::Lt => Opcode::Lt,
10220 BinaryOp::LtEq => Opcode::Lte,
10221 BinaryOp::Gt => Opcode::Gt,
10222 BinaryOp::GtEq => Opcode::Gte,
10223 BinaryOp::Eq => Opcode::Eq,
10224 BinaryOp::NotEq => Opcode::Neq,
10225 BinaryOp::StrictEq => Opcode::StrictEq,
10226 BinaryOp::StrictNotEq => Opcode::StrictNeq,
10227 BinaryOp::In => Opcode::In,
10228 BinaryOp::Instanceof => Opcode::Instanceof,
10229 }
10230}
10231
10232fn compound_opcode(op: AssignOp) -> Opcode {
10233 match op {
10234 AssignOp::Add => Opcode::Add,
10235 AssignOp::Sub => Opcode::Sub,
10236 AssignOp::Mul => Opcode::Mul,
10237 AssignOp::Div => Opcode::Div,
10238 AssignOp::Mod => Opcode::Mod,
10239 AssignOp::Pow => Opcode::Pow,
10240 AssignOp::Shl => Opcode::Shl,
10241 AssignOp::Shr => Opcode::Sar,
10242 AssignOp::UShr => Opcode::Shr,
10243 AssignOp::BitOr => Opcode::Or,
10244 AssignOp::BitXor => Opcode::Xor,
10245 AssignOp::BitAnd => Opcode::And,
10246 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
10247 }
10248}
10249
10250/// Encode the resolved instruction stream, choosing short forms where possible.
10251///
10252/// The peephole pass leaves holes in the instruction list so that label indices
10253/// stay valid. A label names an *instruction index*, and an index that was
10254/// deleted has to resolve to the next surviving instruction, which is what
10255/// [`resolve_label`] does before the byte offsets are known.
10256fn assemble(
10257 insns: &mut [Option<(Opcode, Vec<Op>)>],
10258 insn_pos: &[Option<Position>],
10259 state: &mut FnState,
10260) -> (Vec<u8>, u32, Vec<LineCol>) {
10261 // Compaction: surviving instructions in order, plus the index mapping.
10262 //
10263 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
10264 // point below where instructions are removed — otherwise a stack trace would point
10265 // at the wrong source line as soon as dead-code elimination kicked in.
10266 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
10267 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
10268 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
10269 for (original, entry) in insns.iter_mut().enumerate() {
10270 if let Some((op, operands)) = entry.take() {
10271 original_to_kept[original] = Some(kept.len());
10272 kept.push((op, operands));
10273 spans.push(insn_pos.get(original).copied().flatten());
10274 }
10275 }
10276
10277 if std::env::var_os("QJS_DEBUG").is_some() {
10278 eprintln!("--- assemble entry --- {kept:?}");
10279 }
10280 // How many labels are real, as opposed to the per-instruction ones allocated
10281 // just below. Only a real label marks a spot in the source program.
10282 let real_labels = state.labels.len();
10283
10284 // Give every surviving instruction a label of its own. Jump cleanup below
10285 // redirects jumps to arbitrary instructions, and a jump target has to be a
10286 // label; pre-allocating one per index means a redirect never has to invent
10287 // anything.
10288 let existing = state.labels.len();
10289 let base = kept.len();
10290 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
10291 for offset in 0..=kept.len() {
10292 state.labels.push(Some(0));
10293 index_label.push(Label((existing + offset) as u32));
10294 }
10295 // Point each pre-allocated label at its instruction, reusing the count from
10296 // `original_to_kept` so the mapping survives compaction.
10297 let place_index_labels = |state: &mut FnState,
10298 original_to_kept: &[Option<usize>],
10299 kept_len: usize,
10300 index_label: &[Label]| {
10301 for (original, mapped) in original_to_kept.iter().enumerate() {
10302 if let Some(kept_index) = mapped {
10303 let label = index_label[*kept_index].0 as usize;
10304 state.labels[label] = Some(original);
10305 }
10306 }
10307 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
10308 };
10309 place_index_labels(state, &original_to_kept, base, &index_label);
10310
10311 // Resolve every label to a kept index once; the placement table maps labels
10312 // to original indices, so a second hop lands in kept space.
10313 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
10314 for (id, placed) in state.labels.iter().enumerate() {
10315 let Some(original) = placed else { continue };
10316 label_kept[id] = if *original == usize::MAX {
10317 Some(base)
10318 } else {
10319 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
10320 };
10321 }
10322
10323 // Code after an unconditional transfer is unreachable, and the reference drops it
10324 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
10325 // scans forward until it finds a label something still jumps to, so a run of
10326 // dead instructions between a `throw` and the next live target disappears.
10327 //
10328 // The scan repeats because dropping a jump lowers the reference count of the
10329 // label it pointed at, which can strand what follows. Only a real label keeps an
10330 // instruction alive here; the per-instruction labels allocated above belong to
10331 // this pass, not to the program.
10332 loop {
10333 let mut references = vec![false; kept.len() + 1];
10334 for (_, operands) in &kept {
10335 if let Some(target) = target_kept_index(operands, &label_kept)
10336 && target < references.len()
10337 {
10338 references[target] = true;
10339 }
10340 }
10341 let mut doomed = vec![false; kept.len()];
10342 let mut any = false;
10343 for (index, (op, _)) in kept.iter().enumerate() {
10344 if !is_transfer(*op) {
10345 continue;
10346 }
10347 for next in index + 1..kept.len() {
10348 if references[next] {
10349 break;
10350 }
10351 doomed[next] = true;
10352 any = true;
10353 }
10354 }
10355 if !any {
10356 break;
10357 }
10358 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
10359 }
10360
10361 // A label that lands on an unconditional jump stands for wherever that jump
10362 // goes, so retarget it once and every jump to the label follows for free.
10363 // This is what makes `continue` in a `for` head reach the loop top instead of
10364 // stopping at the update's trailing jump.
10365 let folded: Vec<Option<usize>> = label_kept
10366 .iter()
10367 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
10368 .collect();
10369 label_kept = folded;
10370
10371 // Jump cleanup, in compacted index space. Two rewrites the reference also
10372 // applies while it resolves labels:
10373 // * a jump whose destination is the very next instruction does nothing;
10374 // * a jump to a jump is redirected to its final destination.
10375 // The second can expose the first, so this repeats until it settles.
10376 loop {
10377 let mut delete = vec![false; kept.len()];
10378 let mut changed = false;
10379 for index in 0..kept.len() {
10380 let (op, operands) = &kept[index];
10381 if !is_goto(*op) {
10382 continue;
10383 }
10384 let Some(immediate) = target_kept_index(operands, &label_kept) else {
10385 continue;
10386 };
10387 let target = follow_jump_chain(&kept, &label_kept, immediate);
10388 if target == index + 1 {
10389 delete[index] = true;
10390 changed = true;
10391 } else if matches!(
10392 kept.get(target).map(|(op, _)| *op),
10393 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
10394 ) {
10395 // Jumping straight to a return or throw is the same as doing it
10396 // here, so the jump becomes that instruction.
10397 kept[index] = (kept[target].0, Vec::new());
10398 changed = true;
10399 } else if target != immediate {
10400 // Redirect to the end of the chain.
10401 let label = index_label[target];
10402 kept[index].1 = vec![Op::Label(label)];
10403 changed = true;
10404 }
10405 }
10406 if !changed {
10407 break;
10408 }
10409 if !delete.iter().any(|deleted| *deleted) {
10410 break;
10411 }
10412 // Drop the deleted instructions and renumber everything.
10413 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10414 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10415 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10416 for (old, entry) in kept.into_iter().enumerate() {
10417 if delete[old] {
10418 continue;
10419 }
10420 moved[old] = Some(next.len());
10421 next.push(entry);
10422 next_spans.push(spans[old]);
10423 }
10424 for (id, slot) in label_kept.iter_mut().enumerate() {
10425 let Some(old) = *slot else { continue };
10426 *slot = match moved.get(old).copied().flatten() {
10427 Some(new) => Some(new),
10428 // The target was deleted: the jump now lands on whatever follows.
10429 None => (old..moved.len())
10430 .find_map(|i| moved[i])
10431 .or(Some(next.len())),
10432 };
10433 let _ = id;
10434 }
10435 kept = next;
10436 spans = next_spans;
10437 }
10438
10439 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
10440 // jump to the next instruction and is deleted, leaving the label at the end with
10441 // nothing pointing at it. If that also strands the last instruction, it goes
10442 // too — which is how a `try` whose body always returns ends on its `ret` rather
10443 // than an implicit `return_undef`.
10444 // Which instructions something still jumps to. Reading the surviving jumps is
10445 // what the reference's reference counts amount to: once a jump has been folded
10446 // away the label it named is unreferenced, even though the program still has a
10447 // label there.
10448 let mut references = vec![false; kept.len() + 1];
10449 let _ = real_labels;
10450 for (_, operands) in &kept {
10451 if let Some(target) = target_kept_index(operands, &label_kept)
10452 && target < references.len()
10453 {
10454 references[target] = true;
10455 }
10456 }
10457 let mut end = kept.len();
10458 while end > 0 {
10459 let last = end - 1;
10460 let reachable = references[last] || end < kept.len();
10461 if reachable {
10462 break;
10463 }
10464 let after_transfer = last
10465 .checked_sub(1)
10466 .map(|previous| {
10467 matches!(
10468 kept[previous].0,
10469 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
10470 )
10471 })
10472 .unwrap_or(false);
10473 if !after_transfer {
10474 break;
10475 }
10476 end = last;
10477 }
10478 kept.truncate(end);
10479 spans.truncate(end);
10480
10481 // Choose an opcode for each instruction and its size, so label offsets can be
10482 // computed.
10483 let chosen = choose_opcodes(&kept, &label_kept);
10484 let offsets = instruction_offsets(&chosen);
10485 let offset = *offsets.last().unwrap_or(&0);
10486
10487 let mut code = Vec::with_capacity(offset);
10488 for (position, (_, operands)) in kept.iter().enumerate() {
10489 let op = chosen[position];
10490 code.push(op as u8);
10491 let operands = retarget_labels(operands, &label_kept, kept.len());
10492 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
10493 }
10494 let stack_size = compute_stack_size(&code);
10495 // Keep only the offsets where the position actually changes: a run of
10496 // instructions on one line is one table entry, and the runtime binary searches
10497 // the table for the frame's pc.
10498 //
10499 // The table always starts at pc 0 with the *function's own* position, because the
10500 // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
10501 // last_line_num)` from `fd->source_pos`, the token the function definition starts at
10502 // (`function`, `async`, a method's property name). An instruction before the first
10503 // recorded operator therefore reports the function's own start, which is what makes a
10504 // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
10505 let mut positions: Vec<LineCol> = vec![LineCol {
10506 pc: 0,
10507 line: state.line,
10508 column: state.column,
10509 }];
10510 let mut last: Option<Position> = None;
10511 for (index, span) in spans.iter().enumerate() {
10512 let Some(pos) = *span else { continue };
10513 if last == Some(pos) {
10514 continue;
10515 }
10516 last = Some(pos);
10517 if pos.line == state.line && pos.column == state.column {
10518 // Already the seed entry above.
10519 continue;
10520 }
10521 positions.push(LineCol {
10522 pc: offsets[index] as u32,
10523 line: pos.line,
10524 column: pos.column,
10525 });
10526 }
10527 (code, stack_size, positions)
10528}
10529
10530/// Whether an instruction always transfers control away, so anything after it in the
10531/// same stream is unreachable.
10532fn is_transfer(op: Opcode) -> bool {
10533 matches!(
10534 op,
10535 Opcode::Goto
10536 | Opcode::Goto8
10537 | Opcode::Goto16
10538 | Opcode::Return
10539 | Opcode::ReturnUndef
10540 | Opcode::Throw
10541 | Opcode::ThrowError
10542 | Opcode::Ret
10543 )
10544}
10545
10546/// Remove the marked instructions and renumber the label table so it keeps pointing
10547/// at the same instructions. A label whose instruction went away moves to whatever
10548/// follows it, since a jump is never left with nowhere to land.
10549fn drop_instructions(
10550 kept: Vec<(Opcode, Vec<Op>)>,
10551 spans: Vec<Option<Position>>,
10552 label_kept: &mut [Option<usize>],
10553 doomed: &[bool],
10554) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
10555 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10556 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10557 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10558 for (old, entry) in kept.into_iter().enumerate() {
10559 if doomed.get(old).copied().unwrap_or(false) {
10560 continue;
10561 }
10562 moved[old] = Some(result.len());
10563 result.push(entry);
10564 result_spans.push(spans[old]);
10565 }
10566 for slot in label_kept.iter_mut() {
10567 let Some(old) = *slot else { continue };
10568 *slot = match moved.get(old).copied().flatten() {
10569 Some(new) => Some(new),
10570 None => (old..moved.len())
10571 .find_map(|i| moved[i])
10572 .or(Some(result.len())),
10573 };
10574 }
10575 (result, result_spans)
10576}
10577
10578fn is_goto(op: Opcode) -> bool {
10579 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
10580}
10581
10582/// The kept index a jump operand points at.
10583fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
10584 let id = label_id(operands)?;
10585 label_kept.get(id as usize).copied().flatten()
10586}
10587
10588/// Follow a chain of unconditional jumps to its first real destination.
10589fn follow_jump_chain(
10590 kept: &[(Opcode, Vec<Op>)],
10591 label_kept: &[Option<usize>],
10592 start: usize,
10593) -> usize {
10594 let mut current = start;
10595 // `for(;;)` jumps to itself, so the walk has to be bounded.
10596 for _ in 0..kept.len() {
10597 let Some((op, operands)) = kept.get(current) else {
10598 return current;
10599 };
10600 if !is_goto(*op) {
10601 return current;
10602 }
10603 let Some(next) = target_kept_index(operands, label_kept) else {
10604 return current;
10605 };
10606 if next == current {
10607 return current;
10608 }
10609 current = next;
10610 }
10611 current
10612}
10613
10614/// Rewrite label operands from label ids to kept instruction indices.
10615fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
10616 operands
10617 .iter()
10618 .map(|operand| match operand {
10619 Op::Label(label) => {
10620 let target = label_kept
10621 .get(label.0 as usize)
10622 .copied()
10623 .flatten()
10624 .unwrap_or(kept_len);
10625 Op::Label(Label(target as u32))
10626 }
10627 other => other.clone(),
10628 })
10629 .collect()
10630}
10631
10632/// Encode the resolved instruction stream, choosing short forms where possible.
10633///
10634/// Compute the maximum value-stack depth by exploring the control-flow graph.
10635///
10636/// This is a breadth-first walk from the first instruction, tracking the stack
10637/// depth on entry to each instruction. Every instruction has at most two
10638/// successors (fall through, and a jump target), so a worklist over byte offsets
10639/// is enough. The reference does the same thing in `compute_stack_size`, which is
10640/// why the resulting numbers match exactly.
10641///
10642/// Instructions that pop a variable number of values (`call`, `array_from`, …)
10643/// encode that count in their operand, which is added to the static `n_pop`.
10644fn compute_stack_size(code: &[u8]) -> u32 {
10645 let mut depth_at = vec![u16::MAX; code.len()];
10646 // Each entry carries the enclosing `catch` levels, innermost last, because
10647 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
10648 // offset and forgets that level.
10649 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
10650 let mut max_depth = 0u32;
10651
10652 while let Some((pc, depth, catch_levels)) = worklist.pop() {
10653 if pc >= code.len() {
10654 continue;
10655 }
10656 if depth_at[pc] != u16::MAX {
10657 continue;
10658 }
10659 force_depth(&mut depth_at, pc, depth);
10660
10661 let Some(op) = Opcode::from_u8(code[pc]) else {
10662 break;
10663 };
10664 let info = op.info();
10665 let next = pc + info.size as usize;
10666 if next > code.len() {
10667 break;
10668 }
10669 let mut n_pop = info.n_pop as u32;
10670 let mut n_push = info.n_push as u32;
10671 // Variable-length forms carry their count in the operand.
10672 match info.format {
10673 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
10674 n_pop += read_u16(code, pc + 1) as u32;
10675 }
10676 crate::opcode::OpFormat::Npopx => {
10677 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
10678 }
10679 _ => {}
10680 }
10681 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
10682 // are the `set_` variant; the table already records that, so nothing to
10683 // adjust here.
10684 let _ = &mut n_push;
10685
10686 // The depth before this instruction's own push, which is what a `catch`
10687 // records as its level.
10688 let depth_before = depth;
10689 let mut depth = depth.saturating_sub(n_pop) + n_push;
10690 let mut catch_levels = catch_levels;
10691 if op == Opcode::NipCatch {
10692 // Discard everything above the innermost catch offset, keeping the value
10693 // on top: the frame the code after this sees is the same shape it would
10694 // have had if the `try` were not there.
10695 if let Some(base) = catch_levels.pop() {
10696 depth = base + 1;
10697 }
10698 }
10699 max_depth = max_depth.max(depth);
10700
10701 // Successors.
10702 let target = jump_target_of(code, pc, op);
10703 match op {
10704 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10705 if let Some(target) = target {
10706 worklist.push((target, depth, catch_levels));
10707 }
10708 }
10709 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
10710 if let Some(target) = target {
10711 worklist.push((target, depth, catch_levels.clone()));
10712 }
10713 worklist.push((next, depth, catch_levels));
10714 }
10715 // A `catch` records an exception edge to the handler. The handler is
10716 // entered with the thrown value on top of the stack, in the slot the
10717 // catch offset occupies on the normal path — which is why the handler's
10718 // first instruction can `put_loc` the exception away, and why the depth
10719 // is the same on both paths.
10720 Opcode::Catch => {
10721 if let Some(target) = target {
10722 // The handler is protected by the *enclosing* catch, not by this
10723 // one: an error raised inside it is what the handler's own
10724 // `catch` catches.
10725 worklist.push((target, depth, catch_levels.clone()));
10726 }
10727 catch_levels.push(depth_before);
10728 worklist.push((next, depth, catch_levels));
10729 }
10730 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
10731 // rewind past it too. Its level sits one slot higher than a `catch`'s:
10732 // the iterator and next-method slots occupy the offset's place.
10733 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
10734 if let Some(target) = target {
10735 worklist.push((target, depth, catch_levels.clone()));
10736 }
10737 catch_levels.push(depth_before + 1);
10738 worklist.push((next, depth, catch_levels));
10739 }
10740 // `gosub` calls a subroutine with the return address on top. The opcode
10741 // table records no push for it — `ret` is what pops the slot — so the
10742 // extra one is added here, where the depth of the subroutine's first
10743 // instruction is being computed.
10744 Opcode::Gosub => {
10745 if let Some(target) = target {
10746 worklist.push((target, depth + 1, catch_levels.clone()));
10747 }
10748 worklist.push((next, depth, catch_levels));
10749 }
10750 // `ret` goes back to a `gosub`; nothing here follows it.
10751 Opcode::Ret
10752 | Opcode::Return
10753 | Opcode::ReturnUndef
10754 | Opcode::Throw
10755 | Opcode::ThrowError => {}
10756 _ => worklist.push((next, depth, catch_levels)),
10757 }
10758 }
10759 max_depth
10760}
10761
10762/// Record the stack depth on entry to `pc`, keeping the deeper value if the
10763/// instruction is reachable more than once.
10764fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
10765 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
10766 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
10767 depth_at[pc] = clamped;
10768 }
10769}
10770
10771fn read_u16(code: &[u8], at: usize) -> u16 {
10772 let mut value = 0u16;
10773 for i in 0..2 {
10774 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
10775 }
10776 value
10777}
10778
10779/// The absolute target of a jump instruction, if it has one.
10780fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
10781 let info = op.info();
10782 let position = pc + 1;
10783 match info.format {
10784 crate::opcode::OpFormat::Label8 => {
10785 let offset = *code.get(position)? as i8 as i64;
10786 Some((position as i64 + offset) as usize)
10787 }
10788 crate::opcode::OpFormat::Label16 => {
10789 let offset = read_u16(code, position) as i16 as i64;
10790 Some((position as i64 + offset) as usize)
10791 }
10792 crate::opcode::OpFormat::Label => {
10793 let mut offset = 0i32;
10794 for i in 0..4 {
10795 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
10796 }
10797 Some((position as i64 + offset as i64) as usize)
10798 }
10799 _ => None,
10800 }
10801}
10802
10803fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
10804 use Opcode::*;
10805 match (op, operands.first()) {
10806 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
10807 op.short_form(*value as u32).unwrap_or(op)
10808 }
10809 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
10810 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
10811 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
10812 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
10813 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
10814 // A declared global is reached through its reference cell, so it shares
10815 // the `var_ref` encodings, short forms included.
10816 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
10817 op.short_form(*index).unwrap_or(op)
10818 }
10819 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
10820 op.short_form(*count as u32).unwrap_or(op)
10821 }
10822 _ => op,
10823 }
10824}
10825
10826/// The byte offset each instruction will start at, plus the total code size.
10827fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
10828 let mut offsets = Vec::with_capacity(chosen.len() + 1);
10829 let mut offset = 0usize;
10830 for op in chosen {
10831 offsets.push(offset);
10832 offset += op.size() as usize;
10833 }
10834 offsets.push(offset);
10835 offsets
10836}
10837
10838/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
10839/// the offset actually fits.
10840///
10841/// The choice is circular: an instruction's size decides the offsets of everything after
10842/// it, and the offsets decide whether a jump may be short. So this starts with every jump
10843/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
10844/// Shrinking only ever *shortens* distances, so the loop converges.
10845///
10846/// Doing it in one pass instead — which is what this used to do — silently truncated any
10847/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
10848/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
10849/// with four closures in its body simply stopped, with no error and no output past the
10850/// first iteration.
10851fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
10852 let mut chosen: Vec<Opcode> = kept
10853 .iter()
10854 .map(|(op, operands)| choose_short_form(*op, operands))
10855 .collect();
10856 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
10857 let candidates = |op: Opcode| match op {
10858 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
10859 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
10860 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
10861 _ => None,
10862 };
10863 loop {
10864 let offsets = instruction_offsets(&chosen);
10865 let mut changed = false;
10866 for index in 0..kept.len() {
10867 let (op, operands) = &kept[index];
10868 let Some((short, medium, has_medium)) = candidates(*op) else {
10869 continue;
10870 };
10871 if chosen[index] == short {
10872 continue;
10873 }
10874 let Some(target) = target_kept_index(operands, label_kept) else {
10875 continue;
10876 };
10877 let Some(&target_offset) = offsets.get(target) else {
10878 continue;
10879 };
10880 // A jump is relative to the byte after its opcode, which is the convention
10881 // `jump_target_of` decodes with.
10882 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
10883 if (-128..=127).contains(&relative) {
10884 chosen[index] = short;
10885 changed = true;
10886 } else if has_medium
10887 && chosen[index] == Opcode::Goto
10888 && (-32_768..=32_767).contains(&relative)
10889 {
10890 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
10891 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
10892 // the reference encodes them.
10893 chosen[index] = medium;
10894 changed = true;
10895 }
10896 }
10897 if !changed {
10898 return chosen;
10899 }
10900 }
10901}
10902
10903fn encode_operands(
10904 code: &mut Vec<u8>,
10905 op: Opcode,
10906 operands: &[Op],
10907 position: usize,
10908 offsets: &[usize],
10909) {
10910 use crate::opcode::OpFormat::*;
10911 let info = op.info();
10912 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
10913 let index = match slot {
10914 Slot::Arg(i)
10915 | Slot::Loc(i)
10916 | Slot::VarRef(i)
10917 | Slot::Global(i)
10918 | Slot::GlobalDecl(i) => i,
10919 };
10920 code.extend_from_slice(&(index as u16).to_be_bytes());
10921 };
10922 match info.format {
10923 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
10924 U8 | Const8 => {
10925 if let Some(value) = operands.first().and_then(operand_uint) {
10926 code.push(value as u8);
10927 }
10928 }
10929 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
10930 // like their wide counterparts, only one byte wide.
10931 Loc8 => {
10932 if let Some(Op::Slot(slot)) = operands.first() {
10933 let index = match slot {
10934 Slot::Arg(i)
10935 | Slot::Loc(i)
10936 | Slot::VarRef(i)
10937 | Slot::Global(i)
10938 | Slot::GlobalDecl(i) => *i,
10939 };
10940 code.push(index as u8);
10941 }
10942 }
10943 I8 => {
10944 if let Some(value) = operands.first().and_then(operand_int) {
10945 code.push(value as i8 as u8);
10946 }
10947 }
10948 U16 | Npop => {
10949 if let Some(value) = operands.first().and_then(operand_int) {
10950 code.extend_from_slice(&(value as u16).to_be_bytes());
10951 }
10952 }
10953 I16 => {
10954 if let Some(value) = operands.first().and_then(operand_int) {
10955 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
10956 }
10957 }
10958 I32 => {
10959 if let Some(value) = operands.first().and_then(operand_int) {
10960 code.extend_from_slice(&value.to_be_bytes());
10961 }
10962 }
10963 U32 | Const => {
10964 if let Some(value) = operands.first().and_then(operand_uint) {
10965 code.extend_from_slice(&value.to_be_bytes());
10966 }
10967 }
10968 Loc | Arg | VarRef => {
10969 if let Some(Op::Slot(slot)) = operands.first() {
10970 write_slot(code, *slot);
10971 }
10972 }
10973 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
10974 if let Some(Op::AtomId(index)) = operands.first() {
10975 code.extend_from_slice(&index.to_be_bytes());
10976 }
10977 // The trailing immediate means different things per format, and the
10978 // atom forms that carry a *label* have to resolve it like any other
10979 // jump, so they cannot share the `U8`/`U16` arms above.
10980 match info.format {
10981 AtomU8 | AtomLabelU8 => {
10982 if let Some(value) = operands.get(1).and_then(operand_uint) {
10983 code.push(value as u8);
10984 }
10985 }
10986 AtomU16 | AtomLabelU16 => {
10987 if let Some(value) = operands.get(1).and_then(operand_uint) {
10988 code.extend_from_slice(&(value as u16).to_be_bytes());
10989 }
10990 }
10991 _ => {}
10992 }
10993 }
10994 NpopU16 => {
10995 for operand in operands.iter().take(2) {
10996 if let Some(value) = operand_uint(operand) {
10997 code.extend_from_slice(&(value as u16).to_be_bytes());
10998 }
10999 }
11000 }
11001 Label | Label8 | Label16 | LabelU16 => {
11002 if let Some(Op::Label(label)) = operands.first() {
11003 // Labels were already remapped to kept-instruction indices.
11004 let Some(&target) = offsets.get(label.0 as usize) else {
11005 debug_assert!(false, "label {} is past the end", label.0);
11006 return;
11007 };
11008 let relative = target as i64 - (position as i64 + 1);
11009 match info.format {
11010 Label8 => code.push(relative as i8 as u8),
11011 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
11012 // `label_u16` stores the target followed by an unrelated u16.
11013 LabelU16 => {
11014 code.extend_from_slice(&(relative as i32).to_be_bytes());
11015 if let Some(value) = operands.get(1).and_then(operand_uint) {
11016 code.extend_from_slice(&(value as u16).to_be_bytes());
11017 }
11018 }
11019 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
11020 }
11021 }
11022 }
11023 }
11024}
11025
11026fn operand_int(op: &Op) -> Option<i32> {
11027 match op {
11028 Op::Int(value) => Some(*value),
11029 _ => None,
11030 }
11031}
11032
11033fn operand_uint(op: &Op) -> Option<u32> {
11034 match op {
11035 Op::Const(value) | Op::AtomId(value) => Some(*value),
11036 Op::Int(value) => Some(*value as u32),
11037 _ => None,
11038 }
11039}
11040
11041/// Disassemble a compiled function.
11042pub fn disassemble(function: &CompiledFunction) -> String {
11043 disasm::disassemble_program(function)
11044}
11045
11046/// How many of an object pattern's keys are computed.
11047///
11048/// Only the count matters: a rest element needs a run-time key log exactly when at least one
11049/// key is not a literal, and the log is sized by walking the pattern anyway.
11050fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
11051 properties
11052 .iter()
11053 .flatten()
11054 .filter(|element| {
11055 matches!(
11056 element,
11057 PatternElement::Property {
11058 key: PropName::Computed(_),
11059 ..
11060 }
11061 )
11062 })
11063 .count()
11064}