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 this frame is an `eval` body; see [`Compiler::eval_body`].
542 is_eval_body: bool,
543 /// Whether the function is an arrow, which never gets its own `arguments`.
544 is_arrow: bool,
545 /// The name a *named function expression* binds inside its own body.
546 /// How many parameters count towards `.length`.
547 defined_args: u32,
548 /// Parameters that are not a plain name, with the argument slot each came from.
549 param_prologue: Vec<(usize, Pattern)>,
550 /// What kind of class constructor this function is, if any.
551 ctor_kind: CtorKind,
552 /// Whether the class has instance fields, so the constructor has to run their
553 /// initialiser before it returns.
554 /// What the nested function about to be compiled should be told about its class.
555 class_ctor_pending: Option<CtorKind>,
556 /// Whether this function needs the hidden `this` local, because an arrow inside it
557 /// refers to `this`.
558 ///
559 /// An arrow has no `this` of its own, so the reference materialises the enclosing
560 /// function's receiver into a local and lets the arrow capture it as an ordinary
561 /// closure variable. Declaring the local is not enough on its own: the store that
562 /// fills it has to be prepended to the body, which is what this flag arranges.
563 needs_this_local: bool,
564 /// The same, for `arguments`.
565 needs_arguments_local: bool,
566 /// The same, for `new.target`.
567 needs_new_target_local: bool,
568 /// Whether the body already opens by filling a `this` local, which
569 /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
570 has_this_prologue: bool,
571 /// The same, for `<home_object>`: the object `super` resolves against.
572 ///
573 /// An arrow and a static block have no home object of their own — only the method or
574 /// initialiser they were written in does — so `super.x` inside one is a read of the
575 /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
576 /// by `special_object 4`, the same way `this` is.
577 needs_home_object_local: bool,
578 /// Whether this function has an `arguments` binding of its own.
579 ///
580 /// False for a class field initialiser and a static block: §15.7 puts them outside any
581 /// function, so `arguments` does not exist there and `eval('arguments')` inside one is a
582 /// `SyntaxError` rather than the caller's arguments object. The parser already enforces
583 /// that for written code; this carries the same fact to the `eval` call site, which has
584 /// to compile the eval'd source under the caller's restriction.
585 no_arguments_binding: bool,
586 /// The same, for `this.active_func`: the function `super()` constructs from.
587 ///
588 /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
589 /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
590 /// as a local of the enclosing function; an arrow that escaped the constructor
591 /// (`iter.return = () => super()`) then finds it in its closure even with the
592 /// constructor nowhere on the call stack.
593 needs_active_func_local: bool,
594 /// Hidden locals of the `with` blocks currently open, innermost last.
595 with_names: Vec<String>,
596 /// How many of [`FnState::with_names`] were already open when this function was
597 /// created, i.e. belong to an *enclosing* function.
598 ///
599 /// The distinction decides shadowing, and it is positional rather than lexical. A
600 /// `with` opened **inside** this function's body sits nearer than the function's own
601 /// environment, so it shadows even a `var` of this function:
602 /// `function f(){ with(o){ var v = 1 } }` writes `o.v`. A `with` opened **outside**
603 /// does not: `with(o){ function f(){ var v = 1 } }` writes `f`'s local `v`, because
604 /// `f`'s environment is the inner one. Treating both alike broke one family or the
605 /// other — `S12.10_A1.2` and `S12.10_A1.7` are these two cases.
606 inherited_with_names: usize,
607 /// Set while a with-guard is being emitted, so the guard's own accesses are not
608 /// wrapped in another guard.
609 emitting_with_guard: bool,
610 self_name: Option<String>,
611 /// Where the function body starts, in source order; see [`Function::body_start`].
612 body_start: (u32, u32),
613 /// Whether the body contains a *direct* `eval(...)` call.
614 ///
615 /// A direct eval sees every binding of the function that called it, including ones
616 /// no other code mentions. It also hands those bindings to any closure it creates,
617 /// which can outlive the function. Both need the bindings to live in cells, so this
618 /// flag makes the function treat all of them as captured.
619 has_direct_eval: bool,
620 /// Whether this function's body contains a direct `eval` **anywhere**, known before any
621 /// of it is compiled.
622 ///
623 /// [`Self::has_direct_eval`] is learned as the eval call is compiled, which is too late
624 /// for an lvalue that must be resolved *before* the right-hand side that contains the
625 /// eval. This one is seeded from the AST, so `x *= (eval("var x = 2"), 4)` knows to pin
626 /// the reference before it emits the read.
627 eval_can_declare: bool,
628 /// Whether the parameter list contains a default expression, which is what gives
629 /// the function a second variable environment (see [`PARAM_SCOPE`]).
630 has_parameter_expressions: bool,
631 /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
632 simple_parameter_list: bool,
633 /// Whether the instructions being emitted belong to the parameter list.
634 ///
635 /// References made here must not see the body's `var`s: the body has not run yet,
636 /// and the reference's own model keeps the two scopes apart.
637 in_params: bool,
638 /// Whether an arrow created in this function's parameter list needs the parameter
639 /// scope's `arguments` binding.
640 needs_param_arguments: bool,
641 /// Whether this function was *created* inside a parameter list.
642 ///
643 /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
644 /// arrow too. The name reference is the arrow's, but the scope it must not see
645 /// belongs to the function the arrow was born in.
646 created_in_params: bool,
647 /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
648 ///
649 /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
650 /// final while the body is still being compiled: a named function expression declares
651 /// its own name binding *after* the body, and that binding is exactly what
652 /// `eval("myfunc = 1")` has to find.
653 eval_sites: Vec<EvalSite>,
654 /// Direct `eval` call sites seen so far: where, and the block that was current.
655 pending_eval_sites: Vec<(Span, u64, bool, Vec<EvalPrivate>, bool)>,
656 /// Whether this body contains `await`.
657 ///
658 /// For a *module* this decides whether its body is an async function: top-level
659 /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
660 /// to survive to the compiled function rather than being a local of the compiler.
661 has_await: bool,
662 /// The module tables, when this body is a module.
663 ///
664 /// Only the top-level state ever has one: `export` and `import` are top-level
665 /// statements, so nothing nested can add to these tables.
666 module: Option<ModuleMeta>,
667 /// Whether the self-name prologue (`special_object 2` then the store) has been
668 /// emitted for this function.
669 ///
670 /// A *nested* function's lookup declares the binding early (see
671 /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
672 /// prologue is still needed — the binding existing is not the same as it being
673 /// initialised.
674 self_name_initialized: bool,
675 /// Whether the code emitted so far leaves the program's result on the stack.
676 /// The reference tracks this for the hidden `<ret>` local of an eval script.
677 leaves_value: bool,
678 /// Statement nesting depth, used to tell top-level statements apart.
679 stmt_depth: u32,
680 /// Function declarations waiting to be instantiated at scope entry, as
681 /// (target slot, constant pool index). The reference emits these from
682 /// `instantiate_hoisted_definitions` rather than at the statement, because a
683 /// declaration is visible before it is reached.
684 hoisted: Vec<(u64, HoistTarget, u32)>,
685 /// Function declarations whose bodies are compiled only once the enclosing scope
686 /// has finished hoisting, as (owning block, declaration).
687 ///
688 /// Compiling a body at the declaration makes the result depend on source order: in
689 /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
690 /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
691 /// names first and the bodies second is what removes that dependence.
692 deferred_funcs: Vec<(u64, Box<ast::Function>)>,
693 /// The source position of the node being compiled. Every instruction emitted
694 /// takes it, which is how the position table that feeds stack traces is built.
695 cur_pos: Option<Position>,
696 /// One position per entry in `insns`, index-aligned.
697 insn_pos: Vec<Option<Position>>,
698}
699
700/// Where a hoisted function declaration is stored.
701#[derive(Debug, Clone)]
702enum HoistTarget {
703 Arg(u32),
704 Loc(u32),
705 /// A global, which the resolver looks up by name.
706 Global(String),
707}
708
709impl FnState {
710 /// Whether this function suspends: a generator or an async function.
711 ///
712 /// A suspending function's `return` is a `return_async` and its body starts with an
713 /// `initial_yield`, so almost every statement that touches control flow asks this.
714 fn is_suspending(&self) -> bool {
715 self.kind.is_generator() || self.kind.is_async()
716 }
717
718 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
719 FnState {
720 span: None,
721 name: name.into(),
722 kind,
723 strict: false,
724 args: Vec::new(),
725 vars: Vec::new(),
726 closure_vars: Vec::new(),
727 cpool: Vec::new(),
728 atoms: Vec::new(),
729 blocks: Vec::new(),
730 current_block: 0,
731 created_in_block: NO_PARENT,
732 var_block: Vec::new(),
733 no_value: false,
734 label_since_insn: false,
735 discard_value: false,
736 body_block: 0,
737 block_heads: Vec::new(),
738 jump_targets: Vec::new(),
739 insns: Vec::new(),
740 labels: Vec::new(),
741 var_ref_count: 0,
742 line: 1,
743 column: 1,
744 is_script: false,
745 is_eval_body: false,
746 is_module: false,
747 is_arrow: false,
748 defined_args: 0,
749 param_prologue: Vec::new(),
750 ctor_kind: CtorKind::None,
751 class_ctor_pending: None,
752 needs_this_local: false,
753 needs_arguments_local: false,
754 needs_new_target_local: false,
755 has_this_prologue: false,
756 needs_home_object_local: false,
757 no_arguments_binding: false,
758 needs_active_func_local: false,
759 with_names: Vec::new(),
760 inherited_with_names: 0,
761 emitting_with_guard: false,
762 self_name: None,
763 has_direct_eval: false,
764 eval_can_declare: false,
765 body_start: (0, 0),
766 has_parameter_expressions: false,
767 simple_parameter_list: true,
768 in_params: false,
769 needs_param_arguments: false,
770 created_in_params: false,
771 eval_sites: Vec::new(),
772 pending_eval_sites: Vec::new(),
773 has_await: false,
774 module: None,
775 self_name_initialized: false,
776 leaves_value: false,
777 stmt_depth: 0,
778 hoisted: Vec::new(),
779 deferred_funcs: Vec::new(),
780 cur_pos: None,
781 insn_pos: Vec::new(),
782 }
783 }
784
785 /// The scope a declaration lands in: a script's top-level declarations are
786 /// globals, everything else gets a slot.
787 /// Whether a binding declared *now* becomes a property of the global object.
788 ///
789 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
790 /// The `var` case is decided by the keyword rather than by the cursor position:
791 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
792 /// binding as a `var i` in the body, even though the head has its own block.
793 fn declares_globally(&self, def: &VarDef) -> bool {
794 // A module's top-level declarations are *module*-scoped: they live in the module
795 // record, never on the global object. Two modules can both declare `var x`
796 // without seeing each other, which is the whole point.
797 if self.is_module {
798 return false;
799 }
800 // An `eval` body's lexical declarations belong to the environment §19.2.1.3 creates
801 // for that one evaluation, so they stay locals of the eval's own frame. Its `var`s
802 // do declare globally here — the runtime moves them into the caller's variable
803 // environment — because the compiler cannot tell whether the caller has a function.
804 if self.is_eval_body && def.is_lexical {
805 return false;
806 }
807 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
808 }
809}
810
811/// The compiler's entry point.
812pub struct Compiler {
813 /// The text being compiled, kept so each function can record its own slice for
814 /// `Function.prototype.toString`.
815 source: Option<String>,
816 module: bool,
817 /// Whether the program is an **`eval` body** rather than a script.
818 ///
819 /// §19.2.1.3 declares an eval's `let`/`const`/`class` in a fresh declarative environment
820 /// created for that one evaluation, so they must not reach the realm's global lexical
821 /// table: `eval("let x = 3")` leaves `x` unbound afterwards, and judging by
822 /// `typeof xNonStrict` is exactly what `eval-code/direct/lex-env-distinct-let` does.
823 /// The `var`s are a separate matter — those belong to the caller's variable environment,
824 /// which the *runtime* resolves.
825 eval_body: bool,
826 /// Whether the program itself is the body of an `async` function.
827 ///
828 /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
829 /// completion value is wrapped so a returned promise is not adopted.
830 async_body: bool,
831 /// Enclosing functions, outermost first. The last entry is the current one.
832 stack: Vec<FnState>,
833 /// The private names visible at this point, innermost class body last.
834 ///
835 /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
836 /// to the class body: a method, an arrow inside it and a class nested inside that arrow
837 /// all resolve against the same entries, and the parser accepts exactly that set
838 /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
839 /// class's names the moment a method started.
840 private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
841 /// Whether the expression [`Compiler::expr`] is about to compile is the one its
842 /// statement asked to discard.
843 ///
844 /// `FnState::discard_value` says "the statement's value is thrown away", which is only
845 /// ever true of the statement's own expression — an assignment nested inside it, as in
846 /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
847 /// keeping the answer here is what tells the two apart; without it the nested store
848 /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
849 /// function threw `undefined is not a function`.
850 discard_root: bool,
851}
852
853/// How a use site of a private name compiles.
854///
855/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
856/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
857/// of a setter-only accessor pair.
858#[derive(Clone, Copy, PartialEq, Eq)]
859enum PrivateKind {
860 /// `#x = 1`: an own property keyed by the symbol in the binding.
861 Field,
862 /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
863 Method,
864 /// `get #a() {}`: the binding holds the getter, and a read calls it.
865 Getter,
866 /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
867 /// the same `TypeError` as reading an uninitialised `const`.
868 Setter,
869}
870
871/// What the compiler knows about one `#name` where it is used.
872#[derive(Clone)]
873struct PrivateUse {
874 kind: PrivateKind,
875 /// `#a<set>` when the class defines a setter for this name.
876 ///
877 /// A second binding, not a second field of the first: the reference stores the setter
878 /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
879 setter: Option<String>,
880}
881
882/// The class-scope bindings one class body needs, in declaration order.
883#[derive(Default)]
884struct ClassPlan {
885 /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
886 /// at class entry, in member order.
887 bindings: Vec<String>,
888 /// The private names, for the use sites inside the body.
889 uses: std::collections::HashMap<String, PrivateUse>,
890 /// Computed field keys, by element index, so the emission pass does not have to redo the
891 /// per-half counter that names them.
892 computed: std::collections::HashMap<usize, String>,
893 /// Whether the instance initialiser has to add the brand to `this`.
894 instance_brand: bool,
895 /// Whether the constructor itself has to carry the brand.
896 static_brand: bool,
897}
898
899impl ClassPlan {
900 /// Walk a class body once and decide every class-scope binding it needs.
901 ///
902 /// Order is the reference's: a member's binding is created when the member is parsed, so
903 /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
904 /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
905 /// the disassembly stops matching even when every instruction is right.
906 fn build(class: &Class) -> ClassPlan {
907 let mut plan = ClassPlan::default();
908 let mut instance_keys = 0usize;
909 let mut static_keys = 0usize;
910 for (index, element) in class.elements.iter().enumerate() {
911 match element {
912 ClassElement::Method {
913 key: PropName::Private(ident),
914 kind,
915 is_static,
916 ..
917 } => {
918 let name = format!("#{}", ident.name);
919 let first = !plan.uses.contains_key(&name);
920 if first {
921 plan.bindings.push(name.clone());
922 plan.uses.insert(
923 name.clone(),
924 PrivateUse {
925 kind: match kind {
926 MethodKind::Get => PrivateKind::Getter,
927 MethodKind::Set => PrivateKind::Setter,
928 _ => PrivateKind::Method,
929 },
930 setter: None,
931 },
932 );
933 }
934 match kind {
935 MethodKind::Set => {
936 let binding = format!("{name}<set>");
937 plan.bindings.push(binding.clone());
938 if let Some(use_) = plan.uses.get_mut(&name) {
939 use_.setter = Some(binding);
940 }
941 }
942 // A getter is what makes the name readable, so a pair that started
943 // as a setter becomes readable once the getter arrives.
944 MethodKind::Get => {
945 if let Some(use_) = plan.uses.get_mut(&name) {
946 use_.kind = PrivateKind::Getter;
947 }
948 }
949 _ => {}
950 }
951 if *is_static {
952 plan.static_brand = true;
953 } else {
954 plan.instance_brand = true;
955 }
956 }
957 ClassElement::Method {
958 key: PropName::Computed(_),
959 ..
960 } => {}
961 ClassElement::Method { .. } => {}
962 ClassElement::Field {
963 key: PropName::Private(ident),
964 ..
965 } => {
966 let name = format!("#{}", ident.name);
967 if !plan.uses.contains_key(&name) {
968 plan.bindings.push(name.clone());
969 plan.uses.insert(
970 name,
971 PrivateUse {
972 kind: PrivateKind::Field,
973 setter: None,
974 },
975 );
976 }
977 }
978 ClassElement::Field {
979 key: PropName::Computed(_),
980 is_static,
981 ..
982 } => {
983 let index_in_half = if *is_static {
984 static_keys += 1;
985 static_keys - 1
986 } else {
987 instance_keys += 1;
988 instance_keys - 1
989 };
990 let binding = computed_field_binding(index_in_half, *is_static);
991 plan.bindings.push(binding.clone());
992 plan.computed.insert(index, binding);
993 }
994 ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
995 }
996 }
997 plan
998 }
999
1000 /// How a private name used inside the body compiles, or `None` if no enclosing class
1001 /// declares it.
1002 fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
1003 compiler
1004 .private_scopes
1005 .iter()
1006 .rev()
1007 .find_map(|scope| scope.get(name))
1008 }
1009}
1010
1011impl Compiler {
1012 /// The exact source text of a function, for `Function.prototype.toString`.
1013 ///
1014 /// §20.2.3.5 requires the *original* text: a function must stringify back to what
1015 /// was written, comments and odd spacing included. Slicing the recorded span out of
1016 /// the whole source is the only way to get that — rebuilding it from the AST would
1017 /// normalise the text, and answering `[native code]` for a script function (which is
1018 /// what this engine used to do) makes the result useless for feature detection and
1019 /// for libraries that read their own source.
1020 ///
1021 /// Top-level bodies have no single expression span, so their `source` stays `None`
1022 /// and `toString` falls back to the calling convention the spec allows.
1023 fn function_source(
1024 &self,
1025 span: Option<(usize, usize)>,
1026 line: u32,
1027 column: u32,
1028 ) -> Option<String> {
1029 let source = self.source.as_ref()?;
1030 let span = span?;
1031 let bytes = source.as_bytes();
1032 let start = span.0;
1033 let end = span.1;
1034 if start >= bytes.len() || end > bytes.len() || start >= end {
1035 let _ = (line, column);
1036 return None;
1037 }
1038 Some(source.get(start..end)?.to_string())
1039 }
1040}
1041
1042/// Compile a script.
1043pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1044 Compiler::new(false).compile(program)
1045}
1046
1047/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
1048/// the original source.
1049///
1050/// The separate entry point rather than a parameter on [`compile_script`] because the
1051/// tests and the disassembler compile from an AST they built themselves and have no
1052/// source to give; they keep the `None` behaviour they already relied on.
1053pub fn compile_script_with_source(
1054 program: &Program,
1055 source: &str,
1056) -> Result<CompiledFunction, SyntaxError> {
1057 let mut compiler = Compiler::new(false);
1058 compiler.source = Some(source.to_string());
1059 compiler.compile(program)
1060}
1061
1062/// [`compile_script_with_source`] for a module.
1063pub fn compile_module_with_source(
1064 program: &Program,
1065 source: &str,
1066) -> Result<CompiledFunction, SyntaxError> {
1067 let mut compiler = Compiler::new(true);
1068 compiler.source = Some(source.to_string());
1069 compiler.compile(program)
1070}
1071
1072/// Compile a script whose top level is the body of an `async` function.
1073/// The body is an ordinary script in every other way — it still reports a completion value
1074/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1075/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1076/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1077/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1078/// documents.
1079pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1080 Compiler::for_suspensible_script().compile(program)
1081}
1082
1083/// Compile a module.
1084pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1085 Compiler::new(true).compile(program)
1086}
1087
1088/// Compile a direct `eval` body that inherits private names from its caller.
1089///
1090/// `class C { #m = 44; f() { return eval("this.#m") } }` is legal — private names are
1091/// lexically scoped and the eval runs inside the caller's scope — but the names live in the
1092/// *call site's* compilation unit, so they have to be handed over. Seeding them as the
1093/// outermost private scope is what lets the eval resolve `#m` to the caller's binding: the
1094/// read compiles as an ordinary name lookup of `#m`, which at run time finds the caller's
1095/// slot through the same `eval`-scope machinery every other inherited name uses.
1096///
1097/// `suspensible` selects the `{async: true}` form (`std.evalScript(s, {async: true})`), whose
1098/// body may `await`.
1099pub fn compile_eval_with_private(
1100 program: &Program,
1101 private: &[EvalPrivate],
1102 suspensible: bool,
1103 eval_body: bool,
1104) -> Result<CompiledFunction, SyntaxError> {
1105 let mut compiler = if suspensible {
1106 let mut compiler = Compiler::new(false);
1107 compiler.async_body = true;
1108 compiler
1109 } else {
1110 Compiler::new(false)
1111 };
1112 // `evalScript` reaches this same function but evaluates a *global script*, whose
1113 // top-level `let` is a global lexical binding; only a real `eval` gets the
1114 // per-evaluation environment §19.2.1.3 creates.
1115 compiler.eval_body = eval_body;
1116 if !private.is_empty() {
1117 let scope: std::collections::HashMap<String, PrivateUse> = private
1118 .iter()
1119 .map(|entry| {
1120 (
1121 entry.name.clone(),
1122 PrivateUse {
1123 kind: match entry.kind {
1124 EvalPrivateKind::Field => PrivateKind::Field,
1125 EvalPrivateKind::Method => PrivateKind::Method,
1126 EvalPrivateKind::Getter => PrivateKind::Getter,
1127 EvalPrivateKind::Setter => PrivateKind::Setter,
1128 },
1129 setter: entry.setter.clone(),
1130 },
1131 )
1132 })
1133 .collect();
1134 compiler.private_scopes.push(scope);
1135 }
1136 compiler.compile(program)
1137}
1138
1139impl Compiler {
1140 /// Create a compiler.
1141 pub fn new(module: bool) -> Compiler {
1142 Compiler {
1143 source: None,
1144 module,
1145 eval_body: false,
1146 async_body: false,
1147 stack: Vec::new(),
1148 private_scopes: Vec::new(),
1149 discard_root: false,
1150 }
1151 }
1152
1153 /// Create a compiler for an `eval` body.
1154 /// Create a compiler for a script whose top level is an `async` function body.
1155 fn for_suspensible_script() -> Compiler {
1156 Compiler {
1157 source: None,
1158 module: false,
1159 eval_body: false,
1160 async_body: true,
1161 stack: Vec::new(),
1162 private_scopes: Vec::new(),
1163 discard_root: false,
1164 }
1165 }
1166
1167 /// Compile a whole program into its top-level function.
1168 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1169 let mut state = FnState::new("<eval>", FunctionKind::Normal);
1170 // A module body is *not* a script: it has no completion value, so no hidden
1171 // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1172 // is having no `arguments` of its own and no receiver — see `is_module`.
1173 state.is_script = !self.module;
1174 state.is_module = self.module;
1175 state.is_eval_body = self.eval_body;
1176 if self.module {
1177 state.module = Some(ModuleMeta::default());
1178 }
1179 state.strict = program.strict || self.module;
1180 state.line = program.span.start.line;
1181 state.column = program.span.start.column;
1182 // Locals are numbered in declaration order; `<ret>` is always slot 0.
1183 //
1184 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1185 // slot that only appears in one of the two arrays shifts every later
1186 // binding's block and silently loses the temporal-dead-zone marking for
1187 // the script's own blocks. A function frame has no `<ret>`, which is why
1188 // the misalignment only showed up at the top level.
1189 if !self.module {
1190 state.vars.push(VarDef::var("<ret>"));
1191 state.var_block.push(FUNCTION_SCOPE);
1192 }
1193 self.stack.push(state);
1194 // The body is its own scope, keyed by the position of the program.
1195 // The script body needs a key no statement can produce. Statement keys are
1196 // source offsets, and the program's own start offset is `0` — which is also
1197 // the offset of the first statement, so a top-level `{ let x }` or
1198 // `for (let i …)` used to share the body's block and lose its scope.
1199 let body_key = SCRIPT_BODY;
1200 self.push_block(body_key, NO_PARENT);
1201 self.state().body_block = body_key;
1202 // A module body opens with a re-entry guard. The host evaluates a module exactly
1203 // once, so the guard never fires in practice — but the reference emits it, and a
1204 // module function called a second time (through `eval` of its own source, say)
1205 // must not run its body again.
1206 let module_guard = self.module.then(|| self.new_label());
1207 if let Some(body) = module_guard {
1208 // The guard wraps the *hoisting* too: a second evaluation of the same module
1209 // body must not even re-create its function declarations.
1210 self.emit(Opcode::PushThis, &[]);
1211 self.emit_jump(Opcode::IfFalse, body, &[]);
1212 }
1213 self.hoist(&program.body, body_key)?;
1214 // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1215 // come before the guard's `return_undef`: the reference's jump target sits past
1216 // both, and a second evaluation therefore re-creates nothing.
1217 self.emit_scope_enter(body_key);
1218 if let Some(body) = module_guard {
1219 self.emit(Opcode::ReturnUndef, &[]);
1220 self.place_label(body);
1221 }
1222 // Through `stmts` rather than the loop, so a `using` region at the top level of an
1223 // eval'd body or a module gets its disposal epilogue like any other block.
1224 self.stmts(&program.body)?;
1225 if self.module {
1226 // A module has no completion value; its body simply ends.
1227 self.emit(Opcode::Undefined, &[]);
1228 self.emit(Opcode::ReturnAsync, &[]);
1229 // Top-level `await` makes the body an async function, so the host runs it as
1230 // a coroutine and waits. Without this the `await` opcode would suspend in a
1231 // body that nothing knows how to resume — which is what "a generator body ran
1232 // as an ordinary call" was reporting.
1233 if self.cur().has_await {
1234 self.state().kind = FunctionKind::Async;
1235 }
1236 } else if self.async_body {
1237 // An async body reports its completion value the same way, but through an
1238 // object: the function answers a promise, and resolving that promise *with*
1239 // the completion value would adopt a promise completion instead of reporting
1240 // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1241 // resolve to `{value: <promise>}` rather than to `7`.
1242 //
1243 // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1244 // value in an object so that promises can be safely returned").
1245 self.emit(Opcode::Object, &[]);
1246 self.emit(Opcode::Dup, &[]);
1247 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1248 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1249 self.emit(Opcode::Return, &[]);
1250 self.state().kind = FunctionKind::Async;
1251 } else {
1252 // The program's value is whatever the last expression statement stored in
1253 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1254 // case into a single `set_loc0`.
1255 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1256 self.emit(Opcode::Return, &[]);
1257 }
1258 Ok(self.finish_current())
1259 }
1260
1261 // -- emitting ----------------------------------------------------------
1262
1263 fn state(&mut self) -> &mut FnState {
1264 self.stack.last_mut().expect("a function is being compiled")
1265 }
1266
1267 fn cur(&self) -> &FnState {
1268 self.stack.last().expect("a function is being compiled")
1269 }
1270
1271 fn emit(&mut self, op: Opcode, operands: &[Op]) {
1272 self.state().label_since_insn = false;
1273 let pos = self.cur().cur_pos;
1274 self.state().insns.push(Insn::Fixed {
1275 op,
1276 operands: operands.to_vec(),
1277 });
1278 self.state().insn_pos.push(pos);
1279 }
1280
1281 /// Reset the script's hidden return value to `undefined`.
1282 ///
1283 /// Called at the start of every statement that does not itself produce the
1284 /// program's value, which is how the reference keeps `if`/loop results from
1285 /// leaking into an eval result.
1286 fn reset_value(&mut self) {
1287 if !self.cur().is_script {
1288 return;
1289 }
1290 self.emit(Opcode::Undefined, &[]);
1291 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1292 self.state().leaves_value = false;
1293 }
1294
1295 /// Whether `name` is a local or argument slot rather than a global.
1296 fn is_slot(&self, name: &str) -> bool {
1297 self.cur().vars.iter().any(|v| v.name == name)
1298 || self.cur().args.iter().any(|a| a.name == name)
1299 }
1300
1301 /// `with (object) body`
1302 ///
1303 /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1304 /// what makes the object reachable from a closure created inside the block, and it
1305 /// is also what lets an `eval` find it: the runtime collects the active `With`
1306 /// locals of every frame and resolves names against them before the realm.
1307 ///
1308 /// Inside the block every name reference is spelled as "look in the with objects
1309 /// first", innermost outwards, and falls through to the ordinary access. The test is
1310 /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1311 /// Record asks.
1312 fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1313 // `with (e) s` completes with `UpdateEmpty(s, undefined)` — an *empty* body still
1314 // produces `undefined`, it does not inherit the previous statement's value. So
1315 // `eval("1; with({}){}")` is `undefined` while `eval("1; with({}){2;}")` is `2`.
1316 // Without this the sticky `<ret>` local leaked the `1` through, the same way it
1317 // would for an `if` or a loop.
1318 self.reset_value();
1319 let name = self.next_with_name();
1320 // The object expression is evaluated *outside* the scope it introduces, so no
1321 // wrapper may be emitted for the names it mentions.
1322 let saved = std::mem::take(&mut self.state().with_names);
1323 self.expr(object)?;
1324 self.state().with_names = saved;
1325 self.emit(Opcode::ToObject, &[]);
1326 self.declare_hidden_local(&name, VarKind::With);
1327 // Pushed before the store so the store itself is not guarded by an *outer*
1328 // `with` — the object being stored is the new one, not something to look up.
1329 self.state().with_names.push(name.clone());
1330 self.emit_var(VarAction::Put, &name);
1331 let result = self.stmt(body);
1332 self.state().with_names.pop();
1333 result
1334 }
1335
1336 /// A hidden-local name for one `with` block, distinct from every enclosing one.
1337 fn next_with_name(&self) -> String {
1338 let depth = self.cur().with_names.len();
1339 if depth == 0 {
1340 "<with>".to_string()
1341 } else {
1342 format!("<with{depth}>")
1343 }
1344 }
1345
1346 /// Declare a hidden local that must stay a *local* even in a script.
1347 ///
1348 /// A script's `var` is a property of the global object, but the `with` object is not
1349 /// part of the source program's name space at all — it only exists for the compiler
1350 /// and the runtime — so it goes straight into the frame's slot list.
1351 fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1352 let state = self.state();
1353 if state.vars.iter().any(|v| v.name == name) {
1354 return;
1355 }
1356 state.var_block.push(FUNCTION_SCOPE);
1357 state.vars.push(VarDef {
1358 kind,
1359 ..VarDef::var(name)
1360 });
1361 }
1362
1363 /// Emit a name access, guarded by every active `with` object.
1364 ///
1365 /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1366 /// the read itself; the outer guards and the plain access are what the `if_false`
1367 /// jumps to, so the innermost object wins.
1368 fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1369 let names = self.visible_with_names(name);
1370 let done = self.new_label();
1371 let mut starts = Vec::new();
1372 // Innermost object first: the last `with` opened is the one that shadows the
1373 // others, so its guard has to be the first chance to satisfy the name.
1374 for with_name in names.iter().rev() {
1375 let next = self.new_label();
1376 // `with_has_var` takes the object and carries the name as an atom. It is not
1377 // `in`: an Object Environment Record also consults `Symbol.unscopables`, so
1378 // `globalThis[Symbol.unscopables] = {v: true}` leaves `v` to the outer scope.
1379 self.emit_var(VarAction::Get, with_name);
1380 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1381 self.emit_jump(Opcode::IfFalse, next, &[]);
1382 starts.push(next);
1383 // The operation is `with_get_var`/`with_put_var`, not a plain property access:
1384 // `GetBindingValue`/`SetMutableBinding` ask `HasProperty` **again** before
1385 // getting or setting. That second question is observable — a proxy's `has`
1386 // trap runs one more time (`get-binding-value-call-with-proxy-env` logs
1387 // `has, get unscopables, has, get`) and an `unscopables` getter that deletes
1388 // the property leaves a binding that has gone, which strict code must report
1389 // as a `ReferenceError` rather than write to.
1390 match action {
1391 // A store already has its value on the stack, and `with_put_var` takes the
1392 // pair in `put_field`'s order: object first, then the value.
1393 VarAction::Put | VarAction::PutInit => {
1394 self.emit_var(VarAction::Get, with_name);
1395 self.emit(Opcode::Swap, &[]);
1396 self.emit(Opcode::WithPutVar, &[Op::Atom(Atom::from_text(name))]);
1397 }
1398 _ => {
1399 self.emit_var(VarAction::Get, with_name);
1400 self.emit(Opcode::WithGetVar, &[Op::Atom(Atom::from_text(name))]);
1401 }
1402 }
1403 self.emit_jump(Opcode::Goto, done, &[]);
1404 self.place_label(next);
1405 }
1406 self.emit_var(action, name);
1407 self.place_label(done);
1408 }
1409
1410 /// The `with` blocks that can shadow `name`, innermost last.
1411 ///
1412 /// A parameter or a local of this function is *inside* every `with` this function
1413 /// opened, so those shadow it; a `with` that was already open when this function was
1414 /// created is outside the function's own environment, so the local wins and that
1415 /// block is skipped. See [`FnState::inherited_with_names`].
1416 fn visible_with_names(&self, name: &str) -> Vec<String> {
1417 let state = self.cur();
1418 // The hidden `<with…>` locals are how the guard reaches its own objects, so they
1419 // must never be guarded themselves — not by their own block (which would recurse)
1420 // and not by an enclosing one (which would ask a `with` object whether it has a
1421 // property called `<with>`, always answer no, and waste the chain). Source can
1422 // never spell these names, so exempting all of them changes nothing else.
1423 if state.with_names.iter().any(|hidden| hidden == name) {
1424 return Vec::new();
1425 }
1426 let start = if self.is_slot(name) {
1427 state.inherited_with_names
1428 } else {
1429 0
1430 };
1431 state.with_names[start..]
1432 .iter()
1433 .filter(|hidden| hidden.as_str() != name)
1434 .cloned()
1435 .collect()
1436 }
1437
1438 /// Compile `x` as a **reference** to the with object's property, resolving the object
1439 /// once for the whole read-modify-write.
1440 ///
1441 /// `x += 1`, `x++` and `x ||= v` read and then write the same name. Two independent
1442 /// guards get that wrong the moment the read changes the answer: with
1443 /// `{ get x(){ delete this.x; return 2 } }`, `with (o) { x++ }` reads through the
1444 /// getter — which removes the property — and then the write's own guard no longer
1445 /// finds it, so the store landed on the *global* `x` and `o.x` stayed `undefined`. The
1446 /// reference resolves the base once (`with_make_ref`) and reuses it for both halves.
1447 ///
1448 /// The same shape comes out of compiling the name as a **member** of the with object:
1449 /// `get_field2`/`put_field` already evaluate their receiver once, and the hidden
1450 /// `<with>` local holds exactly the object the guard just tested. So each candidate
1451 /// object gets `if the name is bound here, compile as `this.name`; otherwise fall
1452 /// through to the next object`, and the last fallback is the ordinary name.
1453 fn with_reference(
1454 &mut self,
1455 name: &str,
1456 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1457 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1458 ) -> Result<(), SyntaxError> {
1459 let targets = self.visible_with_names(name);
1460 if targets.is_empty() {
1461 return plain(self);
1462 }
1463 let done = self.new_label();
1464 let result = self.with_reference_inner(name, &targets, guarded, plain, done);
1465 self.place_label(done);
1466 result
1467 }
1468
1469 fn with_reference_inner(
1470 &mut self,
1471 name: &str,
1472 targets: &[String],
1473 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1474 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1475 done: Label,
1476 ) -> Result<(), SyntaxError> {
1477 let Some((innermost, outer)) = targets.split_last() else {
1478 return plain(self);
1479 };
1480 let next = self.new_label();
1481 self.emit_var(VarAction::Get, innermost);
1482 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1483 self.emit_jump(Opcode::IfFalse, next, &[]);
1484 guarded(self, innermost)?;
1485 self.emit_jump(Opcode::Goto, done, &[]);
1486 self.place_label(next);
1487 self.with_reference_inner(name, outer, guarded, plain, done)
1488 }
1489
1490 /// `delete name`, honouring any enclosing `with`.
1491 ///
1492 /// Inside a `with` the name may be a property of the with object, and then `delete`
1493 /// removes *that* property instead of touching the outer binding —
1494 /// `with (o) { delete p }` answers `true` and leaves `o` without `p` even when a
1495 /// global `p` exists. Left to the resolver it deleted the global instead, so the
1496 /// `statements/with/S12.10_A1.*` family then saw a `ReferenceError` on every later
1497 /// `p`.
1498 ///
1499 /// Emitted as a sequence here rather than during resolution because a resolution slot
1500 /// holds one instruction, and this is a loop over the with objects plus a fallback.
1501 fn delete_ident(&mut self, name: &str) {
1502 let names = self.cur().with_names.clone();
1503 let done = self.new_label();
1504 let mut starts = Vec::new();
1505 if !names.is_empty() {
1506 self.state().emitting_with_guard = true;
1507 // Innermost object first, like the read/write guard: the last `with` opened is
1508 // the one that shadows the others.
1509 for with_name in names.iter().rev() {
1510 let next = self.new_label();
1511 self.emit_var(VarAction::Get, with_name);
1512 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1513 self.emit_jump(Opcode::IfFalse, next, &[]);
1514 // `delete` takes the receiver then the key.
1515 self.emit_var(VarAction::Get, with_name);
1516 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1517 self.emit(Opcode::Delete, &[]);
1518 self.emit_jump(Opcode::Goto, done, &[]);
1519 self.place_label(next);
1520 starts.push(next);
1521 }
1522 self.state().emitting_with_guard = false;
1523 }
1524 // The fallback: not a property of any with object, so the ordinary rule applies.
1525 let pos = self.cur().cur_pos;
1526 self.state().insns.push(Insn::DeleteVar {
1527 name: name.to_string(),
1528 });
1529 self.state().insn_pos.push(pos);
1530 if !names.is_empty() {
1531 self.place_label(done);
1532 }
1533 }
1534
1535 fn emit_var(&mut self, action: VarAction, name: &str) {
1536 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1537 // stores and keeps the value in one instruction. The reference does this
1538 // in a post-pass; folding it at emit time keeps instruction indices
1539 // stable, which matters because labels are recorded as indices.
1540 //
1541 // Only slots have a `set_` form: a global is stored with `put_var` and
1542 // read with `get_var`, and the reference does not fold those.
1543 //
1544 // A label between the two cancels the fold. `set_x v` leaves the value on
1545 // the stack, which is only equivalent when the read immediately follows the
1546 // store; when a jump target sits in between, the store must *consume* the
1547 // value and the read must fetch it afresh. A loop head is exactly that
1548 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1549 // condition re-reads it — and folding across the label would make the
1550 // condition compare whatever the previous iteration left on the stack.
1551 if action == VarAction::Get {
1552 let is_slot = self.is_slot(name);
1553 let at_label = std::mem::take(&mut self.state().label_since_insn);
1554 //
1555 // `arguments` is excluded because the reference treats it as a special
1556 // binding: it is initialised once and read many times, and folding its
1557 // initialisation into a `set_` would leave the object on the stack where
1558 // the reference leaves nothing.
1559 if is_slot
1560 && name != "arguments"
1561 && !at_label
1562 && let Some(Insn::Var {
1563 action: previous,
1564 name: previous_name,
1565 ..
1566 }) = self.state().insns.last_mut()
1567 && *previous == VarAction::Put
1568 && previous_name == name
1569 {
1570 *previous = VarAction::Set;
1571 return;
1572 }
1573 }
1574 // Inside a `with`, every name lookup consults the with objects first. Two names
1575 // are exempt:
1576 //
1577 // * the hidden `<with…>` locals themselves, or the guard would recurse;
1578 // * a name this function **declares** — a parameter, a `var`, or a `let` of the
1579 // current body. `with` sits *outside* the function's own environment, so a
1580 // function declared inside a `with` still resolves its own bindings first:
1581 // `with (o) { function f(){ var value = "x" } }` writes `f`'s local `value`, not
1582 // `o.value`. Guarding it anyway wrote through to the with object whenever it
1583 // happened to have the name, which is why
1584 // `statements/with/S12.10_A1.7` saw `myObj.value` change. The runtime's
1585 // `eval_binding_value` already models the same order.
1586 let guarded = !self.visible_with_names(name).is_empty()
1587 && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1588 && !self.state().emitting_with_guard;
1589 if guarded {
1590 self.state().emitting_with_guard = true;
1591 self.emit_with_guarded(action, name);
1592 self.state().emitting_with_guard = false;
1593 return;
1594 }
1595 let block = self.cur().current_block;
1596 self.state().label_since_insn = false;
1597 let pos = self.cur().cur_pos;
1598 let in_params = self.cur().in_params;
1599 self.state().insns.push(Insn::Var {
1600 action,
1601 name: name.to_string(),
1602 block,
1603 in_params,
1604 });
1605 self.state().insn_pos.push(pos);
1606 }
1607
1608 fn new_label(&mut self) -> Label {
1609 let state = self.state();
1610 state.labels.push(None);
1611 Label(state.labels.len() as u32 - 1)
1612 }
1613
1614 fn place_label(&mut self, label: Label) {
1615 let index = self.cur().insns.len();
1616 self.state().label_since_insn = true;
1617 self.state().labels[label.0 as usize] = Some(index);
1618 }
1619
1620 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1621 let mut operands = vec![Op::Label(label)];
1622 operands.extend_from_slice(extra);
1623 self.emit(op, &operands);
1624 }
1625
1626 // -- scopes ------------------------------------------------------------
1627
1628 /// Start a new lexical scope inside `parent`.
1629 fn push_block(&mut self, key: u64, parent: u64) {
1630 let state = self.state();
1631 if !state.blocks.iter().any(|b| b.key == key) {
1632 state.blocks.push(Block { key, parent });
1633 }
1634 state.current_block = key;
1635 }
1636
1637 /// Emit the code that runs when a lexical scope is entered.
1638 ///
1639 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1640 /// so entering its block marks it uninitialised. Hoisted function
1641 /// declarations are created here instead, which is why a call before the
1642 /// declaration still works.
1643 ///
1644 /// The order is not obvious: bindings are emitted in *reverse* declaration
1645 /// order, because the reference walks its scope chain, which is built by
1646 /// prepending.
1647 fn emit_scope_enter(&mut self, block: u64) {
1648 // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1649 // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1650 // so entering an outer scope threw away every nested block's function
1651 // declarations: `function h(){ { function k(){} } return k; }` answered
1652 // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1653 // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1654 // in a block is also a `var` of the enclosing function), and it is what makes the
1655 // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1656 let mut hoisted = std::mem::take(&mut self.state().hoisted);
1657 let mut rest = Vec::with_capacity(hoisted.len());
1658 let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1659 for (owner, target, pool_index) in hoisted.drain(..) {
1660 if owner == block {
1661 mine.push((target, pool_index));
1662 } else {
1663 rest.push((owner, target, pool_index));
1664 }
1665 }
1666 self.state().hoisted = rest;
1667 mine.sort_by_key(|(target, _)| match target {
1668 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1669 HoistTarget::Global(_) => u32::MAX,
1670 });
1671 for (target, pool_index) in mine {
1672 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1673 match target {
1674 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1675 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1676 HoistTarget::Global(name) => {
1677 // A global binding lives in a reference cell, so the store
1678 // goes through `put_var_ref` while reads use `get_var`.
1679 let block = self.cur().current_block;
1680 let pos = self.cur().cur_pos;
1681 let in_params = self.cur().in_params;
1682 self.state().insns.push(Insn::Var {
1683 action: VarAction::PutRef,
1684 name,
1685 block,
1686 in_params,
1687 });
1688 self.state().insn_pos.push(pos);
1689 }
1690 }
1691 }
1692 for index in self.block_vars_reversed(block) {
1693 self.emit(
1694 Opcode::SetLocUninitialized,
1695 &[Op::Slot(Slot::Loc(index as u32))],
1696 );
1697 }
1698 }
1699
1700 /// Emit the code that runs when a lexical scope is exited.
1701 ///
1702 /// A captured binding has to be closed: detaching its reference cell freezes
1703 /// the value the binding had when the block ended, which is what a closure
1704 /// created inside the block must keep seeing.
1705 fn emit_scope_leave(&mut self, block: u64) {
1706 for index in self.block_vars_reversed(block) {
1707 if self.cur().vars[index].is_captured {
1708 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1709 }
1710 }
1711 }
1712
1713 /// Locals declared in `block`, in reverse declaration order.
1714 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1715 let state = self.cur();
1716 let mut out: Vec<usize> = (0..state.vars.len())
1717 .filter(|index| {
1718 state.var_block.get(*index).copied() == Some(block)
1719 && state.vars[*index].is_lexical
1720 // A derived constructor's `this` is lexical but is not initialised by
1721 // entering the scope: `check_ctor` proves it, so its dead-zone marker
1722 // was emitted with the constructor's own prologue.
1723 && state.vars[*index].name != "this"
1724 })
1725 .collect();
1726 out.reverse();
1727 out
1728 }
1729
1730 /// Declare a local, even at the top level of a script.
1731 ///
1732 /// A `catch` parameter is always a local: the reference puts it in the
1733 /// function's own variable list (`1: catch e`), never in the global object,
1734 /// because it only exists while the handler runs.
1735 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1736 let state = self.state();
1737 let index = state.vars.len() as u32;
1738 // A `catch` parameter belongs to a scope even though it is not lexical: the
1739 // runtime instantiates it per handler entry, but it never sits in the
1740 // temporal dead zone.
1741 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1742 state.current_block
1743 } else {
1744 0
1745 };
1746 state.var_block.push(block);
1747 state.vars.push(def);
1748 index
1749 }
1750
1751 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1752 if self.cur().is_module
1753 && self.cur().current_block == self.cur().body_block
1754 && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1755 {
1756 // Only the body's own block: a `let` inside a module-level `{}` is still an
1757 // ordinary local of that block, not a module variable.
1758 //
1759 // A `using` binding is excluded on purpose, and the reference excludes it in
1760 // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1761 // "'using' variables are currently not exported in modules"): a module-level
1762 // `using` is an ordinary *local* of the module body function, not a module
1763 // cell. Two things follow, and both are what the reference does — `export {a}`
1764 // of a `using` binding is "exported variable 'a' does not exist", and
1765 // disposal works, because the disposal epilogue addresses locals by slot.
1766 //
1767 // The hidden dispose-method variable is excluded for a stronger reason: it is
1768 // *always* a local (`add_scope_var` in the reference), and it must sit
1769 // immediately after its value so `using_dispose` can find it at `slot + 1`.
1770 return self.declare_module(name, &def);
1771 }
1772 if self.cur().declares_globally(&def) {
1773 self.declare_global(name, &def);
1774 return 0;
1775 }
1776 let state = self.state();
1777 let index = state.vars.len() as u32;
1778 let block = if def.is_lexical {
1779 state.current_block
1780 } else {
1781 0
1782 };
1783 state.var_block.push(block);
1784 state.vars.push(def);
1785 index
1786 }
1787
1788 /// Declare a `using` binding and its cached dispose method, returning both slots.
1789 ///
1790 /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1791 /// `(value, value + 1)` — the reference does the same and documents the constraint.
1792 fn declare_using(&mut self, name: &str) -> (u32, u32) {
1793 let mut def = VarDef::lexical(name);
1794 def.kind = VarKind::Using;
1795 // A `using` binding is immutable, exactly like a `const`: assigning to one is a
1796 // `TypeError` at run time, which is what `using-invalid-assignment-*-for` assert.
1797 // `VarDef::lexical` leaves `is_const` false, so the store would have landed.
1798 def.is_const = true;
1799 let value = self.declare(name, def);
1800 let mut method = VarDef::lexical(using_method_name(name));
1801 method.kind = VarKind::UsingMethod;
1802 let method_slot = self.declare(&using_method_name(name), method);
1803 (value, method_slot)
1804 }
1805
1806 /// The slot a `using` binding's dispose method lives in.
1807 fn using_method_slot(&self, name: &str) -> Option<u32> {
1808 let hidden = using_method_name(name);
1809 self.cur()
1810 .vars
1811 .iter()
1812 .position(|var| var.name == hidden)
1813 .map(|index| index as u32)
1814 }
1815
1816 // -- statements --------------------------------------------------------
1817
1818 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1819 self.stmt_labelled(stmt, &[])
1820 }
1821
1822 /// Compile a statement that a chain of labels names.
1823 ///
1824 /// Only a loop consumes `labels`; every other statement ignores them (the
1825 /// parser has already rejected a label on a statement that cannot use it).
1826 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1827 // Only a *top-level* expression statement supplies the program's value.
1828 let saved = self.cur().leaves_value;
1829 self.state().leaves_value =
1830 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1831 self.state().stmt_depth += 1;
1832 let result = self.stmt_inner(stmt, labels);
1833 self.state().stmt_depth -= 1;
1834 // A nested statement never contributes the program's value, so the flag
1835 // the wrapper set above is what survives.
1836 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1837 self.state().leaves_value = produced;
1838 let _ = saved;
1839 result
1840 }
1841
1842 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1843 match &stmt.kind {
1844 StmtKind::Empty | StmtKind::Debugger => {}
1845 StmtKind::Expr(expr) => {
1846 // The statement's first token is a position the reference records: an
1847 // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1848 // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1849 // is why an error from a construct with no position of its own (`[...it]`
1850 // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1851 let saved = self.cur().cur_pos;
1852 self.state().cur_pos = Some(expr.span.start);
1853 // An expression statement's value is thrown away — except in a
1854 // script, where it becomes the program's result. `assign` reads this
1855 // and clears it, so a nested assignment still produces a value.
1856 self.state().discard_value = !self.cur().is_script;
1857 let result = self.expr(expr);
1858 self.state().discard_value = false;
1859 result?;
1860 if std::mem::take(&mut self.state().no_value) {
1861 // A store whose value was discarded left nothing to drop.
1862 } else if self.cur().is_script {
1863 // The program's value lands in the hidden `<ret>` local.
1864 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1865 } else {
1866 self.emit(Opcode::Drop, &[]);
1867 }
1868 // Restored last: the trailing `drop` is part of the statement, and in the
1869 // reference it simply inherits whatever the expression last recorded.
1870 self.state().cur_pos = saved;
1871 }
1872 StmtKind::Block(body) => {
1873 // The block's declarations were hoisted with its enclosing
1874 // statement list, so there is nothing left to declare here.
1875 let key = stmt.span.start.offset as u64;
1876 let parent = self.cur().current_block;
1877 self.push_block(key, parent);
1878 self.emit_scope_enter(key);
1879 // A block is where a `using` region lives, so its statements have to go
1880 // through `stmts`: that is what emits the disposal epilogue.
1881 self.stmts(body)?;
1882 self.emit_scope_leave(key);
1883 self.state().current_block = parent;
1884 }
1885 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1886 // A function declaration was already instantiated when its scope was
1887 // entered, so the statement itself emits nothing.
1888 StmtKind::FuncDecl(_) => {}
1889 StmtKind::If { test, cons, alt } => {
1890 self.reset_value();
1891 let else_label = self.new_label();
1892 let end_label = self.new_label();
1893 self.expr(test)?;
1894 self.emit_jump(Opcode::IfFalse, else_label, &[]);
1895 self.stmt(cons)?;
1896 if alt.is_some() {
1897 self.emit_jump(Opcode::Goto, end_label, &[]);
1898 }
1899 self.place_label(else_label);
1900 if let Some(alt) = alt {
1901 self.stmt(alt)?;
1902 self.place_label(end_label);
1903 }
1904 }
1905 StmtKind::While { test, body } => {
1906 self.reset_value();
1907 let top = self.new_label();
1908 let end = self.new_label();
1909 self.place_label(top);
1910 self.expr(test)?;
1911 // The condition's false branch and `break` share one target,
1912 // which is why a `while` loop needs only one end label.
1913 self.emit_jump(Opcode::IfFalse, end, &[]);
1914 self.loop_body(body, labels, top, end)?;
1915 self.emit_jump(Opcode::Goto, top, &[]);
1916 self.place_label(end);
1917 }
1918 StmtKind::DoWhile { body, test } => {
1919 self.reset_value();
1920 let top = self.new_label();
1921 let cont = self.new_label();
1922 let end = self.new_label();
1923 self.place_label(top);
1924 // `continue` in a `do…while` runs the test, so it lands on `cont`
1925 // rather than on the loop head.
1926 self.loop_body(body, labels, cont, end)?;
1927 self.place_label(cont);
1928 self.expr(test)?;
1929 self.emit_jump(Opcode::IfTrue, top, &[]);
1930 self.place_label(end);
1931 }
1932 StmtKind::For {
1933 init,
1934 test,
1935 update,
1936 body,
1937 } => {
1938 self.reset_value();
1939 let for_key = stmt.span.start.offset as u64;
1940 let for_parent = self.cur().current_block;
1941 self.push_block(for_key, for_parent);
1942 self.emit_scope_enter(for_key);
1943 let mut using_head = None;
1944 if let Some(init) = init {
1945 match init {
1946 ForInit::VarDecl(decl) if decl.kind.is_using() => {
1947 // A `using` resource declared in the head lives until the whole
1948 // statement ends, not one iteration, so the disposal region has
1949 // to wrap the loop — and there may be several of them, each
1950 // needing its own region so that a later initialiser that
1951 // throws still disposes the earlier resources
1952 // (`initializer-disposed-if-subsequent-initializer-throws-in-forstatement-head`).
1953 using_head = Some(decl);
1954 }
1955 ForInit::VarDecl(decl) => {
1956 self.var_decl(decl)?;
1957 }
1958 ForInit::Expr(expr) => {
1959 // The head's value is discarded. Saying so lets an
1960 // assignment store with `put` instead of `dup`+`put`, which
1961 // is what the reference emits — and the difference matters:
1962 // a `dup`/`drop` pair around the store gives the peephole a
1963 // chance to fold the store into the *condition's* read.
1964 self.state().discard_value = true;
1965 let result = self.expr(expr);
1966 self.state().discard_value = false;
1967 result?;
1968 if !std::mem::take(&mut self.state().no_value) {
1969 self.emit(Opcode::Drop, &[]);
1970 }
1971 }
1972 }
1973 }
1974 // A `using` head's resource is disposed when the statement ends, on every
1975 // way out: `break`, `return`, an exception, and reaching the end.
1976 let flow = match using_head {
1977 Some(decl) => self.for_using_head(
1978 decl, 0, init, test, update, body, labels, for_key, for_parent,
1979 ),
1980 None => {
1981 self.for_loop_tail(init, test, update, body, labels, for_key, for_parent)
1982 }
1983 };
1984 flow?;
1985 }
1986 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1987 StmtKind::Throw(expr) => {
1988 self.expr(expr)?;
1989 self.emit(Opcode::Throw, &[]);
1990 }
1991 StmtKind::Break(_) | StmtKind::Continue(_) => {
1992 // Labels and loops are wired up in a later milestone; a bare
1993 // break/continue jumps to the innermost enclosing target, which
1994 // the loop helpers register.
1995 self.control_transfer(stmt)?;
1996 }
1997 StmtKind::Labeled { label, body } => {
1998 self.labeled(label, body, stmt)?;
1999 }
2000 StmtKind::Switch {
2001 discriminant,
2002 cases,
2003 } => {
2004 self.switch(discriminant, cases, stmt)?;
2005 }
2006 StmtKind::Try {
2007 block,
2008 handler,
2009 finalizer,
2010 } => {
2011 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
2012 }
2013 StmtKind::ForIn { left, right, body } => {
2014 self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
2015 }
2016 StmtKind::ForOf {
2017 left,
2018 right,
2019 body,
2020 is_await,
2021 } => {
2022 let kind = if *is_await {
2023 ForLoopKind::AwaitOf
2024 } else {
2025 ForLoopKind::Of
2026 };
2027 self.for_in_of(stmt, left, right, body, kind, labels)?;
2028 }
2029 StmtKind::With { object, body } => self.with_stmt(object, body)?,
2030 StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
2031 // `import` emits nothing: hoisting already bound its names, and the host
2032 // fills their cells before the body runs.
2033 StmtKind::Import(_) => {}
2034 StmtKind::Export(decl) => self.export_stmt(decl)?,
2035 }
2036 Ok(())
2037 }
2038
2039 /// Compile `return`, running every enclosing finalizer on the way out.
2040 ///
2041 /// `nip_catch` is what makes this possible: it discards everything on the stack
2042 /// down to and including the `catch` offset while keeping the return value on
2043 /// top, so the frame the finalizer sees has the same shape as on the normal
2044 /// path.
2045 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
2046 let mut has_value = value.is_some();
2047 if let Some(expr) = value {
2048 // `return f(x)` is a tail call *only* when nothing has to happen to the
2049 // value afterwards. A `finally` or an open iterator in scope forces the
2050 // normal path, because the cleanup has to run after the call returns —
2051 // which is exactly what a tail call refuses to do.
2052 //
2053 // A **generator or async function** never tail-calls either: its `return` is
2054 // not a return to the caller but `return_async`, which reads the value off the
2055 // stack and finishes the coroutine. A tail call replaces the frame and hands
2056 // the callee's result straight to whoever resumed us, so the value vanished and
2057 // `it.next(42)` answered `{done: true, value: undefined}` for
2058 // `function* g(){ return f(yield) }`. The reference emits `call1` plus
2059 // `return_async` there and has no tail form for a suspending body at all.
2060 let plain = !self.cur().is_suspending()
2061 // A derived constructor's return is not just the value: a non-object answer
2062 // becomes `this`, so the frame has to survive to run that.
2063 && self.cur().ctor_kind != CtorKind::Derived
2064 && self
2065 .cur()
2066 .jump_targets
2067 .iter()
2068 .all(|target| target.finally_label.is_none() && !target.has_iterator);
2069 if plain && self.expr_if_tail_call(expr)? {
2070 // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
2071 // happen here as well.
2072 self.note_direct_eval(expr);
2073 return Ok(());
2074 }
2075 self.expr(expr)?;
2076 }
2077 // `return v` in an *async generator* awaits `v` before anything else happens —
2078 // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
2079 // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
2080 // exactly that reason ("the await must be done before handling the finally in case
2081 // it raises an exception").
2082 if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
2083 self.emit(Opcode::Await, &[]);
2084 self.state().has_await = true;
2085 }
2086 has_value = self.emit_unwind_for_return(has_value);
2087 // A generator or async function does not return to its caller: it either
2088 // finishes, and the value becomes `{value, done: true}`, or it suspends.
2089 // `return_async` is the "finished" half, and it reads the value off the stack
2090 // rather than carrying it, which is what the resume machinery expects.
2091 if self.cur().is_suspending() {
2092 if !has_value {
2093 self.emit(Opcode::Undefined, &[]);
2094 }
2095 self.emit(Opcode::ReturnAsync, &[]);
2096 return Ok(());
2097 }
2098 // A derived constructor's result is `this` whenever the body does not answer an
2099 // object, and `this` is a local in the dead zone until `super()` returns — which is
2100 // why reading it here is also what turns `constructor(){ return; }` into the
2101 // ReferenceError the reference reports. The interpreter could not do this on its
2102 // own: by the time it sees `undefined` come back, the frame that held `this` is
2103 // gone, and `construct`'s own idea of `this` is the placeholder it made before the
2104 // body ran (`derived-class-return-override-with-{undefined,empty}`).
2105 if self.cur().ctor_kind == CtorKind::Derived {
2106 if !has_value {
2107 self.emit_var(VarAction::Get, "this");
2108 self.emit(Opcode::Return, &[]);
2109 return Ok(());
2110 }
2111 // `return <expr>` is only *sometimes* `this`: `undefined` is, any other
2112 // primitive is a `TypeError` (raised by `construct`), and an object replaces
2113 // `this` outright. Which one it is can only be known at run time.
2114 let keep = self.new_label();
2115 self.emit(Opcode::Dup, &[]);
2116 self.emit(Opcode::IsUndefined, &[]);
2117 self.emit_jump(Opcode::IfFalse, keep, &[]);
2118 self.emit(Opcode::Drop, &[]);
2119 self.emit_var(VarAction::Get, "this");
2120 self.place_label(keep);
2121 self.emit(Opcode::Return, &[]);
2122 return Ok(());
2123 }
2124 if has_value {
2125 self.emit(Opcode::Return, &[]);
2126 } else {
2127 self.emit(Opcode::ReturnUndef, &[]);
2128 }
2129 Ok(())
2130 }
2131
2132 /// Close an iterator: the reference's `emit_iterator_close`.
2133 ///
2134 /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
2135 /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
2136 /// sequence, and three details in it are load-bearing:
2137 ///
2138 /// * the iterator object is compared against `undefined` first, because a loop that
2139 /// ran to completion clears that slot rather than closing an exhausted iterator;
2140 /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
2141 /// * `preserve_completion` keeps whatever was underneath (the return value of the
2142 /// function being left), which is why one branch ends on `nip` and the other on `drop`.
2143 fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
2144 if !is_async {
2145 if preserve_completion {
2146 self.emit(Opcode::Rot3r, &[]);
2147 self.emit(Opcode::Undefined, &[]);
2148 }
2149 self.emit(Opcode::IteratorClose, &[]);
2150 return;
2151 }
2152 if preserve_completion {
2153 // `iter next completion -> completion iter`
2154 self.emit(Opcode::Nip, &[]);
2155 self.emit(Opcode::Swap, &[]);
2156 } else {
2157 // `iter next catch_offset -> iter`
2158 self.emit(Opcode::Drop, &[]);
2159 self.emit(Opcode::Drop, &[]);
2160 }
2161 let done = self.new_label();
2162 let no_return = self.new_label();
2163 self.emit(Opcode::Dup, &[]);
2164 self.emit(Opcode::IsUndefined, &[]);
2165 self.emit_jump(Opcode::IfTrue, done, &[]);
2166 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
2167 self.emit(Opcode::Dup, &[]);
2168 self.emit(Opcode::IsUndefinedOrNull, &[]);
2169 self.emit_jump(Opcode::IfTrue, no_return, &[]);
2170 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
2171 self.emit(Opcode::Await, &[]);
2172 self.state().has_await = true;
2173 self.emit_jump(Opcode::Goto, done, &[]);
2174 self.place_label(no_return);
2175 self.emit(Opcode::Drop, &[]);
2176 self.place_label(done);
2177 self.emit(Opcode::Drop, &[]);
2178 }
2179
2180 /// Emit the finalizer/iterator cleanup for leaving the current position with a
2181 /// return, and report whether a value is now on the stack for it to carry.
2182 ///
2183 /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
2184 /// enclosing `finally` at once, and the two used to be separate — the `yield` path
2185 /// simply emitted `return_async`, so `it.return()` ended the generator without ever
2186 /// running `finally` blocks the body was sitting inside.
2187 fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
2188 let targets = self.cur().jump_targets.clone();
2189 for target in targets.iter().rev() {
2190 if target.finally_label.is_none() && !target.has_iterator {
2191 continue;
2192 }
2193 if !has_value {
2194 // The cleanup expects a value to pass through; with nothing to
2195 // return, `undefined` stands in.
2196 self.emit(Opcode::Undefined, &[]);
2197 has_value = true;
2198 }
2199 self.emit(Opcode::NipCatch, &[]);
2200 if target.has_iterator {
2201 // Rewind to the loop's own slots and hand the close a dummy catch offset:
2202 // the loop is being abandoned, so there is nothing left to catch.
2203 self.emit_iterator_close(target.is_async_iterator, true);
2204 } else if let Some(finally) = target.finally_label {
2205 self.emit_jump(Opcode::Gosub, finally, &[]);
2206 }
2207 }
2208 has_value
2209 }
2210
2211 /// Compile a statement list, stopping at the first statement that cannot
2212 /// fall through.
2213 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2214 for (index, stmt) in body.iter().enumerate() {
2215 // A `using` declaration is not just a binding: everything after it, to the end
2216 // of the list, runs inside its disposal region. Compiling the rest of the list
2217 // recursively is what gives nested regions their innermost-first order.
2218 if Self::using_declaration(stmt).is_some() {
2219 return self.using_region(stmt, &body[index + 1..]);
2220 }
2221 self.stmt(stmt)?;
2222 if Self::terminates(stmt) {
2223 break;
2224 }
2225 }
2226 Ok(())
2227 }
2228
2229 /// The declaration a `using` statement carries, if it is one.
2230 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2231 match &stmt.kind {
2232 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2233 _ => None,
2234 }
2235 }
2236
2237 /// Compile `decl` and then the rest of its block, disposing when the block ends.
2238 ///
2239 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2240 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2241 /// exception — and this engine already funnels all of those through `catch` plus
2242 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2243 /// `return` and `break` dispose without knowing anything about `using`.
2244 ///
2245 /// ```text
2246 /// <declaration> value -> x, method -> x+1
2247 /// catch CATCH <- an exception in the rest lands here
2248 /// REST:
2249 /// <the rest of the block>
2250 /// drop <- the catch offset, on the fall-through path
2251 /// undefined; gosub DISPOSE; drop
2252 /// goto END
2253 /// CATCH:
2254 /// using_dispose x <- merges the failure into the pending exception
2255 /// throw
2256 /// DISPOSE:
2257 /// using_dispose_init
2258 /// using_dispose x
2259 /// using_dispose_end <- rethrows if a dispose failed
2260 /// ret
2261 /// END:
2262 /// ```
2263 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2264 let Some(decl) = Self::using_declaration(stmt) else {
2265 unreachable!("using_region is only called for a using declaration");
2266 };
2267 self.using_declarator(stmt, decl, 0, rest)
2268 }
2269
2270 /// One declarator of a `using` declaration, plus the region around everything after it.
2271 ///
2272 /// A `using` may list several resources — `using a = x, b = y;` — and each one is
2273 /// disposed when the block ends, in **reverse** order: §14.3.1.4 pushes them onto
2274 /// `DisposableResourceStack` in source order and §9.5.5 disposes from the top. Nesting
2275 /// one region per declarator gives exactly that, because the inner region ends first
2276 /// (`multiple-resources-disposed-in-reverse-order`). Compiling only the first left the
2277 /// rest undisposed.
2278 fn using_declarator(
2279 &mut self,
2280 stmt: &Stmt,
2281 decl: &VarDecl,
2282 index: usize,
2283 rest: &[Stmt],
2284 ) -> Result<(), SyntaxError> {
2285 let Some(declarator) = decl.declarators.get(index) else {
2286 return self.stmts(rest);
2287 };
2288 // `using` binds a plain identifier and has no pattern form, which the parser
2289 // enforces; the region still has to know *which* slot to dispose.
2290 let name = match &declarator.target.kind {
2291 PatternKind::Ident(ident) => Some(ident.name.clone()),
2292 _ => None,
2293 };
2294 let single = Stmt {
2295 kind: StmtKind::VarDecl(VarDecl {
2296 kind: decl.kind,
2297 declarators: vec![declarator.clone()],
2298 span: declarator.span,
2299 }),
2300 span: declarator.span,
2301 };
2302 self.stmt(&single)?;
2303 let Some(name) = name else {
2304 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2305 // must not make the compiler panic.
2306 return self.using_declarator(stmt, decl, index + 1, rest);
2307 };
2308 let Some(value_slot) = self.using_value_slot(&name) else {
2309 // Declared globally, which the parser rules out for a script; a module's
2310 // top level is a scope, and there the disposal stays a known gap.
2311 return self.using_declarator(stmt, decl, index + 1, rest);
2312 };
2313 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2314 // exit path already disposed.
2315 let live = !rest.last().is_some_and(Self::terminates);
2316 let _ = stmt;
2317 self.using_region_around(
2318 value_slot,
2319 live,
2320 decl.kind == VarDeclKind::AwaitUsing,
2321 |compiler| compiler.using_declarator(stmt, decl, index + 1, rest),
2322 )
2323 }
2324
2325 /// One `using` declarator of a `for` head, wrapped in its disposal region, and then the
2326 /// next — so the resources nest inside-out and dispose in reverse order.
2327 #[allow(clippy::too_many_arguments)]
2328 fn for_using_head(
2329 &mut self,
2330 decl: &VarDecl,
2331 index: usize,
2332 init: &Option<ForInit>,
2333 test: &Option<Box<Expr>>,
2334 update: &Option<Box<Expr>>,
2335 body: &Stmt,
2336 labels: &[String],
2337 for_key: u64,
2338 for_parent: u64,
2339 ) -> Result<(), SyntaxError> {
2340 let Some(declarator) = decl.declarators.get(index) else {
2341 return self.for_loop_tail(init, test, update, body, labels, for_key, for_parent);
2342 };
2343 let name = match &declarator.target.kind {
2344 PatternKind::Ident(ident) => Some(ident.name.clone()),
2345 _ => None,
2346 };
2347 self.var_decl(&VarDecl {
2348 kind: decl.kind,
2349 declarators: vec![declarator.clone()],
2350 span: declarator.span,
2351 })?;
2352 let Some(slot) = name.and_then(|name| self.using_value_slot(&name)) else {
2353 return self.for_using_head(
2354 decl,
2355 index + 1,
2356 init,
2357 test,
2358 update,
2359 body,
2360 labels,
2361 for_key,
2362 for_parent,
2363 );
2364 };
2365 self.using_region_around(
2366 slot,
2367 true,
2368 decl.kind == VarDeclKind::AwaitUsing,
2369 |compiler| {
2370 compiler.for_using_head(
2371 decl,
2372 index + 1,
2373 init,
2374 test,
2375 update,
2376 body,
2377 labels,
2378 for_key,
2379 for_parent,
2380 )
2381 },
2382 )
2383 }
2384
2385 /// The half of a `for` statement that runs inside its head's disposal region: the
2386 /// per-iteration bindings, the test, the body and the update.
2387 ///
2388 /// Split out so that a `using` head can wrap exactly this much — see the
2389 /// `StmtKind::For` arm — because the resource lives as long as the statement.
2390 #[allow(clippy::too_many_arguments)]
2391 fn for_loop_tail(
2392 &mut self,
2393 init: &Option<ForInit>,
2394 test: &Option<Box<Expr>>,
2395 update: &Option<Box<Expr>>,
2396 body: &Stmt,
2397 labels: &[String],
2398 for_key: u64,
2399 for_parent: u64,
2400 ) -> Result<(), SyntaxError> {
2401 // A `let`/`const` in the head gets a *fresh binding per iteration*,
2402 // so a closure made in the body captures that iteration's value
2403 // instead of sharing one. The reference expresses this with
2404 // `close_loc`, which swaps in a new reference cell holding the
2405 // current value; the three points below are the ones it uses — after
2406 // the initialiser, before the update, and after the loop.
2407 let loop_bindings = match init {
2408 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
2409 let mut names: Vec<String> = Vec::new();
2410 for declarator in &decl.declarators {
2411 let mut idents = Vec::new();
2412 declarator.target.bound_names(&mut idents);
2413 names.extend(idents.into_iter().map(|ident| ident.name));
2414 }
2415 names
2416 }
2417 _ => Vec::new(),
2418 };
2419 // The reference also closes right after the initialiser, so the first
2420 // iteration's closures get their own cell rather than sharing the one
2421 // the initialiser wrote into.
2422 for name in &loop_bindings {
2423 let pos = self.cur().cur_pos;
2424 self.state().insns.push(Insn::CloseCaptured {
2425 name: name.clone(),
2426 block: for_key,
2427 });
2428 self.state().insn_pos.push(pos);
2429 }
2430 let top = self.new_label();
2431 let cont = self.new_label();
2432 let end = self.new_label();
2433 self.place_label(top);
2434 if let Some(test) = test {
2435 self.expr(test)?;
2436 self.emit_jump(Opcode::IfFalse, end, &[]);
2437 }
2438 // `continue` runs the update expression first, so it lands on
2439 // `cont`, which sits just before the update.
2440 self.loop_body(body, labels, cont, end)?;
2441 self.place_label(cont);
2442 // Each iteration ends with a fresh cell, so the closures the body just
2443 // created keep the cell they captured and the update writes to a new
2444 // one. Without this every closure in the loop shares one binding.
2445 let binding_block = for_key;
2446 for name in &loop_bindings {
2447 let pos = self.cur().cur_pos;
2448 self.state().insns.push(Insn::CloseCaptured {
2449 name: name.clone(),
2450 block: binding_block,
2451 });
2452 self.state().insn_pos.push(pos);
2453 }
2454 if let Some(update) = update {
2455 self.state().discard_value = true;
2456 let result = self.expr(update);
2457 self.state().discard_value = false;
2458 result?;
2459 if !std::mem::take(&mut self.state().no_value) {
2460 self.emit(Opcode::Drop, &[]);
2461 }
2462 }
2463 self.emit_jump(Opcode::Goto, top, &[]);
2464 self.place_label(end);
2465 self.emit_scope_leave(for_key);
2466 self.state().current_block = for_parent;
2467 Ok(())
2468 }
2469
2470 /// The slot a `using` binding's value lives in.
2471 fn using_value_slot(&self, name: &str) -> Option<u32> {
2472 self.cur()
2473 .vars
2474 .iter()
2475 .position(|var| var.name == name && var.kind == VarKind::Using)
2476 .map(|index| index as u32)
2477 }
2478
2479 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2480 ///
2481 /// Shared between a `using` statement — which owns the rest of its block — and a
2482 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2483 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2484 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2485 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2486 /// target with a `finally_label` is what makes `return` and `break` dispose without
2487 /// knowing anything about `using`.
2488 ///
2489 /// ```text
2490 /// catch CATCH <- an exception inside lands here
2491 /// <inside>
2492 /// drop <- the catch offset, on the fall-through path
2493 /// undefined; gosub DISPOSE; drop
2494 /// goto END
2495 /// CATCH:
2496 /// using_dispose slot <- merges the failure into the pending exception
2497 /// throw
2498 /// DISPOSE:
2499 /// using_dispose_init
2500 /// using_dispose slot
2501 /// using_dispose_end <- rethrows if a dispose failed
2502 /// ret
2503 /// END:
2504 /// ```
2505 fn using_region_around(
2506 &mut self,
2507 value_slot: u32,
2508 live: bool,
2509 is_await_using: bool,
2510 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2511 ) -> Result<(), SyntaxError> {
2512 let catch_label = self.new_label();
2513 let end_label = self.new_label();
2514 let dispose_label = self.new_label();
2515
2516 self.emit_jump(Opcode::Catch, catch_label, &[]);
2517 self.push_jump_target(JumpTarget {
2518 names: Vec::new(),
2519 break_label: None,
2520 continue_label: None,
2521 // The catch offset is the one thing on the stack that leaving has to remove.
2522 drop_count: 1,
2523 finally_label: Some(dispose_label),
2524 is_regular_stmt: false,
2525 has_iterator: false,
2526 is_async_iterator: false,
2527 });
2528 inside(self)?;
2529 self.pop_jump_target();
2530
2531 if live {
2532 self.emit(Opcode::Drop, &[]);
2533 self.emit(Opcode::Undefined, &[]);
2534 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2535 self.emit(Opcode::Drop, &[]);
2536 self.emit_jump(Opcode::Goto, end_label, &[]);
2537 }
2538
2539 // An exception unwinds to here with the thrown value on the stack, which is exactly
2540 // the shape `using_dispose` expects as its error state.
2541 self.place_label(catch_label);
2542 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2543 self.emit(Opcode::Throw, &[]);
2544
2545 self.place_label(dispose_label);
2546 // Inside the subroutine the return value and the `gosub` return address are both
2547 // live, and neither an outer finalizer nor another region may run before this one
2548 // has finished.
2549 self.push_jump_target(JumpTarget {
2550 names: Vec::new(),
2551 break_label: None,
2552 continue_label: None,
2553 drop_count: 2,
2554 finally_label: None,
2555 is_regular_stmt: false,
2556 has_iterator: false,
2557 is_async_iterator: false,
2558 });
2559 self.emit(Opcode::UsingDisposeInit, &[]);
2560 if is_await_using {
2561 // `AsyncDisposableStack`'s order: call the method, **await** its result, and
2562 // fold a rejection into the error state. The catch is what turns that
2563 // rejection — which arrives as an exception from `await` — into the merged
2564 // error, so one failure is rethrown as itself and two become a
2565 // `SuppressedError` (§27.1.3.3's `DisposeResources` steps 5–6).
2566 //
2567 // The shape is the reference's `js_emit_dispose_scope`, adapted to this
2568 // engine's error-state protocol: `using_dispose_init` pushed the state and
2569 // `using_dispose_end` will consume it, so both arms have to leave it in place.
2570 let catch_label = self.new_label();
2571 let merged_label = self.new_label();
2572 self.emit_jump(Opcode::Catch, catch_label, &[]);
2573 self.emit(
2574 Opcode::UsingDisposeAsync,
2575 &[Op::Slot(Slot::Loc(value_slot))],
2576 );
2577 self.emit(Opcode::Await, &[]);
2578 // The awaited value, and the catch offset the successful path still holds.
2579 self.emit(Opcode::Drop, &[]);
2580 self.emit(Opcode::Drop, &[]);
2581 self.emit_jump(Opcode::Goto, merged_label, &[]);
2582 self.place_label(catch_label);
2583 self.emit(Opcode::UsingDisposeMerge, &[]);
2584 self.place_label(merged_label);
2585 self.state().has_await = true;
2586 } else {
2587 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2588 }
2589 self.emit(Opcode::UsingDisposeEnd, &[]);
2590 self.pop_jump_target();
2591 self.emit(Opcode::Ret, &[]);
2592 self.place_label(end_label);
2593 Ok(())
2594 }
2595
2596 /// Declare every name a statement list introduces, before compiling any of
2597 /// it, so a reference that appears textually before a declaration still
2598 /// resolves.
2599 ///
2600 /// Declarations are walked in source order because that is the order the
2601 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2602 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2603 /// declarations hoist out to the function scope; lexical names belong to the
2604 /// block they were written in, which `block` records.
2605 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2606 let saved = self.cur().current_block;
2607 self.state().current_block = block;
2608 let result = self.hoist_list(body);
2609 // Only now is every binding of this scope known, so the deferred function
2610 // bodies can be compiled against the finished list. Compiled at its own
2611 // declaration instead, a body that names a `var` written further down would
2612 // have resolved that name as a global.
2613 if result.is_ok() {
2614 let deferred = std::mem::take(&mut self.state().deferred_funcs);
2615 let mut outcome = Ok(());
2616 for (owner, func) in deferred {
2617 let previous = self.cur().current_block;
2618 self.state().current_block = owner;
2619 outcome = self.func_decl(&func);
2620 self.state().current_block = previous;
2621 if outcome.is_err() {
2622 break;
2623 }
2624 }
2625 self.state().current_block = saved;
2626 return outcome;
2627 }
2628 // `current_block` is restored by the caller for a block statement, since
2629 // it needs it set while compiling; only clean up on the hoist path.
2630 self.state().current_block = saved;
2631 result
2632 }
2633
2634 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2635 for stmt in body {
2636 self.hoist_stmt(stmt)?;
2637 }
2638 Ok(())
2639 }
2640
2641 /// Whether a statement always transfers control away, making everything after
2642 /// it in the same list unreachable.
2643 ///
2644 /// The reference drops such statements in `skip_dead_code`, so `return 1;
2645 /// let x = 2;` compiles to the same bytecode as `return 1;`.
2646 fn terminates(stmt: &Stmt) -> bool {
2647 matches!(
2648 stmt.kind,
2649 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2650 )
2651 }
2652
2653 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2654 match &stmt.kind {
2655 StmtKind::VarDecl(decl) => {
2656 for declarator in &decl.declarators {
2657 let mut names = Vec::new();
2658 declarator.target.bound_names(&mut names);
2659 for name in names {
2660 let text = name.name.clone();
2661 if decl.kind == VarDeclKind::Var {
2662 let def = VarDef::var(text.clone());
2663 self.declare_var(&text, def);
2664 } else if decl.kind.is_using() {
2665 // Two adjacent slots: the resource, then the dispose method
2666 // snapshotted at declaration. `using_dispose` reads them as a
2667 // pair `(slot, slot + 1)`, so nothing may be declared between
2668 // them — which is why both are declared here, in one step,
2669 // rather than the method being added at emission time.
2670 self.declare_using(&text);
2671 } else {
2672 let def = if decl.kind == VarDeclKind::Const {
2673 VarDef::constant(text.clone())
2674 } else {
2675 VarDef::lexical(text.clone())
2676 };
2677 self.declare(&text, def);
2678 }
2679 }
2680 }
2681 }
2682 StmtKind::FuncDecl(func) => {
2683 if let Some(name) = &func.name {
2684 // A function declaration is a `var` binding that happens to
2685 // hold a function, not a lexical one.
2686 let mut def = VarDef::var(name.name.clone());
2687 // Marked so that an `eval` establishing it can apply
2688 // `CanDeclareGlobalFunction` rather than the laxer `var` rule. Only
2689 // the *global* form is marked: the kind is printed by the
2690 // disassembler, and a local function declaration is `var g` there,
2691 // exactly like the reference.
2692 if self.cur().declares_globally(&def) {
2693 def.kind = crate::bytecode::VarKind::GlobalFunctionDecl;
2694 }
2695 self.declare_var(&name.name.clone(), def);
2696 }
2697 // The function object is created when the scope is entered, so it
2698 // exists before the declaration is reached. Its body is compiled
2699 // *after* this scope's hoisting finishes, so a name it uses resolves
2700 // even when the `var` that declares it comes later in the source.
2701 let owner = self.cur().current_block;
2702 self.state().deferred_funcs.push((owner, func.clone()));
2703 }
2704 StmtKind::ClassDecl(class) => {
2705 if let Some(name) = &class.name {
2706 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2707 }
2708 }
2709 // A module's imports are bound before any of its code runs, and its exports
2710 // declare the very bindings they export — so both hoist the declarations
2711 // their `StmtKind` arm will later emit code for.
2712 StmtKind::Import(decl) => self.hoist_import(decl)?,
2713 StmtKind::Export(decl) => self.hoist_export(decl)?,
2714 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2715 StmtKind::If { cons, alt, .. } => {
2716 self.hoist_stmt(cons)?;
2717 if let Some(alt) = alt {
2718 self.hoist_stmt(alt)?;
2719 }
2720 }
2721 StmtKind::While { body, .. }
2722 | StmtKind::DoWhile { body, .. }
2723 | StmtKind::Labeled { body, .. }
2724 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2725 StmtKind::For { init, body, .. } => {
2726 // A `for` head gets its own scope even when it declares nothing,
2727 // because `let` in the head is scoped to the loop.
2728 let key = stmt.span.start.offset as u64;
2729 let parent = self.cur().current_block;
2730 self.push_block(key, parent);
2731 if let Some(init) = init
2732 && let ForInit::VarDecl(decl) = init
2733 {
2734 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2735 }
2736 self.hoist_stmt(body)?;
2737 self.state().current_block = parent;
2738 }
2739 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2740 let key = stmt.span.start.offset as u64;
2741 let parent = self.cur().current_block;
2742 self.push_block(key, parent);
2743 if let ForHead::VarDecl(decl) = left {
2744 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2745 }
2746 self.hoist_stmt(body)?;
2747 self.state().current_block = parent;
2748 }
2749 StmtKind::Try {
2750 block,
2751 handler,
2752 finalizer,
2753 } => {
2754 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2755 let try_parent = self.cur().current_block;
2756 if let Some(handler) = handler {
2757 // The catch parameter belongs to the function scope, not to a
2758 // block: it is a `catch` binding rather than a `let`, so it is
2759 // never in the temporal dead zone and `emit_scope_enter` must
2760 // not mark it uninitialised. It still has to be declared before
2761 // the handler body is hoisted, so it takes the slot the
2762 // reference gives it (bindings are numbered in source order).
2763 if let Some(pattern) = &handler.param {
2764 // The parameter gets its own scope, so entering the handler
2765 // does not have to re-declare it. It is not lexical, so it
2766 // is never marked uninitialised.
2767 let key = Self::try_block_key(stmt, TryPart::Param);
2768 let parent = self.cur().current_block;
2769 self.push_block(key, parent);
2770 // A destructuring parameter binds several names, one slot each,
2771 // in the order they are written. The reference declares those as
2772 // `let`s rather than as one `catch` binding — its dump prints
2773 // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2774 // so the kind follows the shape of the parameter.
2775 //
2776 // Neither form is in the dead zone: the stores run as the handler
2777 // is entered, so both use the unchecked `put_loc`.
2778 let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2779 let mut names = Vec::new();
2780 pattern.bound_names(&mut names);
2781 for name in names {
2782 let def = VarDef {
2783 name: name.name.clone(),
2784 is_const: false,
2785 is_lexical: destructures,
2786 kind: if destructures {
2787 crate::bytecode::VarKind::LexicalCatch
2788 } else {
2789 crate::bytecode::VarKind::Catch
2790 },
2791 is_captured: false,
2792 scope_level: 0,
2793 scope_next: None,
2794 };
2795 self.declare_local(&name.name.clone(), def);
2796 }
2797 // The handler body nests inside the parameter's scope, so the
2798 // body's bindings chain on to the parameter (the reference
2799 // prints `let y [next:1]`, pointing at `e`).
2800 self.state().current_block = key;
2801 }
2802 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2803 // Back to the block the `try` itself lives in, so the finalizer
2804 // is a sibling of the handler rather than nested in it.
2805 self.state().current_block = try_parent;
2806 }
2807 if let Some(finalizer) = finalizer {
2808 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2809 }
2810 }
2811 StmtKind::Switch { cases, .. } => {
2812 let key = stmt.span.start.offset as u64;
2813 let parent = self.cur().current_block;
2814 self.push_block(key, parent);
2815 for case in cases {
2816 self.hoist_list(&case.body)?;
2817 }
2818 self.state().current_block = parent;
2819 }
2820 _ => {}
2821 }
2822 Ok(())
2823 }
2824
2825 /// Hoist a nested statement list, which is its own lexical scope.
2826 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2827 let parent = self.cur().current_block;
2828 self.push_block(key, parent);
2829 self.hoist_list(body)?;
2830 self.state().current_block = parent;
2831 Ok(())
2832 }
2833
2834 /// A block key for one part of a `try` statement.
2835 ///
2836 /// The three parts are three separate scopes, so they cannot share the key a
2837 /// statement's own offset would give them: the try block, the handler body and
2838 /// the finalizer would then look like one scope, and their `let` bindings would
2839 /// be marked uninitialised only on entering the first of them.
2840 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2841 (stmt.span.start.offset as u64) * 4 + part as u64
2842 }
2843
2844 /// Declare a `var`: it lives in the function's own scope, not the block's.
2845 fn declare_var(&mut self, name: &str, def: VarDef) {
2846 if self.cur().is_module {
2847 self.declare_module(name, &def);
2848 return;
2849 }
2850 if self.cur().declares_globally(&def) {
2851 self.declare_global(name, &def);
2852 return;
2853 }
2854 let state = self.state();
2855 // A binding of the *parameter* scope does not count: the body's `var` of the
2856 // same name is a different binding and needs a slot of its own.
2857 if state.vars.iter().enumerate().any(|(index, v)| {
2858 v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2859 }) {
2860 return;
2861 }
2862 // A `var` belongs to the function scope, never to the enclosing block.
2863 state.var_block.push(FUNCTION_SCOPE);
2864 state.vars.push(def);
2865 }
2866
2867 /// Declare `name` as a binding of the parameter scope, returning its slot.
2868 fn declare_param_var(&mut self, name: &str) -> u32 {
2869 declare_param_var_at(self.state(), name)
2870 }
2871
2872 /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2873 ///
2874 /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2875 /// so each points at the one declared before it and the oldest ends the chain with
2876 /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2877 /// runtime walks when it instantiates them.
2878 fn declare_param_binding(&mut self, name: &str) -> u32 {
2879 let state = self.state();
2880 let previous = state
2881 .vars
2882 .iter()
2883 .enumerate()
2884 .rev()
2885 .find(|(index, var)| {
2886 state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2887 })
2888 .map(|(index, _)| index as i32);
2889 let index = state.vars.len() as u32;
2890 state.var_block.push(PARAM_SCOPE);
2891 let mut def = VarDef::lexical(name);
2892 // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2893 // the function's, and its bindings are initialised one by one rather than all at
2894 // once — which is exactly what the dead zone needs.
2895 def.scope_level = 1;
2896 def.scope_next = Some(previous.unwrap_or(-2));
2897 state.vars.push(def);
2898 index
2899 }
2900
2901 /// The slot of a parameter-list binding, if the list has one by that name.
2902 fn param_binding_slot(&self, name: &str) -> Option<u32> {
2903 let state = self.cur();
2904 state
2905 .vars
2906 .iter()
2907 .enumerate()
2908 .position(|(index, var)| {
2909 var.name == name
2910 && var.is_lexical
2911 && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2912 })
2913 .map(|index| index as u32)
2914 }
2915
2916 /// Every parameter-list binding, in declaration order.
2917 fn param_binding_names(&self) -> Vec<String> {
2918 let state = self.cur();
2919 state
2920 .vars
2921 .iter()
2922 .enumerate()
2923 .filter(|(index, var)| {
2924 var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2925 })
2926 .map(|(_, var)| var.name.clone())
2927 .collect()
2928 }
2929
2930 /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2931 fn body_var_slot(&self, name: &str) -> Option<u32> {
2932 let state = self.cur();
2933 state
2934 .vars
2935 .iter()
2936 .enumerate()
2937 .find(|(index, var)| {
2938 var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2939 })
2940 .map(|(index, _)| index as u32)
2941 }
2942
2943 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2944 /// one.
2945 ///
2946 /// With parameter expressions the reference creates two: an unmapped one in the
2947 /// argument scope, for the defaults and anything they close over, and the body's own.
2948 /// They are separate bindings, which is what makes
2949 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2950 /// report 1 from `p` and 2 from the body.
2951 fn provide_param_arguments(&mut self) {
2952 if !self.cur().has_parameter_expressions {
2953 return;
2954 }
2955 let mentioned = self.cur().needs_param_arguments
2956 || self
2957 .cur()
2958 .insns
2959 .iter()
2960 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2961 if !mentioned {
2962 return;
2963 }
2964 let slot = self.declare_param_var("arguments");
2965 let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2966 0
2967 } else {
2968 1
2969 };
2970 self.prepend_initialiser_to(
2971 slot,
2972 Insn::Fixed {
2973 op: Opcode::SpecialObject,
2974 operands: vec![Op::Int(magic)],
2975 },
2976 );
2977 }
2978
2979 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2980 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2981 let current = self.stack.len() - 1;
2982 let init = [
2983 producer,
2984 Insn::Fixed {
2985 op: Opcode::PutLoc,
2986 operands: vec![Op::Slot(Slot::Loc(slot))],
2987 },
2988 ];
2989 let inserted = init.len();
2990 for (index, instruction) in init.into_iter().enumerate() {
2991 self.stack[current].insns.insert(index, instruction);
2992 }
2993 for placed in self.stack[current].labels.iter_mut().flatten() {
2994 *placed += inserted;
2995 }
2996 self.state().label_since_insn = false;
2997 }
2998
2999 /// Give the function an `arguments` binding if its body mentions one.
3000 ///
3001 /// The check runs on the *instruction* stream rather than the AST: by this point
3002 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
3003 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
3004 /// would renumber every later local slot and stop the bytecode matching the
3005 /// reference, which only adds the binding when the body uses it.
3006 ///
3007 /// `arguments` is a local, initialised at the top of the body by
3008 /// `special_object`; that is the reference's shape, so the disassembly agrees.
3009 fn provide_arguments(&mut self) {
3010 let current = self.stack.len() - 1;
3011 if self.stack[current].is_script || self.stack[current].is_module {
3012 // A module has no `arguments` binding; referring to it is a ReferenceError,
3013 // which is exactly what an unbound name produces.
3014 return;
3015 }
3016 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
3017 // function, which is why `() => arguments` sees the caller's arguments.
3018 if self.stack[current].is_arrow {
3019 if self.mentions("arguments") {
3020 self.ensure_enclosing_arguments();
3021 }
3022 return;
3023 }
3024 // Only a *body* mention needs the body's binding: the parameter list has one of
3025 // its own (see [`Compiler::provide_param_arguments`]).
3026 //
3027 // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
3028 // `Var`, so without this the body got no binding at all — the name resolved to
3029 // the global object and `delete` answered `true` for a binding that cannot be
3030 // deleted. The reference answers `false`.
3031 let mentioned = self.cur().insns.iter().any(|insn| match insn {
3032 Insn::Var {
3033 name, in_params, ..
3034 } => name == "arguments" && !*in_params,
3035 Insn::DeleteVar { name } => name == "arguments",
3036 _ => false,
3037 });
3038 // A mention that resolves to the body's *own* lexical `arguments` is not a request
3039 // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
3040 // implicit binding is not created at all. Providing it anyway was worse than useless:
3041 // its prologue store resolved past the shadowing `let` and landed on the **global**,
3042 // so `function f(p = eval("var arguments")) { let arguments; }` defined
3043 // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
3044 // test262's `fn-body-cntns-arguments-lex-bind` family).
3045 //
3046 // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
3047 // var *is* the binding, and the implicit arguments object is initialised into it at
3048 // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
3049 // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
3050 // `typeof arguments` `"undefined"`.
3051 if self
3052 .cur()
3053 .vars
3054 .iter()
3055 .any(|var| var.name == "arguments" && var.needs_check())
3056 {
3057 return;
3058 }
3059 if !mentioned && !self.cur().needs_arguments_local {
3060 return;
3061 }
3062 // The request may have come only from a parameter-list arrow, in which case the
3063 // parameter scope's binding already answers for it and the body needs none.
3064 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
3065 return;
3066 }
3067 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
3068 //
3069 // With parameter expressions the list and the body are separate environments, so
3070 // an assignment to a parameter cannot be reflected into `arguments` at all — the
3071 // arguments object is unmapped whatever the mode, which is why the reference emits
3072 // `special_object 0` here even in sloppy code.
3073 // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
3074 // object unmapped whatever the mode — §10.4.4 keys the decision on
3075 // `IsSimpleParameterList`, not on strictness alone.
3076 let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
3077 0
3078 } else {
3079 1
3080 };
3081 // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
3082 // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
3083 // The only storage both sides can see is a reference cell, so every parameter the
3084 // object maps gets one — even a parameter no closure captured. Without this the
3085 // slot holds a plain copy and the mapping has nothing to write through.
3086 if magic == 1 {
3087 for arg in &mut self.stack[current].args {
3088 arg.is_captured = true;
3089 }
3090 }
3091 self.prepend_binding("arguments", magic);
3092 }
3093
3094 /// Whether a *body* instruction refers to `arguments`.
3095 fn body_mentions_arguments(&self) -> bool {
3096 self.cur()
3097 .insns
3098 .iter()
3099 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
3100 }
3101
3102 /// Whether the function body's instruction stream refers to `name`.
3103 fn mentions(&self, name: &str) -> bool {
3104 let current = self.stack.len() - 1;
3105 // A binding of the parameter scope does not answer for the body: the body's own
3106 // `arguments` (or self-name) still has to be provided for it.
3107 if self.stack[current]
3108 .vars
3109 .iter()
3110 .enumerate()
3111 .any(|(index, v)| {
3112 v.name == name
3113 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
3114 })
3115 {
3116 return false;
3117 }
3118 self.stack[current]
3119 .insns
3120 .iter()
3121 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
3122 }
3123
3124 /// Bind the name a named function expression uses to refer to itself.
3125 ///
3126 /// The value is `special_object 2`, the function currently running, so the binding
3127 /// is the closure itself and not a copy. It is a local of this function, which is
3128 /// what keeps `g` out of the enclosing scope.
3129 /// Give the function a local `this`, for an arrow inside it to capture.
3130 fn provide_this_local(&mut self) {
3131 let current = self.stack.len() - 1;
3132 if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
3133 return;
3134 }
3135 if !self.stack[current]
3136 .vars
3137 .iter()
3138 .any(|var| var.name == "this")
3139 {
3140 self.declare_hidden_local("this", VarKind::Normal);
3141 }
3142 self.prepend_initialiser(
3143 "this",
3144 Insn::Fixed {
3145 op: Opcode::PushThis,
3146 operands: vec![],
3147 },
3148 );
3149 }
3150
3151 /// Give the function a local `<home_object>`, for an arrow or a static block inside it
3152 /// to read through `super`.
3153 fn provide_home_object_local(&mut self) {
3154 let current = self.stack.len() - 1;
3155 if !self.stack[current].needs_home_object_local {
3156 return;
3157 }
3158 if !self.stack[current]
3159 .vars
3160 .iter()
3161 .any(|var| var.name == HOME_OBJECT)
3162 {
3163 self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
3164 }
3165 self.prepend_initialiser(
3166 HOME_OBJECT,
3167 Insn::Fixed {
3168 op: Opcode::SpecialObject,
3169 operands: vec![Op::Int(4)],
3170 },
3171 );
3172 }
3173
3174 fn provide_self_name(&mut self) {
3175 let current = self.stack.len() - 1;
3176 let Some(name) = self.stack[current].self_name.clone() else {
3177 return;
3178 };
3179 if self.stack[current].self_name_initialized {
3180 return;
3181 }
3182 // Either the body refers to the name, or a nested function already forced the
3183 // binding into existence while being resolved. A direct `eval` can name it
3184 // without mentioning it, so its presence is a third reason: in strict mode
3185 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
3186 // that only happens if the binding exists.
3187 let declared = self.stack[current].vars.iter().any(|v| v.name == name);
3188 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
3189 return;
3190 }
3191 self.stack[current].self_name_initialized = true;
3192 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
3193 }
3194
3195 /// Insert `special_object magic` plus the store to `name` at the top of the body.
3196 ///
3197 /// Prepending shifts every label that has been placed, so they are all moved by
3198 /// the number of instructions inserted.
3199 fn prepend_binding(&mut self, name: &str, magic: i32) {
3200 self.prepend_binding_with(name, magic, VarKind::Normal);
3201 }
3202
3203 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
3204 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
3205 let current = self.stack.len() - 1;
3206 // A function-expression's own name is immutable in strict mode, which is what
3207 // makes `f = 1` inside a strict body throw instead of being dropped.
3208 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
3209 self.declare_var(
3210 name,
3211 VarDef {
3212 kind,
3213 is_const,
3214 ..VarDef::var(name)
3215 },
3216 );
3217 let init = [
3218 Insn::Fixed {
3219 op: Opcode::SpecialObject,
3220 operands: vec![Op::Int(magic)],
3221 },
3222 Insn::Var {
3223 // An initialisation, not an assignment: sloppy mode drops stores to a
3224 // function-expression's own name, and the prologue is what puts the
3225 // value there in the first place.
3226 action: if kind == VarKind::FunctionName {
3227 VarAction::PutInit
3228 } else {
3229 VarAction::Put
3230 },
3231 name: name.to_string(),
3232 block: 0,
3233 in_params: false,
3234 },
3235 ];
3236 let inserted = init.len();
3237 for (index, instruction) in init.into_iter().enumerate() {
3238 self.stack[current].insns.insert(index, instruction);
3239 }
3240 for placed in self.stack[current].labels.iter_mut().flatten() {
3241 *placed += inserted;
3242 }
3243 // A store sits at the insertion point now, so the `put`/`get` fold must not
3244 // reach across it.
3245 self.stack[current].label_since_insn = true;
3246 }
3247
3248 /// Record a top-level script declaration as a global.
3249 ///
3250 /// A script's top-level `var`/`let`/`function` create properties of the
3251 /// global object, not slots in the script's frame, so they show up as closure
3252 /// variables instead.
3253 fn declare_global(&mut self, name: &str, def: &VarDef) {
3254 let state = self.state();
3255 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3256 // The name was already referenced, from a function compiled before this
3257 // declaration was reached — `function a(){ b() } function b(){}` resolves
3258 // `b` while `b` is still unknown, and that guess has to be corrected here.
3259 // Leaving it as a plain global meant the declaration was never registered,
3260 // so the binding did not exist at run time and `a()` threw
3261 // `b is not defined`.
3262 if matches!(existing.closure_type, ClosureType::Global) {
3263 existing.closure_type = ClosureType::GlobalDecl;
3264 existing.is_const = def.is_const;
3265 existing.is_lexical = def.is_lexical;
3266 existing.is_function_decl =
3267 def.kind == crate::bytecode::VarKind::GlobalFunctionDecl;
3268 }
3269 return;
3270 }
3271 state.closure_vars.push(ClosureVar {
3272 name: name.to_string(),
3273 is_const: def.is_const,
3274 is_lexical: def.is_lexical,
3275 is_function_decl: def.kind == crate::bytecode::VarKind::GlobalFunctionDecl,
3276 closure_type: ClosureType::GlobalDecl,
3277 var_idx: 0,
3278 });
3279 }
3280
3281 /// Record a module-level declaration as a module variable.
3282 ///
3283 /// The binding is a closure variable of the module body, so reads and writes are
3284 /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
3285 /// *who fills the cell*: the module record does, before the body runs, and an import
3286 /// points its cell at the exporting module's, which is what makes bindings live and
3287 /// cycles work.
3288 fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
3289 let state = self.state();
3290 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3291 // The name may have been referenced before this declaration was hoisted,
3292 // which resolved it as a plain global. Correct that here, the way
3293 // `declare_global` does.
3294 if matches!(existing.closure_type, ClosureType::Global) {
3295 existing.closure_type = ClosureType::ModuleDecl;
3296 existing.is_const = def.is_const;
3297 existing.is_lexical = def.is_lexical;
3298 }
3299 return 0;
3300 }
3301 state.closure_vars.push(ClosureVar {
3302 name: name.to_string(),
3303 is_const: def.is_const,
3304 is_lexical: def.is_lexical,
3305 is_function_decl: false,
3306 closure_type: ClosureType::ModuleDecl,
3307 var_idx: 0,
3308 });
3309 0
3310 }
3311
3312 /// Declare a module variable and answer its closure-variable index.
3313 ///
3314 /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
3315 /// module variable is not one. The import table needs the real index instead, because
3316 /// that is the position the host writes the cell into.
3317 fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
3318 self.declare_module(name, def);
3319 self.cur()
3320 .closure_vars
3321 .iter()
3322 .position(|c| c.name == name)
3323 .map(|index| index as u32)
3324 .unwrap_or(0)
3325 }
3326
3327 /// Declare one imported binding as a module variable.
3328 ///
3329 /// Returns the closure-variable index, which is what the import table records: the
3330 /// host writes the exporter's cell into that slot before the body runs.
3331 fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
3332 let state = self.state();
3333 if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
3334 // Keep the slot, fix the kind: the name may already have been referenced.
3335 state.closure_vars[index].closure_type = ClosureType::ModuleImport;
3336 state.closure_vars[index].is_const = is_const;
3337 return index as u32;
3338 }
3339 state.closure_vars.push(ClosureVar {
3340 name: name.to_string(),
3341 // An imported binding cannot be assigned: `x = 1` on an import is a
3342 // `TypeError` at run time, which the const flag is what produces.
3343 is_const: true,
3344 // Lexical, so reads go through `get_var_ref_check`: before linking has filled
3345 // the cell an import is in its dead zone, and reading it there must say so
3346 // rather than answer `undefined`.
3347 is_lexical: true,
3348 is_function_decl: false,
3349 closure_type: ClosureType::ModuleImport,
3350 var_idx: 0,
3351 });
3352 state.closure_vars.len() as u32 - 1
3353 }
3354
3355 /// Emit the code an `export` needs.
3356 ///
3357 /// Only `export default <expr>` has any: everything else is a table entry whose
3358 /// binding is declared elsewhere. The expression is stored into the hidden
3359 /// `*default*` variable rather than returned, because the module body has no value
3360 /// to speak of.
3361 fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3362 match &decl.kind {
3363 ExportKind::Declaration(stmt) => self.stmt(stmt),
3364 ExportKind::Default(expr) => {
3365 // `export default class Foo {}`: evaluate the declaration (which binds
3366 // `Foo`), then copy its value into the hidden `*default*` binding, because a
3367 // class declaration is a *statement* and `expr` cannot be compiled as one.
3368 if let ExprKind::Class(class) = &expr.kind
3369 && class.name.is_some()
3370 {
3371 self.stmt(&Stmt {
3372 kind: StmtKind::ClassDecl(class.clone()),
3373 span: expr.span,
3374 })?;
3375 let Some(name) = &class.name else {
3376 return Ok(());
3377 };
3378 self.emit_var(VarAction::Get, &name.name);
3379 let index = self.declare_export_default();
3380 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3381 return Ok(());
3382 }
3383 // A named default function/class is already a module binding; the export
3384 // points at it and there is nothing to evaluate.
3385 if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
3386 return Ok(());
3387 }
3388 self.expr(expr)?;
3389 // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
3390 // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
3391 // name is observable — `imported.default.name` — and without this an
3392 // anonymous `export default class {}` arrived with the empty name.
3393 self.set_name_if_anonymous(expr, &Wtf8::new("default"));
3394 let index = self.declare_export_default();
3395 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3396 Ok(())
3397 }
3398 ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
3399 }
3400 }
3401
3402 /// A module name as the string it denotes.
3403 fn module_name_text(name: &ModuleName) -> &str {
3404 match name {
3405 ModuleName::Ident(ident) => &ident.name,
3406 ModuleName::Str(text) => text,
3407 }
3408 }
3409
3410 /// Bind `import`'s local names and record where each one comes from.
3411 ///
3412 /// Nothing is emitted: an import is not an instruction, it is a promise that the
3413 /// binding's cell will be filled before the body runs. The cell lands in the module's
3414 /// environment at a fixed index, and the host fills it from the exporter's cell —
3415 /// which is why a cyclic import can bind before the other module has evaluated.
3416 fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
3417 let request = self.module_request(&decl.source, &decl.attributes, decl.phase);
3418 for specifier in &decl.specifiers {
3419 let (local, name, is_star) = match specifier {
3420 ImportSpecifier::Default(ident) => {
3421 (ident.name.clone(), "default".to_string(), false)
3422 }
3423 ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3424 ImportSpecifier::Named { imported, local } => (
3425 local.name.clone(),
3426 Self::module_name_text(imported).to_string(),
3427 false,
3428 ),
3429 };
3430 // `import * as ns` is *not* a live binding of another module's variable —
3431 // it is a value of its own, which is why the reference declares it like a
3432 // module variable and the host stores the namespace object in that cell.
3433 let var_idx = if is_star {
3434 // `const`: a namespace object is a value, and the binding is immutable.
3435 self.declare_module_var(&local, &VarDef::constant(local.clone()))
3436 } else {
3437 self.declare_import(&local, true)
3438 };
3439 self.module_meta().imports.push(ImportEntry {
3440 module: request,
3441 name,
3442 var_idx,
3443 is_star,
3444 phase: decl.phase,
3445 });
3446 }
3447 Ok(())
3448 }
3449
3450 /// Record what an `export` offers, declaring the binding it exports.
3451 ///
3452 /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3453 fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3454 match &decl.kind {
3455 ExportKind::Declaration(stmt) => {
3456 // The inner declaration keeps its own hoisting, then every name it binds
3457 // becomes an export of the same name.
3458 self.hoist_stmt(stmt)?;
3459 let mut names = Vec::new();
3460 Self::declared_names(stmt, &mut names);
3461 for name in names {
3462 let var_idx = self.module_binding_index(&name);
3463 self.exports_local(&name, var_idx);
3464 }
3465 }
3466 ExportKind::Default(expr) => {
3467 // The reference puts a default export in a hidden `*default*` variable,
3468 // so `export default function f(){}` can export a *value* while `f` stays
3469 // a binding of the module.
3470 if let ExprKind::Function(func) = &expr.kind
3471 && let Some(name) = &func.name
3472 {
3473 let text = name.name.clone();
3474 self.hoist_stmt(&Stmt {
3475 kind: StmtKind::FuncDecl(func.clone()),
3476 span: expr.span,
3477 })?;
3478 let var_idx = self.module_binding_index(&text);
3479 self.module_meta().exports.push(ExportEntry::Local {
3480 export_name: "default".to_string(),
3481 var_idx,
3482 });
3483 return Ok(());
3484 }
3485 if let ExprKind::Class(class) = &expr.kind
3486 && class.name.is_some()
3487 {
3488 // `export default class Foo {}` binds `Foo` in the module scope **and**
3489 // stores the class into the hidden `*default*` binding — it is a
3490 // declaration *and* a value, unlike `export default class {}` which is
3491 // only a value.
3492 //
3493 // Pointing the `default` export straight at `Foo` looked simpler and was
3494 // wrong twice over: `module_binding_index` did not find the lexical
3495 // binding the hoist had just made, so it declared a second one that
3496 // nothing ever wrote, and `export_stmt` then had no code to emit for the
3497 // declaration either. `imported.default` came out `undefined` and `Foo`
3498 // was not in scope inside its own module.
3499 self.hoist_stmt(&Stmt {
3500 kind: StmtKind::ClassDecl(class.clone()),
3501 span: expr.span,
3502 })?;
3503 let var_idx = self.declare_export_default();
3504 self.exports_local("default", var_idx);
3505 return Ok(());
3506 }
3507 let var_idx = self.declare_export_default();
3508 self.module_meta().exports.push(ExportEntry::Local {
3509 export_name: "default".to_string(),
3510 var_idx,
3511 });
3512 }
3513 ExportKind::Named {
3514 specifiers,
3515 source,
3516 attributes,
3517 } => match source {
3518 Some(source) => {
3519 let request = self.module_request(source, attributes, ImportPhase::Evaluation);
3520 for specifier in specifiers {
3521 self.module_meta().exports.push(ExportEntry::Indirect {
3522 export_name: Self::module_name_text(&specifier.exported).to_string(),
3523 module: request,
3524 import_name: Self::module_name_text(&specifier.local).to_string(),
3525 });
3526 }
3527 }
3528 None => {
3529 for specifier in specifiers {
3530 let local = Self::module_name_text(&specifier.local).to_string();
3531 let export_name = Self::module_name_text(&specifier.exported).to_string();
3532 // `export { x }` where `x` is itself an **import** re-exports the
3533 // binding the import names, not a binding of this module
3534 // (§16.2.1.6.3: a local export whose local name is imported resolves
3535 // through the imported module). Recording it as a local made two
3536 // modules that both forward one import look like two different
3537 // bindings, and the name was reported ambiguous
3538 // (`import-and-export-propagates-binding`;
3539 // `namespace-unambiguous-if-import-star-as-and-export`).
3540 let closure_names: Vec<String> = self
3541 .cur()
3542 .closure_vars
3543 .iter()
3544 .map(|var| var.name.clone())
3545 .collect();
3546 let forwarded = self
3547 .module_meta()
3548 .imports
3549 .iter()
3550 .filter(|entry| {
3551 closure_names
3552 .get(entry.var_idx as usize)
3553 .is_some_and(|name| *name == local)
3554 })
3555 .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3556 .find(|(_, name, is_star)| !is_star || name.is_empty());
3557 if let Some((request, name, is_star)) = forwarded {
3558 // A namespace import has no export *name* of its own; the
3559 // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3560 // which is what the marker below records.
3561 let import_name = if is_star {
3562 "*namespace*".to_string()
3563 } else {
3564 name
3565 };
3566 self.module_meta().exports.push(ExportEntry::Indirect {
3567 export_name,
3568 module: request,
3569 import_name,
3570 });
3571 continue;
3572 }
3573 let var_idx = self.module_binding_index(&local);
3574 self.module_meta().exports.push(ExportEntry::Local {
3575 export_name,
3576 var_idx,
3577 });
3578 }
3579 }
3580 },
3581 ExportKind::All {
3582 source,
3583 exported,
3584 attributes,
3585 } => {
3586 let request = self.module_request(source, attributes, ImportPhase::Evaluation);
3587 match exported {
3588 Some(name) => {
3589 self.module_meta().exports.push(ExportEntry::StarAs {
3590 export_name: Self::module_name_text(name).to_string(),
3591 module: request,
3592 });
3593 }
3594 None => {
3595 self.module_meta()
3596 .exports
3597 .push(ExportEntry::Star { module: request });
3598 }
3599 }
3600 }
3601 }
3602 Ok(())
3603 }
3604
3605 /// The names a declaration binds, which is what `export <decl>` exports.
3606 fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3607 match &stmt.kind {
3608 StmtKind::VarDecl(decl) => {
3609 for declarator in &decl.declarators {
3610 let mut names = Vec::new();
3611 declarator.target.bound_names(&mut names);
3612 out.extend(names.into_iter().map(|name| name.name));
3613 }
3614 }
3615 StmtKind::FuncDecl(func) => {
3616 if let Some(name) = &func.name {
3617 out.push(name.name.clone());
3618 }
3619 }
3620 StmtKind::ClassDecl(class) => {
3621 if let Some(name) = &class.name {
3622 out.push(name.name.clone());
3623 }
3624 }
3625 _ => {}
3626 }
3627 }
3628
3629 /// The closure-variable index of a module binding, declaring it if the name was
3630 /// exported without being declared here.
3631 ///
3632 /// `export { x }` where `x` is not declared in the module is a link-time
3633 /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3634 fn module_binding_index(&mut self, name: &str) -> u32 {
3635 if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3636 return index as u32;
3637 }
3638 self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3639 }
3640
3641 fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3642 self.module_meta().exports.push(ExportEntry::Local {
3643 export_name: export_name.to_string(),
3644 var_idx,
3645 });
3646 }
3647
3648 /// The hidden `*default*` binding `export default <expr>` stores into.
3649 fn declare_export_default(&mut self) -> u32 {
3650 const DEFAULT: &str = "*default*";
3651 if let Some(index) = self
3652 .cur()
3653 .closure_vars
3654 .iter()
3655 .position(|c| c.name == DEFAULT)
3656 {
3657 return index as u32;
3658 }
3659 self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3660 }
3661
3662 /// The module tables, which only the top-level state has.
3663 fn module_meta(&mut self) -> &mut ModuleMeta {
3664 self.state()
3665 .module
3666 .as_mut()
3667 .expect("module tables are only touched while compiling a module")
3668 }
3669
3670 /// The index of `specifier`'s request, adding it if it is new.
3671 ///
3672 /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3673 /// JSON and once as text is two modules with two different contents, which is exactly
3674 /// what `hello_module.js` does.
3675 fn module_request(
3676 &mut self,
3677 specifier: &str,
3678 attributes: &[ImportAttribute],
3679 phase: ImportPhase,
3680 ) -> u32 {
3681 let attributes: Vec<(String, String)> = attributes
3682 .iter()
3683 .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3684 .collect();
3685 let meta = self.module_meta();
3686 // De-duplicated on the specifier *and* the phase: one module can be asked for twice,
3687 // once eagerly and once deferred, and the two answers are different objects.
3688 if let Some(index) = meta.requests.iter().position(|request| {
3689 request.specifier == specifier
3690 && request.attributes == attributes
3691 && request.phase == phase
3692 }) {
3693 return index as u32;
3694 }
3695 meta.requests.push(ModuleRequest {
3696 specifier: specifier.to_string(),
3697 attributes,
3698 phase,
3699 });
3700 meta.requests.len() as u32 - 1
3701 }
3702
3703 /// Compile a loop body with a `break`/`continue` target pushed for it.
3704 fn loop_body(
3705 &mut self,
3706 body: &Stmt,
3707 labels: &[String],
3708 continue_label: Label,
3709 break_label: Label,
3710 ) -> Result<(), SyntaxError> {
3711 self.push_jump_target(JumpTarget {
3712 names: labels.to_vec(),
3713 break_label: Some(break_label),
3714 continue_label: Some(continue_label),
3715 // A loop leaves nothing of its own on the value stack.
3716 drop_count: 0,
3717 finally_label: None,
3718 is_regular_stmt: false,
3719 has_iterator: false,
3720 is_async_iterator: false,
3721 });
3722 let result = self.stmt(body);
3723 self.pop_jump_target();
3724 result
3725 }
3726
3727 fn push_jump_target(&mut self, target: JumpTarget) {
3728 self.state().jump_targets.push(target);
3729 }
3730
3731 fn pop_jump_target(&mut self) {
3732 self.state().jump_targets.pop();
3733 }
3734
3735 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3736 let (label, is_break) = match &stmt.kind {
3737 StmtKind::Break(label) => (label.as_ref(), true),
3738 StmtKind::Continue(label) => (label.as_ref(), false),
3739 _ => unreachable!("control_transfer is only called for break and continue"),
3740 };
3741
3742 // Walk outward from the innermost construct. Everything considered before
3743 // the match is a construct control is leaving, and leaving it has a cost:
3744 // its stack slots go, and its finalizer runs.
3745 let targets = self.cur().jump_targets.clone();
3746 for target in targets.iter().rev() {
3747 let destination = match (label, is_break) {
3748 // An unlabelled `break` skips a labelled non-loop statement: `break`
3749 // may name one, but the bare form only means "leave the loop".
3750 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3751 (None, false) => target.continue_label,
3752 (Some(name), true) => target
3753 .break_label
3754 .filter(|_| target.names.contains(&name.name)),
3755 (Some(name), false) => target
3756 .continue_label
3757 .filter(|_| target.names.contains(&name.name)),
3758 };
3759
3760 if let Some(destination) = destination {
3761 self.emit_jump(Opcode::Goto, destination, &[]);
3762 return Ok(());
3763 }
3764
3765 // Closing the iterator consumes the three slots the loop keeps on the
3766 // stack (iterator, next method, catch offset), so those are not dropped
3767 // again below.
3768 let mut remaining = target.drop_count;
3769 if target.has_iterator {
3770 self.emit_iterator_close(target.is_async_iterator, false);
3771 remaining = remaining.saturating_sub(3);
3772 }
3773 for _ in 0..remaining {
3774 self.emit(Opcode::Drop, &[]);
3775 }
3776 if let Some(finally) = target.finally_label {
3777 // The finalizer runs as a subroutine and is handed a dummy return
3778 // value, which is dropped afterwards to keep the stack the depth it
3779 // had before.
3780 self.emit(Opcode::Undefined, &[]);
3781 self.emit_jump(Opcode::Gosub, finally, &[]);
3782 self.emit(Opcode::Drop, &[]);
3783 }
3784 }
3785
3786 // The parser rejects a break/continue with no target, so reaching here
3787 // means the compiler's own bookkeeping is wrong.
3788 Err(SyntaxError::new(
3789 if is_break {
3790 "break has no enclosing loop or switch"
3791 } else {
3792 "continue has no enclosing loop"
3793 },
3794 stmt.span,
3795 ))
3796 }
3797
3798 /// Compile a labelled statement.
3799 ///
3800 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3801 /// that loop's targets, so the chain is collected and handed to the loop. A
3802 /// label on a non-loop statement only provides a `break` target, because
3803 /// `continue` may not target it.
3804 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3805 let mut names = vec![label.name.clone()];
3806 let mut inner = body;
3807 while let StmtKind::Labeled {
3808 label: next,
3809 body: deeper,
3810 } = &inner.kind
3811 {
3812 names.push(next.name.clone());
3813 inner = deeper;
3814 }
3815 if Self::is_loop(inner) {
3816 return self.stmt_labelled(inner, &names);
3817 }
3818 let end = self.new_label();
3819 self.push_jump_target(JumpTarget {
3820 names,
3821 break_label: Some(end),
3822 continue_label: None,
3823 drop_count: 0,
3824 finally_label: None,
3825 is_regular_stmt: true,
3826 has_iterator: false,
3827 is_async_iterator: false,
3828 });
3829 let result = self.stmt(inner);
3830 self.pop_jump_target();
3831 result?;
3832 self.place_label(end);
3833 let _ = stmt;
3834 Ok(())
3835 }
3836
3837 /// Whether a statement is a loop, i.e. a valid target for `continue`.
3838 fn is_loop(stmt: &Stmt) -> bool {
3839 matches!(
3840 stmt.kind,
3841 StmtKind::While { .. }
3842 | StmtKind::DoWhile { .. }
3843 | StmtKind::For { .. }
3844 | StmtKind::ForIn { .. }
3845 | StmtKind::ForOf { .. }
3846 )
3847 }
3848
3849 /// Compile `switch`.
3850 ///
3851 /// The discriminant is evaluated once and stays on the value stack while the
3852 /// clauses compare against copies of it, so it is dropped at the end — which is
3853 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3854 /// clause's body jumps over the *next* clause's tests straight into its body.
3855 ///
3856 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3857 /// the next run's tests. Only the last run's miss reaches the `default` body, or
3858 /// the end of the switch when there is no `default`. That failure path can point
3859 /// backwards (`default` written first), so the runs and their labels are worked
3860 /// out before any code is emitted.
3861 fn switch(
3862 &mut self,
3863 discriminant: &Expr,
3864 cases: &[SwitchCase],
3865 stmt: &Stmt,
3866 ) -> Result<(), SyntaxError> {
3867 self.reset_value();
3868 // The discriminant is evaluated outside the switch's block scope, before
3869 // any `case` clause exists.
3870 self.expr(discriminant)?;
3871
3872 let switch_key = stmt.span.start.offset as u64;
3873 let switch_parent = self.cur().current_block;
3874 self.push_block(switch_key, switch_parent);
3875 self.emit_scope_enter(switch_key);
3876
3877 let break_label = self.new_label();
3878 self.push_jump_target(JumpTarget {
3879 names: Vec::new(),
3880 break_label: Some(break_label),
3881 // `switch` is a valid `break` target but not a `continue` target.
3882 continue_label: None,
3883 // The discriminant stays on the value stack for the whole statement, so
3884 // a `break` aimed further out has to discard it.
3885 drop_count: 1,
3886 finally_label: None,
3887 is_regular_stmt: false,
3888 has_iterator: false,
3889 is_async_iterator: false,
3890 });
3891
3892 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3893 // its label to the clause after it, so both tests reach the same body.
3894 let mut runs: Vec<(usize, usize)> = Vec::new();
3895 let mut scan = 0;
3896 while scan < cases.len() {
3897 if cases[scan].test.is_some() {
3898 let mut last = scan;
3899 while last + 1 < cases.len()
3900 && cases[last].test.is_some()
3901 && cases[last].body.is_empty()
3902 && cases[last + 1].test.is_some()
3903 {
3904 last += 1;
3905 }
3906 runs.push((scan, last));
3907 scan = last + 1;
3908 } else {
3909 scan += 1;
3910 }
3911 }
3912
3913 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3914 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3915 let default_at = cases.iter().position(|case| case.test.is_none());
3916 // Where the last run sends control when nothing matched.
3917 let miss_target = match default_at {
3918 Some(index) => body_labels[index],
3919 None => break_label,
3920 };
3921
3922 // When `default` comes first, control has to jump over it to reach the
3923 // tests. It only needs to when some clause actually has a test; otherwise
3924 // the default body is the entry point.
3925 let mut entry = None;
3926 if default_at == Some(0) && !runs.is_empty() {
3927 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3928 entry = Some(run_labels[0]);
3929 }
3930
3931 let mut index = 0;
3932 let mut run = 0;
3933 let result = (|| -> Result<(), SyntaxError> {
3934 while index < cases.len() {
3935 if cases[index].test.is_some() {
3936 let (first, last) = runs[run];
3937 // Reaching these tests from the preceding body is a
3938 // fallthrough, which continues inside the body and skips them.
3939 if index > 0 {
3940 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3941 }
3942 if let Some(label) = entry.take() {
3943 self.place_label(label);
3944 }
3945 self.place_label(run_labels[run]);
3946
3947 for (offset, case) in cases[first..=last].iter().enumerate() {
3948 let test = case.test.as_ref().unwrap();
3949 self.emit(Opcode::Dup, &[]);
3950 self.expr(test)?;
3951 self.emit(Opcode::StrictEq, &[]);
3952 if first + offset < last {
3953 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3954 } else {
3955 // Hand over to the next run's tests, or give up.
3956 let next = match runs.get(run + 1) {
3957 Some(_) => run_labels[run + 1],
3958 None => miss_target,
3959 };
3960 self.emit_jump(Opcode::IfFalse, next, &[]);
3961 }
3962 }
3963
3964 self.place_label(body_labels[index]);
3965 for case in &cases[first..=last] {
3966 self.stmts(&case.body)?;
3967 }
3968 index = last + 1;
3969 run += 1;
3970 } else {
3971 // `default`: control arrives here either by falling through or
3972 // because every test missed.
3973 self.place_label(body_labels[index]);
3974 self.stmts(&cases[index].body)?;
3975 index += 1;
3976 }
3977 }
3978 Ok(())
3979 })();
3980
3981 if result.is_ok() {
3982 self.place_label(break_label);
3983 // Discard the discriminant now that no test needs it.
3984 self.emit(Opcode::Drop, &[]);
3985 }
3986
3987 self.pop_jump_target();
3988 self.emit_scope_leave(switch_key);
3989 self.state().current_block = switch_parent;
3990 result
3991 }
3992
3993 /// Compile `try`/`catch`/`finally`.
3994 ///
3995 /// The shape is an exception table built out of `catch` instructions, each of
3996 /// which records where control goes if the instructions that follow raise:
3997 ///
3998 /// ```text
3999 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
4000 /// <guarded block>
4001 /// drop <- discard the catch offset
4002 /// undefined; gosub FINALLY; drop
4003 /// goto END
4004 /// HANDLER:
4005 /// <bind the catch parameter>
4006 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
4007 /// <handler body>
4008 /// drop; undefined; gosub FINALLY; drop; goto END
4009 /// CATCH2:
4010 /// gosub FINALLY; throw <- run the finalizer, then let the error out
4011 /// FINALLY:
4012 /// <finalizer>
4013 /// ret <- return to the `gosub`
4014 /// END:
4015 /// ```
4016 ///
4017 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
4018 /// of the finalizer serves the normal path, the handler path and the
4019 /// propagating-exception path.
4020 ///
4021 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
4022 /// runs with `ret_value` on the stack, and the normal path has no value to
4023 /// keep, so it pushes one to keep the stack depth identical on every path.
4024 fn try_stmt(
4025 &mut self,
4026 stmt: &Stmt,
4027 block: &[Stmt],
4028 handler: &Option<CatchClause>,
4029 finalizer: Option<&[Stmt]>,
4030 ) -> Result<(), SyntaxError> {
4031 self.reset_value();
4032
4033 let catch_label = self.new_label();
4034 let catch2_label = self.new_label();
4035 let finally_label = self.new_label();
4036 let end_label = self.new_label();
4037
4038 self.emit_jump(Opcode::Catch, catch_label, &[]);
4039
4040 // The guarded block. `break` may not target it, so its entry exists purely
4041 // to unwind: a jump out has to discard the catch offset and run the
4042 // finalizer.
4043 self.push_jump_target(JumpTarget {
4044 names: Vec::new(),
4045 break_label: None,
4046 continue_label: None,
4047 drop_count: 1,
4048 finally_label: Some(finally_label),
4049 is_regular_stmt: false,
4050 has_iterator: false,
4051 is_async_iterator: false,
4052 });
4053
4054 let block_key = Self::try_block_key(stmt, TryPart::Block);
4055 let block_parent = self.cur().current_block;
4056 self.push_block(block_key, block_parent);
4057 self.emit_scope_enter(block_key);
4058 self.stmts(block)?;
4059 self.emit_scope_leave(block_key);
4060 self.state().current_block = block_parent;
4061 // A guarded block that ends in a `return`/`throw` never reaches the
4062 // epilogue, so the reference does not emit one.
4063 self.pop_jump_target();
4064 let block_live = !block.last().is_some_and(Self::terminates);
4065
4066 if block_live {
4067 self.emit(Opcode::Drop, &[]);
4068 self.emit(Opcode::Undefined, &[]);
4069 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4070 self.emit(Opcode::Drop, &[]);
4071 self.emit_jump(Opcode::Goto, end_label, &[]);
4072 }
4073
4074 if let Some(handler) = handler {
4075 self.place_label(catch_label);
4076 // The thrown value is on top of the stack: bind it, or discard it for
4077 // `catch { }`.
4078 match &handler.param {
4079 Some(pattern) => {
4080 // The stores resolve the names, so they have to run inside the
4081 // parameter's own scope; otherwise a same-named `catch` further out
4082 // could win. A `catch` binding is never in the dead zone, so the store
4083 // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
4084 let param_key = Self::try_block_key(stmt, TryPart::Param);
4085 let param_parent = self.cur().current_block;
4086 self.push_block(param_key, param_parent);
4087 self.destructure(pattern, Some(VarDeclKind::Var))?;
4088 self.state().current_block = param_parent;
4089 }
4090 None => self.emit(Opcode::Drop, &[]),
4091 }
4092 self.emit_jump(Opcode::Catch, catch2_label, &[]);
4093
4094 self.push_jump_target(JumpTarget {
4095 names: Vec::new(),
4096 break_label: None,
4097 continue_label: None,
4098 drop_count: 1,
4099 finally_label: Some(finally_label),
4100 is_regular_stmt: false,
4101 has_iterator: false,
4102 is_async_iterator: false,
4103 });
4104 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
4105 let catch_parent = self.cur().current_block;
4106 self.push_block(catch_key, catch_parent);
4107 self.emit_scope_enter(catch_key);
4108 self.stmts(&handler.body)?;
4109 self.emit_scope_leave(catch_key);
4110 self.state().current_block = catch_parent;
4111 self.pop_jump_target();
4112 let handler_live = !handler.body.last().is_some_and(Self::terminates);
4113
4114 if handler_live {
4115 self.emit(Opcode::Drop, &[]);
4116 self.emit(Opcode::Undefined, &[]);
4117 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4118 self.emit(Opcode::Drop, &[]);
4119 self.emit_jump(Opcode::Goto, end_label, &[]);
4120 }
4121
4122 // An error raised inside the handler still has to run the finalizer.
4123 self.place_label(catch2_label);
4124 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4125 self.emit(Opcode::Throw, &[]);
4126 } else {
4127 // `try`/`finally` with no handler: the finalizer runs, then the error
4128 // keeps propagating.
4129 self.place_label(catch_label);
4130 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4131 self.emit(Opcode::Throw, &[]);
4132 }
4133
4134 self.place_label(finally_label);
4135 // Inside the finalizer, leaving has a different cost: the return value and
4136 // the `gosub` return address are both on the stack, and neither finalizer nor
4137 // any outer one may run before the block has finished.
4138 self.push_jump_target(JumpTarget {
4139 names: Vec::new(),
4140 break_label: None,
4141 continue_label: None,
4142 drop_count: 2,
4143 finally_label: None,
4144 is_regular_stmt: false,
4145 has_iterator: false,
4146 is_async_iterator: false,
4147 });
4148 // §14.15.3 step 7: a finalizer that completes **normally** is discarded — the
4149 // `try` block's completion is what the statement answers. Only an abrupt exit from
4150 // the finalizer (`break`, `return`, a throw) replaces it, and that path jumps out
4151 // before the restore below.
4152 //
4153 // Without this the finalizer's last expression statement won: `eval('4; try { }
4154 // catch { } finally { 5; }')` answered `5` where the spec says `undefined`
4155 // (`cptn-finally-skip-catch`, `completion-values`).
4156 let saved_completion = if finalizer.is_some() && self.completion_slot().is_some() {
4157 self.declare_hidden_local("<finally.ret>", VarKind::Normal);
4158 self.emit_var(VarAction::Get, "<ret>");
4159 self.emit_var(VarAction::Put, "<finally.ret>");
4160 // And the body starts from *empty*, because an abrupt exit from the finalizer
4161 // keeps whatever the finalizer itself produced: `finally { break; }` answers
4162 // `undefined`, not the `try` block's value, while `finally { 42; break; }`
4163 // answers `42`. §14.15.3's `UpdateEmpty(F, undefined)` is what fills the empty
4164 // one in.
4165 self.emit(Opcode::Undefined, &[]);
4166 self.emit_var(VarAction::Put, "<ret>");
4167 true
4168 } else {
4169 false
4170 };
4171 if let Some(finalizer) = finalizer {
4172 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
4173 let finally_parent = self.cur().current_block;
4174 self.push_block(finally_key, finally_parent);
4175 self.emit_scope_enter(finally_key);
4176 self.stmts(finalizer)?;
4177 self.emit_scope_leave(finally_key);
4178 self.state().current_block = finally_parent;
4179 }
4180 if saved_completion {
4181 // The finalizer's own statements have already run, so restoring now is what
4182 // discards a normal completion.
4183 self.emit_var(VarAction::Get, "<finally.ret>");
4184 self.emit_var(VarAction::Put, "<ret>");
4185 }
4186 self.pop_jump_target();
4187 self.emit(Opcode::Ret, &[]);
4188 self.place_label(end_label);
4189 Ok(())
4190 }
4191
4192 /// The slot of the completion-value local, when this body has one.
4193 ///
4194 /// Only a script or `eval` body has `<ret>`: a function's completion value is not
4195 /// observable, so there is nothing to keep.
4196 fn completion_slot(&self) -> Option<u32> {
4197 self.cur()
4198 .vars
4199 .iter()
4200 .position(|var| var.name == "<ret>")
4201 .map(|index| index as u32)
4202 }
4203
4204 /// Compile `for`/`in` and `for`/`of`.
4205 ///
4206 /// Both keep an enumeration record on the value stack for the whole loop, which
4207 /// is what makes leaving early expensive: the record has to be dropped, or the
4208 /// iterator closed. The layout is
4209 ///
4210 /// ```text
4211 /// <iterated expression>
4212 /// for_in_start | for_of_start <- pushes the record
4213 /// goto TEST
4214 /// NEXT:
4215 /// <bind the loop variable>
4216 /// <body>
4217 /// TEST:
4218 /// for_in_next | for_of_next 0
4219 /// if_false NEXT <- not finished: next iteration
4220 /// drop <- finished: discard the leftover value
4221 /// BREAK:
4222 /// drop | iterator_close <- the one cleanup `break` also uses
4223 /// ```
4224 ///
4225 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
4226 /// normal exit share one copy — which is why `break` inside the loop emits nothing
4227 /// of its own, and only a jump that passes *through* the loop pays for its record.
4228 fn for_in_of(
4229 &mut self,
4230 stmt: &Stmt,
4231 left: &ForHead,
4232 right: &Expr,
4233 body: &Stmt,
4234 kind: ForLoopKind,
4235 labels: &[String],
4236 ) -> Result<(), SyntaxError> {
4237 self.reset_value();
4238
4239 let loop_key = stmt.span.start.offset as u64;
4240 let loop_parent = self.cur().current_block;
4241 self.push_block(loop_key, loop_parent);
4242 self.emit_scope_enter(loop_key);
4243
4244 // The iterated expression is evaluated inside the loop's scope, after the
4245 // bindings exist in the temporal dead zone.
4246 self.expr(right)?;
4247
4248 let next = self.new_label();
4249 let test = self.new_label();
4250 let break_target = self.new_label();
4251
4252 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
4253 match kind {
4254 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
4255 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
4256 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
4257 }
4258 self.emit_jump(Opcode::Goto, test, &[]);
4259
4260 self.push_jump_target(JumpTarget {
4261 // `outer: for (x of xs) … break outer` needs the name here. Without it the
4262 // loop had no label to break to, and the compiler reported "break has no
4263 // enclosing loop" for a loop that was plainly enclosing it.
4264 names: labels.to_vec(),
4265 break_label: Some(break_target),
4266 continue_label: Some(test),
4267 // Passing through the loop has to dispose of its record. A `for`/`of`
4268 // record is three slots, and closing the iterator consumes all of them.
4269 drop_count: if has_iterator { 3 } else { 1 },
4270 finally_label: None,
4271 is_regular_stmt: false,
4272 has_iterator,
4273 is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
4274 });
4275
4276 self.place_label(next);
4277 self.bind_loop_variable(left)?;
4278
4279 // The reference marks the body with its own label here. Nothing jumps to it
4280 // once the loop is laid out, but it is not decoration: a label between the
4281 // store and the body is why `put_loc v; get_loc v` does *not* fold into
4282 // `set_loc v` when the body starts by reading the loop variable.
4283 let body_label = self.new_label();
4284 self.place_label(body_label);
4285 // `for (using x of …)` disposes once per iteration, so the body is a disposal
4286 // region rather than the whole loop: the resource is the element that this
4287 // iteration produced.
4288 let using_head = match left {
4289 ForHead::VarDecl(decl) if decl.kind.is_using() => {
4290 let slot =
4291 decl.declarators
4292 .first()
4293 .and_then(|declarator| match &declarator.target.kind {
4294 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
4295 _ => None,
4296 });
4297 slot.map(|slot| (slot, decl.kind == VarDeclKind::AwaitUsing))
4298 }
4299 _ => None,
4300 };
4301 match using_head {
4302 Some((slot, awaited)) => {
4303 let live = !Self::terminates(body);
4304 self.using_region_around(slot, live, awaited, |compiler| compiler.stmt(body))?;
4305 }
4306 None => self.stmt(body)?,
4307 }
4308
4309 // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
4310 // binding each iteration**, so a closure the body creates keeps that iteration's
4311 // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
4312 // a new reference cell holding the current value.
4313 //
4314 // The position is the *end* of the body, not the start: closing before the body
4315 // would leave the closures pointing at the cell the next `put_loc` overwrites, and
4316 // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
4317 for name in Self::loop_binding_names(left) {
4318 let pos = self.cur().cur_pos;
4319 self.state().insns.push(Insn::CloseCaptured {
4320 name,
4321 block: loop_key,
4322 });
4323 self.state().insn_pos.push(pos);
4324 }
4325 self.place_label(test);
4326 match kind {
4327 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
4328 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
4329 ForLoopKind::AwaitOf => {
4330 // The reference's shape: step, `await` the result, then unpack it.
4331 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
4332 self.emit(Opcode::Await, &[]);
4333 self.state().has_await = true;
4334 self.emit(Opcode::IteratorGetValueDone, &[]);
4335 }
4336 }
4337 self.emit_jump(Opcode::IfFalse, next, &[]);
4338 // The loop is finished; `for_xx_next` left an `undefined` behind.
4339 self.emit(Opcode::Drop, &[]);
4340
4341 self.pop_jump_target();
4342 self.place_label(break_target);
4343 if has_iterator {
4344 // A loop that ran to completion finds its iterator slot already cleared (see
4345 // `iterator_get_value_done`), so this closes only an iterator abandoned by a
4346 // `break` that jumped here.
4347 self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
4348 } else {
4349 self.emit(Opcode::Drop, &[]);
4350 }
4351
4352 self.emit_scope_leave(loop_key);
4353 self.state().current_block = loop_parent;
4354 Ok(())
4355 }
4356
4357 /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
4358 /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
4359 fn loop_binding_names(left: &ForHead) -> Vec<String> {
4360 let ForHead::VarDecl(decl) = left else {
4361 return Vec::new();
4362 };
4363 if decl.kind == VarDeclKind::Var {
4364 return Vec::new();
4365 }
4366 let mut names = Vec::new();
4367 for declarator in &decl.declarators {
4368 let mut idents = Vec::new();
4369 declarator.target.bound_names(&mut idents);
4370 names.extend(idents.into_iter().map(|ident| ident.name));
4371 }
4372 names
4373 }
4374
4375 /// Store the value `for_xx_next` left on the stack into the loop variable.
4376 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
4377 // A declaration *initialises* the binding, which is what takes a `let` out of
4378 // the temporal dead zone, so the store is the unchecked form. Assigning to a
4379 // binding declared elsewhere is an ordinary write and keeps its check.
4380 let (pattern, action) = match left {
4381 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
4382 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
4383 };
4384 match &pattern.kind {
4385 PatternKind::Ident(name) => {
4386 // `for (using x of …)` validates and snapshots each iteration's value
4387 // before the body runs, which is what makes a non-disposable element fail
4388 // on the iteration that produced it rather than at the end of the loop.
4389 if let ForHead::VarDecl(decl) = left
4390 && decl.kind.is_using()
4391 {
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 }
4401 self.emit_var(action, &name.name);
4402 Ok(())
4403 }
4404 // Every other target stores through the same path an assignment pattern
4405 // uses, which is what makes `for (a[0] in obj)` write each key into the
4406 // property instead of refusing the loop outright.
4407 _ => self.destructure(
4408 pattern,
4409 match left {
4410 ForHead::VarDecl(decl) => Some(decl.kind),
4411 ForHead::Assign(_) => None,
4412 },
4413 ),
4414 }
4415 }
4416
4417 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
4418 for declarator in &decl.declarators {
4419 let Some(init) = &declarator.init else {
4420 // `var x;` stays `undefined`. A lexical binding is different: it
4421 // has to be *initialised* to leave the temporal dead zone, so the
4422 // compiler supplies an explicit `undefined`.
4423 if decl.kind.is_lexical() {
4424 // A lexical binding has to be *initialised* to leave the temporal
4425 // dead zone, and a destructuring one is no different — `let {a}`
4426 // with no initialiser is a syntax error, but `let [a] = []` still
4427 // needs `a` to be initialised from an empty source, which the
4428 // pattern does on its own.
4429 self.emit(Opcode::Undefined, &[]);
4430 self.destructure(&declarator.target, Some(decl.kind))?;
4431 }
4432 continue;
4433 };
4434 match &declarator.target.kind {
4435 PatternKind::Ident(name) => {
4436 self.expr(init)?;
4437 self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
4438 if decl.kind.is_using() {
4439 // `using_check` validates the value and snapshots its dispose
4440 // method: `value -> value, method`. The snapshot is what makes a
4441 // later change to `Symbol.dispose` irrelevant, and validating here
4442 // is what keeps the body from running at all when the value is not
4443 // disposable.
4444 let method_slot = self
4445 .using_method_slot(&name.name)
4446 .expect("a using binding was declared during hoisting");
4447 self.emit(
4448 Opcode::UsingCheck,
4449 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4450 );
4451 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4452 self.emit_var(VarAction::PutInit, &name.name);
4453 continue;
4454 }
4455 // A declaration statement produces no value, so nothing is
4456 // duplicated onto the stack.
4457 match decl.kind {
4458 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
4459 _ => self.emit_var(VarAction::PutInit, &name.name),
4460 }
4461 }
4462 _ => {
4463 // A destructuring declaration keeps nothing on the stack: the
4464 // pattern consumes the initialiser.
4465 self.expr(init)?;
4466 self.destructure(&declarator.target, Some(decl.kind))?;
4467 }
4468 }
4469 }
4470 Ok(())
4471 }
4472
4473 /// Bind a destructuring pattern from the value on top of the stack.
4474 ///
4475 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4476 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4477 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4478 /// *assignment*, where a member expression is a legal target and the store is an
4479 /// ordinary property write.
4480 ///
4481 /// The value is consumed. An assignment expression's own result is the right-hand
4482 /// side, which the caller keeps separately — the spec does not make the pattern's
4483 /// last store produce it.
4484 fn destructure(
4485 &mut self,
4486 pattern: &Pattern,
4487 decl: Option<VarDeclKind>,
4488 ) -> Result<(), SyntaxError> {
4489 match &pattern.kind {
4490 PatternKind::Ident(name) => {
4491 match decl {
4492 Some(VarDeclKind::Var) | None => {
4493 self.emit_var(VarAction::Put, &name.name);
4494 }
4495 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4496 }
4497 Ok(())
4498 }
4499 PatternKind::Assign { target, default } => {
4500 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4501 // keeps `null`.
4502 //
4503 // The shape is the reference's: test for `undefined`, and when the value is
4504 // present fall **through** to a single store both paths share. The
4505 // alternatives — branching to the store on each side — need a second store
4506 // and a jump between them, which is what the dump used to show.
4507 let has_value = self.new_label();
4508 self.emit(Opcode::Dup, &[]);
4509 self.emit(Opcode::IsUndefined, &[]);
4510 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4511 self.emit(Opcode::Drop, &[]);
4512 self.expr(default)?;
4513 // `var {f = function(){}} = {}` names the function `f`, like a plain
4514 // `var f = function(){}` does. Both pattern forms do it:
4515 // `BindingInitialization` names the value for a *binding* target, and since
4516 // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4517 // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4518 // no name to give, which is why only an identifier qualifies.
4519 if let PatternKind::Ident(name) = &target.kind {
4520 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4521 }
4522 self.place_label(has_value);
4523 self.destructure(target, decl)
4524 }
4525 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4526 PatternKind::Object { properties, rest } => {
4527 self.destructure_object(properties, rest, decl, pattern)
4528 }
4529 PatternKind::Member(member) if decl.is_none() => {
4530 // An assignment pattern may store into a property. The value is on the
4531 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4532 // put the three in the order `put_array_el`/`put_field` expect.
4533 self.expr(&member.object)?;
4534 match &member.property {
4535 MemberProp::Ident(name) => {
4536 // `value obj` -> `obj value`, the order `put_field` takes.
4537 // Nothing needs to be left behind: a pattern element's value is
4538 // consumed by its own store.
4539 self.emit(Opcode::Swap, &[]);
4540 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4541 }
4542 MemberProp::Computed(index) => {
4543 self.expr(index)?;
4544 // `value obj key` -> `obj key value`.
4545 self.emit(Opcode::Rot3l, &[]);
4546 self.emit(Opcode::PutArrayEl, &[]);
4547 }
4548 MemberProp::Private(name) => {
4549 // `value obj` -> `obj value`, and the store half of the assignment is
4550 // the same one `obj.#x = value` uses — only without `insert2`,
4551 // because a pattern element's value is not wanted back.
4552 let binding = format!("#{}", name.name);
4553 let (kind, setter) = self.private_use(&binding, member.span)?;
4554 self.emit(Opcode::Swap, &[]);
4555 self.private_store(&binding, kind, setter.as_deref())?;
4556 }
4557 }
4558 Ok(())
4559 }
4560 PatternKind::Rest(inner) => self.destructure(inner, decl),
4561 PatternKind::Invalid(expr) => {
4562 Err(SyntaxError::new("invalid assignment target", expr.span))
4563 }
4564 _ => Err(SyntaxError::new(
4565 "this destructuring target is not supported by the compiler yet",
4566 pattern.span,
4567 )),
4568 }
4569 }
4570
4571 /// `[…]` on the left: drain an iterator, binding one target per element.
4572 ///
4573 /// A target that stores into a **property** — `[o.p] = it` — has its reference worked
4574 /// out *before* the value is pulled. That ordering is observable twice over
4575 /// (`array-elem-iter-thrw-close`):
4576 ///
4577 /// * `next` must not have been called yet when the reference throws, so
4578 /// `[ {}[thrower()] ] = iterable` reports `nextCount === 0`;
4579 /// * the iterator must still be closed, because the throw happens while the record is
4580 /// live — which is `catch_here`'s `catch_offset 0` doing its work.
4581 ///
4582 /// Doing it the other way round — pull the value, then evaluate the reference — got
4583 /// both wrong: an extra `next` call, and, when the reference threw, an iterator that had
4584 /// already been drained past.
4585 fn destructure_array(
4586 &mut self,
4587 elements: &[Option<PatternElement>],
4588 rest: &Option<Box<RestElement>>,
4589 decl: Option<VarDeclKind>,
4590 ) -> Result<(), SyntaxError> {
4591 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4592 // pattern accepts any iterable and closes the iterator when the pattern ends
4593 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4594 // first because it is on top.
4595 //
4596 // It also counts as an open iterator for `return` and `break`: a pattern is not a
4597 // loop, but the record is live across everything the pattern evaluates, so
4598 // `function* g(){ [ {} = yield ] = it }` resumed with `return()` has to close it
4599 // (`array-elem-iter-rtrn-close`). `emit_unwind_for_return` finds it by this entry
4600 // and `nip_catch` uncovers exactly the `iter next` pairs it left behind.
4601 //
4602 // A `break`/`continue` cannot occur inside a pattern, so `names` and both labels
4603 // are empty and `drop_count` — read only by that unreachable path — keeps the
4604 // reference's 2.
4605 self.push_jump_target(JumpTarget {
4606 names: Vec::new(),
4607 break_label: None,
4608 continue_label: None,
4609 drop_count: 2,
4610 finally_label: None,
4611 is_regular_stmt: false,
4612 has_iterator: true,
4613 is_async_iterator: false,
4614 });
4615 self.emit(Opcode::ForOfStart, &[]);
4616 for element in elements {
4617 match element {
4618 Some(PatternElement::Pattern(pattern)) => {
4619 match Self::member_element_target(pattern, decl) {
4620 // A prepared reference sits above the record, so `for_of_next` is
4621 // told how many values are in the way.
4622 Some(member) => {
4623 let extra = self.prepare_member_target(member)?;
4624 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4625 self.emit(Opcode::Drop, &[]);
4626 self.destructure_prepared(pattern, member)?;
4627 }
4628 None => {
4629 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4630 self.emit(Opcode::Drop, &[]);
4631 self.destructure(pattern, decl)?;
4632 }
4633 }
4634 }
4635 Some(PatternElement::Property { span, .. }) => {
4636 return Err(SyntaxError::new(
4637 "a property pattern is not a valid array element",
4638 *span,
4639 ));
4640 }
4641 // An elision skips the value, which is already on the stack.
4642 None => {
4643 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4644 self.emit(Opcode::Drop, &[]);
4645 self.emit(Opcode::Drop, &[]);
4646 }
4647 }
4648 }
4649 if let Some(rest) = rest {
4650 // The remaining values go into a fresh array. The target and its running
4651 // index stay on the stack above the iterator, which is what the operand of
4652 // `for_of_next` accounts for: two values sit above the iterator triple.
4653 let prepared = match decl {
4654 None => Self::member_rest_target(rest),
4655 // A binding pattern cannot store into a property.
4656 Some(_) => None,
4657 };
4658 let extra = match prepared {
4659 Some(member) => 2 + self.prepare_member_target(member)?,
4660 None => 2,
4661 };
4662 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4663 self.emit(Opcode::Push0, &[]);
4664 let top = self.new_label();
4665 self.place_label(top);
4666 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4667 let done = self.new_label();
4668 self.emit_jump(Opcode::IfTrue, done, &[]);
4669 self.emit(Opcode::DefineArrayEl, &[]);
4670 self.emit(Opcode::Inc, &[]);
4671 self.emit_jump(Opcode::Goto, top, &[]);
4672 self.place_label(done);
4673 self.emit(Opcode::Drop, &[]);
4674 self.emit(Opcode::Drop, &[]);
4675 match prepared {
4676 Some(member) => self.store_member_value(member)?,
4677 None => self.destructure_rest(rest, decl)?,
4678 }
4679 }
4680 self.emit(Opcode::IteratorClose, &[]);
4681 self.pop_jump_target();
4682 Ok(())
4683 }
4684
4685 /// The property an array element stores into, when it stores into one at all.
4686 ///
4687 /// `Assign` is peeled because `[o.p = d] = it` evaluates `o.p`'s reference at the same
4688 /// point `[o.p] = it` does; the default value is applied afterwards, on the pulled
4689 /// value. Nothing deeper is: a nested pattern's own targets are reached by recursing
4690 /// into `destructure`, and those never straddle a `for_of_next`.
4691 fn member_element_target(
4692 pattern: &Pattern,
4693 decl: Option<VarDeclKind>,
4694 ) -> Option<&ast::MemberPattern> {
4695 if decl.is_some() {
4696 return None;
4697 }
4698 match &pattern.kind {
4699 PatternKind::Member(member) => Some(member),
4700 PatternKind::Assign { target, .. } => Self::member_element_target(target, decl),
4701 _ => None,
4702 }
4703 }
4704
4705 /// The same, for a rest element.
4706 fn member_rest_target(rest: &RestElement) -> Option<&ast::MemberPattern> {
4707 match rest {
4708 RestElement::Member(member) => Some(member),
4709 RestElement::Pattern(pattern) => match &pattern.kind {
4710 PatternKind::Member(member) => Some(member),
4711 _ => None,
4712 },
4713 }
4714 }
4715
4716 /// Push a member target's reference — the object, and the key when the property is
4717 /// computed — and answer how many values that put above the iterator record.
4718 fn prepare_member_target(&mut self, member: &ast::MemberPattern) -> Result<i32, SyntaxError> {
4719 self.expr(&member.object)?;
4720 match &member.property {
4721 MemberProp::Ident(_) | MemberProp::Private(_) => Ok(1),
4722 MemberProp::Computed(index) => {
4723 self.expr(index)?;
4724 Ok(2)
4725 }
4726 }
4727 }
4728
4729 /// Store the value on top of the stack through a prepared member reference.
4730 ///
4731 /// `obj value` for a named property, `obj key value` for a computed one — the orders
4732 /// `put_field` and `put_array_el` take, so no reordering is needed here. The `swap` and
4733 /// `rot3l` in [`Compiler::destructure`]'s member case exist only because *it* starts
4734 /// with the value already on the stack.
4735 fn store_member_value(&mut self, member: &ast::MemberPattern) -> Result<(), SyntaxError> {
4736 match &member.property {
4737 MemberProp::Ident(name) => {
4738 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4739 }
4740 MemberProp::Computed(_) => self.emit(Opcode::PutArrayEl, &[]),
4741 MemberProp::Private(name) => {
4742 let binding = format!("#{}", name.name);
4743 let (kind, setter) = self.private_use(&binding, member.span)?;
4744 self.private_store(&binding, kind, setter.as_deref())?;
4745 }
4746 }
4747 Ok(())
4748 }
4749
4750 /// The value of an array element whose member reference is already prepared.
4751 ///
4752 /// Only the default-value test differs from [`Compiler::destructure`]: the reference
4753 /// and the value are both on the stack while the test runs, which is why the object is
4754 /// evaluated before the default rather than after it.
4755 fn destructure_prepared(
4756 &mut self,
4757 pattern: &Pattern,
4758 member: &ast::MemberPattern,
4759 ) -> Result<(), SyntaxError> {
4760 if let PatternKind::Assign { default, .. } = &pattern.kind {
4761 let has_value = self.new_label();
4762 self.emit(Opcode::Dup, &[]);
4763 self.emit(Opcode::IsUndefined, &[]);
4764 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4765 self.emit(Opcode::Drop, &[]);
4766 self.expr(default)?;
4767 self.place_label(has_value);
4768 }
4769 self.store_member_value(member)
4770 }
4771
4772 /// `{…}` on the left: read properties off one boxed source object.
4773 fn destructure_object(
4774 &mut self,
4775 properties: &[Option<PatternElement>],
4776 rest: &Option<Box<RestElement>>,
4777 decl: Option<VarDeclKind>,
4778 pattern: &Pattern,
4779 ) -> Result<(), SyntaxError> {
4780 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4781 // aside for the rest element below.
4782 self.emit(Opcode::ToObject, &[]);
4783 let mut taken: Vec<Wtf8> = Vec::new();
4784 // A computed key's *value* is only known at run time, so with a rest element the
4785 // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4786 // local array that every key is written into as the pattern is walked — literal
4787 // keys by name, computed ones by the value the expression produced. Without this,
4788 // `let { [k]: a, ...rest } = o` was refused outright.
4789 let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4790 let key_log = if needs_key_log {
4791 let name = "<rest_exclude>";
4792 self.declare_hidden_local(name, VarKind::Normal);
4793 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4794 self.emit_var(VarAction::Put, name);
4795 Some(name)
4796 } else {
4797 None
4798 };
4799 for property in properties {
4800 let Some(PatternElement::Property {
4801 key, value, span, ..
4802 }) = property
4803 else {
4804 return Err(SyntaxError::new(
4805 "a bare pattern is not a valid object property",
4806 properties
4807 .iter()
4808 .flatten()
4809 .map(|element| match element {
4810 PatternElement::Pattern(pattern) => pattern.span,
4811 PatternElement::Property { span, .. } => *span,
4812 })
4813 .next()
4814 .unwrap_or(pattern.span),
4815 ));
4816 };
4817 // Every read needs the source twice: to read from, and to keep for the next
4818 // property. `get_field2` is that duplicate-and-read in one instruction, but it
4819 // leaves the copy *under* the value, so it is only usable when whatever
4820 // consumes the value tolerates that. See [`reads_with_get_field2`].
4821 let nested = reads_with_get_field2(decl, value);
4822 if !nested {
4823 self.emit(Opcode::Dup, &[]);
4824 }
4825 let slot = taken.len();
4826 match key {
4827 PropName::Literal(literal) => {
4828 let name = self.property_key_text(literal, *span)?;
4829 taken.push(name.clone());
4830 if let Some(log) = &key_log {
4831 // `arr index key -> arr`: the key is written into the log before
4832 // the read, so the order of observable operations is unchanged.
4833 self.emit_var(VarAction::Get, log);
4834 self.push_number(slot as f64);
4835 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4836 self.emit(Opcode::PutArrayEl, &[]);
4837 }
4838 self.emit(
4839 if nested {
4840 Opcode::GetField2
4841 } else {
4842 Opcode::GetField
4843 },
4844 &[Op::Atom(Atom::from_wtf8(&name))],
4845 );
4846 }
4847 PropName::Computed(index) => {
4848 self.expr(index)?;
4849 // `key key`: one stays on the stack for the read, the other goes into
4850 // the exclusion log. The index is a compile-time constant, so no counter
4851 // local is needed.
4852 if let Some(log) = &key_log {
4853 taken.push(Wtf8::default());
4854 self.emit(Opcode::Dup, &[]);
4855 self.emit_var(VarAction::Get, log);
4856 self.emit(Opcode::Swap, &[]);
4857 self.push_number(slot as f64);
4858 self.emit(Opcode::Swap, &[]);
4859 self.emit(Opcode::PutArrayEl, &[]);
4860 }
4861 self.emit(Opcode::GetArrayEl, &[]);
4862 }
4863 PropName::Private(_) => {
4864 return Err(SyntaxError::new(
4865 "private fields are not supported by the compiler yet",
4866 value.span,
4867 ));
4868 }
4869 }
4870 self.destructure(value, decl)?;
4871 }
4872 match rest {
4873 Some(rest) => {
4874 // `target src exclude`: the exclusion list is an array of the keys the
4875 // literal part already took, so the rest object gets only the others.
4876 self.emit(Opcode::Object, &[]);
4877 self.emit(Opcode::Swap, &[]);
4878 match &key_log {
4879 // Built while walking the pattern; see `needs_key_log`.
4880 Some(log) => {
4881 self.emit_var(VarAction::Get, log);
4882 }
4883 None => {
4884 for name in &taken {
4885 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4886 }
4887 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4888 }
4889 }
4890 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4891 self.emit(Opcode::Drop, &[]);
4892 self.emit(Opcode::Drop, &[]);
4893 self.destructure_rest(rest, decl)?;
4894 }
4895 // The source was only kept for a rest element.
4896 None => self.emit(Opcode::Drop, &[]),
4897 }
4898 Ok(())
4899 }
4900
4901 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4902 fn destructure_rest(
4903 &mut self,
4904 rest: &RestElement,
4905 decl: Option<VarDeclKind>,
4906 ) -> Result<(), SyntaxError> {
4907 match rest {
4908 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4909 // `[...a.b] = c` stores into a property.
4910 RestElement::Member(member) => {
4911 let pattern = Pattern {
4912 kind: PatternKind::Member(member.clone()),
4913 span: member.span,
4914 };
4915 self.destructure(&pattern, decl)
4916 }
4917 }
4918 }
4919
4920 /// Compile a function declaration and queue it for instantiation at scope
4921 /// entry.
4922 ///
4923 /// A declaration is visible before the statement that declares it, so the
4924 /// code that creates the function object belongs at the top of the enclosing
4925 /// scope, not at the declaration.
4926 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4927 let name = func.name.as_ref().expect("a declaration has a name");
4928 let function = self.compile_function(func)?;
4929 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4930 let target = self.hoist_target(&name.name);
4931 let block = self.cur().current_block;
4932 self.state().hoisted.push((block, target, pool_index));
4933 Ok(())
4934 }
4935
4936 /// Where a name lives, for a hoisted declaration.
4937 fn hoist_target(&self, name: &str) -> HoistTarget {
4938 let state = self.cur();
4939 if let Some(index) = state.args.iter().position(|a| a.name == name) {
4940 return HoistTarget::Arg(index as u32);
4941 }
4942 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4943 return HoistTarget::Loc(index as u32);
4944 }
4945 // A global function declaration is not a slot at all.
4946 HoistTarget::Global(name.to_string())
4947 }
4948
4949 // -- expressions -------------------------------------------------------
4950
4951 /// Compile one expression, recording where its instructions sit.
4952 ///
4953 /// The position is the node's operator when it has one and its first token
4954 /// otherwise, and it is restored on the way out so a parent's own instructions —
4955 /// which are emitted *after* its children — are blamed on the parent. Without the
4956 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4957 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4958 // `discard_value` belongs to the *statement* that is about to be compiled, so it
4959 // may only be honoured by that statement's own top-level expression. Taking it here
4960 // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4961 // the argument list is a different expression — it must still leave its value on the
4962 // stack. Without this the argument vanished, and `call` then consumed the callee as
4963 // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4964 // function).
4965 self.discard_root = std::mem::take(&mut self.state().discard_value);
4966 let saved = self.cur().cur_pos;
4967 // Only the node kinds the reference calls `emit_source_pos` for record a position:
4968 // the operator a node exists for, and a variable *read*, which the reference
4969 // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4970 // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4971 // start, a parenthesised group, an anonymous function expression — leaves the
4972 // previous position in place, because a table entry the reference never writes is
4973 // one we must not write either: the instruction that inherits a position (the
4974 // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4975 // report a more recent token than the reference does.
4976 let pos = expr.op_pos.or(match &expr.kind {
4977 ExprKind::Ident(ident) => Some(ident.span.start),
4978 _ => None,
4979 });
4980 match pos {
4981 Some(pos) => self.state().cur_pos = Some(pos),
4982 // A node the reference records nothing for: its own instructions stay
4983 // unpositioned, so they inherit whatever was written last — which is what an
4984 // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4985 // enclosing position instead would blame them on a token the reference has not
4986 // reached yet: a spread's `iterator_open` reports the expression it follows, and
4987 // a template's `to_propkey` the interpolation.
4988 None => self.state().cur_pos = None,
4989 }
4990 // Note a direct `eval` call before compiling it, because the *whole* function
4991 // is affected: an eval can name any binding the function declares, so every one
4992 // of them has to live in a cell for a closure it creates to capture it.
4993 self.note_direct_eval(expr);
4994 let result = self.expr_inner(expr);
4995 self.discard_root = false;
4996 self.state().cur_pos = saved;
4997 result
4998 }
4999
5000 /// Record which bindings are in scope at a direct `eval` call.
5001 ///
5002 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
5003 /// resolves names from a string at run time, so the only chance to pin down *which*
5004 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
5005 /// its block is the current block, an enclosing one, or the function scope.
5006 fn materialize_eval_sites(&mut self) {
5007 let pending = std::mem::take(&mut self.state().pending_eval_sites);
5008 for (span, site_block, in_params, private, arguments_allowed) in pending {
5009 self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
5010 }
5011 }
5012
5013 /// Resolve the bindings visible at one `eval` call.
5014 fn resolve_eval_site(
5015 &mut self,
5016 span: Span,
5017 site_block: u64,
5018 site_in_params: bool,
5019 private_names: Vec<EvalPrivate>,
5020 arguments_allowed: bool,
5021 ) {
5022 /// How near a binding is: function distance first, then block depth, then the
5023 /// later declaration (which shadows the earlier one in the same block).
5024 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
5025
5026 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
5027 // walked, innermost function first: a direct `eval` sees every enclosing
5028 // function's bindings, and none of them can be resolved at run time because the
5029 // runtime only has names to go on.
5030 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
5031 let deepest = self.stack.len() - 1;
5032 for (level, state) in self.stack.iter().enumerate().rev() {
5033 let owner = (deepest - level) as u32;
5034 // The innermost function's block is the one the call sat in, which is not
5035 // the block the compiler is in now; the enclosing functions are still at
5036 // the point where this one was created.
5037 let here = if level == deepest {
5038 site_block
5039 } else {
5040 state.current_block
5041 };
5042 // The chain of live blocks, innermost first, with a depth for each. The walk
5043 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
5044 // block can start at source offset zero.
5045 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
5046 let mut block = here;
5047 while let Some(parent) = state
5048 .blocks
5049 .iter()
5050 .find(|candidate| candidate.key == block)
5051 .map(|candidate| candidate.parent)
5052 .filter(|parent| *parent != NO_PARENT)
5053 .filter(|parent| parent != &block)
5054 {
5055 live.push((parent, live.len()));
5056 block = parent;
5057 }
5058 let depth_of = |key: u64| {
5059 live.iter()
5060 .find(|(candidate, _)| *candidate == key)
5061 .map(|(_, depth)| *depth)
5062 // The function scope is the outermost depth there is. A binding of a
5063 // block this site is not inside lands here too, which pushes it
5064 // behind every live one — the right answer: it is out of scope.
5065 .unwrap_or(live.len())
5066 };
5067 for (index, arg) in state.args.iter().enumerate() {
5068 bindings.push((
5069 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
5070 EvalVisible {
5071 name: arg.name.clone(),
5072 is_arg: true,
5073 index: index as u32,
5074 owner,
5075 },
5076 ));
5077 }
5078 // A parameter list cannot see the body, so a body `var` is not a binding the
5079 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
5080 // not let that eval write the body's `c`.
5081 let hides_body = if level == deepest {
5082 site_in_params
5083 } else {
5084 state.created_in_params
5085 };
5086 for (index, var) in state.vars.iter().enumerate() {
5087 let block = state
5088 .var_block
5089 .get(index)
5090 .copied()
5091 .unwrap_or(FUNCTION_SCOPE);
5092 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
5093 continue;
5094 }
5095 bindings.push((
5096 (
5097 owner as usize,
5098 depth_of(block),
5099 std::cmp::Reverse(index as u32),
5100 ),
5101 EvalVisible {
5102 name: var.name.clone(),
5103 is_arg: false,
5104 index: index as u32,
5105 owner,
5106 },
5107 ));
5108 }
5109 }
5110 // Innermost function first, then innermost block, then the later declaration
5111 // (which shadows the earlier one within a block).
5112 bindings.sort_by_key(|(priority, _)| *priority);
5113 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
5114 self.state().eval_sites.push(EvalSite {
5115 line: span.start.line,
5116 column: span.start.column,
5117 bindings,
5118 private_names,
5119 arguments_allowed,
5120 });
5121 }
5122
5123 /// The private names visible from the compiler's current position, innermost last.
5124 ///
5125 /// A direct `eval` inherits these because private names are lexically scoped
5126 /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
5127 /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
5128 /// shadowing `ClassPlan::find` gives a use site inside the body.
5129 fn visible_private_names(&self) -> Vec<EvalPrivate> {
5130 let mut out: Vec<EvalPrivate> = Vec::new();
5131 for scope in &self.private_scopes {
5132 for (name, use_) in scope {
5133 if out.iter().any(|entry| &entry.name == name) {
5134 continue;
5135 }
5136 out.push(EvalPrivate {
5137 name: name.clone(),
5138 kind: match use_.kind {
5139 PrivateKind::Field => EvalPrivateKind::Field,
5140 PrivateKind::Method => EvalPrivateKind::Method,
5141 PrivateKind::Getter => EvalPrivateKind::Getter,
5142 PrivateKind::Setter => EvalPrivateKind::Setter,
5143 },
5144 setter: use_.setter.clone(),
5145 });
5146 }
5147 }
5148 out
5149 }
5150
5151 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
5152 ///
5153 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
5154 /// a bare identifier callee counts.
5155 /// Record everything a direct `eval` call site has to tell the runtime.
5156 ///
5157 /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
5158 /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
5159 /// entirely. Missing the tail-call path is not hypothetical — it is why
5160 /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
5161 /// names were otherwise wired through.
5162 fn note_direct_eval(&mut self, expr: &Expr) {
5163 if !Self::is_direct_eval(expr) {
5164 return;
5165 }
5166 // Every enclosing function is affected too: the eval sees the whole scope chain,
5167 // and a closure it creates can capture a binding of any of them.
5168 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
5169 // because the closure the eval builds outlives the loop iteration.
5170 for state in &mut self.stack {
5171 state.has_direct_eval = true;
5172 }
5173 let block = self.cur().current_block;
5174 let in_params = self.cur().in_params;
5175 // The private names are snapshotted **here**, at the call site, not when the sites
5176 // are materialised: materialisation happens once the whole function is compiled, by
5177 // which point every class scope has been popped and the answer would always be
5178 // empty.
5179 let private = self.visible_private_names();
5180 // An arrow has no `arguments` of its own and inherits the restriction from the
5181 // nearest real function: `x = () => { () => eval('arguments') }` is still a
5182 // class field initializer's arrow, and still has no `arguments` to see.
5183 let arguments_allowed = !self
5184 .stack
5185 .iter()
5186 .rev()
5187 .find(|state| !state.is_arrow)
5188 .is_some_and(|state| state.no_arguments_binding);
5189 self.state().pending_eval_sites.push((
5190 expr.span,
5191 block,
5192 in_params,
5193 private,
5194 arguments_allowed,
5195 ));
5196 }
5197
5198 fn is_direct_eval(expr: &Expr) -> bool {
5199 matches!(
5200 &expr.kind,
5201 ExprKind::Call { callee, .. }
5202 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
5203 )
5204 }
5205
5206 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5207 match &expr.kind {
5208 ExprKind::Number(value) => self.push_number(*value),
5209 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
5210 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
5211 ExprKind::Null => self.emit(Opcode::Null, &[]),
5212 ExprKind::String(text) => self.push_string(text),
5213 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
5214 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
5215 ExprKind::This => self.this_expression(),
5216 ExprKind::NewTarget => self.new_target_expression(),
5217 ExprKind::Paren(inner) => self.expr(inner)?,
5218 ExprKind::Binary { op, left, right } => {
5219 self.expr(left)?;
5220 self.expr(right)?;
5221 self.emit(binary_opcode(*op), &[]);
5222 }
5223 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
5224 ExprKind::Unary {
5225 op: UnaryOp::Minus,
5226 argument,
5227 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
5228 let ExprKind::Number(value) = argument.unparen().kind else {
5229 unreachable!("matched above")
5230 };
5231 // The reference folds a negative literal only when the negation is
5232 // exact in the integer range: `-1` becomes `push_minus1` and
5233 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
5234 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
5235 // `-Infinity`, not `Infinity` — and folding a fraction would change
5236 // which instruction the reference emits.
5237 let negated = -value;
5238 // `-2147483648` is deliberately excluded: its magnitude is one past
5239 // `i32::MAX`, so the reference sends it through the constant pool and
5240 // negates at run time instead.
5241 if value > 0.0
5242 && negated == negated.trunc()
5243 && negated >= -(i32::MAX as f64)
5244 && negated < 0.0
5245 {
5246 self.push_number(negated);
5247 } else {
5248 self.push_number(value);
5249 self.emit(Opcode::Neg, &[]);
5250 }
5251 }
5252 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
5253 ExprKind::Conditional { test, cons, alt } => {
5254 let else_label = self.new_label();
5255 let end_label = self.new_label();
5256 self.expr(test)?;
5257 self.emit_jump(Opcode::IfFalse, else_label, &[]);
5258 self.expr(cons)?;
5259 self.emit_jump(Opcode::Goto, end_label, &[]);
5260 self.place_label(else_label);
5261 self.expr(alt)?;
5262 self.place_label(end_label);
5263 }
5264 ExprKind::Assign { op, target, value } => {
5265 let discard = std::mem::take(&mut self.discard_root);
5266 self.assign(*op, target, value, discard)?
5267 }
5268 ExprKind::Update {
5269 op,
5270 argument,
5271 prefix,
5272 } => self.update(*op, argument, *prefix)?,
5273 ExprKind::Sequence(items) => {
5274 for (index, item) in items.iter().enumerate() {
5275 self.expr(item)?;
5276 if index + 1 != items.len() {
5277 self.emit(Opcode::Drop, &[]);
5278 }
5279 }
5280 }
5281 ExprKind::Call { .. } => self.chain_link_top(expr)?,
5282 ExprKind::Member { .. } => self.chain_link_top(expr)?,
5283 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
5284 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
5285 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
5286 ExprKind::Template(template) => self.template_literal(template)?,
5287 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
5288 ExprKind::New { callee, arguments } => {
5289 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
5290 // The `dup` is not redundant: `call_constructor` takes the
5291 // constructor twice, once as the target and once as `new.target`,
5292 // which is what makes `new.target === C` inside the body.
5293 self.expr(callee)?;
5294 self.emit(Opcode::Dup, &[]);
5295 let args = arguments.as_deref().unwrap_or(&[]);
5296 if Self::has_spread(args) {
5297 // `C C array`: the duplicated callee is already both the target
5298 // and `new.target`, so no reordering is needed before `apply 1`.
5299 self.argument_array(args)?;
5300 self.emit(Opcode::Apply, &[Op::Int(1)]);
5301 return Ok(());
5302 }
5303 for argument in args {
5304 self.expr(argument)?;
5305 }
5306 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
5307 }
5308 ExprKind::Class(class) => self.class_definition(class, true)?,
5309 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
5310 ExprKind::Yield { argument, delegate } => {
5311 self.yield_expression(argument.as_deref(), *delegate)?
5312 }
5313 ExprKind::Await(argument) => self.await_expression(argument)?,
5314 ExprKind::RegExp { pattern, flags } => {
5315 // A literal is compiled *here*, at parse time, not when the line runs. The
5316 // spec is explicit that an invalid pattern is an early error (§12.9.4:
5317 // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
5318 // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
5319 // also validates `\p{…}` names: 163 conformance cases are patterns that have
5320 // to be rejected before any code runs.
5321 //
5322 // This is the whole reason the engine lives in its own crate rather than
5323 // inside `quickjs-pure`: the compiler could not depend on the interpreter
5324 // (`pure` depends on `compile`), but both need this.
5325 // The lexer already rejected an unknown or repeated flag, so an unparsable
5326 // flag string here would be a bug in the lexer rather than in the script;
5327 // fall back to the default flags instead of inventing a second message.
5328 let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
5329 let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
5330 SyntaxError::new(
5331 format!("invalid regular expression: {}", error.message),
5332 expr.span,
5333 )
5334 })?;
5335 // The tree is thrown away and rebuilt when the literal first runs: keeping it
5336 // would mean serialising the syntax tree into the function's constant pool,
5337 // and a literal is created once per evaluation of its expression anyway.
5338 let _ = parsed;
5339 // The pattern and its flags travel as two string constants; `regexp` builds
5340 // the object. A dedicated opcode (rather than a call to the constructor) is
5341 // what the reference does too, so that a literal never goes through the
5342 // public `RegExp` function and its string-coercion rules.
5343 self.push_string(&Wtf8::new(pattern));
5344 self.push_string(&Wtf8::new(flags));
5345 self.emit(Opcode::Regexp, &[]);
5346 }
5347 ExprKind::Arrow(func) => {
5348 let function = self.compile_function(func)?;
5349 let index = self.push_constant(Constant::Function(Box::new(function)));
5350 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5351 }
5352 ExprKind::Function(func) => {
5353 let function = self.compile_function_with_name(func, true)?;
5354 let index = self.push_constant(Constant::Function(Box::new(function)));
5355 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5356 }
5357 // `import.meta`: the host fills a per-module object at link time.
5358 ExprKind::ImportMeta => {
5359 self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
5360 }
5361 // `import("x")` compiles to a two-slot push followed by one opcode: the
5362 // specifier, then the options object. Both are evaluated, in that order, because
5363 // §13.3.10.1 numbers them that way and their side effects are observable — the
5364 // absent second argument is a literal `undefined`, which evaluates to nothing.
5365 ExprKind::ImportCall(specifier, options, phase) => {
5366 self.expr(specifier)?;
5367 match options {
5368 Some(options) => self.expr(options)?,
5369 None => {
5370 self.emit(Opcode::Undefined, &[]);
5371 }
5372 }
5373 // The phase is the opcode, not an operand: `import(x)` and `import.defer(x)`
5374 // have the same stack shape, and a separate instruction keeps the ordinary
5375 // form byte-identical to the reference's.
5376 match phase {
5377 ImportPhase::Evaluation => self.emit(Opcode::Import, &[]),
5378 ImportPhase::Defer => self.emit(Opcode::ImportDefer, &[]),
5379 ImportPhase::Source => self.emit(Opcode::ImportSource, &[]),
5380 }
5381 }
5382 ExprKind::PrivateIn { name, object } => {
5383 // `#x in o`: the object, then the binding, then one opcode which decides what
5384 // to do with the second operand. A field's binding holds a symbol and the
5385 // answer is an own-property test; a method's holds a function and the answer
5386 // is a brand check — both live in `private_in`, so the compiler emits the
5387 // same instruction for either.
5388 self.expr(object)?;
5389 self.emit_var(VarAction::Get, &format!("#{}", name.name));
5390 self.emit(Opcode::PrivateIn, &[]);
5391 }
5392 _ => {
5393 return Err(SyntaxError::new(
5394 "this expression form is not supported by the compiler yet",
5395 expr.span,
5396 ));
5397 }
5398 }
5399 Ok(())
5400 }
5401
5402 /// Build one array holding the evaluated call arguments, which is how a call
5403 /// containing a spread is compiled: the reference does the same, building the
5404 /// list on the stack and handing it to `apply`.
5405 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5406 let elements: Vec<Option<ArrayElement>> = arguments
5407 .iter()
5408 .map(|argument| match &argument.unparen().kind {
5409 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
5410 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
5411 })
5412 .collect();
5413 self.array_literal(&elements, Span::default())
5414 }
5415
5416 /// Whether any argument is a spread, which is what selects the `apply` form.
5417 fn has_spread(arguments: &[Expr]) -> bool {
5418 arguments
5419 .iter()
5420 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
5421 }
5422
5423 /// Compile `a${x}b`.
5424 ///
5425 /// A template is a `+` chain built left to right: the leading chunk (or an empty
5426 /// string when the template starts with a substitution), then for each
5427 /// substitution its value, `to_propkey` and `add`, then the following chunk when
5428 /// it is not empty. `to_propkey` is what makes a number or object substitute the
5429 /// way `ToString` would while leaving the result a string for `add` to
5430 /// concatenate.
5431 ///
5432 /// The chunk is an atom rather than a constant-pool string, because a non-empty
5433 /// chunk always lands where a value is pushed and `push_atom_value` is the
5434 /// instruction the reference uses for it; the empty first chunk has its own
5435 /// zero-byte form.
5436 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
5437 let first = template.quasis.first();
5438 match first.and_then(|quasi| quasi.cooked.clone()) {
5439 Some(text) if !text.is_empty() => {
5440 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5441 }
5442 // Either the template begins with a substitution, or the chunk is
5443 // empty — in both cases the chain needs a string to start from.
5444 _ => self.emit(Opcode::PushEmptyString, &[]),
5445 }
5446 for (index, expression) in template.expressions.iter().enumerate() {
5447 self.expr(expression)?;
5448 self.emit(Opcode::ToPropkey, &[]);
5449 self.emit(Opcode::Add, &[]);
5450 if let Some(text) = template
5451 .quasis
5452 .get(index + 1)
5453 .and_then(|quasi| quasi.cooked.clone())
5454 && !text.is_empty()
5455 {
5456 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5457 self.emit(Opcode::Add, &[]);
5458 }
5459 }
5460 Ok(())
5461 }
5462
5463 /// Compile an object literal.
5464 ///
5465 /// The object is built in place: `object` pushes it, and each property leaves it
5466 /// on the stack with one field more, so no temporary is needed and later
5467 /// properties can overwrite earlier ones.
5468 ///
5469 /// The instruction depends on *how* the property was written, not on what kind
5470 /// of value it holds:
5471 ///
5472 /// | source | instruction |
5473 /// |---|---|
5474 /// | `{ a: v }` | `define_field a` |
5475 /// | `{ __proto__: v }` | `set_proto` |
5476 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
5477 /// | `{ m() {} }` | `define_method m,4` |
5478 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
5479 /// | `{ [k]() {} }` | `define_method_computed 4` |
5480 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
5481 ///
5482 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
5483 /// key itself, which is why the trailing `drop` is absent there too.
5484 /// `tag`…``: a call whose first argument is the call site's template object.
5485 ///
5486 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
5487 /// array beside it, so `String.raw` can read the source text back. It is a constant
5488 /// because its contents never change; the reference builds one per call site and
5489 /// reuses it, while this builds one per evaluation, which only `tag` code that
5490 /// compares template objects across calls could tell apart.
5491 /// A fresh template site id. See [`Constant::Template`].
5492 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
5493 let cooked = quasi
5494 .quasis
5495 .iter()
5496 .map(|chunk| chunk.cooked.clone())
5497 .collect();
5498 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
5499 let index = self.push_constant(Constant::Template {
5500 site: next_template_site(),
5501 cooked,
5502 raw,
5503 });
5504 let count = quasi.expressions.len() + 1;
5505 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
5506 if let ExprKind::Member {
5507 object, property, ..
5508 } = &tag.unparen().kind
5509 {
5510 self.expr(object)?;
5511 match property {
5512 MemberProp::Ident(name) => {
5513 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5514 }
5515 MemberProp::Computed(key) => {
5516 self.expr(key)?;
5517 self.emit(Opcode::GetArrayEl2, &[]);
5518 }
5519 MemberProp::Private(name) => {
5520 let binding = format!("#{}", name.name);
5521 let (kind, _) = self.private_use(&binding, tag.span)?;
5522 self.private_callee(&binding, kind)?;
5523 }
5524 }
5525 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5526 for expression in &quasi.expressions {
5527 self.expr(expression)?;
5528 }
5529 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
5530 return Ok(());
5531 }
5532 self.expr(tag)?;
5533 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5534 for expression in &quasi.expressions {
5535 self.expr(expression)?;
5536 }
5537 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
5538 Ok(())
5539 }
5540
5541 fn object_literal(
5542 &mut self,
5543 properties: &[ObjectProperty],
5544 span: Span,
5545 ) -> Result<(), SyntaxError> {
5546 self.emit(Opcode::Object, &[]);
5547 for property in properties {
5548 match property {
5549 ObjectProperty::Spread(value) => {
5550 // `copy_data_properties` takes the target, the source and an
5551 // exclusion list; a literal `null` means "exclude nothing".
5552 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
5553 // exclusion list by stack offset.
5554 self.expr(spread_argument(value))?;
5555 self.emit(Opcode::Null, &[]);
5556 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
5557 self.emit(Opcode::Drop, &[]);
5558 self.emit(Opcode::Drop, &[]);
5559 }
5560 ObjectProperty::Property {
5561 key,
5562 value,
5563 kind,
5564 shorthand,
5565 span: property_span,
5566 } => match key {
5567 PropName::Computed(key_expr) => {
5568 self.expr(key_expr)?;
5569 match kind {
5570 PropertyKind::Value => {
5571 self.emit(Opcode::ToPropkey, &[]);
5572 self.expr(value)?;
5573 self.set_name_if_anonymous_computed(value);
5574 self.emit(Opcode::DefineArrayEl, &[]);
5575 // `define_array_el` leaves the object and the key;
5576 // the key is no longer needed.
5577 self.emit(Opcode::Drop, &[]);
5578 }
5579 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5580 self.emit_method_function(value)?;
5581 self.emit(
5582 Opcode::DefineMethodComputed,
5583 &[Op::Int(define_method_flags(*kind))],
5584 );
5585 }
5586 }
5587 }
5588 PropName::Literal(key) => {
5589 let name = self.property_key_text(key, *property_span)?;
5590 match kind {
5591 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5592 self.emit_method_function(value)?;
5593 self.emit(
5594 Opcode::DefineMethod,
5595 &[
5596 Op::Atom(Atom::from_wtf8(&name)),
5597 Op::Int(define_method_flags(*kind)),
5598 ],
5599 );
5600 }
5601 PropertyKind::Value => {
5602 self.expr(value)?;
5603 // `{__proto__: x}` sets the prototype instead of
5604 // creating a property; the shorthand `{__proto__}`
5605 // is an ordinary property and does not.
5606 if name == "__proto__" && !shorthand {
5607 self.emit(Opcode::SetProto, &[]);
5608 } else {
5609 self.set_name_if_anonymous(value, &name);
5610 self.emit(
5611 Opcode::DefineField,
5612 &[Op::Atom(Atom::from_wtf8(&name))],
5613 );
5614 }
5615 }
5616 }
5617 }
5618 PropName::Private(_) => {
5619 return Err(SyntaxError::new(
5620 "private names are not valid in object literals",
5621 *property_span,
5622 ));
5623 }
5624 },
5625 }
5626 }
5627 let _ = span;
5628 Ok(())
5629 }
5630
5631 /// Emit the function a method/accessor property defines.
5632 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
5633 self.expr(value)
5634 }
5635
5636 /// The name a literal property key contributes.
5637 ///
5638 /// String keys are used as written. A numeric key is converted the way
5639 /// `ToString` would convert it, because the atom is made from that spelling:
5640 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5641 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5642 match key {
5643 PropKey::Str(text) => Ok(text.clone()),
5644 PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5645 }
5646 }
5647
5648 /// Compile an optional chain.
5649 ///
5650 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5651 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5652 /// `undefined`. So the chain is compiled with one end label and every guard
5653 /// jumps to it. The parser hands us the extent of that spine as an
5654 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5655 /// exactly the scope the label has to cover.
5656 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5657 let end = self.new_label();
5658 self.chain_link(inner, end)?;
5659 self.place_label(end);
5660 Ok(())
5661 }
5662
5663 /// A member access or call reached from outside any optional chain.
5664 ///
5665 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5666 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5667 /// still created because [`Self::chain_link`] takes it, and placing it at the
5668 /// end is a no-op that keeps a single code path.
5669 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5670 let end = self.new_label();
5671 self.chain_link(expr, end)?;
5672 self.place_label(end);
5673 Ok(())
5674 }
5675
5676 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5677 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5678 match &expr.kind {
5679 ExprKind::Member {
5680 object,
5681 property,
5682 optional,
5683 } => {
5684 // `super.x` is not a lookup on a value: it starts at the home object's
5685 // prototype and keeps `this` as the receiver, so it cannot go through
5686 // `chain_link` and the ordinary field read.
5687 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5688 self.super_base();
5689 match property {
5690 MemberProp::Ident(name) => self.emit(
5691 Opcode::PushAtomValue,
5692 &[Op::Atom(Atom::from_text(&name.name))],
5693 ),
5694 MemberProp::Computed(index) => self.expr(index)?,
5695 MemberProp::Private(_) => {
5696 return Err(SyntaxError::new(
5697 "private fields are not supported by the compiler yet",
5698 expr.span,
5699 ));
5700 }
5701 }
5702 self.emit(Opcode::GetSuperValue, &[]);
5703 return Ok(());
5704 }
5705 self.chain_link(object, end)?;
5706 if *optional {
5707 self.optional_guard(end);
5708 }
5709 match property {
5710 // `.length` has its own opcode. The reference emits it for every
5711 // object, not just arrays, so a name-based rule is right and
5712 // cheaper than the generic field read.
5713 MemberProp::Ident(name) if name.name == "length" => {
5714 self.emit(Opcode::GetLength, &[]);
5715 }
5716 MemberProp::Ident(name) => {
5717 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5718 }
5719 MemberProp::Computed(index) => {
5720 self.expr(index)?;
5721 self.emit(Opcode::GetArrayEl, &[]);
5722 }
5723 MemberProp::Private(name) => {
5724 // The binding comes from the class scope, so a read from outside the
5725 // class cannot name it at all. `?.` checks the object, not the field:
5726 // `o?.#x` guards on `o` being nullish.
5727 let binding = format!("#{}", name.name);
5728 let (kind, _) = self.private_use(&binding, expr.span)?;
5729 self.private_load(&binding, kind, expr.span)?;
5730 }
5731 }
5732 Ok(())
5733 }
5734 ExprKind::Call {
5735 callee,
5736 arguments,
5737 optional,
5738 } => {
5739 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5740 // cannot: it reads the function and then calls it with no
5741 // receiver at all. The reference's answer is to keep the object
5742 // under the function value — `get_field2` reads a field and leaves
5743 // its base in place — and to use `call_method`, which takes the
5744 // receiver from the stack. Missing this does not just cost an
5745 // instruction, it loses the `this` binding.
5746 if let ExprKind::Member {
5747 object,
5748 property,
5749 optional: member_optional,
5750 } = &callee.unparen().kind
5751 {
5752 // `super.m()` reads the method off the home object's prototype but
5753 // calls it with `this`, so the receiver goes under the read instead of
5754 // being replaced by it.
5755 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5756 self.super_base();
5757 match property {
5758 MemberProp::Ident(name) => self.emit(
5759 Opcode::PushAtomValue,
5760 &[Op::Atom(Atom::from_text(&name.name))],
5761 ),
5762 MemberProp::Computed(index) => self.expr(index)?,
5763 MemberProp::Private(_) => {
5764 return Err(SyntaxError::new(
5765 "private fields are not supported by the compiler yet",
5766 expr.span,
5767 ));
5768 }
5769 }
5770 // The two-output form would drop the receiver; this one replaces
5771 // the prototype and the key, leaving `this` underneath.
5772 self.emit(Opcode::GetArrayEl, &[]);
5773 if Self::has_spread(arguments) {
5774 self.argument_array(arguments)?;
5775 self.emit(Opcode::Perm3, &[]);
5776 self.emit(Opcode::Apply, &[Op::Int(0)]);
5777 return Ok(());
5778 }
5779 for argument in arguments {
5780 self.expr(argument)?;
5781 }
5782 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5783 return Ok(());
5784 }
5785 self.chain_link(object, end)?;
5786 if *member_optional {
5787 self.optional_guard(end);
5788 }
5789 match property {
5790 MemberProp::Ident(name) => {
5791 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5792 }
5793 MemberProp::Computed(index) => {
5794 self.expr(index)?;
5795 // The key is not needed after the read, so this is the
5796 // two-output form: object, value.
5797 self.emit(Opcode::GetArrayEl2, &[]);
5798 }
5799 MemberProp::Private(name) => {
5800 // The receiver is already under the callee, which is exactly the
5801 // shape `call_method` and `apply` want — so nothing is dropped.
5802 let binding = format!("#{}", name.name);
5803 let (kind, _) = self.private_use(&binding, expr.span)?;
5804 self.private_callee(&binding, kind)?;
5805 }
5806 }
5807 if Self::has_spread(arguments) {
5808 // Stack is `obj func`; the array goes on top, then `perm3`
5809 // reorders to the `func this array` that `apply` wants.
5810 self.argument_array(arguments)?;
5811 self.emit(Opcode::Perm3, &[]);
5812 self.emit(Opcode::Apply, &[Op::Int(0)]);
5813 return Ok(());
5814 }
5815 for argument in arguments {
5816 self.expr(argument)?;
5817 }
5818 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5819 return Ok(());
5820 }
5821 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5822 // with `get_field2` so the base stays under it, and on the short-circuit
5823 // path pushes an extra `undefined` as a placeholder receiver — the call
5824 // then throws, which is what calling a missing optional chain should do.
5825 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5826 && let ExprKind::Member {
5827 object,
5828 property,
5829 optional: member_optional,
5830 } = &inner.unparen().kind
5831 {
5832 let call = self.new_label();
5833 // A guard target of its own: the outer `end` skips the whole
5834 // expression, and a short-circuited receiver still has to reach the
5835 // call so that calling it throws.
5836 let short = self.new_label();
5837 self.chain_link(object, end)?;
5838 if *member_optional {
5839 self.optional_guard(short);
5840 }
5841 match property {
5842 MemberProp::Ident(name) => {
5843 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5844 }
5845 MemberProp::Computed(index) => {
5846 self.expr(index)?;
5847 self.emit(Opcode::GetArrayEl2, &[]);
5848 }
5849 MemberProp::Private(name) => {
5850 let binding = format!("#{}", name.name);
5851 let (kind, _) = self.private_use(&binding, expr.span)?;
5852 self.private_callee(&binding, kind)?;
5853 }
5854 }
5855 self.emit_jump(Opcode::Goto, call, &[]);
5856 self.place_label(short);
5857 self.emit(Opcode::Undefined, &[]);
5858 self.place_label(call);
5859 if Self::has_spread(arguments) {
5860 self.argument_array(arguments)?;
5861 self.emit(Opcode::Perm3, &[]);
5862 self.emit(Opcode::Apply, &[Op::Int(0)]);
5863 return Ok(());
5864 }
5865 for argument in arguments {
5866 self.expr(argument)?;
5867 }
5868 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5869 return Ok(());
5870 }
5871 self.chain_link(callee, end)?;
5872 if *optional {
5873 self.optional_guard(end);
5874 }
5875 if Self::has_spread(arguments) {
5876 // `func array -> func undefined array`, which is the plain-call
5877 // form of `apply`: the receiver is `undefined`.
5878 self.argument_array(arguments)?;
5879 self.emit(Opcode::Undefined, &[]);
5880 self.emit(Opcode::Swap, &[]);
5881 self.emit(Opcode::Apply, &[Op::Int(0)]);
5882 return Ok(());
5883 }
5884 for argument in arguments {
5885 self.expr(argument)?;
5886 }
5887 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5888 Ok(())
5889 }
5890 _ => self.expr(expr),
5891 }
5892 }
5893
5894 /// Compile `expr` as a tail call when it is one, reporting whether it was.
5895 ///
5896 /// `tail_call` reuses the current frame instead of pushing a new one, so a
5897 /// tail-recursive function runs in constant stack space. It also has to be the
5898 /// *last* thing the function does, which is why only a `return` reaches here.
5899 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5900 let ExprKind::Call {
5901 callee,
5902 arguments,
5903 optional: false,
5904 } = &expr.unparen().kind
5905 else {
5906 return Ok(false);
5907 };
5908 // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5909 // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5910 // as an ordinary call costs the one frame the optimisation was saving and keeps the
5911 // semantics — the alternative was reaching the spread expression below and failing
5912 // with "this expression form is not supported", which is how `return super.m(...a)`
5913 // stopped compiling. Checked before anything is emitted, because the decision cannot
5914 // be taken back once `super_base` or a `get_field2` is on the stack.
5915 if Self::has_spread(arguments) {
5916 return Ok(false);
5917 }
5918 let end = self.new_label();
5919 if let ExprKind::Member {
5920 object,
5921 property,
5922 optional: false,
5923 } = &callee.unparen().kind
5924 {
5925 // `super.m()` in tail position is still an ordinary method call with `this`
5926 // as the receiver; only the read of the method differs.
5927 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5928 self.super_base();
5929 match property {
5930 MemberProp::Ident(name) => self.emit(
5931 Opcode::PushAtomValue,
5932 &[Op::Atom(Atom::from_text(&name.name))],
5933 ),
5934 MemberProp::Computed(index) => self.expr(index)?,
5935 MemberProp::Private(_) => return Ok(false),
5936 }
5937 self.emit(Opcode::GetArrayEl, &[]);
5938 for argument in arguments {
5939 self.expr(argument)?;
5940 }
5941 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5942 self.place_label(end);
5943 return Ok(true);
5944 }
5945 self.chain_link(object, end)?;
5946 match property {
5947 MemberProp::Ident(name) => {
5948 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5949 }
5950 MemberProp::Computed(index) => {
5951 self.expr(index)?;
5952 self.emit(Opcode::GetArrayEl2, &[]);
5953 }
5954 MemberProp::Private(_) => return Ok(false),
5955 }
5956 for argument in arguments {
5957 self.expr(argument)?;
5958 }
5959 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5960 self.place_label(end);
5961 return Ok(true);
5962 }
5963 self.chain_link(callee, end)?;
5964 for argument in arguments {
5965 self.expr(argument)?;
5966 }
5967 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5968 self.place_label(end);
5969 Ok(true)
5970 }
5971
5972 /// The `?.` guard: keep the value if it is neither null nor undefined,
5973 /// otherwise replace it with `undefined` and leave the whole chain.
5974 fn optional_guard(&mut self, end: Label) {
5975 let cont = self.new_label();
5976 self.emit(Opcode::Dup, &[]);
5977 self.emit(Opcode::IsUndefinedOrNull, &[]);
5978 self.emit_jump(Opcode::IfFalse, cont, &[]);
5979 self.emit(Opcode::Drop, &[]);
5980 self.emit(Opcode::Undefined, &[]);
5981 self.emit_jump(Opcode::Goto, end, &[]);
5982 self.place_label(cont);
5983 }
5984
5985 fn push_number(&mut self, value: f64) {
5986 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5987 // goes into the constant pool.
5988 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5989 let int = value as i32;
5990 if (-1..=7).contains(&int) {
5991 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5992 return;
5993 }
5994 if (-128..=127).contains(&int) {
5995 self.emit(Opcode::PushI8, &[Op::Int(int)]);
5996 return;
5997 }
5998 if (-32768..=32767).contains(&int) {
5999 self.emit(Opcode::PushI16, &[Op::Int(int)]);
6000 return;
6001 }
6002 self.emit(Opcode::PushI32, &[Op::Int(int)]);
6003 return;
6004 }
6005 let index = self.push_constant(Constant::Number(value));
6006 self.emit(Opcode::PushConst, &[Op::Const(index)]);
6007 }
6008
6009 /// Push a `BigInt` literal.
6010 ///
6011 /// A value that fits an `i32` uses the immediate form, which is what the reference
6012 /// emits too; anything larger goes into the constant pool, because the operand of
6013 /// `push_bigint` is only four bytes wide.
6014 fn push_bigint(&mut self, digits: &str, radix: u32) {
6015 if radix == 10
6016 && let Ok(value) = digits.parse::<i64>()
6017 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
6018 {
6019 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
6020 return;
6021 }
6022 let index = self.push_constant(Constant::BigInt {
6023 digits: digits.to_string(),
6024 radix,
6025 });
6026 self.emit(Opcode::PushConst, &[Op::Const(index)]);
6027 }
6028
6029 fn push_string(&mut self, text: &Wtf8) {
6030 if text.is_empty() {
6031 self.emit(Opcode::PushEmptyString, &[]);
6032 return;
6033 }
6034 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
6035 }
6036
6037 /// Name an anonymous function from the binding it is assigned to.
6038 ///
6039 /// `var f = function(){}` produces a function whose `name` is `f`, which the
6040 /// runtime cannot know without being told: the function object is created
6041 /// before the store. `set_name` carries the name across.
6042 fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
6043 if !value.is_anonymous_function_definition() {
6044 return;
6045 }
6046 // A class cannot use `set_name`, because its static field initialisers have already
6047 // run by the time the store happens and they can see `this.name`:
6048 // `var E = class { static f = this.name }` has to answer `"E"`. The reference patches
6049 // the `define_class` instruction's name operand instead, which is why
6050 // `set_class_name` is a compile-time marker with no runtime effect
6051 // (`class-name-static-initializer-anonymous`).
6052 if matches!(value.unparen().kind, ExprKind::Class(_)) {
6053 if let Some(index) = self.last_define_class() {
6054 let atom = Atom::from_wtf8(name);
6055 if let Some(Insn::Fixed { operands, .. }) = self.state().insns.get_mut(index) {
6056 // `define_class <atom> <flags>`: the name is operand 0.
6057 operands[0] = Op::Atom(atom);
6058 }
6059 }
6060 return;
6061 }
6062 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
6063 }
6064
6065 /// The index of the most recent `define_class` in this function's instruction stream.
6066 ///
6067 /// A backwards scan, because everything the class body emitted for the *enclosing*
6068 /// function is still there after it — the static initialiser's call, the class
6069 /// binding's store, `leave_scope` — and only the `define_class` carries the name.
6070 fn last_define_class(&self) -> Option<usize> {
6071 self.cur().insns.iter().rposition(|insn| {
6072 matches!(
6073 insn,
6074 Insn::Fixed {
6075 op: Opcode::DefineClass,
6076 ..
6077 }
6078 )
6079 })
6080 }
6081
6082 /// The same, for a computed key: the name comes from the value on the stack
6083 /// rather than from an atom, so a different instruction carries it.
6084 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
6085 if value.is_anonymous_function_definition() {
6086 self.emit(Opcode::SetNameComputed, &[]);
6087 }
6088 }
6089
6090 /// Compile a function body that exists only in the compiler's head — a class's
6091 /// implicit constructor or its field initialiser.
6092 ///
6093 /// Everything structural is the same as a written function: a fresh `FnState`, its
6094 /// own body block, and resolution while the frame is still on the stack. Only the
6095 /// statements differ.
6096 fn compile_synthetic_function(
6097 &mut self,
6098 name: &str,
6099 strict: bool,
6100 span: Span,
6101 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
6102 ) -> Result<CompiledFunction, SyntaxError> {
6103 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
6104 state.span = Some((span.start.offset as usize, span.end.offset as usize));
6105 state.strict = strict;
6106 state.created_in_block = self.cur().current_block;
6107 state.with_names = self.cur().with_names.clone();
6108 state.line = span.start.line;
6109 state.column = span.start.column;
6110 let depth = self.stack.len();
6111 self.stack.push(state);
6112 let body_key = span.start.offset as u64;
6113 self.push_block(body_key, NO_PARENT);
6114 self.state().body_block = body_key;
6115 let result = (|| {
6116 self.emit_scope_enter(body_key);
6117 body(self)?;
6118 if self.end_is_reachable() {
6119 self.emit(Opcode::ReturnUndef, &[]);
6120 }
6121 Ok(())
6122 })();
6123 if result.is_err() {
6124 self.stack.truncate(depth);
6125 return result.map(|()| unreachable!());
6126 }
6127 Ok(self.finish_current())
6128 }
6129
6130 /// The implicit return of a class constructor.
6131 ///
6132 /// A constructor that falls off the end initialises its instance fields first, and a
6133 /// derived one returns `this` — which is what makes `new D()` the object `super()`
6134 /// built rather than `undefined`.
6135 fn emit_class_constructor_tail(&mut self) {
6136 match self.cur().ctor_kind {
6137 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
6138 // Nothing to install: a base constructor did it in its prologue and a derived
6139 // one at each `super()` site, which is where `this` first exists.
6140 CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
6141 CtorKind::Derived => {
6142 // `get_loc_check` rather than `get_loc`: reaching the end without ever
6143 // running `super()` is a ReferenceError, not `undefined`.
6144 self.emit_var(VarAction::Get, "this");
6145 self.emit(Opcode::Return, &[]);
6146 }
6147 }
6148 }
6149
6150 /// `yield expr` / `yield* expr`.
6151 ///
6152 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
6153 /// it to the caller and parks the frame. On resume the stack holds the value the
6154 /// caller passed *and* a "magic" number saying which method resumed it — `next`
6155 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
6156 /// `if_false <continue>` asks whether this was an ordinary `next`:
6157 ///
6158 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
6159 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
6160 /// and uses the value sitting under the magic number.
6161 ///
6162 /// A `throw` never reaches here: the interpreter unwinds instead (see
6163 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
6164 fn yield_expression(
6165 &mut self,
6166 argument: Option<&Expr>,
6167 delegate: bool,
6168 ) -> Result<(), SyntaxError> {
6169 if delegate {
6170 return self.yield_star(argument);
6171 }
6172 // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
6173 // does the same for the `return(v)` that can resume it — which is why an async
6174 // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
6175 // generator's is just `yield`.
6176 let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
6177 match argument {
6178 Some(value) => self.expr(value)?,
6179 None => self.emit(Opcode::Undefined, &[]),
6180 }
6181 if is_async {
6182 self.emit(Opcode::Await, &[]);
6183 self.state().has_await = true;
6184 }
6185 self.emit(Opcode::Yield, &[]);
6186 let resume = self.new_label();
6187 self.emit_jump(Opcode::IfFalse, resume, &[]);
6188 // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
6189 // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
6190 // finished the generator and never ran the `finally`.
6191 if is_async {
6192 self.emit(Opcode::Await, &[]);
6193 }
6194 self.emit_unwind_for_return(true);
6195 self.emit(Opcode::ReturnAsync, &[]);
6196 self.place_label(resume);
6197 // Nothing is emitted here: the value the caller passed to `next` *is* the value
6198 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
6199 // it through the ordinary expression-statement discard.
6200 Ok(())
6201 }
6202
6203 /// `yield* iterable`.
6204 ///
6205 /// The shape is the reference's, and it is a fall-through chain rather than a
6206 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
6207 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
6208 /// the inner iterator and finishes, `throw` forwards the exception into it and
6209 /// continues only if it has a `throw` method.
6210 ///
6211 /// The stack is `iter next catch value` throughout, `catch` being the offset
6212 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
6213 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
6214 match argument {
6215 Some(value) => self.expr(value)?,
6216 // The parser rejects a bare `yield*`, so this is unreachable in practice.
6217 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
6218 }
6219 // `for await of` is the same protocol as `for of` with two differences that matter
6220 // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
6221 // every `next()` result is a promise the delegate has to await.
6222 let is_async = self.cur().kind.is_async();
6223 self.emit(
6224 if is_async {
6225 Opcode::ForAwaitOfStart
6226 } else {
6227 Opcode::ForOfStart
6228 },
6229 &[],
6230 );
6231 self.emit(Opcode::Drop, &[]);
6232 self.emit(Opcode::Undefined, &[]);
6233 self.emit(Opcode::Undefined, &[]);
6234 let next = self.new_label();
6235 let resume = self.new_label();
6236 let finished = self.new_label();
6237 let rethrow = self.new_label();
6238 let throw_no_method = self.new_label();
6239 let done = self.new_label();
6240 self.place_label(next);
6241 self.emit(Opcode::IteratorNext, &[]);
6242 if is_async {
6243 self.emit(Opcode::Await, &[]);
6244 self.state().has_await = true;
6245 }
6246 self.emit(Opcode::IteratorCheckObject, &[]);
6247 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6248 self.emit_jump(Opcode::IfTrue, done, &[]);
6249 // The suspension. `resume` is both the label the return path jumps back to in order
6250 // to yield one more value and where the caller's answer arrives, as the value
6251 // followed by the magic number.
6252 //
6253 // The two forms differ in what they hand the suspension: `yield_star` takes the
6254 // result object itself, `async_yield_star` takes `.value`, because an async
6255 // generator awaits and re-wraps whatever it yields.
6256 self.place_label(resume);
6257 if is_async {
6258 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6259 self.emit(Opcode::AsyncYieldStar, &[]);
6260 } else {
6261 self.emit(Opcode::YieldStar, &[]);
6262 }
6263 self.emit(Opcode::Dup, &[]);
6264 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
6265 self.emit(Opcode::Drop, &[]);
6266 self.emit_jump(Opcode::Goto, next, &[]);
6267
6268 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
6269 self.place_label(rethrow);
6270 self.emit(Opcode::PushI32, &[Op::Int(2)]);
6271 self.emit(Opcode::StrictEq, &[]);
6272 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
6273 // A `return` closes the inner iterator; if it had none, the delegate simply
6274 // finishes with the requested value. In an async generator both the call and its
6275 // result are awaited, because the inner `return` may itself be async.
6276 if is_async {
6277 self.emit(Opcode::Await, &[]);
6278 }
6279 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
6280 self.emit_jump(Opcode::IfTrue, finished, &[]);
6281 if is_async {
6282 self.emit(Opcode::Await, &[]);
6283 }
6284 self.emit(Opcode::IteratorCheckObject, &[]);
6285 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6286 self.emit_jump(Opcode::IfFalse, resume, &[]);
6287 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6288 self.place_label(finished);
6289 self.emit(Opcode::Nip, &[]);
6290 self.emit(Opcode::Nip, &[]);
6291 self.emit(Opcode::Nip, &[]);
6292 // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
6293 // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
6294 // awaits the value in an async generator and then runs the same `finally`/iterator
6295 // unwinding a written `return` would. Skipping the unwinding made
6296 // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
6297 if is_async {
6298 self.emit(Opcode::Await, &[]);
6299 }
6300 self.emit_unwind_for_return(true);
6301 self.emit(Opcode::ReturnAsync, &[]);
6302
6303 // `throw(e)`: forward it into the inner iterator.
6304 self.place_label(throw_no_method);
6305 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
6306 let no_throw = self.new_label();
6307 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
6308 if is_async {
6309 self.emit(Opcode::Await, &[]);
6310 }
6311 self.emit(Opcode::IteratorCheckObject, &[]);
6312 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6313 self.emit_jump(Opcode::IfFalse, resume, &[]);
6314 self.emit_jump(Opcode::Goto, done, &[]);
6315 // No `throw` method: close the iterator, then report the spec's TypeError. The
6316 // `if_true` before the `await` is the reference's shape — the flag it consumes is
6317 // what `iterator_call` leaves behind, and a close that *did* find no `return`
6318 // method has nothing to await.
6319 self.place_label(no_throw);
6320 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
6321 let no_close = self.new_label();
6322 self.emit_jump(Opcode::IfTrue, no_close, &[]);
6323 if is_async {
6324 self.emit(Opcode::Await, &[]);
6325 }
6326 self.place_label(no_close);
6327 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
6328
6329 // The inner iterator finished: the delegate's value is the `yield*` expression's
6330 // value, so it is left on the stack for whatever consumes it.
6331 self.place_label(done);
6332 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6333 self.emit(Opcode::Nip, &[]);
6334 self.emit(Opcode::Nip, &[]);
6335 self.emit(Opcode::Nip, &[]);
6336 Ok(())
6337 }
6338
6339 /// `await expr`: exactly one instruction.
6340 ///
6341 /// No resume-magic branch follows it. The reference's `await` leaves a single value
6342 /// on the stack and completion is signalled by the `return_async` at the end of the
6343 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
6344 /// reference never emits, and a `for await` loop — which reaches `await` through the
6345 /// same opcode — would then spill a value the loop's unpacking does not expect.
6346 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
6347 self.expr(argument)?;
6348 self.emit(Opcode::Await, &[]);
6349 self.state().has_await = true;
6350 Ok(())
6351 }
6352
6353 /// The `super` base: the receiver followed by the home object's prototype.
6354 ///
6355 /// Everything `super` does needs both. A *read* starts at the prototype but reports
6356 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
6357 /// prototype but calls it with the receiver.
6358 fn super_base(&mut self) {
6359 self.this_expression();
6360 self.home_object();
6361 self.emit(Opcode::GetSuper, &[]);
6362 }
6363
6364 /// `[[HomeObject]]` as `super` sees it.
6365 ///
6366 /// A method, a constructor and a field initialiser each carry one — `set_home_object`
6367 /// put it there — so for them the special object *is* the answer. An arrow and a
6368 /// static block have none: they read the enclosing function's, which has to be
6369 /// materialised into a local, exactly as `this` is for an arrow.
6370 ///
6371 /// The name matches what the reference stores, so the disassembly agrees; it is not a
6372 /// name any program can write.
6373 fn home_object(&mut self) {
6374 if !self.cur().is_arrow {
6375 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
6376 return;
6377 }
6378 if let Some(target) = self.enclosing_function() {
6379 self.state_at(target).needs_home_object_local = true;
6380 self.declare_at(target, HOME_OBJECT);
6381 }
6382 self.emit_var(VarAction::Get, HOME_OBJECT);
6383 }
6384
6385 /// `super(args)`: construct the parent class and adopt the result as `this`.
6386 ///
6387 /// The parent is the prototype of the constructor that is running, which is exactly
6388 /// what `extends` set up. `new.target` is passed through unchanged so that
6389 /// `new.target` inside the parent is the class actually being constructed.
6390 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
6391 self.active_func_expression();
6392 self.emit(Opcode::GetSuper, &[]);
6393 self.new_target_expression();
6394 if Self::has_spread(arguments) {
6395 self.argument_array(arguments)?;
6396 self.emit(Opcode::Apply, &[Op::Int(1)]);
6397 } else {
6398 for argument in arguments {
6399 self.expr(argument)?;
6400 }
6401 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
6402 }
6403 // The value stays on the stack: `super()` is an expression, and a derived
6404 // constructor's `this` may only be initialised once.
6405 self.emit(Opcode::Dup, &[]);
6406 self.emit_var(VarAction::PutInitChecked, "this");
6407 // Instance fields are installed here, not at the top of the body: a derived
6408 // constructor has no `this` to install them on until `super()` returns. The
6409 // reference emits the same call at every `super()` site.
6410 self.call_field_initialiser();
6411 Ok(())
6412 }
6413
6414 /// `this` as a local, which every class constructor and field initialiser needs.
6415 ///
6416 /// The reference materialises the receiver into a local rather than reading
6417 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
6418 /// and a field initialiser has to see the final value.
6419 fn begin_this_local(&mut self) {
6420 self.declare_hidden_local("this", VarKind::Normal);
6421 self.emit(Opcode::PushThis, &[]);
6422 self.emit_var(VarAction::Put, "this");
6423 // The store is already at the top of the body, so `provide_this_local` has
6424 // nothing left to prepend. Without this the initialiser ended up with
6425 // `push_this; put_loc0 this` twice whenever the class also held a field
6426 // initialiser whose body read `this` through an arrow.
6427 self.state().has_this_prologue = true;
6428 }
6429
6430 /// Compile a constructor the class wrote.
6431 ///
6432 /// The flags have to be in place before the body is compiled, but
6433 /// `compile_function_with_name` creates its own state — so the caller's state is
6434 /// marked instead and the new one inherits it. That is the same trick the parameter
6435 /// prologue uses, and it keeps one code path for both.
6436 fn compile_class_constructor(
6437 &mut self,
6438 func: &ast::Function,
6439 has_heritage: bool,
6440 ) -> Result<CompiledFunction, SyntaxError> {
6441 let saved = self.cur().ctor_kind;
6442 self.state().class_ctor_pending = Some(if has_heritage {
6443 CtorKind::Derived
6444 } else {
6445 CtorKind::Base
6446 });
6447 let result = self.compile_function_with_name(func, false);
6448 self.state().ctor_kind = saved;
6449 self.state().class_ctor_pending = None;
6450 result
6451 }
6452
6453 /// The constructor a class gets when it does not declare one.
6454 ///
6455 /// A base class's is empty; a derived class's forwards every argument to the parent
6456 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
6457 /// instance field initialiser afterwards when the class has fields, which is why the
6458 /// initialiser is captured rather than inlined.
6459 fn compile_implicit_constructor(
6460 &mut self,
6461 class: &Class,
6462 has_heritage: bool,
6463 ) -> Result<CompiledFunction, SyntaxError> {
6464 self.compile_synthetic_function(
6465 "",
6466 true,
6467 Span::new(class.body_end, class.body_end),
6468 |compiler| {
6469 if has_heritage {
6470 // A derived constructor's `this` does not exist until `super()` returns,
6471 // so it starts in the dead zone and `init_ctor` fills it.
6472 compiler.declare("this", VarDef::lexical("this"));
6473 compiler.emit(
6474 Opcode::SetLocUninitialized,
6475 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6476 );
6477 compiler.emit(Opcode::InitCtor, &[]);
6478 compiler.emit(
6479 Opcode::PutLocCheckInit,
6480 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6481 );
6482 } else {
6483 compiler.begin_this_local();
6484 compiler.emit(Opcode::CheckCtor, &[]);
6485 }
6486 compiler.call_field_initialiser();
6487 // A derived constructor returns `this`, the object `super()` built. Without
6488 // this the implicit constructor fell through to `return_undef`, and `new B()`
6489 // handed back the empty object `construct` had made instead of the one the
6490 // parent constructor initialised.
6491 if has_heritage {
6492 compiler.emit_var(VarAction::Get, "this");
6493 compiler.emit(Opcode::Return, &[]);
6494 }
6495 Ok(())
6496 },
6497 )
6498 }
6499
6500 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
6501 ///
6502 /// A class with no instance fields leaves the binding `undefined`, and calling it
6503 /// would throw; the reference emits the same guard rather than branching at compile
6504 /// time because a class can be extended by a subclass whose fields still have to run.
6505 fn call_field_initialiser(&mut self) {
6506 let skip = self.new_label();
6507 self.emit_var(VarAction::Get, "<class_fields_init>");
6508 self.emit(Opcode::Dup, &[]);
6509 self.emit_jump(Opcode::IfFalse, skip, &[]);
6510 self.emit_var(VarAction::Get, "this");
6511 self.emit(Opcode::Swap, &[]);
6512 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6513 self.place_label(skip);
6514 self.emit(Opcode::Drop, &[]);
6515 }
6516
6517 /// The function that defines one class's fields on `this`, and runs its static blocks.
6518 ///
6519 /// `define_field` rather than `put_field`: a field is an own property created
6520 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
6521 /// `x = 1` field must not call the setter.
6522 ///
6523 /// One function serves the whole class: it is called once per instance (or once, for
6524 /// the static half) and walks the members in source order. Static blocks are compiled
6525 /// into the same function because they *are* part of the same sequence — `static a =
6526 /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
6527 /// different values, so the two kinds cannot be split apart.
6528 fn compile_field_initialiser(
6529 &mut self,
6530 items: &[StaticInitItem<'_>],
6531 span: Span,
6532 instance: bool,
6533 add_brand: bool,
6534 ) -> Result<CompiledFunction, SyntaxError> {
6535 self.compile_synthetic_function("", true, span, |compiler| {
6536 // A field initialiser and a static block are not functions, so neither has an
6537 // `arguments` of its own; see `FnState::no_arguments_binding`.
6538 let current = compiler.stack.len() - 1;
6539 compiler.stack[current].no_arguments_binding = true;
6540 if instance {
6541 // An instance initialiser always carries a `<home_object>` local, because the
6542 // brand block below reads it — even when that block turns out to be dead. The
6543 // reference has the same artefact, and the store is visible in its dump.
6544 let current = compiler.stack.len() - 1;
6545 compiler.stack[current].needs_home_object_local = true;
6546 }
6547 compiler.begin_this_local();
6548 if instance {
6549 // `this` gets the brand the prototype created, before any field is defined —
6550 // which is what makes `#m()` usable from inside a field initialiser.
6551 //
6552 // The reference always emits `push_false; if_false L; this; home; add_brand;
6553 // L:` and patches the `push_false` to `push_true` from the class parse when
6554 // the class has private methods; either way the branch folds, but the *mark*
6555 // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
6556 // `this` local from being fused into a `set_loc`.
6557 let skip = compiler.new_label();
6558 if add_brand {
6559 compiler.emit(Opcode::PushTrue, &[]);
6560 } else {
6561 compiler.emit(Opcode::PushFalse, &[]);
6562 }
6563 compiler.emit_jump(Opcode::IfFalse, skip, &[]);
6564 compiler.emit_var(VarAction::Get, "this");
6565 compiler.emit_var(VarAction::Get, HOME_OBJECT);
6566 compiler.emit(Opcode::AddBrand, &[]);
6567 compiler.place_label(skip);
6568 }
6569 for item in items {
6570 match item {
6571 StaticInitItem::Field(key, value) => {
6572 // A private field is *defined*, not assigned: `define_private_field`
6573 // reads `obj symbol value`, and its point is that it fails on a
6574 // receiver that is not this class's — which `put_field` would not.
6575 //
6576 // The three shapes are the reference's: `define_field <atom>` for a
6577 // static name, `define_array_el` for a key that is only known at run
6578 // time (`obj key value`), `define_private_field` for `#x`, and a
6579 // computed key is read from its binding rather than recomputed.
6580 compiler.emit_var(VarAction::Get, "this");
6581 match key {
6582 FieldKey::Private(binding) | FieldKey::Computed(binding) => {
6583 compiler.emit_var(VarAction::Get, binding);
6584 }
6585 FieldKey::Literal(_) => {}
6586 }
6587 match value {
6588 Some(value) => {
6589 compiler.expr(value)?;
6590 // A field initialiser is a `NamedEvaluation` target:
6591 // `x = function(){}` names the function `"x"`, and a private
6592 // field keeps its `#` (`static #f = () => 1` is named
6593 // `"#f"` (elements/static-field-anonymous-function-name).
6594 match key {
6595 FieldKey::Literal(literal) => {
6596 let text = compiler.property_key_text(literal, span)?;
6597 compiler.set_name_if_anonymous(value, &text);
6598 }
6599 FieldKey::Private(binding) => {
6600 compiler.set_name_if_anonymous(value, &Wtf8::new(binding));
6601 }
6602 // The key is a value on the stack, and `set_name_computed`
6603 // is exactly the instruction for that.
6604 FieldKey::Computed(_) => {
6605 compiler.set_name_if_anonymous_computed(value);
6606 }
6607 }
6608 }
6609 None => compiler.emit(Opcode::Undefined, &[]),
6610 }
6611 match key {
6612 FieldKey::Literal(literal) => {
6613 let text = compiler.property_key_text(literal, span)?;
6614 compiler
6615 .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
6616 }
6617 FieldKey::Computed(_) => {
6618 compiler.emit(Opcode::DefineArrayEl, &[]);
6619 // `define_array_el` leaves `obj key`; the key is consumed by
6620 // the copy the pattern machinery wants, so both go.
6621 compiler.emit(Opcode::Drop, &[]);
6622 }
6623 FieldKey::Private(_) => {
6624 compiler.emit(Opcode::DefinePrivateField, &[]);
6625 }
6626 }
6627 compiler.emit(Opcode::Drop, &[]);
6628 }
6629 StaticInitItem::Block { body, body_start } => {
6630 let block = compiler.compile_static_block(body, *body_start)?;
6631 let index = compiler.push_constant(Constant::Function(Box::new(block)));
6632 // `this fclosure`, so `call_method` finds the receiver below the
6633 // callee: the block runs with `this` bound to the class.
6634 compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
6635 compiler.emit_var(VarAction::Get, "this");
6636 compiler.emit(Opcode::Swap, &[]);
6637 compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
6638 // Nothing the block evaluates is wanted; its effects are the point.
6639 compiler.emit(Opcode::Drop, &[]);
6640 }
6641 }
6642 }
6643 Ok(())
6644 })
6645 }
6646
6647 /// Compile a `static { … }` body into the function the class calls for it.
6648 ///
6649 /// Shaped like an arrow, because that is the one function form with no `this`,
6650 /// `new.target` or `arguments` of its own: all three reach the enclosing static
6651 /// initialiser, and through it the class. `arguments` never gets that far — the parser
6652 /// rejects the reference — but `this` and `super` both depend on it.
6653 ///
6654 /// The body is hoisted like a function body's, because the reference parses it as one:
6655 /// `var` inside a block is a local of the block's function, not of whatever encloses
6656 /// the class.
6657 fn compile_static_block(
6658 &mut self,
6659 body: &[Stmt],
6660 body_start: Position,
6661 ) -> Result<CompiledFunction, SyntaxError> {
6662 let mut state = FnState::new(String::new(), FunctionKind::Normal);
6663 // Class bodies are strict, so a static block is too.
6664 state.strict = true;
6665 // The one property that makes this an arrow: nothing of its own to bind `this` to,
6666 // so `this` and `super` come from the initialiser that calls it.
6667 state.is_arrow = true;
6668 state.created_in_block = self.cur().current_block;
6669 state.with_names = self.cur().with_names.clone();
6670 state.line = body_start.line;
6671 state.column = body_start.column;
6672 let depth = self.stack.len();
6673 self.stack.push(state);
6674 let body_key = body_start.offset as u64;
6675 self.push_block(body_key, NO_PARENT);
6676 self.state().body_block = body_key;
6677 let result = (|| {
6678 self.hoist(body, body_key)?;
6679 self.emit_scope_enter(body_key);
6680 for statement in body {
6681 self.stmt(statement)?;
6682 }
6683 if self.end_is_reachable() {
6684 self.emit(Opcode::ReturnUndef, &[]);
6685 }
6686 Ok(())
6687 })();
6688 if result.is_err() {
6689 self.stack.truncate(depth);
6690 return result.map(|()| unreachable!());
6691 }
6692 Ok(self.finish_current())
6693 }
6694
6695 /// Compile a class, leaving the constructor on the stack when `keep`.
6696 ///
6697 /// The shape follows the reference: the class body is its own scope holding the
6698 /// class's *inner* name as a `const` — which is what lets a method refer to the
6699 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6700 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6701 /// on the top of the stack: the prototype for instance members, the constructor
6702 /// itself for `static` ones, which is why a static member costs an extra `swap`.
6703 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6704 let parent_block = self.cur().current_block;
6705 let key = class.span.start.offset as u64;
6706 self.push_block(key, parent_block);
6707 let name = class.name.as_ref().map(|ident| ident.name.clone());
6708 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6709 // resolves `E` without a global lookup. An *unnamed* class expression has no such
6710 // binding, and `define_class` is handed the empty name.
6711 if let Some(name) = &name {
6712 self.declare(name, VarDef::constant(name.clone()));
6713 }
6714 self.emit_scope_enter(key);
6715
6716 // The heritage clause is evaluated outside the class's own scope: it cannot see
6717 // the class binding it is about to initialise.
6718 let saved_block = self.cur().current_block;
6719 self.state().current_block = parent_block;
6720 match &class.super_class {
6721 Some(parent) => self.expr(parent)?,
6722 None => self.emit(Opcode::Undefined, &[]),
6723 }
6724 self.state().current_block = saved_block;
6725 let has_heritage = class.super_class.is_some();
6726
6727 // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6728 // lands after the heritage's code — which is where the reference puts it, because it
6729 // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6730 // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6731 // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6732 // came out in the opposite order from the reference's.
6733 //
6734 // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6735 // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6736 // a const accepts — so the old comment's worry ("a const would refuse the second
6737 // store") did not apply: there is no second store.
6738 // Every `#name` the class declares gets a `const` binding in the class scope, and so
6739 // does every computed field key. That is how the reference does it
6740 // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6741 // what makes a private name resolve like any other class-scope variable — including
6742 // through a nested function's closure — while remaining invisible outside.
6743 //
6744 // All of them are declared *before* `<class_fields_init>`, in member order, because
6745 // that is when the reference's parser creates them.
6746 let plan = ClassPlan::build(class);
6747 // The body's private names are visible from here to the end of the class, and shadow
6748 // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6749 // — it is compiled first because `define_class` consumes it, but its body can name
6750 // `#x` like any other member's.
6751 self.private_scopes.push(plan.uses.clone());
6752 let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6753 for binding in &plan.bindings {
6754 class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6755 }
6756 let fci = self.declare(
6757 "<class_fields_init>",
6758 VarDef::constant("<class_fields_init>"),
6759 );
6760 // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6761 // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6762 // members' bindings follow in reverse.
6763 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6764 for slot in class_slots.iter().rev() {
6765 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6766 }
6767
6768 // The constructor is compiled before `define_class` because that instruction
6769 // consumes it; a class without one gets the implicit version.
6770 let constructor = class.elements.iter().find_map(|element| match element {
6771 ClassElement::Method {
6772 kind: MethodKind::Constructor,
6773 func,
6774 ..
6775 } => Some(&**func),
6776 _ => None,
6777 });
6778 // A constructor is compiled differently from a method: it owns `this`. The flags
6779 // go on the *enclosing* state because a constructor is a nested function and
6780 // `compile_function_with_name` starts a fresh one.
6781 let ctor = match constructor {
6782 Some(func) => self.compile_class_constructor(func, has_heritage)?,
6783 None => self.compile_implicit_constructor(class, has_heritage)?,
6784 };
6785 // A closure, not the bare constant: the constructor captures
6786 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6787 // has to hold the cell rather than a copy of its value.
6788 //
6789 // The pool slot is left unassigned for now, because the reference gives the
6790 // constructor the *last* index of the members' range: `js_parse_class` emits a
6791 // `push_const` whose operand is patched at the end of the class parse, after every
6792 // method has taken a slot. Emitting the members first and the constant second is how
6793 // the numbering comes out the same; the instruction itself stays where it is.
6794 let ctor_insn = self.cur().insns.len();
6795 self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6796 let flags = if has_heritage { 1 } else { 0 };
6797 self.emit(
6798 Opcode::DefineClass,
6799 &[
6800 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6801 Op::Int(flags),
6802 ],
6803 );
6804
6805 // Instance fields and static fields are two different functions: the first runs
6806 // per instance from the constructor, the second runs once, here.
6807 let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6808 let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6809 for (index, element) in class.elements.iter().enumerate() {
6810 match element {
6811 ClassElement::Method {
6812 key: member_key,
6813 is_static,
6814 kind,
6815 func,
6816 span,
6817 } => {
6818 if *kind == MethodKind::Constructor {
6819 continue;
6820 }
6821 // `static(x)` is a *method* named `static`, not a static method; the
6822 // parser already decided which by putting it in `kind`.
6823 if *is_static {
6824 self.emit(Opcode::Swap, &[]);
6825 }
6826 // A computed key is evaluated *here*, before the method's closure
6827 // exists, and stays under it: `define_method_computed` pops
6828 // `function, key, object`, so the stack has to read
6829 // `[class, prototype, key, function]`. Evaluating the key after the
6830 // `fclosure` and swapping the two put the prototype *below* the
6831 // closure, which defined the method on the function and lost the
6832 // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6833 // also the spec's — a class body evaluates every element's name before
6834 // that element's function.
6835 if let PropName::Computed(key) = member_key {
6836 self.expr(key)?;
6837 }
6838 let function = self.compile_function_with_name(func, true)?;
6839 let index = self.push_constant(Constant::Function(Box::new(function)));
6840 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6841 match member_key {
6842 // A private method is not a property of the prototype: it is a
6843 // closure in the class scope, which is why nothing outside can reach
6844 // it and why a use site has to brand-check. `set_name` gives the
6845 // function its `name` (`#m`), which an accessor does not get — the
6846 // reference leaves that commented out.
6847 PropName::Private(ident) => {
6848 let name = format!("#{}", ident.name);
6849 // `set_home_object` first: the brand check reads the function's
6850 // home object, and for a method that is the prototype.
6851 self.emit(Opcode::SetHomeObject, &[]);
6852 let binding = if *kind == MethodKind::Set {
6853 format!("{name}<set>")
6854 } else {
6855 name.clone()
6856 };
6857 if *kind == MethodKind::Method {
6858 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6859 }
6860 self.emit_var(VarAction::PutInit, &binding);
6861 }
6862 PropName::Computed(_) => {
6863 self.emit(
6864 Opcode::DefineMethodComputed,
6865 &[Op::Int(class_method_flags(*kind))],
6866 );
6867 }
6868 PropName::Literal(literal) => {
6869 let text = self.property_key_text(literal, *span)?;
6870 self.emit(
6871 Opcode::DefineMethod,
6872 &[
6873 Op::Atom(Atom::from_wtf8(&text)),
6874 Op::Int(class_method_flags(*kind)),
6875 ],
6876 );
6877 }
6878 }
6879 if *is_static {
6880 self.emit(Opcode::Swap, &[]);
6881 }
6882 }
6883 ClassElement::Field {
6884 key: field_key,
6885 is_static,
6886 value,
6887 ..
6888 } => {
6889 // A private field's *symbol* is created here, at the member, and stored
6890 // in its binding: the field's property is keyed by it, so it has to exist
6891 // before any initialiser runs, and a fresh one per class body is what
6892 // makes two classes that both write `#x` independent.
6893 //
6894 // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6895 // whose `toString` has a side effect must not run again per instance.
6896 let key = match field_key {
6897 PropName::Private(ident) => {
6898 let binding = format!("#{}", ident.name);
6899 if *is_static {
6900 self.emit(Opcode::Swap, &[]);
6901 }
6902 self.emit(
6903 Opcode::PrivateSymbol,
6904 &[Op::Atom(Atom::from_text(&binding))],
6905 );
6906 self.emit_var(VarAction::PutInit, &binding);
6907 if *is_static {
6908 self.emit(Opcode::Swap, &[]);
6909 }
6910 FieldKey::Private(binding)
6911 }
6912 PropName::Computed(expression) => {
6913 let binding = plan
6914 .computed
6915 .get(&index)
6916 .cloned()
6917 .expect("every computed key got a binding");
6918 if *is_static {
6919 self.emit(Opcode::Swap, &[]);
6920 }
6921 self.expr(expression)?;
6922 self.emit(Opcode::ToPropkey, &[]);
6923 self.emit_var(VarAction::PutInit, &binding);
6924 if *is_static {
6925 self.emit(Opcode::Swap, &[]);
6926 }
6927 FieldKey::Computed(binding)
6928 }
6929 PropName::Literal(literal) => FieldKey::Literal(literal),
6930 };
6931 if *is_static {
6932 static_items.push(StaticInitItem::Field(key, value.as_deref()));
6933 } else {
6934 instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6935 }
6936 }
6937 ClassElement::StaticBlock {
6938 body, body_start, ..
6939 } => static_items.push(StaticInitItem::Block {
6940 body,
6941 body_start: *body_start,
6942 }),
6943 }
6944 }
6945
6946 // Now that every member has its slot, the constructor can have the next one and the
6947 // `fclosure` above can name it.
6948 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6949 match self.state().insns.get_mut(ctor_insn) {
6950 Some(Insn::Fixed { operands, .. }) => {
6951 operands[0] = Op::Const(ctor_index);
6952 }
6953 // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6954 // loudly beats emitting a `fclosure` of slot 4294967295.
6955 _ => {
6956 return Err(SyntaxError::new(
6957 "the class constructor's fclosure went missing",
6958 class.span,
6959 ));
6960 }
6961 }
6962
6963 // The instance brand: a symbol created once on the prototype, which every instance
6964 // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6965 // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6966 // copy is created. The prototype is on top of the stack at this point.
6967 if plan.instance_brand {
6968 self.emit(Opcode::Dup, &[]);
6969 self.emit(Opcode::Null, &[]);
6970 self.emit(Opcode::Swap, &[]);
6971 self.emit(Opcode::AddBrand, &[]);
6972 }
6973
6974 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6975 // class has no instance fields. The constructor calls it only when it is defined.
6976 //
6977 // A class with private *methods* but no fields still needs one, because adding the
6978 // brand to each new instance is the initialiser's job.
6979 if instance_fields.is_empty() && !plan.instance_brand {
6980 self.emit(Opcode::Undefined, &[]);
6981 } else {
6982 let initialiser = self.compile_field_initialiser(
6983 &instance_fields,
6984 class.span,
6985 true,
6986 plan.instance_brand,
6987 )?;
6988 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6989 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6990 // `set_home_object` reads `obj func`, so the prototype stays where it is.
6991 self.emit(Opcode::SetHomeObject, &[]);
6992 }
6993 self.emit_var(VarAction::PutInit, "<class_fields_init>");
6994 // The prototype has done its job: every instance member is defined on it. What
6995 // is left under it is the constructor.
6996 self.emit(Opcode::Drop, &[]);
6997
6998 // The static brand, for `static #m() {}`: same opcode, but the home object is the
6999 // constructor itself, so the symbol lands on the class and the class carries it.
7000 if plan.static_brand {
7001 self.emit(Opcode::Dup, &[]);
7002 self.emit(Opcode::Dup, &[]);
7003 self.emit(Opcode::AddBrand, &[]);
7004 }
7005
7006 // The class binding is initialised *before* static fields run, so a static field
7007 // can refer to the class by name (`static y = S.x`).
7008 // `set_loc` leaves the constructor on the stack, which is what the static field
7009 // call and the outer store both consume.
7010 //
7011 // Only when there *is* such a binding: an anonymous class expression declares no
7012 // class-scope name, and asking for one by the empty string resolved to nothing —
7013 // which made `var x = class {}` assign `undefined` and put a bogus global store in
7014 // the instruction stream.
7015 if let Some(name) = &name {
7016 self.emit_var(VarAction::SetInit, name);
7017 }
7018 if !static_items.is_empty() {
7019 // The static half has no brand prologue of its own: the constructor got its
7020 // brand above, before this runs.
7021 let initialiser =
7022 self.compile_field_initialiser(&static_items, class.span, false, false)?;
7023 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
7024 self.emit(Opcode::Dup, &[]);
7025 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
7026 self.emit(Opcode::SetHomeObject, &[]);
7027 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7028 self.emit(Opcode::Drop, &[]);
7029 }
7030 // The body is over, and with it this class's private names.
7031 let _ = self.private_scopes.pop();
7032 self.emit_scope_leave(key);
7033 self.state().current_block = parent_block;
7034 if keep {
7035 // A class *expression* is its own value; the class-scope binding was only
7036 // ever an alias for it.
7037 return Ok(());
7038 }
7039 // A declaration stores into the binding the enclosing statement declared.
7040 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
7041 Ok(())
7042 }
7043
7044 fn push_this(&mut self) {
7045 self.emit(Opcode::PushThis, &[]);
7046 }
7047
7048 /// `this`, which an arrow does not have of its own.
7049 ///
7050 /// The reference gives the enclosing function a local named `this`, initialised from
7051 /// `push_this` at the top of its body, and the arrow then reads it as a captured
7052 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
7053 /// the arrow is called with none.
7054 fn this_expression(&mut self) {
7055 // In a class constructor `this` is a local: a derived constructor only gets one
7056 // when `super()` returns, and reading the raw receiver would give the *outer*
7057 // one instead.
7058 if self.cur().ctor_kind != CtorKind::None {
7059 self.emit_var(VarAction::Get, "this");
7060 return;
7061 }
7062 if !self.cur().is_arrow {
7063 self.push_this();
7064 return;
7065 }
7066 // An arrow at the **top level** of a script or module has no enclosing function,
7067 // but it still inherits `this` — the script's or module's own. Falling through to
7068 // `emit_var(Get, "this")` without a target made that a *global* lookup, so
7069 // `var f = () => typeof this` at top level reported
7070 // `ReferenceError: 'this' is not defined` instead of `"object"`
7071 // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
7072 // is the test262 case that reaches it, through a native `forEach`).
7073 //
7074 // The script state is the bottom of the stack, so it is the fallback target. Its
7075 // own `provide_this_local` then prepends the `push_this` the arrow reads.
7076 let target = self.enclosing_function().unwrap_or(0);
7077 self.state_at(target).needs_this_local = true;
7078 self.declare_at(target, "this");
7079 self.emit_var(VarAction::Get, "this");
7080 }
7081
7082 /// `new.target`, which an arrow likewise does not own.
7083 fn new_target_expression(&mut self) {
7084 if !self.cur().is_arrow {
7085 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
7086 return;
7087 }
7088 if let Some(target) = self.enclosing_function() {
7089 self.state_at(target).needs_new_target_local = true;
7090 self.declare_at(target, NEW_TARGET);
7091 }
7092 self.emit_var(VarAction::Get, NEW_TARGET);
7093 }
7094
7095 /// `this.active_func`: the function `super()` resolves against.
7096 ///
7097 /// In a constructor or a method that is the function being run, so the special object
7098 /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
7099 /// a closure variable — see [`FnState::needs_active_func_local`].
7100 fn active_func_expression(&mut self) {
7101 if !self.cur().is_arrow {
7102 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
7103 return;
7104 }
7105 if let Some(target) = self.enclosing_function() {
7106 self.state_at(target).needs_active_func_local = true;
7107 self.declare_at(target, ACTIVE_FUNC);
7108 }
7109 self.emit_var(VarAction::Get, ACTIVE_FUNC);
7110 }
7111
7112 /// Give the function a local `<active_func>`, for an arrow inside it to capture.
7113 fn provide_active_func_local(&mut self) {
7114 let current = self.stack.len() - 1;
7115 if !self.stack[current].needs_active_func_local {
7116 return;
7117 }
7118 if !self.stack[current]
7119 .vars
7120 .iter()
7121 .any(|var| var.name == ACTIVE_FUNC)
7122 {
7123 self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
7124 }
7125 self.prepend_initialiser(
7126 ACTIVE_FUNC,
7127 Insn::Fixed {
7128 op: Opcode::SpecialObject,
7129 operands: vec![Op::Int(2)],
7130 },
7131 );
7132 }
7133
7134 /// Give the function a local `new.target`, for an arrow inside it to capture.
7135 fn provide_new_target_local(&mut self) {
7136 let current = self.stack.len() - 1;
7137 if !self.stack[current].needs_new_target_local {
7138 return;
7139 }
7140 if !self.stack[current]
7141 .vars
7142 .iter()
7143 .any(|var| var.name == NEW_TARGET)
7144 {
7145 self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
7146 }
7147 self.prepend_initialiser(
7148 NEW_TARGET,
7149 Insn::Fixed {
7150 op: Opcode::SpecialObject,
7151 operands: vec![Op::Int(3)],
7152 },
7153 );
7154 }
7155
7156 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
7157 /// function.
7158 fn ensure_enclosing_arguments(&mut self) {
7159 // An arrow created in a parameter list needs the *parameter* scope's
7160 // `arguments`, not the body's: the two are separate bindings and the arrow was
7161 // born before the body existed.
7162 let from_params = self.cur().created_in_params;
7163 if let Some(target) = self.enclosing_function() {
7164 self.state_at(target).needs_arguments_local = true;
7165 if from_params {
7166 self.state_at(target).needs_param_arguments = true;
7167 // Declare it now, not at the enclosing function's `finish_current`: the
7168 // arrow resolves its own `arguments` before that runs, and a binding that
7169 // does not exist yet resolves as a global.
7170 declare_param_var_at(&mut self.stack[target], "arguments");
7171 }
7172 self.declare_at(target, "arguments");
7173 }
7174 }
7175
7176 /// The innermost enclosing frame that is a real function — an arrow inherits from it
7177 /// rather than starting a scope of its own.
7178 /// The innermost enclosing frame that can own a lexical binding an arrow reads —
7179 /// a real function, or a **script** top level.
7180 ///
7181 /// A script is in the list because an `eval` body is compiled as one and an arrow
7182 /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
7183 /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
7184 /// a *global* lookup of `new.target`, which no frame provides — so it raised
7185 /// `ReferenceError` instead of answering the caller's value
7186 /// (`arrow-body-direct-eval-err-contains-newtarget`).
7187 fn enclosing_function(&self) -> Option<usize> {
7188 (0..self.stack.len())
7189 .rev()
7190 .find(|index| !self.stack[*index].is_arrow)
7191 }
7192
7193 fn state_at(&mut self, index: usize) -> &mut FnState {
7194 &mut self.stack[index]
7195 }
7196
7197 /// Declare a `var` binding directly in a specific frame.
7198 fn declare_at(&mut self, index: usize, name: &str) {
7199 let state = &mut self.stack[index];
7200 if state.vars.iter().any(|var| var.name == name) {
7201 return;
7202 }
7203 state.var_block.push(FUNCTION_SCOPE);
7204 state.vars.push(VarDef::var(name));
7205 }
7206
7207 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
7208 /// the reference calls a `special_object` gets initialised on entry.
7209 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
7210 let current = self.stack.len() - 1;
7211 let init = [
7212 producer,
7213 Insn::Var {
7214 action: VarAction::Put,
7215 name: name.to_string(),
7216 block: 0,
7217 // A prologue initialiser runs before the body proper, but it is body
7218 // code: `this` and `arguments` are provided for it, not by it.
7219 in_params: false,
7220 },
7221 ];
7222 let inserted = init.len();
7223 for (index, instruction) in init.into_iter().enumerate() {
7224 self.stack[current].insns.insert(index, instruction);
7225 }
7226 for placed in self.stack[current].labels.iter_mut().flatten() {
7227 *placed += inserted;
7228 }
7229 self.stack[current].label_since_insn = true;
7230 }
7231
7232 fn push_constant(&mut self, constant: Constant) -> u32 {
7233 let state = self.state();
7234 let index = state.cpool.len() as u32;
7235 state.cpool.push(constant);
7236 index
7237 }
7238
7239 /// Compile `a && b`, `a || b`, `a ?? b`.
7240 ///
7241 /// A run of the *same* operator shares one end label, so `a || b || c` tests
7242 /// `a` once and jumps past everything when it is truthy, instead of falling
7243 /// into `b`'s test. The parser builds such a run left-associated —
7244 /// `((a || b) || c)` — so the operands are collected off the left spine.
7245 ///
7246 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
7247 /// `||`'s label, because the inner chain really does end before `&&` begins.
7248 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
7249 let mut operands = Vec::new();
7250 collect_same_operator(op, left, &mut operands);
7251 operands.push(right);
7252
7253 let end = self.new_label();
7254 // Every operand but the last decides whether the chain stops here.
7255 let last = operands.pop().expect("the right operand is always present");
7256 for operand in operands {
7257 self.expr(operand)?;
7258 self.emit(Opcode::Dup, &[]);
7259 match op {
7260 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
7261 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
7262 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
7263 // `0 || b` is `b`. The dedicated test keeps the value unless it is
7264 // null-ish, so the jump is taken on `false`.
7265 LogicalOp::Coalesce => {
7266 self.emit(Opcode::IsUndefinedOrNull, &[]);
7267 self.emit_jump(Opcode::IfFalse, end, &[]);
7268 }
7269 }
7270 self.emit(Opcode::Drop, &[]);
7271 }
7272 self.expr(last)?;
7273 self.place_label(end);
7274 Ok(())
7275 }
7276
7277 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
7278 match op {
7279 UnaryOp::Typeof => {
7280 // `typeof x` must not throw on an undeclared name.
7281 if let ExprKind::Ident(name) = &argument.kind {
7282 self.emit_var(VarAction::GetUndef, &name.name);
7283 } else {
7284 self.expr(argument)?;
7285 }
7286 self.emit(Opcode::Typeof, &[]);
7287 }
7288 UnaryOp::Delete => {
7289 // `delete obj.prop` really deletes, and answers whether it could.
7290 // Deleting a *binding* is always `false`: a local, an argument and a
7291 // declared global are all non-configurable, which the reference encodes
7292 // as a constant `push_false` rather than a runtime check. Only a
7293 // property access has anything to do at run time.
7294 // `delete super.x` is not a delete at all: the spec refuses it, and the
7295 // reference encodes the refusal as a `throw_error`. The receiver and the
7296 // key are still evaluated first, which is what keeps the evaluation order
7297 // of the operand intact.
7298 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
7299 // nothing to delete, and a failed delete is not the same as a skipped
7300 // one. The reference emits the guards so they land on a `drop; push_true`
7301 // tail, which is what this reproduces.
7302 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
7303 && let ExprKind::Member {
7304 object, property, ..
7305 } = &inner.unparen().kind
7306 {
7307 let end = self.new_label();
7308 let done = self.new_label();
7309 self.chain_link(object, end)?;
7310 match property {
7311 MemberProp::Ident(name) => self.emit(
7312 Opcode::PushAtomValue,
7313 &[Op::Atom(Atom::from_text(&name.name))],
7314 ),
7315 MemberProp::Computed(index) => self.expr(index)?,
7316 MemberProp::Private(_) => {
7317 return Err(SyntaxError::new(
7318 "deleting a private field is not allowed",
7319 argument.span,
7320 ));
7321 }
7322 }
7323 self.emit(Opcode::Delete, &[]);
7324 self.emit_jump(Opcode::Goto, done, &[]);
7325 self.place_label(end);
7326 self.emit(Opcode::Drop, &[]);
7327 self.emit(Opcode::PushTrue, &[]);
7328 self.place_label(done);
7329 return Ok(());
7330 }
7331 if let ExprKind::Member { object, .. } = &argument.unparen().kind
7332 && matches!(object.unparen().kind, ExprKind::SuperProp)
7333 {
7334 self.super_base();
7335 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
7336 return Ok(());
7337 }
7338 // Parentheses are transparent to `delete`: `(x)` is still a Reference to
7339 // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
7340 // does, and `delete (a().b)` still evaluates `a()`. Matching on the
7341 // unparenthesised operand is what keeps both — matching on `argument.kind`
7342 // sent every parenthesised form to the "not a Reference" arm, which cost
7343 // `delete(__variable) === false` in test262's `S12.2_A2`.
7344 match &argument.unparen().kind {
7345 ExprKind::Member {
7346 object, property, ..
7347 } => {
7348 self.expr(object)?;
7349 match property {
7350 MemberProp::Ident(name) => {
7351 self.emit(
7352 Opcode::PushAtomValue,
7353 &[Op::Atom(Atom::from_text(&name.name))],
7354 );
7355 }
7356 MemberProp::Computed(index) => self.expr(index)?,
7357 MemberProp::Private(_) => {
7358 return Err(SyntaxError::new(
7359 "deleting a private field is not allowed",
7360 argument.span,
7361 ));
7362 }
7363 }
7364 self.emit(Opcode::Delete, &[]);
7365 }
7366 ExprKind::Ident(name) => {
7367 self.delete_ident(&name.name);
7368 }
7369 // §13.5.1.2 step 2: an operand that is **not** a Reference Record
7370 // answers `true` — there is nothing to delete, and "nothing needed
7371 // deleting" is success. `delete !0`, `delete (1 + 2)` and
7372 // `delete typeof 0` are all `true`, and the operand is still evaluated
7373 // (which is why it is `Drop`ed rather than skipped:
7374 // `delete f()` must call `f`).
7375 //
7376 // Answering `false` here is the C reference's old behaviour and was
7377 // wrong in an observable way: test262's
7378 // `dynamic-import/assignment-expression/logical-and-expr` builds a
7379 // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
7380 // half turned the whole `&&` into `false`, so the import asked for a
7381 // module named "false".
7382 _ => {
7383 self.expr(argument)?;
7384 self.emit(Opcode::Drop, &[]);
7385 self.emit(Opcode::PushTrue, &[]);
7386 }
7387 }
7388 }
7389 UnaryOp::Void => {
7390 self.expr(argument)?;
7391 self.emit(Opcode::Drop, &[]);
7392 self.emit(Opcode::Undefined, &[]);
7393 }
7394 UnaryOp::Minus => {
7395 self.expr(argument)?;
7396 self.emit(Opcode::Neg, &[]);
7397 }
7398 UnaryOp::Plus => {
7399 self.expr(argument)?;
7400 self.emit(Opcode::Plus, &[]);
7401 }
7402 UnaryOp::Not => {
7403 self.expr(argument)?;
7404 self.emit(Opcode::Lnot, &[]);
7405 }
7406 UnaryOp::BitNot => {
7407 self.expr(argument)?;
7408 self.emit(Opcode::Not, &[]);
7409 }
7410 }
7411 Ok(())
7412 }
7413
7414 /// A store to `name` while a `with` may capture it.
7415 ///
7416 /// The reference is resolved **first**, before the right-hand side runs. That order is
7417 /// the whole point: in `x = (delete env.x, 0)` the resolution has already decided that
7418 /// `x` is `env`'s property, so `PutValue` then finds it gone and strict code throws
7419 /// `ReferenceError` (`set-mutable-binding-binding-deleted-with-typed-array-in-
7420 /// proto-chain-strict-mode`). The ordinary path evaluates the right-hand side before
7421 /// the guard runs, which put the guard *after* the mutation.
7422 ///
7423 /// Shapes mirror [`Compiler::assign_ident_plain`] and the member arms of
7424 /// [`Compiler::assign`], with `dup; with_get_var` in place of `get_field2` and
7425 /// `with_put_var` in place of `put_field` — the same stack effects, but each half also
7426 /// asks the `HasProperty` that `GetBindingValue`/`SetMutableBinding` require.
7427 fn with_assign(
7428 &mut self,
7429 with_local: &str,
7430 name: &Ident,
7431 op: AssignOp,
7432 value: &Expr,
7433 keep: bool,
7434 ) -> Result<(), SyntaxError> {
7435 let atom = Atom::from_text(&name.name);
7436 self.state().cur_pos = Some(name.span.start);
7437 match op {
7438 AssignOp::Assign => {
7439 self.expr(value)?;
7440 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7441 if keep {
7442 self.emit(Opcode::Dup, &[]);
7443 }
7444 self.state().no_value = !keep;
7445 self.emit_var(VarAction::Get, with_local);
7446 self.emit(Opcode::Swap, &[]);
7447 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7448 }
7449 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7450 let (keep_label, end) = (self.new_label(), self.new_label());
7451 self.emit_var(VarAction::Get, with_local);
7452 self.emit(Opcode::Dup, &[]);
7453 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7454 // `obj value` — the object stays underneath for the store.
7455 self.emit(Opcode::Dup, &[]);
7456 self.emit_logical_test(op);
7457 self.emit_jump(logical_jump(op), keep_label, &[]);
7458 self.emit(Opcode::Drop, &[]);
7459 self.expr(value)?;
7460 self.emit(Opcode::Insert2, &[]);
7461 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7462 self.emit_jump(Opcode::Goto, end, &[]);
7463 self.place_label(keep_label);
7464 self.emit(Opcode::Nip, &[]);
7465 self.place_label(end);
7466 }
7467 _ => {
7468 self.emit_var(VarAction::Get, with_local);
7469 self.emit(Opcode::Dup, &[]);
7470 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7471 self.expr(value)?;
7472 self.state().cur_pos = Some(name.span.start);
7473 self.emit(compound_opcode(op), &[]);
7474 self.state().no_value = !keep;
7475 if keep {
7476 self.emit(Opcode::Insert2, &[]);
7477 }
7478 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7479 }
7480 }
7481 Ok(())
7482 }
7483
7484 /// `x++` / `++x` while a `with` may capture `x`, with one resolution for both halves.
7485 fn with_update(
7486 &mut self,
7487 with_local: &str,
7488 name: &Ident,
7489 op: UpdateOp,
7490 prefix: bool,
7491 ) -> Result<(), SyntaxError> {
7492 let instruction = match (op, prefix) {
7493 (UpdateOp::Increment, true) => Opcode::Inc,
7494 (UpdateOp::Increment, false) => Opcode::PostInc,
7495 (UpdateOp::Decrement, true) => Opcode::Dec,
7496 (UpdateOp::Decrement, false) => Opcode::PostDec,
7497 };
7498 let atom = Atom::from_text(&name.name);
7499 self.state().cur_pos = Some(name.span.start);
7500 self.emit_var(VarAction::Get, with_local);
7501 self.emit(Opcode::Dup, &[]);
7502 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7503 self.emit(instruction, &[]);
7504 self.emit(
7505 if prefix {
7506 Opcode::Insert2
7507 } else {
7508 Opcode::Perm3
7509 },
7510 &[],
7511 );
7512 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7513 Ok(())
7514 }
7515
7516 /// A store to a plain identifier, with no `with` in the way.
7517 fn assign_ident_plain(
7518 &mut self,
7519 op: AssignOp,
7520 name: &Ident,
7521 value: &Expr,
7522 discard: bool,
7523 ) -> Result<(), SyntaxError> {
7524 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7525 // about, so it is set only when this assignment *is* that expression.
7526 let keep = !discard;
7527 // A *simple* store is blamed on the identifier, not on the `=`: a
7528 // strict-mode `not_def = 1` raises when the name is written, which the
7529 // reference reports at the name's column. A compound store is blamed on
7530 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
7531 // which the reference reports at the `+=`), so only the simple case
7532 // moves the position.
7533 let saved = self.cur().cur_pos;
7534 let name_pos = Some(name.span.start);
7535 if matches!(op, AssignOp::Assign) {
7536 self.state().cur_pos = name_pos;
7537 }
7538 // A *compound* store reads the binding before it combines, and that read
7539 // is blamed on the identifier: `not_def += 2` fails while reading
7540 // `not_def`, so the position is the name's, not the `+=`'s. The
7541 // combination that follows is blamed on the operator, which is why
7542 // `cur_pos` is put back to the operator position before it is emitted.
7543 self.state().cur_pos = name_pos;
7544 // A direct `eval` in the right-hand side can declare a `var` with this name in the
7545 // *caller's* variable environment, and from then on the name means that binding.
7546 // §13.15.3 resolves the lvalue once, at step 1, and stores through it at step 7 —
7547 // so the binding has to be pinned before the right-hand side runs.
7548 // `compound-assignment/S11.13.2_A6.*` and `assignment/S11.13.1_A6_*` are entirely
7549 // about this. One `__proto__`-shaped corner costs a reference object; every other
7550 // assignment is byte-for-byte what it was.
7551 let pinned = self.cur().eval_can_declare;
7552 if pinned {
7553 self.emit_var(VarAction::MakeRef, &name.name);
7554 }
7555 match op {
7556 AssignOp::Assign => {
7557 self.expr(value)?;
7558 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7559 if pinned {
7560 // `[ref, v] -> [v, ref, v] -> [v]`, the same `insert2` fold the
7561 // member stores use.
7562 if keep {
7563 self.emit(Opcode::Insert2, &[]);
7564 }
7565 self.emit(Opcode::PutRefValue, &[]);
7566 self.state().no_value = !keep;
7567 self.state().cur_pos = saved;
7568 return Ok(());
7569 }
7570 // A discarded store to a *slot* consumes its value, so no copy
7571 // is needed. A global store goes through `put_var`, which the
7572 // reference always pairs with a `dup` — matching it keeps the
7573 // bytecode identical. Getting this wrong is not only an extra
7574 // instruction: a stray copy gives the peephole a chance to fold
7575 // the store into an unrelated later read.
7576 let slot = self.is_slot(&name.name);
7577 if keep || !slot {
7578 self.emit(Opcode::Dup, &[]);
7579 }
7580 self.state().no_value = !keep && slot;
7581 self.emit_var(VarAction::Put, &name.name);
7582 }
7583 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7584 let end = self.new_label();
7585 // The pinned read leaves `[ref, v]`, so the branch that skips the store has
7586 // to `nip` the reference away; the branch that stores consumes it.
7587 self.emit_var(
7588 if pinned {
7589 VarAction::GetRef
7590 } else {
7591 VarAction::Get
7592 },
7593 &name.name,
7594 );
7595 self.state().cur_pos = saved;
7596 self.emit(Opcode::Dup, &[]);
7597 self.emit_logical_test(op);
7598 self.emit_jump(logical_jump(op), end, &[]);
7599 self.emit(Opcode::Drop, &[]);
7600 self.expr(value)?;
7601 // `x ||= function(){}` is a `NamedEvaluation` of the right-hand side, so the
7602 // function is named `x` — the same rule plain assignment follows
7603 // (`lgcl-*-namedevaluation-function`).
7604 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7605 if pinned {
7606 self.emit(Opcode::Insert2, &[]);
7607 self.emit(Opcode::PutRefValue, &[]);
7608 } else {
7609 self.emit(Opcode::Dup, &[]);
7610 self.emit_var(VarAction::Put, &name.name);
7611 }
7612 self.place_label(end);
7613 if pinned {
7614 self.emit(Opcode::Nip, &[]);
7615 }
7616 }
7617 _ => {
7618 self.emit_var(
7619 if pinned {
7620 VarAction::GetRef
7621 } else {
7622 VarAction::Get
7623 },
7624 &name.name,
7625 );
7626 self.expr(value)?;
7627 self.state().cur_pos = saved;
7628 self.emit(compound_opcode(op), &[]);
7629 if pinned {
7630 self.emit(Opcode::Insert2, &[]);
7631 self.emit(Opcode::PutRefValue, &[]);
7632 } else {
7633 self.emit(Opcode::Dup, &[]);
7634 self.emit_var(VarAction::Put, &name.name);
7635 }
7636 }
7637 }
7638 self.state().cur_pos = saved;
7639 Ok(())
7640 }
7641
7642 /// Compile an assignment.
7643 ///
7644 /// Three operator families, three shapes:
7645 ///
7646 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
7647 /// the value is kept, because `put_field`/`put_array_el` consume both the
7648 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
7649 /// the pair it wants and leaves a copy on top.
7650 /// * **compound** `+=` … — read the place, apply the operator, store. A member
7651 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
7652 /// index) underneath the value precisely so the store can follow.
7653 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
7654 /// right-hand side. The test *keeps* the current value and skips the store
7655 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
7656 /// `a` is already truthy.
7657 fn assign(
7658 &mut self,
7659 op: AssignOp,
7660 target: &Pattern,
7661 value: &Expr,
7662 discard: bool,
7663 ) -> Result<(), SyntaxError> {
7664 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7665 // about, so it is set only when this assignment *is* that expression.
7666 let keep = !discard;
7667 match &target.kind {
7668 PatternKind::Ident(name) => {
7669 // Any store to a name a `with` may capture resolves the reference first and
7670 // keeps that resolution for both halves — see [`Compiler::with_assign`].
7671 // Plain `=` needs it just as much as `+=`: `x = (delete env.x, 0)` must
7672 // resolve `x` before the right-hand side deletes it.
7673 let plain_name = name.name.clone();
7674 if !self.visible_with_names(&plain_name).is_empty() {
7675 return self.with_reference(
7676 &plain_name,
7677 &mut |compiler, with_local| {
7678 compiler.with_assign(with_local, name, op, value, !discard)
7679 },
7680 &mut |compiler| compiler.assign_ident_plain(op, name, value, discard),
7681 );
7682 }
7683 self.assign_ident_plain(op, name, value, discard)
7684 }
7685 PatternKind::Member(member) => {
7686 // `super.x = v` is not a store through a value: it starts at the home
7687 // object's prototype but writes to `this`, so it goes through
7688 // `put_super_value` rather than `put_field`. The receiver, prototype, key
7689 // and value are handed over together.
7690 if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
7691 return self.assign_super(member, op, value);
7692 }
7693 // A store is blamed on the selector punctuator (`.` or `[`), the same
7694 // token a load is blamed on — the reference records `put_field obj.a`
7695 // at the `.`, so a setter that throws reports that column and not the
7696 // `=` of the assignment it sits in. The inner expressions restore their
7697 // own positions, so the selector's sticks for the store instructions.
7698 let saved = self.cur().cur_pos;
7699 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7700 self.expr(&member.object)?;
7701 match &member.property {
7702 MemberProp::Ident(property) => {
7703 let atom = Atom::from_text(&property.name);
7704 match op {
7705 AssignOp::Assign => {
7706 self.expr(value)?;
7707 // `put_field` consumes the object and the value, so
7708 // without `insert2` nothing is left over for the
7709 // statement to drop.
7710 self.state().no_value = !keep;
7711 if keep {
7712 self.emit(Opcode::Insert2, &[]);
7713 }
7714 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7715 }
7716 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7717 // `get_field2` leaves the object under the value, so
7718 // the keep path has an object to dispose of. The store
7719 // path must jump *over* that cleanup: falling into it
7720 // would `nip` a stack that only holds the value.
7721 let (keep_label, end) = (self.new_label(), self.new_label());
7722 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7723 self.emit(Opcode::Dup, &[]);
7724 self.emit_logical_test(op);
7725 self.emit_jump(logical_jump(op), keep_label, &[]);
7726 self.emit(Opcode::Drop, &[]);
7727 self.expr(value)?;
7728 self.emit(Opcode::Insert2, &[]);
7729 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7730 self.emit_jump(Opcode::Goto, end, &[]);
7731 self.place_label(keep_label);
7732 self.emit(Opcode::Nip, &[]);
7733 self.place_label(end);
7734 }
7735 _ => {
7736 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7737 self.expr(value)?;
7738 self.emit(compound_opcode(op), &[]);
7739 self.state().no_value = !keep;
7740 if keep {
7741 self.emit(Opcode::Insert2, &[]);
7742 }
7743 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7744 }
7745 }
7746 }
7747 MemberProp::Computed(index) => {
7748 self.expr(index)?;
7749 match op {
7750 AssignOp::Assign => {
7751 self.expr(value)?;
7752 self.state().no_value = !keep;
7753 if keep {
7754 self.emit(Opcode::Insert3, &[]);
7755 }
7756 self.emit(Opcode::PutArrayEl, &[]);
7757 }
7758 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7759 let (keep_label, end) = (self.new_label(), self.new_label());
7760 self.emit(Opcode::GetArrayEl3, &[]);
7761 self.emit(Opcode::Dup, &[]);
7762 self.emit_logical_test(op);
7763 self.emit_jump(logical_jump(op), keep_label, &[]);
7764 self.emit(Opcode::Drop, &[]);
7765 self.expr(value)?;
7766 self.emit(Opcode::Insert3, &[]);
7767 self.emit(Opcode::PutArrayEl, &[]);
7768 self.emit_jump(Opcode::Goto, end, &[]);
7769 self.place_label(keep_label);
7770 // Both the object and the index are left over.
7771 self.emit(Opcode::Nip, &[]);
7772 self.emit(Opcode::Nip, &[]);
7773 self.place_label(end);
7774 }
7775 _ => {
7776 self.emit(Opcode::GetArrayEl3, &[]);
7777 self.expr(value)?;
7778 self.emit(compound_opcode(op), &[]);
7779 self.state().no_value = !keep;
7780 if keep {
7781 self.emit(Opcode::Insert3, &[]);
7782 }
7783 self.emit(Opcode::PutArrayEl, &[]);
7784 }
7785 }
7786 }
7787 MemberProp::Private(name) => {
7788 // `obj value` is on the stack, and every private store wants exactly
7789 // that. A top-level private name cannot be assigned (the parser rejects
7790 // `#x = 1`), so the only way here is `this.#x = …` inside the class.
7791 //
7792 // The reference emits `insert2` whether or not the value is wanted,
7793 // so this does too: the copy left behind is the assignment expression's
7794 // value, and a discarded one is simply never read.
7795 let binding = format!("#{}", name.name);
7796 let (kind, setter) = self.private_use(&binding, member.span)?;
7797 match op {
7798 AssignOp::Assign => {
7799 self.expr(value)?;
7800 if keep {
7801 self.emit(Opcode::Insert2, &[]);
7802 }
7803 self.private_store(&binding, kind, setter.as_deref())?;
7804 self.state().no_value = !keep;
7805 }
7806 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7807 let (keep_label, end) = (self.new_label(), self.new_label());
7808 self.emit(Opcode::Dup, &[]);
7809 self.private_load(&binding, kind, member.span)?;
7810 self.emit(Opcode::Dup, &[]);
7811 self.emit_logical_test(op);
7812 self.emit_jump(logical_jump(op), keep_label, &[]);
7813 self.emit(Opcode::Drop, &[]);
7814 self.expr(value)?;
7815 self.emit(Opcode::Insert2, &[]);
7816 self.private_store(&binding, kind, setter.as_deref())?;
7817 self.emit_jump(Opcode::Goto, end, &[]);
7818 self.place_label(keep_label);
7819 self.emit(Opcode::Nip, &[]);
7820 self.place_label(end);
7821 }
7822 _ => {
7823 self.emit(Opcode::Dup, &[]);
7824 self.private_load(&binding, kind, member.span)?;
7825 self.expr(value)?;
7826 self.emit(compound_opcode(op), &[]);
7827 self.emit(Opcode::Insert2, &[]);
7828 self.private_store(&binding, kind, setter.as_deref())?;
7829 }
7830 }
7831 }
7832 }
7833 self.state().cur_pos = saved;
7834 Ok(())
7835 }
7836 // A destructuring assignment: the right-hand side is the expression's own
7837 // value, so it is evaluated once and kept under the pattern's stores.
7838 PatternKind::Array { .. } | PatternKind::Object { .. } => {
7839 self.expr(value)?;
7840 if keep {
7841 self.emit(Opcode::Dup, &[]);
7842 }
7843 self.destructure(target, None)?;
7844 self.state().no_value = !keep;
7845 Ok(())
7846 }
7847 _ => Err(SyntaxError::new(
7848 "this assignment target is not supported by the compiler yet",
7849 target.span,
7850 )),
7851 }
7852 }
7853
7854 /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
7855 ///
7856 /// The stack has to carry four values — receiver, prototype, key, value — because
7857 /// `put_super_value` takes them together; the receiver is what makes a setter found on
7858 /// the prototype run with `this`, and the key has to survive until the store, which is
7859 /// why a compound form converts it to a property key once and `dup3`s rather than
7860 /// evaluating it twice.
7861 fn assign_super(
7862 &mut self,
7863 member: &MemberPattern,
7864 op: AssignOp,
7865 value: &Expr,
7866 ) -> Result<(), SyntaxError> {
7867 let saved = self.cur().cur_pos;
7868 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7869 self.super_base();
7870 match &member.property {
7871 MemberProp::Ident(property) => self.emit(
7872 Opcode::PushAtomValue,
7873 &[Op::Atom(Atom::from_text(&property.name))],
7874 ),
7875 MemberProp::Computed(index) => self.expr(index)?,
7876 MemberProp::Private(_) => {
7877 return Err(SyntaxError::new(
7878 "private fields are not supported by the compiler yet",
7879 member.span,
7880 ));
7881 }
7882 }
7883 match op {
7884 AssignOp::Assign => {
7885 // The key is only converted once, by `put_super_value` itself, so a
7886 // computed key's `toString` runs exactly once.
7887 self.expr(value)?;
7888 self.emit(Opcode::Insert4, &[]);
7889 self.emit(Opcode::PutSuperValue, &[]);
7890 }
7891 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7892 let (keep_label, end) = (self.new_label(), self.new_label());
7893 self.emit(Opcode::ToPropkey, &[]);
7894 self.emit(Opcode::Dup3, &[]);
7895 self.emit(Opcode::GetSuperValue, &[]);
7896 self.emit(Opcode::Dup, &[]);
7897 self.emit_logical_test(op);
7898 self.emit_jump(logical_jump(op), keep_label, &[]);
7899 self.emit(Opcode::Drop, &[]);
7900 self.expr(value)?;
7901 self.emit(Opcode::Insert4, &[]);
7902 self.emit(Opcode::PutSuperValue, &[]);
7903 self.emit_jump(Opcode::Goto, end, &[]);
7904 self.place_label(keep_label);
7905 // The prototype and the key are still under the value that was read.
7906 self.emit(Opcode::Nip, &[]);
7907 self.emit(Opcode::Nip, &[]);
7908 self.emit(Opcode::Nip, &[]);
7909 self.place_label(end);
7910 }
7911 _ => {
7912 self.emit(Opcode::ToPropkey, &[]);
7913 self.emit(Opcode::Dup3, &[]);
7914 self.emit(Opcode::GetSuperValue, &[]);
7915 self.expr(value)?;
7916 self.emit(compound_opcode(op), &[]);
7917 self.emit(Opcode::Insert4, &[]);
7918 self.emit(Opcode::PutSuperValue, &[]);
7919 }
7920 }
7921 // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7922 // is still on the stack when the store finishes, and the expression statement is
7923 // what disposes of it — the same arrangement as `put_field`, reached from the other
7924 // side: there the store consumes the value (`no_value`), here it leaves it
7925 // (`keep` already false, so nothing tells the statement otherwise).
7926 self.state().cur_pos = saved;
7927 Ok(())
7928 }
7929
7930 /// The test a logical assignment applies to the current value.
7931 ///
7932 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7933 /// assign, while `0 ||= b` must not.
7934 fn emit_logical_test(&mut self, op: AssignOp) {
7935 if op == AssignOp::Coalesce {
7936 self.emit(Opcode::IsUndefinedOrNull, &[]);
7937 }
7938 }
7939
7940 /// The private name `#name` this use site resolves against.
7941 ///
7942 /// The parser has already rejected a name no enclosing class declares, so a miss here
7943 /// means the compiler lost track of a class scope — which is worth a real error rather
7944 /// than an `unwrap`.
7945 fn private_use(
7946 &self,
7947 binding: &str,
7948 span: Span,
7949 ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7950 ClassPlan::find(self, binding)
7951 .map(|use_| (use_.kind, use_.setter.clone()))
7952 .ok_or_else(|| {
7953 SyntaxError::new(
7954 format!("the private name '{binding}' is out of scope here"),
7955 span,
7956 )
7957 })
7958 }
7959
7960 /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7961 ///
7962 /// The three readable kinds take three different instructions, because a private name
7963 /// holds three different things — a symbol, a method function, a getter function — and
7964 /// only the first one is a property read at all.
7965 fn private_load(
7966 &mut self,
7967 binding: &str,
7968 kind: PrivateKind,
7969 span: Span,
7970 ) -> Result<(), SyntaxError> {
7971 match kind {
7972 PrivateKind::Field => {
7973 self.emit_var(VarAction::Get, binding);
7974 self.emit(Opcode::GetPrivateField, &[]);
7975 }
7976 PrivateKind::Method => {
7977 self.emit_var(VarAction::Get, binding);
7978 self.emit(Opcode::CheckBrand, &[]);
7979 // `check_brand` reads `obj func` and leaves both; the method itself is what
7980 // `this.#m` evaluates to.
7981 self.emit(Opcode::Nip, &[]);
7982 }
7983 PrivateKind::Getter => {
7984 self.emit_var(VarAction::Get, binding);
7985 self.emit(Opcode::CheckBrand, &[]);
7986 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7987 }
7988 // `#a` is declared but never filled when only a setter exists, so reading it is
7989 // the same refusal as assigning to a `const`. The reference reports it with the
7990 // generic read-only wording and leaves the better message as a `XXX`.
7991 PrivateKind::Setter => self.emit(
7992 Opcode::ThrowError,
7993 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7994 ),
7995 }
7996 let _ = span;
7997 Ok(())
7998 }
7999
8000 /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
8001 fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
8002 match kind {
8003 // A method *is* the callee, so only the check goes in between.
8004 PrivateKind::Method => {
8005 self.emit_var(VarAction::Get, binding);
8006 self.emit(Opcode::CheckBrand, &[]);
8007 }
8008 _ => self.private_load(binding, kind, Span::default())?,
8009 }
8010 Ok(())
8011 }
8012
8013 /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
8014 /// wanted back.
8015 ///
8016 /// A getter/setter pair is a *method call*, not a property store: the reference reads
8017 /// the setter out of its own binding and calls it with the receiver, which is why the
8018 /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
8019 /// keeps the assignment's value for an expression context.
8020 fn private_store(
8021 &mut self,
8022 binding: &str,
8023 kind: PrivateKind,
8024 setter: Option<&str>,
8025 ) -> Result<(), SyntaxError> {
8026 match kind {
8027 PrivateKind::Field => {
8028 self.emit_var(VarAction::Get, binding);
8029 self.emit(Opcode::PutPrivateField, &[]);
8030 }
8031 PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
8032 Some(setter) => {
8033 self.emit_var(VarAction::Get, setter);
8034 // `obj func value` -> `value obj func` for the check, and back again for
8035 // the call, which wants `obj func arg`.
8036 self.emit(Opcode::Swap, &[]);
8037 self.emit(Opcode::Rot3r, &[]);
8038 self.emit(Opcode::CheckBrand, &[]);
8039 self.emit(Opcode::Rot3l, &[]);
8040 self.emit(Opcode::CallMethod, &[Op::Int(1)]);
8041 // The setter's return value is discarded; the assignment's own value is
8042 // whatever the caller left underneath.
8043 self.emit(Opcode::Drop, &[]);
8044 }
8045 None => self.emit(
8046 Opcode::ThrowError,
8047 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
8048 ),
8049 },
8050 }
8051 Ok(())
8052 }
8053
8054 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
8055 // `x++` inside a `with` is a read-modify-write of a *property*, so the object is
8056 // resolved once for both halves. See [`Compiler::with_reference`].
8057 let unparened = argument.unparen();
8058 if let ExprKind::Ident(ident) = &unparened.kind {
8059 let name = ident.name.clone();
8060 if !self.visible_with_names(&name).is_empty() {
8061 return self.with_reference(
8062 &name,
8063 &mut |compiler, with_local| compiler.with_update(with_local, ident, op, prefix),
8064 &mut |compiler| compiler.update_plain(op, unparened, prefix),
8065 );
8066 }
8067 }
8068 self.update_plain(op, argument, prefix)
8069 }
8070
8071 fn update_plain(
8072 &mut self,
8073 op: UpdateOp,
8074 argument: &Expr,
8075 prefix: bool,
8076 ) -> Result<(), SyntaxError> {
8077 let instruction = match (op, prefix) {
8078 (UpdateOp::Increment, true) => Opcode::Inc,
8079 (UpdateOp::Increment, false) => Opcode::PostInc,
8080 (UpdateOp::Decrement, true) => Opcode::Dec,
8081 (UpdateOp::Decrement, false) => Opcode::PostDec,
8082 };
8083 // `(y)++` and `((o.x))++` are the same updates as the unparenthesised forms: §13.4
8084 // evaluates the operand as a `LeftHandSideExpression` and the parentheses around a
8085 // reference change nothing — they do not copy the value. Reading `argument.kind`
8086 // directly therefore rejected every parenthesised target with "increment of a
8087 // non-variable", which is not a thing the language has (`target-cover-id`).
8088 let argument = argument.unparen();
8089 if let ExprKind::Member {
8090 object,
8091 property,
8092 optional: _,
8093 } = &argument.kind
8094 {
8095 // `o.x++` needs the receiver twice, so the last link is read with the
8096 // `get_*2`/`get_*3` form that keeps it, and the update is written back
8097 // with `put_field`/`put_array_el`. The reordering in between is what puts
8098 // the old value below the receiver for a postfix update and the new one
8099 // above it for a prefix one:
8100 //
8101 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
8102 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
8103 //
8104 // This mirrors the reference instruction for instruction.
8105 self.expr(object)?;
8106 match property {
8107 MemberProp::Ident(name) => {
8108 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
8109 self.emit(instruction, &[]);
8110 self.emit(
8111 if prefix {
8112 Opcode::Insert2
8113 } else {
8114 Opcode::Perm3
8115 },
8116 &[],
8117 );
8118 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
8119 }
8120 MemberProp::Computed(index) => {
8121 self.expr(index)?;
8122 self.emit(Opcode::GetArrayEl3, &[]);
8123 self.emit(instruction, &[]);
8124 self.emit(
8125 if prefix {
8126 Opcode::Insert3
8127 } else {
8128 Opcode::Perm4
8129 },
8130 &[],
8131 );
8132 self.emit(Opcode::PutArrayEl, &[]);
8133 }
8134 MemberProp::Private(name) => {
8135 // The receiver is duplicated and the read keeps it, exactly as `get_field2`
8136 // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
8137 // `perm3` -> `old obj new` -> store.
8138 let binding = format!("#{}", name.name);
8139 let (kind, setter) = self.private_use(&binding, argument.span)?;
8140 self.emit(Opcode::Dup, &[]);
8141 self.private_load(&binding, kind, argument.span)?;
8142 self.emit(instruction, &[]);
8143 self.emit(
8144 if prefix {
8145 Opcode::Insert2
8146 } else {
8147 Opcode::Perm3
8148 },
8149 &[],
8150 );
8151 self.private_store(&binding, kind, setter.as_deref())?;
8152 }
8153 }
8154 return Ok(());
8155 }
8156 let ExprKind::Ident(name) = &argument.kind else {
8157 return Err(SyntaxError::new(
8158 "increment of a non-variable is not supported by the compiler yet",
8159 argument.span,
8160 ));
8161 };
8162 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
8163 // reference's `inc_loc` folds those three into one, but it does so only in some
8164 // positions (a `for` update and not a bare statement, and never for a lexical
8165 // binding), so emitting it unconditionally would move *away* from its output.
8166 // The instruction is equivalent either way; matching the reference matters more
8167 // than saving two instructions.
8168 let _ = !std::mem::take(&mut self.state().discard_value);
8169 self.emit_var(VarAction::Get, &name.name);
8170 self.emit(instruction, &[]);
8171 if prefix {
8172 self.emit(Opcode::Dup, &[]);
8173 }
8174 self.emit_var(VarAction::Put, &name.name);
8175 Ok(())
8176 }
8177
8178 /// Compile an array literal.
8179 ///
8180 /// The reference splits this into three phases, and the split is load-bearing
8181 /// rather than an optimisation detail:
8182 ///
8183 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
8184 /// the array in one instruction.
8185 /// 2. **Everything up to the first spread** is appended with explicit indices
8186 /// (`define_field <index>`), because a hole has no element to pass to
8187 /// `array_from`. A hole here is what makes `length` need fixing up: an
8188 /// explicit index does not extend the array the way a pushed element does.
8189 /// 3. **From the first spread on** the index lives on the stack, so `append` and
8190 /// `define_array_el` can consume it and `inc` advances it.
8191 ///
8192 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
8193 /// forces phase 2, and `[...a]` forces phase 3.
8194 fn array_literal(
8195 &mut self,
8196 elements: &[Option<ArrayElement>],
8197 span: Span,
8198 ) -> Result<(), SyntaxError> {
8199 let _ = span;
8200 let mut index: u32 = 0;
8201 let mut cursor = 0usize;
8202
8203 // Phase 1: a leading run of plain elements, at most 32 of them.
8204 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
8205 if index >= 32 {
8206 break;
8207 }
8208 self.expr(element)?;
8209 index += 1;
8210 cursor += 1;
8211 }
8212 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
8213
8214 // Phase 2: explicit indices, up to the first spread.
8215 let mut need_length = false;
8216 while let Some(element) = elements.get(cursor) {
8217 if matches!(element, Some(ArrayElement::Spread(_))) {
8218 break;
8219 }
8220 need_length = true;
8221 if let Some(ArrayElement::Expr(expression)) = element {
8222 self.expr(expression)?;
8223 self.emit_define_index(index);
8224 need_length = false;
8225 }
8226 index += 1;
8227 cursor += 1;
8228 }
8229
8230 if cursor >= elements.len() {
8231 if need_length {
8232 // `define_field` cannot set `length`, which is not configurable.
8233 self.emit(Opcode::Dup, &[]);
8234 self.push_number(index as f64);
8235 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8236 }
8237 return Ok(());
8238 }
8239
8240 // Phase 3: the index moves onto the stack for the spreading tail.
8241 //
8242 // `need_length` deliberately carries over from phase 2: a hole before the
8243 // first spread still has to be reflected in `length`, and only the final
8244 // check can do it because the array is not finished until the tail is
8245 // appended.
8246 self.push_number(index as f64);
8247 while let Some(element) = elements.get(cursor) {
8248 match element {
8249 Some(ArrayElement::Spread(expression)) => {
8250 // `append` copies an iterable and leaves the next index behind,
8251 // so no `inc` is needed here.
8252 self.expr(spread_argument(expression))?;
8253 self.emit(Opcode::Append, &[]);
8254 }
8255 None | Some(ArrayElement::Expr(_)) => {
8256 need_length = true;
8257 if let Some(ArrayElement::Expr(expression)) = element {
8258 self.expr(expression)?;
8259 self.emit(Opcode::DefineArrayEl, &[]);
8260 need_length = false;
8261 }
8262 self.emit(Opcode::Inc, &[]);
8263 }
8264 }
8265 cursor += 1;
8266 }
8267 if need_length {
8268 self.emit(Opcode::Dup1, &[]);
8269 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8270 } else {
8271 self.emit(Opcode::Drop, &[]);
8272 }
8273 Ok(())
8274 }
8275
8276 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
8277 fn emit_define_index(&mut self, index: u32) {
8278 self.emit(
8279 Opcode::DefineField,
8280 &[Op::Atom(Atom::from_text(&index.to_string()))],
8281 );
8282 }
8283
8284 // -- functions ---------------------------------------------------------
8285
8286 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
8287 self.compile_function_with_name(func, false)
8288 }
8289
8290 /// Compile a function, recording whether it is a *named function expression*.
8291 ///
8292 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
8293 /// must not leak outside. The reference does that by declaring `g` as a local of
8294 /// the function itself and initialising it with `special_object 2` (the current
8295 /// function), which is why this has to be known at compile time.
8296 fn compile_function_with_name(
8297 &mut self,
8298 func: &ast::Function,
8299 is_expression: bool,
8300 ) -> Result<CompiledFunction, SyntaxError> {
8301 let kind = match (func.is_generator, func.is_async) {
8302 (false, false) => FunctionKind::Normal,
8303 (true, false) => FunctionKind::Generator,
8304 (false, true) => FunctionKind::Async,
8305 (true, true) => FunctionKind::AsyncGenerator,
8306 };
8307 let mut state = FnState::new(
8308 func.name
8309 .as_ref()
8310 .map(|n| n.name.clone())
8311 .unwrap_or_default(),
8312 kind,
8313 );
8314 // The function's own mode, recorded by the parser. Inheriting the enclosing
8315 // function's instead let a nested `"use strict"` directive be ignored, so the
8316 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
8317 state.strict = func.strict;
8318 // A function defined inside a `with` block keeps seeing that object: the guard
8319 // chain names the enclosing `<with>` locals, which resolve outward into closure
8320 // variables exactly like any other captured binding.
8321 state.inherited_with_names = self.cur().with_names.len();
8322 state.with_names = self.cur().with_names.clone();
8323 state.is_arrow = func.is_arrow;
8324 // Known before the body is compiled, so an lvalue can decide whether to pin its
8325 // reference before emitting the read. See [`FnState::eval_can_declare`].
8326 state.eval_can_declare = func.has_direct_eval;
8327 state.created_in_block = self.cur().current_block;
8328 // A default anywhere in the parameter list is what gives the function two
8329 // variable environments. The reference decides this the same way: it scans the
8330 // parenthesis for a top-level `=`, so a destructured name without a default
8331 // stays a plain function-scope binding.
8332 state.in_params = false;
8333 // The reference scans the parenthesis for *any* `=`, including one nested inside
8334 // a pattern, so `function f({a = 1})` has parameter expressions even though the
8335 // parameter itself carries no initialiser.
8336 state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
8337 // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
8338 // flag above this looks at the *shape* of each parameter, not just for `=`.
8339 state.simple_parameter_list = func
8340 .params
8341 .iter()
8342 .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
8343 // A function born inside a parameter list inherits the prohibition: it must not
8344 // see the body bindings of the function it was created in.
8345 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
8346 // A class constructor knows what it is only because the class told it.
8347 if let Some(kind) = self.cur().class_ctor_pending {
8348 state.ctor_kind = kind;
8349 }
8350 // A named *expression* binds its own name; a declaration's name is already
8351 // bound in the enclosing scope.
8352 state.self_name = if is_expression && !func.is_arrow {
8353 func.name.as_ref().map(|n| n.name.clone())
8354 } else {
8355 None
8356 };
8357 // Keep the written range so `Function.prototype.toString` can answer with the
8358 // original text rather than `[native code]`.
8359 //
8360 // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
8361 // accessor and generator prefixes, and for a method it must not include the name
8362 // or a leading `static`. `params_span` is exactly that boundary.
8363 // A *method* keeps the old `[native code]` answer: its reported text is defined
8364 // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
8365 // the comments in between kept verbatim), and reconstructing that from a byte
8366 // span got it wrong in more cases than it got right. A plain function and an
8367 // arrow are the shapes libraries actually introspect, and those are exact.
8368 // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
8369 // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
8370 // so the same slice works for every form. (`Params_span` is the boundary that
8371 // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
8372 // `source_span` is set only where the reported text is not the function's own
8373 // range — a class's constructor reports the whole class definition.
8374 let reported = func.source_span.unwrap_or(func.span);
8375 state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
8376 state.line = func.span.start.line;
8377 state.column = func.span.start.column;
8378 // A function body has no hidden `<ret>` local; the value comes back on
8379 // the stack. Only a script keeps one.
8380 // Parameters are positional, so even a pattern occupies one argument slot. A
8381 // simple name is that slot itself; anything else (a pattern, a default, a rest
8382 // parameter) takes an anonymous slot and is unpicked into locals at the top of
8383 // the body, which is the only way one argument can bind several names.
8384 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
8385 // `.length` stops at the first parameter that can be substituted: a default
8386 // fills a missing argument in, and a rest parameter absorbs the rest.
8387 let mut defined_args = func.params.len() as u32;
8388 for (index, param) in func.params.iter().enumerate() {
8389 match simple_parameter(param) {
8390 Some(name) => state.args.push(VarDef::var(name.name.clone())),
8391 None => {
8392 state.args.push(VarDef::var(ANONYMOUS_BINDING));
8393 prologue.push((index, param.clone()));
8394 }
8395 }
8396 }
8397 // A default anywhere before the end also ends the count, which the loop above
8398 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
8399 for (position, param) in func.params.iter().enumerate() {
8400 if matches!(
8401 param.kind,
8402 PatternKind::Assign { .. } | PatternKind::Rest(_)
8403 ) {
8404 defined_args = position as u32;
8405 break;
8406 }
8407 }
8408 state.defined_args = defined_args;
8409 state.param_prologue = prologue;
8410 let depth = self.stack.len();
8411 self.stack.push(state);
8412 let result = self.compile_function_body(func);
8413 if result.is_err() {
8414 // A failed compile must not leave its `FnState` behind. Every caller
8415 // reads `self.state()` as "the function being compiled", so a leftover
8416 // frame silently retargets all later bookkeeping at a dead function.
8417 self.stack.truncate(depth);
8418 }
8419 result
8420 }
8421
8422 /// The body of a function, with its frame already pushed.
8423 fn compile_function_body(
8424 &mut self,
8425 func: &ast::Function,
8426 ) -> Result<CompiledFunction, SyntaxError> {
8427 let body_key = func.params_span.end.offset as u64;
8428 // Where the body begins, in source order. The runtime needs this to tell a
8429 // closure created by a default expression from one the body creates — the two see
8430 // different variable environments — and a bytecode offset would not survive the
8431 // instruction shuffling that building the frame does. Positions are in source
8432 // order, so a comparison answers it.
8433 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
8434 self.push_block(body_key, NO_PARENT);
8435 self.state().body_block = body_key;
8436 // An arrow with an expression body has no statements; the expression is
8437 // its `return`. Building the statement here keeps one code path below, and
8438 // matters for correctness beyond convenience: returning early with the new
8439 // `FnState` still on the stack would leave the compiler looking at the
8440 // wrong function, which surfaces as an unrelated underflow later.
8441 let concise = match &func.body {
8442 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
8443 StmtKind::Return(Some(Box::new((**value).clone()))),
8444 value.span,
8445 )),
8446 js_parse::ast::FunctionBody::Block(_) => None,
8447 };
8448 let body: &[Stmt] = match &concise {
8449 Some(stmt) => std::slice::from_ref(stmt),
8450 None => func
8451 .body
8452 .statements()
8453 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
8454 };
8455 let prologue = std::mem::take(&mut self.state().param_prologue);
8456 let has_param_scope = self.cur().has_parameter_expressions;
8457 // The parameter scope's own bindings, declared in source order.
8458 //
8459 // With parameter expressions the list gets a variable environment of its own, and
8460 // every name it binds is a `let` there. That is what puts the *list* in the
8461 // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
8462 // and `function f(x = y, y){}` does the same, where a single shared environment
8463 // would answer `undefined` to both.
8464 if has_param_scope {
8465 let mut declared: Vec<String> = Vec::new();
8466 for param in &func.params {
8467 let mut names = Vec::new();
8468 param.bound_names(&mut names);
8469 for name in names {
8470 if declared.contains(&name.name) {
8471 continue;
8472 }
8473 declared.push(name.name.clone());
8474 self.declare_param_binding(&name.name);
8475 }
8476 }
8477 }
8478 // A pattern parameter binds its names as function-scope locals, so they have to
8479 // exist — and be unpicked from the argument — before the body runs. With a
8480 // parameter scope these are the *second* environment: the pattern fills the
8481 // parameter's copy, and the body's binding is filled from it afterwards.
8482 for (_, pattern) in &prologue {
8483 let mut names = Vec::new();
8484 pattern.bound_names(&mut names);
8485 for name in names {
8486 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
8487 }
8488 }
8489 self.hoist(body, body_key)?;
8490 // A constructor's prologue is not a parameter unpacking but the `this` binding:
8491 // a base constructor takes the receiver, a derived one starts in the dead zone
8492 // because only `super()` may produce it.
8493 match self.cur().ctor_kind {
8494 CtorKind::None => {}
8495 CtorKind::Base => {
8496 self.begin_this_local();
8497 self.emit(Opcode::CheckCtor, &[]);
8498 // Instance fields are installed at the top of a base constructor's body,
8499 // before any statement — `class C { x = 1; constructor() { this.x } }` sees
8500 // `1`. This used to be emitted at the *tail*, which made every field read
8501 // `undefined` inside the constructor that declared it.
8502 self.call_field_initialiser();
8503 }
8504 CtorKind::Derived => {
8505 self.declare("this", VarDef::lexical("this"));
8506 let slot = self.cur().vars.len() as u32 - 1;
8507 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8508 self.emit(Opcode::CheckCtor, &[]);
8509 }
8510 }
8511 // Entering the parameter list: everything it binds starts in the dead zone.
8512 // The order is the reference's — it walks the scope chain, which is prepended, so
8513 // the bindings come out newest first.
8514 for name in self.param_binding_names().into_iter().rev() {
8515 if let Some(slot) = self.param_binding_slot(&name) {
8516 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8517 }
8518 }
8519 // The whole parameter list is one scope, and nothing in the body exists yet, so
8520 // every name it mentions resolves against the parameter bindings and outward.
8521 self.state().in_params = has_param_scope;
8522 for (index, param) in func.params.iter().enumerate() {
8523 if let Some(pattern) = prologue_pattern(&prologue, index) {
8524 // A destructuring parameter *initialises* its bindings: with a parameter
8525 // scope they are the list's own `let`s, which is why the stores skip the
8526 // dead-zone check, and why the reference reads their properties with
8527 // `get_field2` — a `let` needs no reference.
8528 let kind = if has_param_scope {
8529 VarDeclKind::Let
8530 } else {
8531 VarDeclKind::Var
8532 };
8533 match &pattern.kind {
8534 // `...rest` collects what is left rather than reading one slot.
8535 PatternKind::Rest(inner) => {
8536 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8537 self.destructure(inner, Some(kind))?;
8538 }
8539 _ => {
8540 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8541 self.destructure(pattern, Some(kind))?;
8542 }
8543 }
8544 continue;
8545 }
8546 // A plain name binds straight from its argument slot. With a parameter scope
8547 // the slot is also copied into the parameter binding, which is what a later
8548 // default (or a closure made among the defaults) reads.
8549 let Some(name) = simple_parameter(param) else {
8550 continue;
8551 };
8552 let target = self.param_binding_slot(&name.name);
8553 if matches!(param.kind, PatternKind::Rest(_)) {
8554 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8555 if let Some(slot) = target {
8556 self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
8557 }
8558 // `put_arg` rather than `set_arg`: the array is the last thing on the
8559 // stack and nothing keeps it. Named by hand because a name in the
8560 // parameter list resolves to the parameter binding, and this store has to
8561 // reach the *argument* — that is what the body reads.
8562 self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
8563 continue;
8564 }
8565 if let PatternKind::Assign { default, .. } = ¶m.kind {
8566 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8567 let has_value = self.new_label();
8568 self.emit(Opcode::Dup, &[]);
8569 self.emit(Opcode::IsUndefined, &[]);
8570 self.emit_jump(Opcode::IfFalse, has_value, &[]);
8571 self.emit(Opcode::Drop, &[]);
8572 self.expr(default)?;
8573 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
8574 // The argument slot keeps the substituted value, because the *body* reads
8575 // the slot rather than the parameter binding — so this store is named
8576 // explicitly, like the rest parameter's.
8577 self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8578 self.place_label(has_value);
8579 if let Some(slot) = target {
8580 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8581 }
8582 continue;
8583 }
8584 if let Some(slot) = target {
8585 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8586 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8587 }
8588 }
8589 // Copy the parameter scope into the body. A plain parameter needs nothing: the
8590 // body reads its argument slot, and the list kept the two in step. A name a
8591 // pattern bound has no argument slot of its own, so the body gets a `var` filled
8592 // from the parameter's copy — and *that* is why an assignment inside a default
8593 // does not reach the body.
8594 if has_param_scope {
8595 for (_, pattern) in &prologue {
8596 let mut names = Vec::new();
8597 pattern.bound_names(&mut names);
8598 for name in names {
8599 let Some(slot) = self.param_binding_slot(&name.name) else {
8600 continue;
8601 };
8602 let Some(body) = self.body_var_slot(&name.name) else {
8603 continue;
8604 };
8605 self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
8606 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
8607 }
8608 }
8609 }
8610 // The parameter list is over; from here on a direct `eval` belongs to the body.
8611 self.state().in_params = false;
8612 // Entering the body's own scope comes *after* the parameter list: the body's
8613 // `let`s are not in existence while the defaults run, and the reference emits
8614 // their `set_loc_uninitialized` only once the parameters are bound.
8615 self.emit_scope_enter(body_key);
8616 // A generator starts suspended: `initial_yield` parks the body so that creating one
8617 // runs no body code until the first `next()`.
8618 //
8619 // It comes *after* the parameter unpacking, not before, because a parameter
8620 // initialiser is not body code — `function* g(a = sideEffect())` must run
8621 // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
8622 // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
8623 // until the first `next()` and 29 test262 cases that check for a synchronous throw
8624 // saw none at all.
8625 //
8626 // An async function does **not** get one. Its body runs synchronously up to the
8627 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
8628 // before its caller's next statement — so an `initial_yield` here would park the
8629 // body before it started, which is not fixable at run time: the suspension looks
8630 // exactly like a real `await`.
8631 if self.cur().kind.is_generator() {
8632 self.emit(Opcode::InitialYield, &[]);
8633 }
8634 // Through `stmts`: the body is a block, and a `using` declaration in it is a
8635 // disposal region.
8636 self.stmts(body)?;
8637 // The implicit return only exists if control can actually get here: an
8638 // infinite loop never falls off the end.
8639 if self.end_is_reachable() {
8640 if self.cur().is_suspending() {
8641 // Falling off the end finishes the generator with `undefined`, and the
8642 // value is what tells the resume machinery "completed" rather than
8643 // "suspended".
8644 self.emit(Opcode::Undefined, &[]);
8645 self.emit(Opcode::ReturnAsync, &[]);
8646 } else {
8647 self.emit_class_constructor_tail();
8648 }
8649 }
8650 // Resolution runs while this function is still on the stack: capturing a
8651 // variable from an enclosing function means reaching into that
8652 // function's state, which requires the whole chain to be present.
8653 Ok(self.finish_current())
8654 }
8655
8656 /// Put every binding of a function that contains a direct `eval` into a cell.
8657 ///
8658 /// A direct eval can name any binding in scope, and any closure it creates has to
8659 /// keep sharing that binding after the function returns — `for (let i …)
8660 /// eval("push(() => i)")` collects one closure per iteration and each must read its
8661 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
8662 /// a cell. Doing this unconditionally for such functions is the cheap, honest
8663 /// answer: the alternative is knowing at compile time which names a string will
8664 /// mention.
8665 fn capture_everything_for_eval(&mut self) {
8666 let current = self.stack.len() - 1;
8667 if !self.stack[current].has_direct_eval {
8668 return;
8669 }
8670 for arg in &mut self.stack[current].args {
8671 arg.is_captured = true;
8672 }
8673 for var in &mut self.stack[current].vars {
8674 var.is_captured = true;
8675 }
8676 }
8677
8678 /// Whether the current position in the instruction stream can be reached.
8679 ///
8680 /// A walk over the control-flow graph, using labels as instruction indices.
8681 /// The reference does the same thing to decide whether an implicit
8682 /// `return_undef` is needed.
8683 fn end_is_reachable(&self) -> bool {
8684 let state = self.cur();
8685 reachable_instructions(state, state.insns.len())[state.insns.len()]
8686 }
8687
8688 /// Resolve and assemble the function on top of the compiler stack, then pop
8689 /// it.
8690 fn finish_current(&mut self) -> CompiledFunction {
8691 self.provide_param_arguments();
8692 self.provide_arguments();
8693 self.provide_this_local();
8694 self.provide_new_target_local();
8695 self.provide_home_object_local();
8696 self.provide_active_func_local();
8697 self.provide_self_name();
8698 self.materialize_eval_sites();
8699 self.capture_everything_for_eval();
8700 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
8701 // Captured bindings need a reference cell; the count goes in the header so
8702 // the runtime knows how many cells to allocate on entry.
8703 let current = self.stack.len() - 1;
8704 let captured = self.stack[current]
8705 .args
8706 .iter()
8707 .filter(|a| a.is_captured)
8708 .count()
8709 + self.stack[current]
8710 .vars
8711 .iter()
8712 .filter(|v| v.is_captured)
8713 .count();
8714 self.stack[current].var_ref_count = captured as u32;
8715 // The scope chain is only final now that every binding is known.
8716 rebuild_scope_chain(&mut self.stack[current]);
8717 let (code, stack_size, positions) =
8718 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
8719 let _ = &mut resolved;
8720 let mut state = self.stack.pop().expect("a function is being compiled");
8721 CompiledFunction {
8722 name: state.name,
8723 kind: state.kind,
8724 strict: state.strict,
8725 is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
8726 // `is_script`/`is_module` are set only on the outermost function, which is
8727 // exactly the "script, eval or module body" the flag names.
8728 is_script_body: state.is_script || state.is_module,
8729 is_arrow: state.is_arrow,
8730 has_parameter_expressions: state.has_parameter_expressions,
8731 simple_parameter_list: state.simple_parameter_list,
8732 body_start: state.body_start,
8733 args: state.args,
8734 defined_args: state.defined_args,
8735 vars: state.vars,
8736 closure_vars: state.closure_vars,
8737 cpool: state.cpool,
8738 atoms: state.atoms,
8739 code,
8740 stack_size,
8741 var_ref_count: state.var_ref_count,
8742 positions,
8743 source: self.function_source(state.span, state.line, state.column),
8744 line: state.line,
8745 column: state.column,
8746 filename: None,
8747 eval_sites: state.eval_sites,
8748 module: state.module.take().map(Box::new),
8749 }
8750 }
8751}
8752
8753/// Assign each binding a scope level and rebuild the scope chains.
8754///
8755/// Levels are numbered in the order the blocks appear, with 0 reserved for the
8756/// function scope where `var` and hoisted functions live. Every binding outside
8757/// level 0 gets a `scope_next` link to the next binding visible from the same
8758/// point, so walking a block's chain enumerates exactly the bindings live there.
8759///
8760/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
8761/// point at `b`, which is declared later in the source but earlier in the chain.
8762fn rebuild_scope_chain(state: &mut FnState) {
8763 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
8764 // real block that happens to start at offset zero keeps its own level instead of
8765 // being merged into the function scope.
8766 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
8767 for block in &state.blocks {
8768 if !levels.contains(&block.key) {
8769 levels.push(block.key);
8770 }
8771 }
8772 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
8773 let parent_level = |level: usize| -> usize {
8774 if level == 0 {
8775 return 0;
8776 }
8777 let key = levels[level];
8778 let parent = state
8779 .blocks
8780 .iter()
8781 .find(|b| b.key == key)
8782 .map(|b| b.parent)
8783 .unwrap_or(FUNCTION_SCOPE);
8784 level_of(parent)
8785 };
8786
8787 // Own bindings per level, in declaration order.
8788 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
8789 let keys: Vec<u64> = (0..state.vars.len())
8790 .map(|index| {
8791 state
8792 .var_block
8793 .get(index)
8794 .copied()
8795 .unwrap_or(FUNCTION_SCOPE)
8796 })
8797 .collect();
8798 for (index, key) in keys.into_iter().enumerate() {
8799 // The parameter scope is not a block: it is a level of its own with no parent,
8800 // assigned below. Letting it land in level 0 would chain the body's bindings onto
8801 // it, which the reference does not do — the two environments are siblings.
8802 if key == PARAM_SCOPE {
8803 continue;
8804 }
8805 let level = level_of(key);
8806 state.vars[index].scope_level = level as u32;
8807 // A `catch` parameter is part of the runtime scope chain even though it is
8808 // not lexical: the handler's own bindings chain on to it, which is why the
8809 // reference prints `let y [next:1]` with `e` at 1.
8810 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
8811 {
8812 own[level].push(index);
8813 }
8814 }
8815
8816 // A scope's chain is its own bindings in reverse declaration order followed
8817 // by the enclosing scope's chain.
8818 let mut head = vec![-1i32; levels.len()];
8819 for level in 0..levels.len() {
8820 let inherited = if level == 0 {
8821 -1
8822 } else {
8823 head[parent_level(level)]
8824 };
8825 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
8826 head[level] = chain.first().map_or(inherited, |first| *first as i32);
8827 for (position, &index) in chain.iter().enumerate() {
8828 let next = chain
8829 .get(position + 1)
8830 .map_or(inherited, |next| *next as i32);
8831 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
8832 }
8833 }
8834 state.block_heads = head;
8835
8836 // The parameter list is a scope of its own, and it has no parent: the reference pops
8837 // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
8838 // the `-1` a block uses. A level past every real block keeps it out of the walk above
8839 // — nothing but the dump reads it — and the links run newest-to-oldest through the
8840 // bindings themselves, which is the order `set_loc_uninitialized` walks.
8841 let param_level = levels.len() as u32;
8842 let mut previous: Option<usize> = None;
8843 for index in 0..state.vars.len() {
8844 if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
8845 {
8846 continue;
8847 }
8848 state.vars[index].scope_level = param_level;
8849 state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
8850 previous = Some(index);
8851 }
8852}
8853
8854/// This is where names become slots and where the temporal dead zone shows up in
8855/// the instruction stream: a read of a `let`/`const` binding compiles to
8856/// `get_loc_check`, which throws if the binding is still uninitialised.
8857///
8858/// The peephole pass from the reference implementation is applied at the end,
8859/// for the same reason it is applied to resolved bytecode there: the patterns are
8860/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
8861/// resolution. Deleted instructions stay in the list as `None` so that label
8862/// indices remain valid; [`Assembler`] maps them to byte offsets.
8863/// A resolved instruction and the source position it came from.
8864type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
8865
8866/// A resolved instruction paired with its position, which is what `assemble` consumes.
8867type PositionedInsn = (Opcode, Vec<Op>);
8868
8869fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
8870 let current = stack.len() - 1;
8871 // Dead-code elimination, on the symbolic form where labels are still
8872 // instruction indices. A `break` inside a loop leaves the trailing `goto`
8873 // unreachable, and a `return` leaves everything after it unreachable; the
8874 // reference drops both. Doing it here means the emitter never has to think
8875 // about reachability.
8876 strip_empty_gosubs(stack, current);
8877 eliminate_dead_code(stack, current);
8878 let insns = std::mem::take(&mut stack[current].insns);
8879 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
8880 // `insns`, and every arm below pushes exactly one instruction, so the positions
8881 // stay aligned with `out`.
8882 let positions = std::mem::take(&mut stack[current].insn_pos);
8883 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
8884 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8885 for (index, insn) in insns.iter().enumerate() {
8886 let pos = positions.get(index).copied().flatten();
8887 out_pos.push(pos);
8888 match insn {
8889 Insn::Fixed { op, operands } => {
8890 let operands = operands
8891 .iter()
8892 .map(|operand| match operand {
8893 Op::Atom(atom) => {
8894 Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
8895 }
8896 other => other.clone(),
8897 })
8898 .collect();
8899 out.push(Some((*op, operands)));
8900 }
8901 Insn::Var {
8902 action,
8903 name,
8904 block,
8905 in_params,
8906 } => {
8907 // Both reads and writes in the parameter list address the parameter
8908 // scope. That is what puts the list in the temporal dead zone — a read of
8909 // a later parameter is `get_loc_check` on an uninitialised slot — and it
8910 // is also what keeps an assignment made inside a default away from the
8911 // body, which sees a separate environment.
8912 let slot = resolve_slot(stack, current, name, *block, *in_params);
8913 // A store to the name of a named function expression is special: the
8914 // reference drops it in sloppy mode and throws in strict mode, because
8915 // the binding is immutable but only *checked* when the body is strict.
8916 // The same rule applies when the name is reached through a closure:
8917 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8918 // the store in the arrow too, not just in the function that owns the
8919 // binding. Reaching the owner means walking the chain of closure
8920 // entries, which is what `self_name_binding` does.
8921 let self_name = matches!(action, VarAction::Put | VarAction::Set)
8922 .then(|| {
8923 // A local of this function is the common case and needs no
8924 // chain walk; only an access that resolves elsewhere can be
8925 // pointing at an enclosing function's name binding.
8926 if let Slot::Loc(index) = slot {
8927 stack[current]
8928 .vars
8929 .get(index as usize)
8930 .filter(|var| var.kind == VarKind::FunctionName)
8931 .map(|var| var.is_const)
8932 } else {
8933 self_name_binding(stack, current, name, *block)
8934 }
8935 })
8936 .flatten();
8937 if let Some(is_const) = self_name {
8938 out.push(Some(if is_const {
8939 (
8940 Opcode::ThrowError,
8941 vec![
8942 Op::AtomId(intern_atom(&mut stack[current], name)),
8943 Op::Int(0),
8944 ],
8945 )
8946 } else {
8947 (Opcode::Drop, Vec::new())
8948 }));
8949 continue;
8950 }
8951 if *action == VarAction::MakeRef {
8952 // A reference to a *local* has to keep working after the enclosing
8953 // frame is gone, and `get_ref_value` reads a cell — so the binding is
8954 // forced into one, exactly as the reference implementation's
8955 // `capture_var` does. Only an access that a direct `eval` in the same
8956 // function can shadow ever asks for this, so the cost is confined to
8957 // functions that contain one.
8958 match slot {
8959 Slot::Loc(index) => {
8960 if let Some(var) = stack[current].vars.get_mut(index as usize) {
8961 var.is_captured = true;
8962 }
8963 }
8964 Slot::Arg(index) => {
8965 if let Some(arg) = stack[current].args.get_mut(index as usize) {
8966 arg.is_captured = true;
8967 }
8968 }
8969 _ => {}
8970 }
8971 }
8972 let (opcode, mut operands) = variable_instruction(stack, current, *action, slot);
8973 if *action == VarAction::MakeRef {
8974 // Operand 0 is the placeholder `variable_instruction` could not fill
8975 // in; the name is in hand here, and it has to be *interned* — this arm
8976 // bypasses `Insn::Fixed`, which is where `Op::Atom` normally becomes an
8977 // `Op::AtomId`.
8978 operands[0] = Op::AtomId(intern_atom(&mut stack[current], name));
8979 }
8980 out.push(Some((opcode, operands)));
8981 }
8982 Insn::CloseCaptured { name, block } => {
8983 // The block matters: a loop variable is scoped to the `for` head's own
8984 // block, so resolving it against block 0 would miss it entirely and
8985 // silently emit nothing.
8986 let slot = resolve_slot(stack, current, name, *block, false);
8987 // Only a local with a reference cell has anything to close. A global
8988 // or a never-captured local resolves to no instruction at all, which
8989 // keeps the bytecode identical to the reference's.
8990 if let Slot::Loc(index) = slot
8991 && stack[current]
8992 .vars
8993 .get(index as usize)
8994 .is_some_and(|v| v.is_captured)
8995 {
8996 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
8997 } else {
8998 out.push(None);
8999 }
9000 }
9001 Insn::DeleteVar { name } => {
9002 // A binding — a local, an argument, or a declared global — cannot be
9003 // deleted, and the reference encodes that as a constant `push_false`.
9004 // Only an implicit global needs the runtime lookup.
9005 // `GlobalDecl` counts: a script-level `var` is a property of the global
9006 // object and the delete is answered there (non-configurable, so `false`),
9007 // but a `var` an `eval` created lives in the caller's `LocalVars` and *is*
9008 // deletable (§19.2.1.3 creates it with `deletable = true`). Emitting a
9009 // constant `false` decided that at compile time and made
9010 // `eval("var x; delete x")` answer `false`
9011 // (`eval-code/direct/var-env-var-init-local-new-delete`).
9012 if matches!(
9013 resolve_slot(stack, current, name, 0, false),
9014 Slot::Global(_) | Slot::GlobalDecl(_)
9015 ) {
9016 let atom = intern_atom(&mut stack[current], name);
9017 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
9018 } else {
9019 out.push(Some((Opcode::PushFalse, Vec::new())));
9020 }
9021 }
9022 Insn::Dead => out.push(None),
9023 }
9024 }
9025 // Which label (if any) sits on each instruction, so the jump patterns can
9026 // tell whether they would cross a jump target.
9027 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
9028 for (id, placed) in stack[current].labels.iter().enumerate() {
9029 if let Some(index) = *placed
9030 && index < label_at.len()
9031 && label_at[index].is_none()
9032 {
9033 label_at[index] = Some(id as u32);
9034 }
9035 }
9036 if std::env::var_os("QJS_DEBUG").is_some() {
9037 eprintln!("--- peephole entry ---");
9038 for (i, e) in out.iter().enumerate() {
9039 eprintln!("{i}: {e:?}");
9040 }
9041 eprintln!("label_at: {label_at:?}");
9042 }
9043 peephole(&mut out, &label_at, &stack[current].labels);
9044 (out, out_pos)
9045}
9046
9047/// Find where `name` lives, capturing it in an enclosing function when needed.
9048///
9049/// The search runs outward through the enclosing functions' states, which are
9050/// still on the compiler stack while a nested function is resolved. Finding the
9051/// name in an enclosing function is what creates a closure reference, and every
9052/// function in between has to forward it — a function can only reach its own
9053/// parent's frame.
9054///
9055/// A name declared nowhere is a global. The reference does *not* look it up by
9056/// name from the inner function: the top-level function gets one `[global]`
9057/// entry and every nested function gets a `[global_ref<n>]` pointing at its
9058/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
9059/// rather than `[global]`.
9060/// The lexical blocks enclosing `block`, innermost first.
9061fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
9062 let mut chain = Vec::new();
9063 let mut current = Some(block);
9064 while let Some(key) = current {
9065 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
9066 // explicitly (rather than on "no block with this key") is what keeps a block
9067 // that happens to sit at offset zero from being mistaken for the terminator.
9068 if key == NO_PARENT || chain.contains(&key) {
9069 break;
9070 }
9071 chain.push(key);
9072 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
9073 }
9074 chain
9075}
9076
9077/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
9078///
9079/// The binding may be several functions away: an arrow nested in `function myfunc`
9080/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
9081/// means following `Ref` entries down and then reading the owning function's var table.
9082fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
9083 let state = stack.get(current)?;
9084 // A parameter shadows everything and is never a function-expression name.
9085 if state.args.iter().any(|arg| arg.name == name) {
9086 return None;
9087 }
9088 // A local of this very function: the answer is in its var table.
9089 if let Some(index) = local_slot_index(state, name, block) {
9090 let var = state.vars.get(index)?;
9091 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
9092 }
9093 // Otherwise the name lives further out, and the closure entry says how to get
9094 // there. `Local` names the owner's slot directly; `Ref` names the next level's
9095 // closure entry, so the walk continues downwards.
9096 let mut level = current;
9097 let mut index = state
9098 .closure_vars
9099 .iter()
9100 .position(|closure| closure.name == name)?;
9101 loop {
9102 let state = stack.get(level)?;
9103 let closure = state.closure_vars.get(index)?;
9104 match closure.closure_type {
9105 ClosureType::Local => {
9106 let owner = stack.get(level.checked_sub(1)?)?;
9107 let var = owner.vars.get(closure.var_idx as usize)?;
9108 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
9109 }
9110 ClosureType::Arg => return None,
9111 ClosureType::Ref => {
9112 level -= 1;
9113 index = closure.var_idx as usize;
9114 }
9115 // A global is never a function-expression name.
9116 ClosureType::Global
9117 | ClosureType::GlobalDecl
9118 | ClosureType::GlobalRef
9119 | ClosureType::ModuleDecl
9120 | ClosureType::ModuleImport => return None,
9121 }
9122 }
9123}
9124
9125/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
9126fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
9127 block_chain(state, block).into_iter().find_map(|scope| {
9128 state.vars.iter().enumerate().find_map(|(index, var)| {
9129 (var.name == name && state.var_block.get(index).copied() == Some(scope))
9130 .then_some(index)
9131 })
9132 })
9133}
9134
9135/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
9136fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
9137 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
9138 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
9139 }) {
9140 return index as u32;
9141 }
9142 state.var_block.push(PARAM_SCOPE);
9143 state.vars.push(VarDef::var(name));
9144 state.vars.len() as u32 - 1
9145}
9146
9147/// The name a parameter binds straight from its argument slot, if it has one.
9148///
9149/// A plain name does — with or without a default, and with or without `...`. Everything
9150/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
9151/// reference names the argument in the first case and leaves it `<null>` in the second,
9152/// so both the dump and the closures that capture the argument depend on this.
9153fn simple_parameter(param: &Pattern) -> Option<&Ident> {
9154 match ¶m.kind {
9155 PatternKind::Ident(name) => Some(name),
9156 PatternKind::Assign { target, .. } => match &target.kind {
9157 PatternKind::Ident(name) => Some(name),
9158 _ => None,
9159 },
9160 PatternKind::Rest(inner) => match &inner.kind {
9161 PatternKind::Ident(name) => Some(name),
9162 _ => None,
9163 },
9164 _ => None,
9165 }
9166}
9167
9168/// The pattern a parameter list has to unpick, if `index` is one of them.
9169fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
9170 prologue
9171 .iter()
9172 .find(|(at, _)| *at == index)
9173 .map(|(_, pattern)| pattern)
9174}
9175
9176fn pattern_has_default(pattern: &Pattern) -> bool {
9177 match &pattern.kind {
9178 PatternKind::Assign { .. } => true,
9179 PatternKind::Rest(inner) => pattern_has_default(inner),
9180 PatternKind::Array { elements, rest } => {
9181 elements.iter().flatten().any(element_has_default)
9182 || rest.as_deref().is_some_and(rest_has_default)
9183 }
9184 PatternKind::Object { properties, rest } => {
9185 properties.iter().flatten().any(element_has_default)
9186 || rest.as_deref().is_some_and(rest_has_default)
9187 }
9188 _ => false,
9189 }
9190}
9191
9192fn element_has_default(element: &PatternElement) -> bool {
9193 match element {
9194 PatternElement::Pattern(pattern) => pattern_has_default(pattern),
9195 PatternElement::Property { value, .. } => pattern_has_default(value),
9196 }
9197}
9198
9199fn rest_has_default(rest: &RestElement) -> bool {
9200 match rest {
9201 RestElement::Pattern(pattern) => pattern_has_default(pattern),
9202 RestElement::Member(_) => false,
9203 }
9204}
9205
9206/// Whether a function-scope binding is visible to the parameter list.
9207///
9208/// The parameter list runs before the body, so the body's `var`s and function
9209/// declarations do not exist yet — a name that only the body declares has to resolve
9210/// outward instead. What *does* exist by then is the compiler's own prologue: the
9211/// self-name of a named function expression (bound by `special_object 2` before anything
9212/// else), `this` and `new.target`. Those stay visible, which is what makes
9213/// `function f(a = this)` and `var f = function f(a = f)` work.
9214///
9215/// `arguments` is handled separately, as a binding of the parameter scope itself: with
9216/// parameter expressions the reference creates two of them, and the one the parameter
9217/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
9218fn visible_in_params(var: &VarDef) -> bool {
9219 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
9220}
9221
9222fn resolve_slot(
9223 stack: &mut [FnState],
9224 current: usize,
9225 name: &str,
9226 block: u64,
9227 in_params: bool,
9228) -> Slot {
9229 // The parameter list's own bindings. They are consulted first because they shadow
9230 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
9231 // `a` in the parameter scope, so a closure made there reads the parameter even after
9232 // the body assigns to its own `a`.
9233 if in_params
9234 && let Some(index) = stack[current]
9235 .vars
9236 .iter()
9237 .enumerate()
9238 .position(|(index, var)| {
9239 var.name == name
9240 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
9241 })
9242 {
9243 return Slot::Loc(index as u32);
9244 }
9245 // A name can be bound more than once: two `catch` parameters in nested
9246 // handlers are two slots. The binding that wins is the one whose scope encloses
9247 // the access, and among those the innermost — so the blocks are walked outward
9248 // and the first binding found on the way is the one that counts. A binding in
9249 // no block (`var`) is reachable from anywhere, which is why the function scope
9250 // is the end of the walk.
9251 //
9252 // The block walk comes *before* the argument slots, because a block may shadow a
9253 // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
9254 // slot is only the answer once nothing nearer claims the name.
9255 let chain = block_chain(&stack[current], block);
9256 for scope in &chain {
9257 let found = stack[current]
9258 .vars
9259 .iter()
9260 .enumerate()
9261 .find(|(index, var)| {
9262 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
9263 })
9264 .map(|(index, _)| index);
9265 if let Some(index) = found {
9266 return Slot::Loc(index as u32);
9267 }
9268 }
9269 // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
9270 // its own slot, and `var` of the same name in the body is the same binding.
9271 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
9272 return Slot::Arg(index as u32);
9273 }
9274 // Function-scope bindings — `var` and function declarations — are recorded with
9275 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
9276 // them. They are reachable from anywhere in the function, which is exactly what
9277 // the sentinel means.
9278 //
9279 // This pass is *only* for those. A lexical binding has to be found through the
9280 // chain or not at all, and looking a name up without its block is precisely how
9281 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
9282 // block leaked out of it.
9283 let function_scoped = stack[current]
9284 .vars
9285 .iter()
9286 .enumerate()
9287 .find(|(index, var)| {
9288 var.name == name
9289 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
9290 && (!in_params || visible_in_params(var))
9291 })
9292 .map(|(index, _)| index);
9293 if let Some(index) = function_scoped {
9294 return Slot::Loc(index as u32);
9295 }
9296 if let Some(index) = stack[current]
9297 .closure_vars
9298 .iter()
9299 .position(|c| c.name == name)
9300 {
9301 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
9302 }
9303
9304 for owner in (0..current).rev() {
9305 // The nested function was created inside one of this frame's blocks, and the
9306 // outermost visible binding is the innermost block on that chain — not whatever
9307 // comes first in the variable table. `function f(){ class S{} }` has two `S`
9308 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
9309 // the class body is the one a method may see.
9310 let entry = stack
9311 .get(owner + 1)
9312 .map(|s| s.created_in_block)
9313 .unwrap_or(0);
9314 let lexical = block_chain(&stack[owner], entry)
9315 .into_iter()
9316 .find_map(|scope| {
9317 stack[owner]
9318 .vars
9319 .iter()
9320 .enumerate()
9321 .find(|(index, var)| {
9322 var.name == name
9323 && stack[owner].var_block.get(*index).copied() == Some(scope)
9324 })
9325 .map(|(index, _)| index)
9326 });
9327 // A function born in a parameter list sees that list's bindings, not the body's:
9328 // the parameter scope is the environment it was created in.
9329 let in_param_scope = stack
9330 .get(owner + 1)
9331 .is_some_and(|child| child.created_in_params)
9332 .then(|| {
9333 stack[owner]
9334 .vars
9335 .iter()
9336 .enumerate()
9337 .position(|(index, var)| {
9338 var.name == name
9339 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
9340 })
9341 })
9342 .flatten();
9343 let found = if let Some(index) = in_param_scope {
9344 let var = &stack[owner].vars[index];
9345 Some(Found::Local(
9346 ClosureType::Local,
9347 index as u32,
9348 var.is_const,
9349 var.needs_check(),
9350 ))
9351 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
9352 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
9353 } else if let Some(index) = lexical {
9354 let var = &stack[owner].vars[index];
9355 Some(Found::Local(
9356 ClosureType::Local,
9357 index as u32,
9358 var.is_const,
9359 var.needs_check(),
9360 ))
9361 } else if let Some(index) = stack[owner]
9362 .vars
9363 .iter()
9364 .enumerate()
9365 .find_map(|(index, var)| {
9366 // A function created inside a parameter list must not see the body of the
9367 // function it was born in; see [`FnState::created_in_params`].
9368 let hidden = stack
9369 .get(owner + 1)
9370 .is_some_and(|child| child.created_in_params);
9371 (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
9372 })
9373 {
9374 let var = &stack[owner].vars[index];
9375 Some(Found::Local(
9376 ClosureType::Local,
9377 index as u32,
9378 var.is_const,
9379 var.needs_check(),
9380 ))
9381 } else if stack[owner].self_name.as_deref() == Some(name) {
9382 // A named function expression's own name. The reference declares it here,
9383 // on the first lookup that fails, rather than up front — and that is what
9384 // makes it reachable from a *nested* function: the nested lookup is what
9385 // walks out and creates the binding. A direct reference in the body is
9386 // caught the same way, which is why `provide_self_name` only has to add
9387 // the prologue.
9388 let strict = stack[owner].strict;
9389 stack[owner].var_block.push(FUNCTION_SCOPE);
9390 stack[owner].vars.push(VarDef {
9391 kind: VarKind::FunctionName,
9392 // In strict mode the name is immutable, so a store raises; sloppy
9393 // mode drops the store instead (see `variable_instruction`).
9394 is_const: strict,
9395 ..VarDef::var(name)
9396 });
9397 let index = stack[owner].vars.len() as u32 - 1;
9398 Some(Found::Local(ClosureType::Local, index, strict, false))
9399 } else if let Some(index) = stack[owner]
9400 .closure_vars
9401 .iter()
9402 .position(|c| c.name == name)
9403 {
9404 let closure = &stack[owner].closure_vars[index];
9405 Some(match closure.closure_type {
9406 // `GlobalRef` belongs here too: it is a *global* reached through this
9407 // frame's reference table, so treating it as a `Ref` to a local cell makes
9408 // the reader look for a cell no frame ever fills. That is how a second
9409 // function using `eval` in its parameter list read `undefined` after a
9410 // sibling had already made `eval` a closure entry.
9411 ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
9412 Found::Global(index as u32)
9413 }
9414 // A module variable is a cell in the *module's* environment, which is
9415 // the module body's parent as far as a nested function is concerned — so
9416 // it is captured as a plain reference, not looked up as a global.
9417 ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
9418 ClosureType::Ref,
9419 index as u32,
9420 closure.is_const,
9421 closure.is_lexical,
9422 ),
9423 _ => Found::Local(
9424 ClosureType::Ref,
9425 index as u32,
9426 closure.is_const,
9427 closure.is_lexical,
9428 ),
9429 })
9430 } else {
9431 None
9432 };
9433 let Some(found) = found else { continue };
9434
9435 let (is_const, is_lexical) = match found {
9436 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
9437 Found::Global(_) => (false, false),
9438 };
9439 // Mark the owner's binding as captured so it moves into a reference cell.
9440 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
9441 let slot = match found {
9442 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
9443 _ => &mut stack[owner].vars[index as usize],
9444 };
9445 slot.is_captured = true;
9446 }
9447 // Forward the reference through every function in between.
9448 let mut previous = match found {
9449 Found::Local(kind, index, _, _) => (kind, index),
9450 Found::Global(index) => (ClosureType::Global, index),
9451 };
9452 for level in owner + 1..=current {
9453 let kind = match (previous.0, level) {
9454 // A global stays a global at *every* level. Without `GlobalRef` in
9455 // this arm the second nested function over the same global got a
9456 // `Ref` to a cell no frame ever held, so the innermost closure read
9457 // `undefined` — which is how a two-deep getter lost its outer
9458 // variable.
9459 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
9460 ClosureType::GlobalRef
9461 }
9462 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
9463 _ => ClosureType::Ref,
9464 };
9465 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
9466 previous = (kind, index);
9467 }
9468 let index = previous.1;
9469 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
9470 }
9471
9472 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
9473 // creating a property. The top-level function holds the entry.
9474 let mut previous = (
9475 ClosureType::Global,
9476 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
9477 );
9478 for level in 1..=current {
9479 let index = ensure_closure(
9480 stack,
9481 level,
9482 name,
9483 false,
9484 false,
9485 ClosureType::GlobalRef,
9486 previous.1,
9487 );
9488 previous = (ClosureType::GlobalRef, index);
9489 }
9490 Slot::Global(previous.1)
9491}
9492
9493/// What an outward search turned up.
9494#[derive(Debug, Clone, Copy)]
9495enum Found {
9496 /// A binding in an enclosing function, reachable through a closure of this
9497 /// type, with its const/lexical flags.
9498 Local(ClosureType, u32, bool, bool),
9499 /// A global, reached through the enclosing function's closure entry.
9500 Global(u32),
9501}
9502
9503/// Add a closure entry to `level` if it is not there yet.
9504fn ensure_closure(
9505 stack: &mut [FnState],
9506 level: usize,
9507 name: &str,
9508 is_const: bool,
9509 is_lexical: bool,
9510 closure_type: ClosureType,
9511 var_idx: u32,
9512) -> u32 {
9513 if let Some(index) = stack[level]
9514 .closure_vars
9515 .iter()
9516 .position(|c| c.name == name)
9517 {
9518 return index as u32;
9519 }
9520 stack[level].closure_vars.push(ClosureVar {
9521 name: name.to_string(),
9522 is_const,
9523 is_lexical,
9524 // Only a declaration in the script's own scope can be one, and that path records
9525 // it directly (`declare_global`); a capture of it forwards the name, not the kind.
9526 is_function_decl: false,
9527 closure_type,
9528 var_idx: var_idx as u16,
9529 });
9530 stack[level].closure_vars.len() as u32 - 1
9531}
9532
9533fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
9534 match closure.closure_type {
9535 // A `global_ref` only says *how* the binding is found (through the
9536 // parent's closure table); the access itself is an ordinary global one.
9537 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
9538 ClosureType::GlobalDecl => Slot::GlobalDecl(index),
9539 // A module variable is a real cell in the module's environment, so it is reached
9540 // exactly like a captured local — the host, not the global object, is what fills
9541 // the slot.
9542 ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
9543 _ => Slot::VarRef(index),
9544 }
9545}
9546
9547/// Pick the opcode for one variable access.
9548///
9549/// The `_check` variants are what enforce the temporal dead zone. They are used
9550/// for every access to a `let`/`const` binding except its own initialisation —
9551/// which is exactly the operation that takes the binding out of the dead zone.
9552fn variable_instruction(
9553 stack: &[FnState],
9554 current: usize,
9555 action: VarAction,
9556 slot: Slot,
9557) -> (Opcode, Vec<Op>) {
9558 let lexical = match slot {
9559 Slot::Loc(index) => stack[current]
9560 .vars
9561 .get(index as usize)
9562 .is_some_and(|v| v.needs_check()),
9563 Slot::VarRef(index) => stack[current]
9564 .closure_vars
9565 .get(index as usize)
9566 .is_some_and(|c| c.is_lexical),
9567 _ => false,
9568 };
9569 let operand = vec![Op::Slot(slot)];
9570 // `make_*_ref` carries the name as well as the slot: the reference's runtime resolution
9571 // consults the names a direct `eval` has declared in this frame, which is a by-name
9572 // question, so the atom cannot be dropped. `variable_instruction` never sees the name, so
9573 // the caller patches operand 0 in (see `Compiler::emit_var`).
9574 //
9575 // Operand 1 is a *bare* slot index, not an `Op::Slot`: the opcode already says which
9576 // table it counts in, and `OpFormat::AtomU16`'s second operand is written by the plain
9577 // `u16` encoder, which an `Op::Slot` would silently skip — leaving the instruction two
9578 // bytes short and the whole stream desynchronised.
9579 let ref_slot = match slot {
9580 Slot::Arg(index)
9581 | Slot::Loc(index)
9582 | Slot::VarRef(index)
9583 | Slot::Global(index)
9584 | Slot::GlobalDecl(index) => index,
9585 };
9586 let ref_operand = vec![Op::AtomId(0), Op::Int(ref_slot as i32)];
9587 match (action, slot) {
9588 (VarAction::Get, Slot::Loc(index)) => (
9589 if lexical {
9590 Opcode::GetLocCheck
9591 } else {
9592 Opcode::GetLoc
9593 },
9594 vec![Op::Slot(Slot::Loc(index))],
9595 ),
9596 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
9597 (VarAction::Get, Slot::VarRef(index)) => (
9598 if lexical {
9599 Opcode::GetVarRefCheck
9600 } else {
9601 Opcode::GetVarRef
9602 },
9603 vec![Op::Slot(Slot::VarRef(index))],
9604 ),
9605 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
9606 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
9607 // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
9608 // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
9609 // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
9610 // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
9611 // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
9612 // `ReferenceError`.
9613 (VarAction::GetUndef, Slot::Loc(index)) => (
9614 if lexical {
9615 Opcode::GetLocCheck
9616 } else {
9617 Opcode::GetLoc
9618 },
9619 vec![Op::Slot(Slot::Loc(index))],
9620 ),
9621 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
9622 (VarAction::GetUndef, Slot::VarRef(index)) => (
9623 if lexical {
9624 Opcode::GetVarRefCheck
9625 } else {
9626 Opcode::GetVarRef
9627 },
9628 vec![Op::Slot(Slot::VarRef(index))],
9629 ),
9630 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9631 (Opcode::GetVarUndef, operand)
9632 }
9633
9634 (VarAction::Put, Slot::Loc(_)) => (
9635 if lexical {
9636 Opcode::PutLocCheck
9637 } else {
9638 Opcode::PutLoc
9639 },
9640 operand,
9641 ),
9642 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
9643 (VarAction::Put, Slot::VarRef(_)) => (
9644 if lexical {
9645 Opcode::PutVarRefCheck
9646 } else {
9647 Opcode::PutVarRef
9648 },
9649 operand,
9650 ),
9651 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
9652 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9653 // Initialisation is what ends the dead zone, so it never checks.
9654 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9655 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
9656 // `this` in a derived constructor is always a local, so these cannot happen;
9657 // routing them to the ordinary forms keeps the match total without inventing
9658 // opcodes the reference does not have.
9659 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
9660 // The captured form of `PutLocCheckInit`: `super()` inside an arrow that closes over
9661 // the constructor's `this` still has to refuse a second initialisation, and the
9662 // plain store accepted it (`fields-run-once-on-double-super`).
9663 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRefCheckInit, operand),
9664 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9665 (Opcode::PutVarInit, operand)
9666 }
9667 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
9668 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9669 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9670 (Opcode::PutVarInit, operand)
9671 }
9672 (VarAction::Set, Slot::Loc(_)) => (
9673 if lexical {
9674 Opcode::SetLocCheck
9675 } else {
9676 Opcode::SetLoc
9677 },
9678 operand,
9679 ),
9680 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
9681 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
9682 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9683 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9684 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
9685 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9686 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
9687 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
9688 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9689 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
9690 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9691 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
9692 // A reference pins the binding so that one lvalue can be read and stored without
9693 // resolving the name in between. Which opcode builds it depends on where the
9694 // binding lives; the atom rides along because the *runtime* resolution can still
9695 // override the static answer — see `Interp::make_var_ref`.
9696 (VarAction::MakeRef, Slot::Loc(_)) => (Opcode::MakeLocRef, ref_operand),
9697 (VarAction::MakeRef, Slot::Arg(_)) => (Opcode::MakeArgRef, ref_operand),
9698 (VarAction::MakeRef, Slot::VarRef(_)) => (Opcode::MakeVarRefRef, ref_operand),
9699 (VarAction::MakeRef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9700 (Opcode::MakeVarRef, vec![ref_operand[0].clone()])
9701 }
9702 // Reading through a reference does not consult the binding at all — the reference
9703 // already points at it — so the slot plays no part.
9704 (VarAction::GetRef, _) => (Opcode::GetRefValue, Vec::new()),
9705 }
9706}
9707
9708/// The instruction-rewriting pass.
9709///
9710/// These are the reference implementation's patterns, restricted to the ones the
9711/// constructs this compiler supports can produce. Each entry is a comment on the
9712/// bytecode it removes, because the whole point is that the result is one
9713/// instruction shorter than the literal translation of the AST.
9714fn peephole(
9715 insns: &mut [Option<(Opcode, Vec<Op>)>],
9716 label_at: &[Option<u32>],
9717 placed: &[Option<usize>],
9718) {
9719 fold_dup_patterns(insns, label_at);
9720
9721 // `drop` before `return_undef` is dead: the return discards the whole frame
9722 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
9723 // consumes its own `drop`; removing the drop first would leave the `dup` and
9724 // produce a `set_` where the reference has a `put_`.
9725 for index in 0..insns.len() {
9726 if opcode_at(insns, index) != Some(Opcode::Drop) {
9727 continue;
9728 }
9729 // Skip over a run of drops, but stop at a jump target: removing code on
9730 // one side of a label would silently retarget the jump.
9731 let mut next = index + 1;
9732 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
9733 next += 1;
9734 }
9735 if is_label_at(label_at, next) {
9736 continue;
9737 }
9738 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
9739 for entry in &mut insns[index..next] {
9740 *entry = None;
9741 }
9742 }
9743 }
9744
9745 // The rewrites below all decide against one fixed snapshot, which is what the
9746 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
9747 // the pass, so a rule never observes what an earlier rule removed. Gathering
9748 // every deletion first and applying them together reproduces that.
9749 let snapshot: Vec<Option<Opcode>> = insns
9750 .iter()
9751 .map(|entry| entry.as_ref().map(|(op, _)| *op))
9752 .collect();
9753 // The next instruction that is still there. Holes left by dead-code
9754 // elimination are not instructions, so a rule looks past them.
9755 let next_op = |index: usize| -> Option<usize> {
9756 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
9757 };
9758
9759 let mut doomed = vec![false; insns.len()];
9760 for index in 0..insns.len() {
9761 // A constant pushed only to be dropped does nothing at all. This is what a
9762 // comma expression with a literal left operand compiles to — `(0, f)()` — and
9763 // the reference removes the pair rather than making the reader step over it.
9764 let constant = matches!(
9765 snapshot[index],
9766 Some(
9767 Opcode::Undefined
9768 | Opcode::Null
9769 | Opcode::PushMinus1
9770 | Opcode::Push0
9771 | Opcode::Push1
9772 | Opcode::Push2
9773 | Opcode::Push3
9774 | Opcode::Push4
9775 | Opcode::Push5
9776 | Opcode::Push6
9777 | Opcode::Push7
9778 | Opcode::PushTrue
9779 | Opcode::PushFalse
9780 | Opcode::PushI32
9781 )
9782 );
9783 if constant
9784 && let Some(next) = next_op(index)
9785 && snapshot[next] == Some(Opcode::Drop)
9786 {
9787 doomed[index] = true;
9788 doomed[next] = true;
9789 }
9790 }
9791 for (index, entry) in insns.iter_mut().enumerate() {
9792 if doomed[index] {
9793 *entry = None;
9794 }
9795 }
9796
9797 // A conditional whose destination is the very next instruction just pops its
9798 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
9799 // compiles to.
9800 //
9801 // Order matters, and it is the reference's order: this runs *before* the
9802 // folding below, on the instruction the conditional originally had. Folding
9803 // moves a conditional's destination, and the reference never re-examines it
9804 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
9805 // a conditional even though folding leaves it pointing at the next
9806 // instruction.
9807 for (index, entry) in insns.iter_mut().enumerate() {
9808 let Some((op, operands)) = entry.clone() else {
9809 continue;
9810 };
9811 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
9812 continue;
9813 }
9814 let Some(id) = label_id(&operands) else {
9815 continue;
9816 };
9817 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
9818 *entry = Some((Opcode::Drop, Vec::new()));
9819 }
9820 }
9821
9822 // A constant condition is decided here rather than at run time.
9823 fold_constant_conditions(insns, label_at);
9824 // The conditional folding below is about pairs of *real* branches, so it runs
9825 // before a jump to the next instruction is dropped: `do { … if (c) continue }
9826 // while (t)` puts `continue` exactly on the condition, and the reference inverts
9827 // the branch first and only then notices the jump goes nowhere.
9828 fold_conditional_jumps(insns, label_at, placed);
9829
9830 // A jump whose destination is the very next instruction does nothing, which is
9831 // what constant folding leaves behind for `while (1) { … }`.
9832 remove_jump_to_next(insns, placed);
9833
9834 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
9835 // a use of the same variable boils down to.
9836 for index in 0..insns.len() {
9837 let Some((put_op, _)) = insns[index].clone() else {
9838 continue;
9839 };
9840 if !is_foldable_put(put_op) {
9841 continue;
9842 }
9843 if is_label_at(label_at, index + 1) {
9844 continue;
9845 }
9846 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
9847 continue;
9848 };
9849 if get_op != get_form_of(put_op) {
9850 continue;
9851 }
9852 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
9853 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
9854 continue;
9855 }
9856 insns[index] = Some((set_form_of(put_op), get_operands));
9857 insns[index + 1] = None;
9858 }
9859}
9860
9861/// Drop `gosub`s that call an empty subroutine.
9862///
9863/// A `gosub` whose target starts with `ret` returns immediately, so the reference
9864/// drops the call. This is how `try`/`catch` without a `finally` loses its
9865/// finalizer plumbing: the finalizer block is empty, its first instruction is
9866/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
9867/// [`eliminate_dead_code`] then removes.
9868fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
9869 let state = &stack[current];
9870 let mut targets = Vec::new();
9871 for insn in &state.insns {
9872 if let Insn::Fixed { op, operands } = insn
9873 && *op == Opcode::Gosub
9874 && let Some(id) = label_id(operands)
9875 && let Some(target) = state.labels.get(id as usize).copied().flatten()
9876 {
9877 targets.push(target);
9878 }
9879 }
9880 let empty: Vec<usize> = targets
9881 .into_iter()
9882 .filter(|target| {
9883 stack[current]
9884 .insns
9885 .get(*target)
9886 .map(|insn| {
9887 matches!(
9888 insn,
9889 Insn::Fixed {
9890 op: Opcode::Ret,
9891 ..
9892 }
9893 )
9894 })
9895 .unwrap_or(false)
9896 })
9897 .collect();
9898 if empty.is_empty() {
9899 return;
9900 }
9901 for insn in stack[current].insns.iter_mut() {
9902 if let Insn::Fixed { op, operands } = insn
9903 && *op == Opcode::Gosub
9904 && let Some(id) = label_id(operands)
9905 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
9906 && empty.contains(&target)
9907 {
9908 *insn = Insn::Dead;
9909 }
9910 }
9911}
9912
9913/// Replace unreachable instructions with [`Insn::Dead`].
9914fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
9915 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
9916 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
9917 if !reachable[index] {
9918 *insn = Insn::Dead;
9919 }
9920 }
9921}
9922
9923/// Mark every instruction index reachable from the entry, plus the index one past
9924/// the last instruction.
9925///
9926/// `seen[len]` answers "can control reach the end of this function", and the
9927/// entries before it identify dead code. Both DCE and the implicit-return decision
9928/// read the same result, which keeps them from disagreeing.
9929fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
9930 let mut seen = vec![false; count + 1];
9931 let mut worklist = vec![0usize];
9932 while let Some(index) = worklist.pop() {
9933 if index > count || seen[index] {
9934 continue;
9935 }
9936 seen[index] = true;
9937 if index == count {
9938 continue;
9939 }
9940 let (op, operands) = match &state.insns[index] {
9941 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
9942 // A variable access never transfers control, and a removed
9943 // instruction is only reachable if it is already marked.
9944 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
9945 worklist.push(index + 1);
9946 continue;
9947 }
9948 };
9949 match op {
9950 // A return, a throw and a `ret` all leave this instruction stream: the
9951 // first two give control to the caller or the handler, and `ret`
9952 // returns to a `gosub` elsewhere.
9953 // A tail call leaves the function too: the callee's result becomes this
9954 // function's result, so nothing after it runs.
9955 Opcode::Return
9956 | Opcode::ReturnUndef
9957 | Opcode::ReturnAsync
9958 | Opcode::TailCall
9959 | Opcode::TailCallMethod
9960 | Opcode::Throw
9961 | Opcode::ThrowError
9962 | Opcode::Ret => {}
9963 // A `catch` records where exceptions from the code that follows go.
9964 // That code is not reachable through normal control flow, but it is
9965 // reachable — through the exception edge — so the walk has to follow
9966 // it, or dead-code elimination would delete every handler.
9967 Opcode::Catch => {
9968 if let Some(target) = placed_label(state, operands) {
9969 worklist.push(target);
9970 }
9971 worklist.push(index + 1);
9972 }
9973 // A `gosub` calls a subroutine and then continues, so both edges count.
9974 Opcode::Gosub => {
9975 if let Some(target) = placed_label(state, operands) {
9976 worklist.push(target);
9977 }
9978 worklist.push(index + 1);
9979 }
9980 Opcode::Goto => {
9981 if let Some(target) = placed_label(state, operands) {
9982 worklist.push(target);
9983 }
9984 }
9985 Opcode::IfTrue | Opcode::IfFalse => {
9986 if let Some(target) = placed_label(state, operands) {
9987 worklist.push(target);
9988 }
9989 worklist.push(index + 1);
9990 }
9991 _ => worklist.push(index + 1),
9992 }
9993 }
9994 seen
9995}
9996
9997/// The instruction index a jump operand points at, resolved through the label
9998/// placement table.
9999fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
10000 let id = label_id(operands)?;
10001 state.labels.get(id as usize).copied().flatten()
10002}
10003
10004/// The label an instruction refers to.
10005fn label_id(operands: &[Op]) -> Option<u32> {
10006 operands.iter().find_map(|operand| match operand {
10007 Op::Label(label) => Some(label.0),
10008 _ => None,
10009 })
10010}
10011
10012/// Turn `if_false L; goto M; L:` into `if_true M`.
10013///
10014/// A conditional whose alternate branch is an unconditional jump needs one jump,
10015/// not two. This is the shape `if (c) break;` produces, so folding it removes an
10016/// instruction and a label from every conditional `break`.
10017/// The boolean a constant-push instruction produces, or `None` if it is not one.
10018///
10019/// Only the operators whose truthiness is decided by the opcode are covered; a
10020/// constant that needs the constant pool (a string) is left alone, because reading it
10021/// would mean threading the pool through the peephole for a case the reference also
10022/// skips.
10023fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
10024 match op {
10025 // `push_0` returns -1 for zero, `push_1` 1, and so on.
10026 Opcode::PushMinus1 => Some(true),
10027 Opcode::Push0 => Some(false),
10028 Opcode::Push1
10029 | Opcode::Push2
10030 | Opcode::Push3
10031 | Opcode::Push4
10032 | Opcode::Push5
10033 | Opcode::Push6
10034 | Opcode::Push7 => Some(true),
10035 Opcode::PushTrue => Some(true),
10036 Opcode::PushFalse => Some(false),
10037 Opcode::Undefined | Opcode::Null => Some(false),
10038 Opcode::PushI32 => match operands.first() {
10039 Some(Op::Int(value)) => Some(*value != 0),
10040 _ => None,
10041 },
10042 _ => None,
10043 }
10044}
10045
10046/// Fold a branch on a constant condition.
10047///
10048/// `if (0) a() else b()` must not test anything at run time, and the reference
10049/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
10050/// which is why the bytecode for a `while (1)` loop has no condition at all.
10051///
10052/// Two instructions become one, so the slot the test occupied is left empty rather
10053/// than shifting everything after it: labels have already been resolved to indices.
10054fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
10055 for index in 0..insns.len() {
10056 let Some((push_op, push_operands)) = insns[index].clone() else {
10057 continue;
10058 };
10059 let Some(truth) = constant_truth(push_op, &push_operands) else {
10060 continue;
10061 };
10062 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
10063 continue;
10064 };
10065 // A label on the branch means something else jumps *here* — the value is on the
10066 // stack and the conditional is what pops it. Deleting the branch would leave that
10067 // jump with no instruction, and a label whose slot is empty resolves to the next
10068 // one that is not, i.e. to the far side of the branch. That is how
10069 // `if (a && false) then else` jumped to `then`: `&&` ends its chain on a label, and
10070 // the constant `false` sits directly in front of the statement's own conditional.
10071 if is_label_at(label_at, index + 1) {
10072 continue;
10073 }
10074 let (destination, taken) = match branch_op {
10075 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
10076 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
10077 _ => continue,
10078 };
10079 let Some(destination) = destination else {
10080 continue;
10081 };
10082 insns[index] = if taken {
10083 // The branch is always taken, so it becomes an unconditional jump.
10084 Some((Opcode::Goto, vec![destination]))
10085 } else {
10086 // The branch never runs: both instructions disappear and control falls
10087 // through to what came after.
10088 None
10089 };
10090 insns[index + 1] = None;
10091 }
10092}
10093
10094/// Remove a jump whose destination is the instruction right after it.
10095///
10096/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
10097/// its test into nothing, and the loop-end jump then points at the following
10098/// instruction. The reference drops them, so `stack_size` and the listing agree.
10099fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
10100 for index in 0..insns.len() {
10101 let Some((op, operands)) = insns[index].clone() else {
10102 continue;
10103 };
10104 if !is_goto(op) {
10105 continue;
10106 }
10107 let Some(id) = label_id(&operands) else {
10108 continue;
10109 };
10110 // The next instruction that still exists, which is what "the instruction
10111 // after this jump" means once earlier folds have punched holes.
10112 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
10113 if placed.get(id as usize).copied().flatten() == next {
10114 insns[index] = None;
10115 }
10116 }
10117}
10118
10119fn fold_conditional_jumps(
10120 insns: &mut [Option<(Opcode, Vec<Op>)>],
10121 label_at: &[Option<u32>],
10122 placed: &[Option<usize>],
10123) {
10124 for index in 0..insns.len() {
10125 let Some((op, operands)) = insns[index].clone() else {
10126 continue;
10127 };
10128 let inverted = match op {
10129 Opcode::IfFalse => Opcode::IfTrue,
10130 Opcode::IfTrue => Opcode::IfFalse,
10131 _ => continue,
10132 };
10133 // Next must be an unconditional jump that is not itself a target, and the
10134 // instruction after it must be exactly where the conditional goes.
10135 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
10136 continue;
10137 };
10138 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
10139 continue;
10140 }
10141 // The conditional must land on the instruction *after* the jump. Several
10142 // labels can share a position, so this asks where *this* label was put
10143 // rather than what label happens to sit there.
10144 let Some(taken) = label_id(&operands) else {
10145 continue;
10146 };
10147 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
10148 continue;
10149 }
10150 let Some(destination) = next_operands.first().cloned() else {
10151 continue;
10152 };
10153 insns[index] = Some((inverted, vec![destination]));
10154 insns[index + 1] = None;
10155 }
10156}
10157
10158/// Whether a jump target is placed at this instruction index.
10159fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
10160 label_at.get(index).copied().flatten().is_some()
10161}
10162
10163fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
10164 // `dup put_x(n)` -> `set_x(n)`
10165 // `dup put_x(n) drop` -> `put_x(n)`
10166 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
10167 for index in 0..insns.len() {
10168 if opcode_at(insns, index) != Some(Opcode::Dup) {
10169 continue;
10170 }
10171 if is_label_at(label_at, index + 1) {
10172 continue;
10173 }
10174 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
10175 continue;
10176 };
10177 if !is_foldable_put(put_op) {
10178 continue;
10179 }
10180 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
10181 continue;
10182 };
10183 let mut new_op = set_form_of(put_op);
10184 let mut end = index + 2;
10185 if is_label_at(label_at, end) {
10186 // The `put` has to stay as it is; only the `dup` can be folded.
10187 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
10188 insns[index + 1] = None;
10189 continue;
10190 }
10191 // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
10192 // Deleting it moves the label's target onto whatever follows, and the code that
10193 // jumps there arrives with a different stack than the fall-through path: that is
10194 // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
10195 // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
10196 // an empty stack. The store had already consumed the value it was supposed to
10197 // leave behind.
10198 if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
10199 new_op = put_op;
10200 end += 1;
10201 if opcode_at(insns, end) == Some(get_form_of(put_op))
10202 && !is_label_at(label_at, end)
10203 && insns[end]
10204 .as_ref()
10205 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
10206 {
10207 new_op = set_form_of(put_op);
10208 end += 1;
10209 }
10210 }
10211 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
10212 for entry in &mut insns[index + 1..end] {
10213 *entry = None;
10214 }
10215 }
10216}
10217
10218fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
10219 insns
10220 .get(index)
10221 .and_then(|entry| entry.as_ref())
10222 .map(|(op, _)| *op)
10223}
10224
10225/// The four `put_` families that have a `set_` twin. Deliberately not including
10226/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
10227/// these, and folding the others would produce instructions that do not exist.
10228fn is_foldable_put(op: Opcode) -> bool {
10229 matches!(
10230 op,
10231 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
10232 )
10233}
10234
10235fn set_form_of(op: Opcode) -> Opcode {
10236 match op {
10237 Opcode::PutLoc => Opcode::SetLoc,
10238 Opcode::PutLocCheck => Opcode::SetLocCheck,
10239 Opcode::PutArg => Opcode::SetArg,
10240 Opcode::PutVarRef => Opcode::SetVarRef,
10241 other => other,
10242 }
10243}
10244
10245fn get_form_of(op: Opcode) -> Opcode {
10246 match op {
10247 Opcode::PutLoc => Opcode::GetLoc,
10248 Opcode::PutLocCheck => Opcode::GetLocCheck,
10249 Opcode::PutArg => Opcode::GetArg,
10250 Opcode::PutVarRef => Opcode::GetVarRef,
10251 other => other,
10252 }
10253}
10254
10255/// Atom interning, per function.
10256///
10257/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
10258/// identifiers, so the array-index rule applies here rather than at the handful of
10259/// call sites that build property keys.
10260fn intern_atom(state: &mut FnState, name: &str) -> u32 {
10261 intern_atom_value(state, Atom::from_text(name))
10262}
10263
10264/// [`intern_atom`] for an operand that is already an [`Atom`].
10265///
10266/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
10267/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
10268/// would have looked up.
10269fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
10270 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
10271 return index as u32;
10272 }
10273 state.atoms.push(atom);
10274 state.atoms.len() as u32 - 1
10275}
10276
10277fn binary_opcode(op: BinaryOp) -> Opcode {
10278 match op {
10279 BinaryOp::Add => Opcode::Add,
10280 BinaryOp::Sub => Opcode::Sub,
10281 BinaryOp::Mul => Opcode::Mul,
10282 BinaryOp::Div => Opcode::Div,
10283 BinaryOp::Mod => Opcode::Mod,
10284 BinaryOp::Pow => Opcode::Pow,
10285 BinaryOp::BitOr => Opcode::Or,
10286 BinaryOp::BitXor => Opcode::Xor,
10287 BinaryOp::BitAnd => Opcode::And,
10288 BinaryOp::Shl => Opcode::Shl,
10289 BinaryOp::Shr => Opcode::Sar,
10290 BinaryOp::UShr => Opcode::Shr,
10291 BinaryOp::Lt => Opcode::Lt,
10292 BinaryOp::LtEq => Opcode::Lte,
10293 BinaryOp::Gt => Opcode::Gt,
10294 BinaryOp::GtEq => Opcode::Gte,
10295 BinaryOp::Eq => Opcode::Eq,
10296 BinaryOp::NotEq => Opcode::Neq,
10297 BinaryOp::StrictEq => Opcode::StrictEq,
10298 BinaryOp::StrictNotEq => Opcode::StrictNeq,
10299 BinaryOp::In => Opcode::In,
10300 BinaryOp::Instanceof => Opcode::Instanceof,
10301 }
10302}
10303
10304fn compound_opcode(op: AssignOp) -> Opcode {
10305 match op {
10306 AssignOp::Add => Opcode::Add,
10307 AssignOp::Sub => Opcode::Sub,
10308 AssignOp::Mul => Opcode::Mul,
10309 AssignOp::Div => Opcode::Div,
10310 AssignOp::Mod => Opcode::Mod,
10311 AssignOp::Pow => Opcode::Pow,
10312 AssignOp::Shl => Opcode::Shl,
10313 AssignOp::Shr => Opcode::Sar,
10314 AssignOp::UShr => Opcode::Shr,
10315 AssignOp::BitOr => Opcode::Or,
10316 AssignOp::BitXor => Opcode::Xor,
10317 AssignOp::BitAnd => Opcode::And,
10318 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
10319 }
10320}
10321
10322/// Encode the resolved instruction stream, choosing short forms where possible.
10323///
10324/// The peephole pass leaves holes in the instruction list so that label indices
10325/// stay valid. A label names an *instruction index*, and an index that was
10326/// deleted has to resolve to the next surviving instruction, which is what
10327/// [`resolve_label`] does before the byte offsets are known.
10328fn assemble(
10329 insns: &mut [Option<(Opcode, Vec<Op>)>],
10330 insn_pos: &[Option<Position>],
10331 state: &mut FnState,
10332) -> (Vec<u8>, u32, Vec<LineCol>) {
10333 // Compaction: surviving instructions in order, plus the index mapping.
10334 //
10335 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
10336 // point below where instructions are removed — otherwise a stack trace would point
10337 // at the wrong source line as soon as dead-code elimination kicked in.
10338 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
10339 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
10340 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
10341 for (original, entry) in insns.iter_mut().enumerate() {
10342 if let Some((op, operands)) = entry.take() {
10343 original_to_kept[original] = Some(kept.len());
10344 kept.push((op, operands));
10345 spans.push(insn_pos.get(original).copied().flatten());
10346 }
10347 }
10348
10349 if std::env::var_os("QJS_DEBUG").is_some() {
10350 eprintln!("--- assemble entry --- {kept:?}");
10351 }
10352 // How many labels are real, as opposed to the per-instruction ones allocated
10353 // just below. Only a real label marks a spot in the source program.
10354 let real_labels = state.labels.len();
10355
10356 // Give every surviving instruction a label of its own. Jump cleanup below
10357 // redirects jumps to arbitrary instructions, and a jump target has to be a
10358 // label; pre-allocating one per index means a redirect never has to invent
10359 // anything.
10360 let existing = state.labels.len();
10361 let base = kept.len();
10362 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
10363 for offset in 0..=kept.len() {
10364 state.labels.push(Some(0));
10365 index_label.push(Label((existing + offset) as u32));
10366 }
10367 // Point each pre-allocated label at its instruction, reusing the count from
10368 // `original_to_kept` so the mapping survives compaction.
10369 let place_index_labels = |state: &mut FnState,
10370 original_to_kept: &[Option<usize>],
10371 kept_len: usize,
10372 index_label: &[Label]| {
10373 for (original, mapped) in original_to_kept.iter().enumerate() {
10374 if let Some(kept_index) = mapped {
10375 let label = index_label[*kept_index].0 as usize;
10376 state.labels[label] = Some(original);
10377 }
10378 }
10379 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
10380 };
10381 place_index_labels(state, &original_to_kept, base, &index_label);
10382
10383 // Resolve every label to a kept index once; the placement table maps labels
10384 // to original indices, so a second hop lands in kept space.
10385 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
10386 for (id, placed) in state.labels.iter().enumerate() {
10387 let Some(original) = placed else { continue };
10388 label_kept[id] = if *original == usize::MAX {
10389 Some(base)
10390 } else {
10391 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
10392 };
10393 }
10394
10395 // Code after an unconditional transfer is unreachable, and the reference drops it
10396 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
10397 // scans forward until it finds a label something still jumps to, so a run of
10398 // dead instructions between a `throw` and the next live target disappears.
10399 //
10400 // The scan repeats because dropping a jump lowers the reference count of the
10401 // label it pointed at, which can strand what follows. Only a real label keeps an
10402 // instruction alive here; the per-instruction labels allocated above belong to
10403 // this pass, not to the program.
10404 loop {
10405 let mut references = vec![false; kept.len() + 1];
10406 for (_, operands) in &kept {
10407 if let Some(target) = target_kept_index(operands, &label_kept)
10408 && target < references.len()
10409 {
10410 references[target] = true;
10411 }
10412 }
10413 let mut doomed = vec![false; kept.len()];
10414 let mut any = false;
10415 for (index, (op, _)) in kept.iter().enumerate() {
10416 if !is_transfer(*op) {
10417 continue;
10418 }
10419 for next in index + 1..kept.len() {
10420 if references[next] {
10421 break;
10422 }
10423 doomed[next] = true;
10424 any = true;
10425 }
10426 }
10427 if !any {
10428 break;
10429 }
10430 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
10431 }
10432
10433 // A label that lands on an unconditional jump stands for wherever that jump
10434 // goes, so retarget it once and every jump to the label follows for free.
10435 // This is what makes `continue` in a `for` head reach the loop top instead of
10436 // stopping at the update's trailing jump.
10437 let folded: Vec<Option<usize>> = label_kept
10438 .iter()
10439 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
10440 .collect();
10441 label_kept = folded;
10442
10443 // Jump cleanup, in compacted index space. Two rewrites the reference also
10444 // applies while it resolves labels:
10445 // * a jump whose destination is the very next instruction does nothing;
10446 // * a jump to a jump is redirected to its final destination.
10447 // The second can expose the first, so this repeats until it settles.
10448 loop {
10449 let mut delete = vec![false; kept.len()];
10450 let mut changed = false;
10451 for index in 0..kept.len() {
10452 let (op, operands) = &kept[index];
10453 if !is_goto(*op) {
10454 continue;
10455 }
10456 let Some(immediate) = target_kept_index(operands, &label_kept) else {
10457 continue;
10458 };
10459 let target = follow_jump_chain(&kept, &label_kept, immediate);
10460 if target == index + 1 {
10461 delete[index] = true;
10462 changed = true;
10463 } else if matches!(
10464 kept.get(target).map(|(op, _)| *op),
10465 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
10466 ) {
10467 // Jumping straight to a return or throw is the same as doing it
10468 // here, so the jump becomes that instruction.
10469 kept[index] = (kept[target].0, Vec::new());
10470 changed = true;
10471 } else if target != immediate {
10472 // Redirect to the end of the chain.
10473 let label = index_label[target];
10474 kept[index].1 = vec![Op::Label(label)];
10475 changed = true;
10476 }
10477 }
10478 if !changed {
10479 break;
10480 }
10481 if !delete.iter().any(|deleted| *deleted) {
10482 break;
10483 }
10484 // Drop the deleted instructions and renumber everything.
10485 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10486 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10487 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10488 for (old, entry) in kept.into_iter().enumerate() {
10489 if delete[old] {
10490 continue;
10491 }
10492 moved[old] = Some(next.len());
10493 next.push(entry);
10494 next_spans.push(spans[old]);
10495 }
10496 for (id, slot) in label_kept.iter_mut().enumerate() {
10497 let Some(old) = *slot else { continue };
10498 *slot = match moved.get(old).copied().flatten() {
10499 Some(new) => Some(new),
10500 // The target was deleted: the jump now lands on whatever follows.
10501 None => (old..moved.len())
10502 .find_map(|i| moved[i])
10503 .or(Some(next.len())),
10504 };
10505 let _ = id;
10506 }
10507 kept = next;
10508 spans = next_spans;
10509 }
10510
10511 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
10512 // jump to the next instruction and is deleted, leaving the label at the end with
10513 // nothing pointing at it. If that also strands the last instruction, it goes
10514 // too — which is how a `try` whose body always returns ends on its `ret` rather
10515 // than an implicit `return_undef`.
10516 // Which instructions something still jumps to. Reading the surviving jumps is
10517 // what the reference's reference counts amount to: once a jump has been folded
10518 // away the label it named is unreferenced, even though the program still has a
10519 // label there.
10520 let mut references = vec![false; kept.len() + 1];
10521 let _ = real_labels;
10522 for (_, operands) in &kept {
10523 if let Some(target) = target_kept_index(operands, &label_kept)
10524 && target < references.len()
10525 {
10526 references[target] = true;
10527 }
10528 }
10529 let mut end = kept.len();
10530 while end > 0 {
10531 let last = end - 1;
10532 let reachable = references[last] || end < kept.len();
10533 if reachable {
10534 break;
10535 }
10536 let after_transfer = last
10537 .checked_sub(1)
10538 .map(|previous| {
10539 matches!(
10540 kept[previous].0,
10541 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
10542 )
10543 })
10544 .unwrap_or(false);
10545 if !after_transfer {
10546 break;
10547 }
10548 end = last;
10549 }
10550 kept.truncate(end);
10551 spans.truncate(end);
10552
10553 // Choose an opcode for each instruction and its size, so label offsets can be
10554 // computed.
10555 let chosen = choose_opcodes(&kept, &label_kept);
10556 let offsets = instruction_offsets(&chosen);
10557 let offset = *offsets.last().unwrap_or(&0);
10558
10559 let mut code = Vec::with_capacity(offset);
10560 for (position, (_, operands)) in kept.iter().enumerate() {
10561 let op = chosen[position];
10562 code.push(op as u8);
10563 let operands = retarget_labels(operands, &label_kept, kept.len());
10564 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
10565 }
10566 let stack_size = compute_stack_size(&code);
10567 // Keep only the offsets where the position actually changes: a run of
10568 // instructions on one line is one table entry, and the runtime binary searches
10569 // the table for the frame's pc.
10570 //
10571 // The table always starts at pc 0 with the *function's own* position, because the
10572 // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
10573 // last_line_num)` from `fd->source_pos`, the token the function definition starts at
10574 // (`function`, `async`, a method's property name). An instruction before the first
10575 // recorded operator therefore reports the function's own start, which is what makes a
10576 // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
10577 let mut positions: Vec<LineCol> = vec![LineCol {
10578 pc: 0,
10579 line: state.line,
10580 column: state.column,
10581 }];
10582 let mut last: Option<Position> = None;
10583 for (index, span) in spans.iter().enumerate() {
10584 let Some(pos) = *span else { continue };
10585 if last == Some(pos) {
10586 continue;
10587 }
10588 last = Some(pos);
10589 if pos.line == state.line && pos.column == state.column {
10590 // Already the seed entry above.
10591 continue;
10592 }
10593 positions.push(LineCol {
10594 pc: offsets[index] as u32,
10595 line: pos.line,
10596 column: pos.column,
10597 });
10598 }
10599 (code, stack_size, positions)
10600}
10601
10602/// Whether an instruction always transfers control away, so anything after it in the
10603/// same stream is unreachable.
10604fn is_transfer(op: Opcode) -> bool {
10605 matches!(
10606 op,
10607 Opcode::Goto
10608 | Opcode::Goto8
10609 | Opcode::Goto16
10610 | Opcode::Return
10611 | Opcode::ReturnUndef
10612 | Opcode::Throw
10613 | Opcode::ThrowError
10614 | Opcode::Ret
10615 )
10616}
10617
10618/// Remove the marked instructions and renumber the label table so it keeps pointing
10619/// at the same instructions. A label whose instruction went away moves to whatever
10620/// follows it, since a jump is never left with nowhere to land.
10621fn drop_instructions(
10622 kept: Vec<(Opcode, Vec<Op>)>,
10623 spans: Vec<Option<Position>>,
10624 label_kept: &mut [Option<usize>],
10625 doomed: &[bool],
10626) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
10627 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10628 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10629 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10630 for (old, entry) in kept.into_iter().enumerate() {
10631 if doomed.get(old).copied().unwrap_or(false) {
10632 continue;
10633 }
10634 moved[old] = Some(result.len());
10635 result.push(entry);
10636 result_spans.push(spans[old]);
10637 }
10638 for slot in label_kept.iter_mut() {
10639 let Some(old) = *slot else { continue };
10640 *slot = match moved.get(old).copied().flatten() {
10641 Some(new) => Some(new),
10642 None => (old..moved.len())
10643 .find_map(|i| moved[i])
10644 .or(Some(result.len())),
10645 };
10646 }
10647 (result, result_spans)
10648}
10649
10650fn is_goto(op: Opcode) -> bool {
10651 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
10652}
10653
10654/// The kept index a jump operand points at.
10655fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
10656 let id = label_id(operands)?;
10657 label_kept.get(id as usize).copied().flatten()
10658}
10659
10660/// Follow a chain of unconditional jumps to its first real destination.
10661fn follow_jump_chain(
10662 kept: &[(Opcode, Vec<Op>)],
10663 label_kept: &[Option<usize>],
10664 start: usize,
10665) -> usize {
10666 let mut current = start;
10667 // `for(;;)` jumps to itself, so the walk has to be bounded.
10668 for _ in 0..kept.len() {
10669 let Some((op, operands)) = kept.get(current) else {
10670 return current;
10671 };
10672 if !is_goto(*op) {
10673 return current;
10674 }
10675 let Some(next) = target_kept_index(operands, label_kept) else {
10676 return current;
10677 };
10678 if next == current {
10679 return current;
10680 }
10681 current = next;
10682 }
10683 current
10684}
10685
10686/// Rewrite label operands from label ids to kept instruction indices.
10687fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
10688 operands
10689 .iter()
10690 .map(|operand| match operand {
10691 Op::Label(label) => {
10692 let target = label_kept
10693 .get(label.0 as usize)
10694 .copied()
10695 .flatten()
10696 .unwrap_or(kept_len);
10697 Op::Label(Label(target as u32))
10698 }
10699 other => other.clone(),
10700 })
10701 .collect()
10702}
10703
10704/// Encode the resolved instruction stream, choosing short forms where possible.
10705///
10706/// Compute the maximum value-stack depth by exploring the control-flow graph.
10707///
10708/// This is a breadth-first walk from the first instruction, tracking the stack
10709/// depth on entry to each instruction. Every instruction has at most two
10710/// successors (fall through, and a jump target), so a worklist over byte offsets
10711/// is enough. The reference does the same thing in `compute_stack_size`, which is
10712/// why the resulting numbers match exactly.
10713///
10714/// Instructions that pop a variable number of values (`call`, `array_from`, …)
10715/// encode that count in their operand, which is added to the static `n_pop`.
10716fn compute_stack_size(code: &[u8]) -> u32 {
10717 let mut depth_at = vec![u16::MAX; code.len()];
10718 // Each entry carries the enclosing `catch` levels, innermost last, because
10719 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
10720 // offset and forgets that level.
10721 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
10722 let mut max_depth = 0u32;
10723
10724 while let Some((pc, depth, catch_levels)) = worklist.pop() {
10725 if pc >= code.len() {
10726 continue;
10727 }
10728 if depth_at[pc] != u16::MAX {
10729 continue;
10730 }
10731 force_depth(&mut depth_at, pc, depth);
10732
10733 let Some(op) = Opcode::from_u8(code[pc]) else {
10734 break;
10735 };
10736 let info = op.info();
10737 let next = pc + info.size as usize;
10738 if next > code.len() {
10739 break;
10740 }
10741 let mut n_pop = info.n_pop as u32;
10742 let mut n_push = info.n_push as u32;
10743 // Variable-length forms carry their count in the operand.
10744 match info.format {
10745 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
10746 n_pop += read_u16(code, pc + 1) as u32;
10747 }
10748 crate::opcode::OpFormat::Npopx => {
10749 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
10750 }
10751 _ => {}
10752 }
10753 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
10754 // are the `set_` variant; the table already records that, so nothing to
10755 // adjust here.
10756 let _ = &mut n_push;
10757
10758 // The depth before this instruction's own push, which is what a `catch`
10759 // records as its level.
10760 let depth_before = depth;
10761 let mut depth = depth.saturating_sub(n_pop) + n_push;
10762 let mut catch_levels = catch_levels;
10763 if op == Opcode::NipCatch {
10764 // Discard everything above the innermost catch offset, keeping the value
10765 // on top: the frame the code after this sees is the same shape it would
10766 // have had if the `try` were not there.
10767 if let Some(base) = catch_levels.pop() {
10768 depth = base + 1;
10769 }
10770 }
10771 max_depth = max_depth.max(depth);
10772
10773 // Successors.
10774 let target = jump_target_of(code, pc, op);
10775 match op {
10776 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10777 if let Some(target) = target {
10778 worklist.push((target, depth, catch_levels));
10779 }
10780 }
10781 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
10782 if let Some(target) = target {
10783 worklist.push((target, depth, catch_levels.clone()));
10784 }
10785 worklist.push((next, depth, catch_levels));
10786 }
10787 // A `catch` records an exception edge to the handler. The handler is
10788 // entered with the thrown value on top of the stack, in the slot the
10789 // catch offset occupies on the normal path — which is why the handler's
10790 // first instruction can `put_loc` the exception away, and why the depth
10791 // is the same on both paths.
10792 Opcode::Catch => {
10793 if let Some(target) = target {
10794 // The handler is protected by the *enclosing* catch, not by this
10795 // one: an error raised inside it is what the handler's own
10796 // `catch` catches.
10797 worklist.push((target, depth, catch_levels.clone()));
10798 }
10799 catch_levels.push(depth_before);
10800 worklist.push((next, depth, catch_levels));
10801 }
10802 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
10803 // rewind past it too. Its level sits one slot higher than a `catch`'s:
10804 // the iterator and next-method slots occupy the offset's place.
10805 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
10806 if let Some(target) = target {
10807 worklist.push((target, depth, catch_levels.clone()));
10808 }
10809 catch_levels.push(depth_before + 1);
10810 worklist.push((next, depth, catch_levels));
10811 }
10812 // `gosub` calls a subroutine with the return address on top. The opcode
10813 // table records no push for it — `ret` is what pops the slot — so the
10814 // extra one is added here, where the depth of the subroutine's first
10815 // instruction is being computed.
10816 Opcode::Gosub => {
10817 if let Some(target) = target {
10818 worklist.push((target, depth + 1, catch_levels.clone()));
10819 }
10820 worklist.push((next, depth, catch_levels));
10821 }
10822 // `ret` goes back to a `gosub`; nothing here follows it.
10823 Opcode::Ret
10824 | Opcode::Return
10825 | Opcode::ReturnUndef
10826 | Opcode::Throw
10827 | Opcode::ThrowError => {}
10828 _ => worklist.push((next, depth, catch_levels)),
10829 }
10830 }
10831 max_depth
10832}
10833
10834/// Record the stack depth on entry to `pc`, keeping the deeper value if the
10835/// instruction is reachable more than once.
10836fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
10837 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
10838 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
10839 depth_at[pc] = clamped;
10840 }
10841}
10842
10843fn read_u16(code: &[u8], at: usize) -> u16 {
10844 let mut value = 0u16;
10845 for i in 0..2 {
10846 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
10847 }
10848 value
10849}
10850
10851/// The absolute target of a jump instruction, if it has one.
10852fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
10853 let info = op.info();
10854 let position = pc + 1;
10855 match info.format {
10856 crate::opcode::OpFormat::Label8 => {
10857 let offset = *code.get(position)? as i8 as i64;
10858 Some((position as i64 + offset) as usize)
10859 }
10860 crate::opcode::OpFormat::Label16 => {
10861 let offset = read_u16(code, position) as i16 as i64;
10862 Some((position as i64 + offset) as usize)
10863 }
10864 crate::opcode::OpFormat::Label => {
10865 let mut offset = 0i32;
10866 for i in 0..4 {
10867 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
10868 }
10869 Some((position as i64 + offset as i64) as usize)
10870 }
10871 _ => None,
10872 }
10873}
10874
10875fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
10876 use Opcode::*;
10877 match (op, operands.first()) {
10878 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
10879 op.short_form(*value as u32).unwrap_or(op)
10880 }
10881 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
10882 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
10883 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
10884 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
10885 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
10886 // A declared global is reached through its reference cell, so it shares
10887 // the `var_ref` encodings, short forms included.
10888 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
10889 op.short_form(*index).unwrap_or(op)
10890 }
10891 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
10892 op.short_form(*count as u32).unwrap_or(op)
10893 }
10894 _ => op,
10895 }
10896}
10897
10898/// The byte offset each instruction will start at, plus the total code size.
10899fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
10900 let mut offsets = Vec::with_capacity(chosen.len() + 1);
10901 let mut offset = 0usize;
10902 for op in chosen {
10903 offsets.push(offset);
10904 offset += op.size() as usize;
10905 }
10906 offsets.push(offset);
10907 offsets
10908}
10909
10910/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
10911/// the offset actually fits.
10912///
10913/// The choice is circular: an instruction's size decides the offsets of everything after
10914/// it, and the offsets decide whether a jump may be short. So this starts with every jump
10915/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
10916/// Shrinking only ever *shortens* distances, so the loop converges.
10917///
10918/// Doing it in one pass instead — which is what this used to do — silently truncated any
10919/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
10920/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
10921/// with four closures in its body simply stopped, with no error and no output past the
10922/// first iteration.
10923fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
10924 let mut chosen: Vec<Opcode> = kept
10925 .iter()
10926 .map(|(op, operands)| choose_short_form(*op, operands))
10927 .collect();
10928 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
10929 let candidates = |op: Opcode| match op {
10930 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
10931 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
10932 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
10933 _ => None,
10934 };
10935 loop {
10936 let offsets = instruction_offsets(&chosen);
10937 let mut changed = false;
10938 for index in 0..kept.len() {
10939 let (op, operands) = &kept[index];
10940 let Some((short, medium, has_medium)) = candidates(*op) else {
10941 continue;
10942 };
10943 if chosen[index] == short {
10944 continue;
10945 }
10946 let Some(target) = target_kept_index(operands, label_kept) else {
10947 continue;
10948 };
10949 let Some(&target_offset) = offsets.get(target) else {
10950 continue;
10951 };
10952 // A jump is relative to the byte after its opcode, which is the convention
10953 // `jump_target_of` decodes with.
10954 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
10955 if (-128..=127).contains(&relative) {
10956 chosen[index] = short;
10957 changed = true;
10958 } else if has_medium
10959 && chosen[index] == Opcode::Goto
10960 && (-32_768..=32_767).contains(&relative)
10961 {
10962 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
10963 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
10964 // the reference encodes them.
10965 chosen[index] = medium;
10966 changed = true;
10967 }
10968 }
10969 if !changed {
10970 return chosen;
10971 }
10972 }
10973}
10974
10975fn encode_operands(
10976 code: &mut Vec<u8>,
10977 op: Opcode,
10978 operands: &[Op],
10979 position: usize,
10980 offsets: &[usize],
10981) {
10982 use crate::opcode::OpFormat::*;
10983 let info = op.info();
10984 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
10985 let index = match slot {
10986 Slot::Arg(i)
10987 | Slot::Loc(i)
10988 | Slot::VarRef(i)
10989 | Slot::Global(i)
10990 | Slot::GlobalDecl(i) => i,
10991 };
10992 code.extend_from_slice(&(index as u16).to_be_bytes());
10993 };
10994 match info.format {
10995 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
10996 U8 | Const8 => {
10997 if let Some(value) = operands.first().and_then(operand_uint) {
10998 code.push(value as u8);
10999 }
11000 }
11001 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
11002 // like their wide counterparts, only one byte wide.
11003 Loc8 => {
11004 if let Some(Op::Slot(slot)) = operands.first() {
11005 let index = match slot {
11006 Slot::Arg(i)
11007 | Slot::Loc(i)
11008 | Slot::VarRef(i)
11009 | Slot::Global(i)
11010 | Slot::GlobalDecl(i) => *i,
11011 };
11012 code.push(index as u8);
11013 }
11014 }
11015 I8 => {
11016 if let Some(value) = operands.first().and_then(operand_int) {
11017 code.push(value as i8 as u8);
11018 }
11019 }
11020 U16 | Npop => {
11021 if let Some(value) = operands.first().and_then(operand_int) {
11022 code.extend_from_slice(&(value as u16).to_be_bytes());
11023 }
11024 }
11025 I16 => {
11026 if let Some(value) = operands.first().and_then(operand_int) {
11027 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
11028 }
11029 }
11030 I32 => {
11031 if let Some(value) = operands.first().and_then(operand_int) {
11032 code.extend_from_slice(&value.to_be_bytes());
11033 }
11034 }
11035 U32 | Const => {
11036 if let Some(value) = operands.first().and_then(operand_uint) {
11037 code.extend_from_slice(&value.to_be_bytes());
11038 }
11039 }
11040 Loc | Arg | VarRef => {
11041 if let Some(Op::Slot(slot)) = operands.first() {
11042 write_slot(code, *slot);
11043 }
11044 }
11045 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
11046 if let Some(Op::AtomId(index)) = operands.first() {
11047 code.extend_from_slice(&index.to_be_bytes());
11048 }
11049 // The trailing immediate means different things per format, and the
11050 // atom forms that carry a *label* have to resolve it like any other
11051 // jump, so they cannot share the `U8`/`U16` arms above.
11052 match info.format {
11053 AtomU8 | AtomLabelU8 => {
11054 if let Some(value) = operands.get(1).and_then(operand_uint) {
11055 code.push(value as u8);
11056 }
11057 }
11058 AtomU16 | AtomLabelU16 => {
11059 if let Some(value) = operands.get(1).and_then(operand_uint) {
11060 code.extend_from_slice(&(value as u16).to_be_bytes());
11061 }
11062 }
11063 _ => {}
11064 }
11065 }
11066 NpopU16 => {
11067 for operand in operands.iter().take(2) {
11068 if let Some(value) = operand_uint(operand) {
11069 code.extend_from_slice(&(value as u16).to_be_bytes());
11070 }
11071 }
11072 }
11073 Label | Label8 | Label16 | LabelU16 => {
11074 if let Some(Op::Label(label)) = operands.first() {
11075 // Labels were already remapped to kept-instruction indices.
11076 let Some(&target) = offsets.get(label.0 as usize) else {
11077 debug_assert!(false, "label {} is past the end", label.0);
11078 return;
11079 };
11080 let relative = target as i64 - (position as i64 + 1);
11081 match info.format {
11082 Label8 => code.push(relative as i8 as u8),
11083 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
11084 // `label_u16` stores the target followed by an unrelated u16.
11085 LabelU16 => {
11086 code.extend_from_slice(&(relative as i32).to_be_bytes());
11087 if let Some(value) = operands.get(1).and_then(operand_uint) {
11088 code.extend_from_slice(&(value as u16).to_be_bytes());
11089 }
11090 }
11091 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
11092 }
11093 }
11094 }
11095 }
11096}
11097
11098fn operand_int(op: &Op) -> Option<i32> {
11099 match op {
11100 Op::Int(value) => Some(*value),
11101 _ => None,
11102 }
11103}
11104
11105fn operand_uint(op: &Op) -> Option<u32> {
11106 match op {
11107 Op::Const(value) | Op::AtomId(value) => Some(*value),
11108 Op::Int(value) => Some(*value as u32),
11109 _ => None,
11110 }
11111}
11112
11113/// Disassemble a compiled function.
11114pub fn disassemble(function: &CompiledFunction) -> String {
11115 disasm::disassemble_program(function)
11116}
11117
11118/// How many of an object pattern's keys are computed.
11119///
11120/// Only the count matters: a rest element needs a run-time key log exactly when at least one
11121/// key is not a literal, and the log is sized by walking the pattern anyway.
11122fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
11123 properties
11124 .iter()
11125 .flatten()
11126 .filter(|element| {
11127 matches!(
11128 element,
11129 PatternElement::Property {
11130 key: PropName::Computed(_),
11131 ..
11132 }
11133 )
11134 })
11135 .count()
11136}