js_compile/compiler.rs
1//! The bytecode compiler.
2//!
3//! Compilation is a single walk over the AST that emits *symbolic* instructions
4//! (jump targets are label ids, variable references are names), followed by a
5//! resolution pass that turns them into final bytecode. Splitting it this way
6//! keeps the emitter readable: nothing has to know slot indices or byte offsets
7//! while it is still discovering them.
8//!
9//! Variable resolution follows the reference implementation's model:
10//!
11//! * every function has a flat table of arguments and locals;
12//! * block scopes form a chain through [`VarDef::scope_next`], which is what makes
13//! `let`/`const` bindings visible only inside their block and lets the runtime
14//! put them back into the temporal dead zone on entry;
15//! * a name that is not in the current function is looked up in the enclosing
16//! ones; if found, the variable is marked captured and reached through a
17//! closure reference;
18//! * a name found nowhere is a global, reached through a closure entry as well.
19//!
20//! Emission order and instruction choice deliberately mirror `quickjs.c`: the
21//! differential test compares disassembly with the reference opcode by opcode, so
22//! an unnecessary `dup` or a differently chosen short form shows up immediately.
23
24use crate::bytecode::LineCol;
25use crate::bytecode::{
26 ANONYMOUS_BINDING, Atom, ClosureType, ClosureVar, Constant, EvalSite, EvalVisible, ExportEntry,
27 Function as CompiledFunction, FunctionKind, ImportEntry, ModuleMeta, ModuleRequest, VarDef,
28 VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::Wtf8;
36use js_parse::ast::{self, *};
37
38/// A label id, local to the function being compiled.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Label(u32);
41
42/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
43///
44/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
45/// is why the brackets are part of the name; nothing a program writes can collide with it.
46const HOME_OBJECT: &str = "<home_object>";
47
48/// The local holding the function `super()` constructs from.
49///
50/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
51/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
52const ACTIVE_FUNC: &str = "this.active_func";
53
54/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
55const NEW_TARGET: &str = "new.target";
56
57/// Stand-in for a constant-pool index that is only known later in the instruction stream.
58///
59/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
60/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
61/// billion members is not a thing — and the compiler patches it before resolution runs, so a
62/// missed patch is a panic-free compiler error rather than a wrong jump.
63const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
64
65/// One step of a class's initialisation, in source order.
66///
67/// A static block is not a member the class keeps — it is a run of statements that executes
68/// at the point the class definition reaches it — so it belongs *inside* the initialiser
69/// function rather than alongside the fields as a separate pass. Merging the two is what
70/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
71/// same way the reference is.
72enum StaticInitItem<'a> {
73 /// `static x = value`, or `x = value` for the instance half.
74 Field(FieldKey<'a>, Option<&'a Expr>),
75 /// `static { … }`
76 Block {
77 body: &'a [Stmt],
78 /// Position of the `{`, which is where the reference puts the function.
79 body_start: Position,
80 },
81}
82
83/// How one field names its property.
84///
85/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
86/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
87/// is fixed when the class is created. Keeping the expression here instead made
88/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
89/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
90/// `{1: "a"}`.
91enum FieldKey<'a> {
92 /// `x`, `"x"`, `0` — the property name is static text.
93 Literal(&'a PropKey),
94 /// `#x`: the class-scope binding that holds the private symbol.
95 Private(String),
96 /// `[expr]`: the class-scope binding that holds the evaluated key.
97 Computed(String),
98}
99
100/// The `var_block` sentinel for a binding that lives at function scope.
101///
102/// It has to be a value a *real* block key can never take. Block keys are source
103/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
104/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
105/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
106/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
107/// sentinel takes the slot below it.
108const FUNCTION_SCOPE: u64 = u64::MAX - 3;
109
110/// The `var_block` sentinel for a binding of the parameter list.
111///
112/// A function whose parameter list contains a default expression gets *two* variable
113/// environments: one for the parameters and one for the body, so a `var` in the body
114/// that shares a name with a parameter is a different binding. The parameter bindings
115/// therefore need a scope key of their own: reachable while the defaults are
116/// evaluated, invisible to the body, and never merged with a body `var` of the same
117/// name.
118///
119/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
120/// the closure and the body shared one slot, when only the parameters were in scope
121/// when it was created.
122const PARAM_SCOPE: u64 = u64::MAX - 4;
123
124/// The name of the hidden local a `using` declaration caches its dispose method in.
125///
126/// It has to be a name no source can produce, because a script may declare anything: the
127/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
128fn using_method_name(name: &str) -> String {
129 format!("<using.method {name}>")
130}
131
132/// The `blocks` parent sentinel for "this block has no enclosing block".
133///
134/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
135/// also the terminator the chain walk from the script body reached the file's
136/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
137/// leaked into the body scope.
138const NO_PARENT: u64 = u64::MAX - 2;
139
140/// The block key for a script body. Distinct from both sentinels and unreachable from
141/// any source offset.
142const SCRIPT_BODY: u64 = u64::MAX - 1;
143
144/// An operand of a symbolic instruction.
145#[derive(Debug, Clone, PartialEq)]
146enum Op {
147 /// An immediate integer.
148 Int(i32),
149 /// A jump target.
150 Label(Label),
151 /// A constant pool index.
152 Const(u32),
153 /// An atom, before interning.
154 Atom(Atom),
155 /// An interned atom, as an index into [`Function::atoms`].
156 AtomId(u32),
157 /// A resolved slot.
158 Slot(Slot),
159}
160
161/// Where a resolved variable lives.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163enum Slot {
164 Arg(u32),
165 Loc(u32),
166 VarRef(u32),
167 /// A global, by closure-var index.
168 Global(u32),
169 /// A global *declared* in this script. The reference keeps these bindings in
170 /// reference cells so that the script and any closure share one variable, so
171 /// a store goes through `put_var_ref` while a read uses `get_var`.
172 GlobalDecl(u32),
173}
174
175/// What a symbolic variable access does, which decides the final opcode.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177enum VarAction {
178 /// Read the value.
179 Get,
180 /// Read the value, yielding `undefined` for an undeclared global.
181 GetUndef,
182 /// Write, leaving nothing on the stack.
183 Put,
184 /// Write and initialise, leaving the value on the stack.
185 PutInit,
186 /// Write, leaving the value on the stack.
187 Set,
188 /// Initialise a binding that may only be initialised once, such as a derived
189 /// constructor's `this`.
190 PutInitChecked,
191 /// Initialise, leaving the value on the stack and without the `const` check.
192 ///
193 /// A class's own scope binding is a `const` that has to be initialised in the middle
194 /// of the definition — after the constructor exists but before the static fields run
195 /// — and the value has to survive for the outer store to use.
196 SetInit,
197 /// Write a binding that lives in a reference cell.
198 PutRef,
199}
200
201#[derive(Debug, Clone)]
202enum Insn {
203 /// A fully determined instruction.
204 Fixed { op: Opcode, operands: Vec<Op> },
205 /// A variable access, resolved in the second pass.
206 ///
207 /// `block` is the lexical block the access appears in, which is what makes
208 /// shadowing work: two bindings can share a name, and the one that wins is
209 /// whichever scope encloses the access.
210 Var {
211 action: VarAction,
212 name: String,
213 block: u64,
214 /// Whether the access was written in the parameter list; see
215 /// [`FnState::in_params`].
216 in_params: bool,
217 },
218 /// Close a binding *if* it turned out to be captured.
219 ///
220 /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
221 /// only known once the body has been compiled — a closure created there is the
222 /// thing that makes it necessary. The reference emits `close_loc` exactly in that
223 /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
224 /// of emitted blind.
225 CloseCaptured { name: String, block: u64 },
226 /// `delete name`, which can only answer `false` once the binding is known.
227 ///
228 /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
229 /// looks the name up on the global object, which is what distinguishes an implicit
230 /// global (configurable, deletable) from a declared one (a binding, always `false`).
231 DeleteVar { name: String },
232 /// An instruction that dead-code elimination removed. It keeps its slot so
233 /// that label indices stay valid, and resolves to no bytecode.
234 Dead,
235}
236
237/// Where `break` and `continue` jump to.
238///
239/// Targets are stacked as the compiler enters loops and labelled statements, so a
240/// bare `break` needs no analysis: it is simply the innermost target. A labelled
241/// one searches outward by name.
242#[derive(Debug, Clone)]
243struct JumpTarget {
244 /// The labels attached to this target. `l: for(;;)` gives one name; a bare
245 /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
246 /// same statement and `break a` must reach the same place as `break b`.
247 names: Vec<String>,
248 /// Where `break` lands. `None` for a construct `break` may only leave, not
249 /// target — a `try`, whose entry exists purely to unwind.
250 break_label: Option<Label>,
251 /// Where `continue` lands. `None` for anything that is not a loop.
252 continue_label: Option<Label>,
253 /// Stack slots to discard when control leaves this construct by a jump.
254 ///
255 /// Both `switch` and `try` leave something on the value stack for the duration
256 /// of the construct — the discriminant, or the `catch` offset — and a jump out
257 /// has to take it with it. A loop leaves nothing.
258 drop_count: u32,
259 /// The finalizer to run when control leaves this construct.
260 ///
261 /// Set on a `try` even when it has no `finally`: the label is always emitted and
262 /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
263 /// does not have to know whether a finalizer exists.
264 finally_label: Option<Label>,
265 /// Whether this is a labelled non-loop statement, which an unlabelled `break`
266 /// does not reach.
267 is_regular_stmt: bool,
268 /// Whether leaving this construct has to close an iterator.
269 ///
270 /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
271 /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
272 /// is dropped rather than closed.
273 has_iterator: bool,
274 /// Whether that iterator speaks the *async* protocol.
275 ///
276 /// An async close has to `await` the inner `return`, so it is an inline instruction
277 /// sequence rather than one opcode — the reference's `emit_iterator_close`.
278 is_async_iterator: bool,
279}
280
281/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
282///
283/// Both leave `source value` on the stack, so this is purely which spelling the reference
284/// picked, and it picked it by whether it had to build a *reference* for the target:
285///
286/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
287/// consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
288/// destructures);
289/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
290/// * a `var`, and any assignment target, go through `dup; get_field`, because the
291/// reference builds a reference for them — which is what `with` needs.
292fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
293 nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
294}
295
296/// Whether binding this pattern starts by boxing the value it was handed.
297fn nests_a_pattern(pattern: &Pattern) -> bool {
298 match &pattern.kind {
299 PatternKind::Array { .. } | PatternKind::Object { .. } => true,
300 PatternKind::Assign { target, .. } => nests_a_pattern(target),
301 _ => false,
302 }
303}
304
305/// `copy_data_properties` flags for an object-literal spread.
306///
307/// The byte packs three fields: the low bits are the stack offset of the source,
308/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
309/// as well as string keys. A spread passes a literal `null` exclusion list right
310/// below the source, so that field stays zero and only the source offset and the
311/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
312const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
313
314/// The expression a `...` introduces.
315///
316/// The parser marks the spread in two places — the element/property variant and an
317/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
318/// stepped through before the argument can be compiled.
319fn spread_argument(spread: &Expr) -> &Expr {
320 match &spread.kind {
321 ExprKind::Spread(inner) => inner,
322 _ => spread,
323 }
324}
325
326/// The flag byte `define_method` takes.
327///
328/// The low two bits pick value/getter/setter; bit 2 marks the property
329/// enumerable, which every object-literal method is.
330/// What kind of class constructor a function is being compiled as.
331///
332/// A constructor is not an ordinary method: a base one materialises `this` and refuses
333/// to run without `new`, and a derived one starts with `this` in the dead zone until
334/// `super()` produces it.
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336enum CtorKind {
337 /// Not a class constructor.
338 None,
339 /// A constructor of a class without `extends`.
340 Base,
341 /// A constructor of a class with `extends`.
342 Derived,
343}
344
345/// The flag byte `define_method` takes for a class member.
346///
347/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
348/// a class method is *not* — that is the whole difference from an object-literal method,
349/// and the reason `Object.keys(C.prototype)` stays empty.
350fn class_method_flags(kind: MethodKind) -> i32 {
351 match kind {
352 MethodKind::Constructor | MethodKind::Method => 0,
353 MethodKind::Get => 1,
354 MethodKind::Set => 2,
355 }
356}
357
358fn define_method_flags(kind: PropertyKind) -> i32 {
359 let base = match kind {
360 PropertyKind::Value | PropertyKind::Method => 0,
361 PropertyKind::Get => 1,
362 PropertyKind::Set => 2,
363 };
364 base | 4
365}
366
367/// Convert a numeric property key to the text an atom would be made from.
368///
369/// Only the range where Rust and JavaScript agree on the spelling is accepted.
370/// Both print the shortest representation that round-trips, so plain decimal
371/// digits match; they diverge at the extremes, where JavaScript switches to an
372/// exponent (`1e-7`, `1e+21`) and Rust does not. Rather than emit an atom that
373/// differs from the reference, those keys are rejected.
374fn numeric_key_text(value: f64, span: Span) -> Result<String, SyntaxError> {
375 if !value.is_finite() {
376 return Err(SyntaxError::new(
377 "a non-finite numeric property key is not supported by the compiler yet",
378 span,
379 ));
380 }
381 if value == value.trunc() && value.abs() < 1e21 {
382 return Ok(format!("{}", value as i64));
383 }
384 if value.abs() >= 1e-6 && value.abs() < 1e21 {
385 return Ok(format!("{value}"));
386 }
387 Err(SyntaxError::new(
388 "a numeric property key outside [1e-6, 1e21) is not supported by the compiler yet",
389 span,
390 ))
391}
392
393/// Collect the operands of a same-operator logical run, in source order.
394///
395/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
396/// the caller appends `c`. A node with a different operator is one operand.
397fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
398 if let ExprKind::Logical {
399 op: inner_op,
400 left,
401 right,
402 } = &expr.kind
403 && *inner_op == op
404 {
405 collect_same_operator(op, left, out);
406 out.push(right);
407 return;
408 }
409 out.push(expr);
410}
411
412/// The jump a logical assignment or `??` takes when the value is kept.
413///
414/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
415/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
416/// the value when it is *not* null-ish, so it is the `if_false` side.
417fn logical_jump(op: AssignOp) -> Opcode {
418 match op {
419 AssignOp::Or => Opcode::IfTrue,
420 AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
421 _ => Opcode::IfFalse,
422 }
423}
424
425/// Whether a loop enumerates keys or values.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427enum ForLoopKind {
428 /// `for (x in o)` — the keys of an object.
429 In,
430 /// `for (x of o)` — the values of an iterable.
431 Of,
432 /// `for await (x of o)` — the values of an async iterable, or of a sync one.
433 AwaitOf,
434}
435
436/// Which part of a `try` statement a block key refers to.
437#[derive(Debug, Clone, Copy)]
438enum TryPart {
439 /// The guarded block.
440 Block = 0,
441 /// The handler body, excluding the catch parameter.
442 Catch = 1,
443 /// The finalizer block.
444 Finally = 2,
445 /// The catch parameter's own scope.
446 Param = 3,
447}
448
449/// A lexical scope, identified while hoisting and numbered at the end.
450///
451/// Scope identity is needed in two passes that must agree: declarations are
452/// hoisted in source order (so slots come out in source order, as in the
453/// reference), but a binding belongs to the block it was written in, which is only
454/// entered later. Blocks are therefore keyed by the source position of their
455/// opening brace, which is stable across both walks.
456#[derive(Debug, Clone, Copy)]
457struct Block {
458 /// Source position of the block.
459 key: u64,
460 /// The block this one is nested in; `0` for the function scope.
461 parent: u64,
462}
463
464/// One function under construction.
465struct FnState {
466 /// The function's own source range, used to record its text for
467 /// `Function.prototype.toString`.
468 span: Option<(usize, usize)>,
469 name: String,
470 kind: FunctionKind,
471 strict: bool,
472 args: Vec<VarDef>,
473 vars: Vec<VarDef>,
474 closure_vars: Vec<ClosureVar>,
475 cpool: Vec<Constant>,
476 atoms: Vec<Atom>,
477 /// Every lexical scope, in creation order.
478 blocks: Vec<Block>,
479 /// The block currently being parsed or compiled.
480 current_block: u64,
481 /// The block a *nested* function was created in, so a capture made from here can be
482 /// resolved against the enclosing function's lexical scopes rather than against a
483 /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
484 /// function's own `let S` instead of the class body's `const S`.
485 created_in_block: u64,
486 /// The block each local was declared in, parallel to `vars`. `0` means the
487 /// function scope, where `var` bindings live.
488 var_block: Vec<u64>,
489 /// Set when the expression just compiled left no value on the stack.
490 ///
491 /// Only a store can do that: `put_field` consumes the object and the value, so
492 /// an assignment whose result is unused emits nothing extra. The expression
493 /// statement then has nothing to drop.
494 no_value: bool,
495 /// Whether a label was placed since the last instruction was emitted.
496 ///
497 /// The `put`/`get` fold is only valid when the two are adjacent in the final
498 /// stream; a label in between means a jump can land on the read, so the store has
499 /// to keep consuming its value. A flag is enough and avoids having to reason about
500 /// which index a label recorded.
501 label_since_insn: bool,
502 /// Whether the value of the expression being compiled is thrown away.
503 ///
504 /// Only an expression *statement* discards its value, and only the outermost
505 /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
506 /// still has to produce a value. Consumed by [`Compiler::assign`], which is
507 /// the one construct whose bytecode depends on it.
508 discard_value: bool,
509 /// The block that holds the function body.
510 body_block: u64,
511 /// Head of each scope's binding chain, indexed by level. Filled in by
512 /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
513 block_heads: Vec<i32>,
514 /// Enclosing `break`/`continue` targets, innermost last.
515 jump_targets: Vec<JumpTarget>,
516 insns: Vec<Insn>,
517 labels: Vec<Option<usize>>,
518 /// Captured locals, which need a reference cell.
519 var_ref_count: u32,
520 line: u32,
521 column: u32,
522 /// Whether this is a script body. A script's top-level declarations create
523 /// global properties rather than locals, which is why they show up as
524 /// closure variables with `[global_decl]`.
525 is_script: bool,
526 /// Whether this is a module body.
527 ///
528 /// A module body is a script in every respect that matters here — no `arguments`,
529 /// no `this` of its own — but its top-level declarations are *module*-scoped
530 /// instead of global, which is what this flag changes.
531 is_module: bool,
532 /// Whether the function is an arrow, which never gets its own `arguments`.
533 is_arrow: bool,
534 /// The name a *named function expression* binds inside its own body.
535 /// How many parameters count towards `.length`.
536 defined_args: u32,
537 /// Parameters that are not a plain name, with the argument slot each came from.
538 param_prologue: Vec<(usize, Pattern)>,
539 /// What kind of class constructor this function is, if any.
540 ctor_kind: CtorKind,
541 /// Whether the class has instance fields, so the constructor has to run their
542 /// initialiser before it returns.
543 /// What the nested function about to be compiled should be told about its class.
544 class_ctor_pending: Option<CtorKind>,
545 /// Whether this function needs the hidden `this` local, because an arrow inside it
546 /// refers to `this`.
547 ///
548 /// An arrow has no `this` of its own, so the reference materialises the enclosing
549 /// function's receiver into a local and lets the arrow capture it as an ordinary
550 /// closure variable. Declaring the local is not enough on its own: the store that
551 /// fills it has to be prepended to the body, which is what this flag arranges.
552 needs_this_local: bool,
553 /// The same, for `arguments`.
554 needs_arguments_local: bool,
555 /// The same, for `new.target`.
556 needs_new_target_local: bool,
557 /// Whether the body already opens by filling a `this` local, which
558 /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
559 has_this_prologue: bool,
560 /// The same, for `<home_object>`: the object `super` resolves against.
561 ///
562 /// An arrow and a static block have no home object of their own — only the method or
563 /// initialiser they were written in does — so `super.x` inside one is a read of the
564 /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
565 /// by `special_object 4`, the same way `this` is.
566 needs_home_object_local: bool,
567 /// The same, for `this.active_func`: the function `super()` constructs from.
568 ///
569 /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
570 /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
571 /// as a local of the enclosing function; an arrow that escaped the constructor
572 /// (`iter.return = () => super()`) then finds it in its closure even with the
573 /// constructor nowhere on the call stack.
574 needs_active_func_local: bool,
575 /// Hidden locals of the `with` blocks currently open, innermost last.
576 with_names: Vec<String>,
577 /// Set while a with-guard is being emitted, so the guard's own accesses are not
578 /// wrapped in another guard.
579 emitting_with_guard: bool,
580 self_name: Option<String>,
581 /// Where the function body starts, in source order; see [`Function::body_start`].
582 body_start: (u32, u32),
583 /// Whether the body contains a *direct* `eval(...)` call.
584 ///
585 /// A direct eval sees every binding of the function that called it, including ones
586 /// no other code mentions. It also hands those bindings to any closure it creates,
587 /// which can outlive the function. Both need the bindings to live in cells, so this
588 /// flag makes the function treat all of them as captured.
589 has_direct_eval: bool,
590 /// Whether the parameter list contains a default expression, which is what gives
591 /// the function a second variable environment (see [`PARAM_SCOPE`]).
592 has_parameter_expressions: bool,
593 /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
594 simple_parameter_list: bool,
595 /// Whether the instructions being emitted belong to the parameter list.
596 ///
597 /// References made here must not see the body's `var`s: the body has not run yet,
598 /// and the reference's own model keeps the two scopes apart.
599 in_params: bool,
600 /// Whether an arrow created in this function's parameter list needs the parameter
601 /// scope's `arguments` binding.
602 needs_param_arguments: bool,
603 /// Whether this function was *created* inside a parameter list.
604 ///
605 /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
606 /// arrow too. The name reference is the arrow's, but the scope it must not see
607 /// belongs to the function the arrow was born in.
608 created_in_params: bool,
609 /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
610 ///
611 /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
612 /// final while the body is still being compiled: a named function expression declares
613 /// its own name binding *after* the body, and that binding is exactly what
614 /// `eval("myfunc = 1")` has to find.
615 eval_sites: Vec<EvalSite>,
616 /// Direct `eval` call sites seen so far: where, and the block that was current.
617 pending_eval_sites: Vec<(Span, u64, bool)>,
618 /// Whether this body contains `await`.
619 ///
620 /// For a *module* this decides whether its body is an async function: top-level
621 /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
622 /// to survive to the compiled function rather than being a local of the compiler.
623 has_await: bool,
624 /// The module tables, when this body is a module.
625 ///
626 /// Only the top-level state ever has one: `export` and `import` are top-level
627 /// statements, so nothing nested can add to these tables.
628 module: Option<ModuleMeta>,
629 /// Whether the self-name prologue (`special_object 2` then the store) has been
630 /// emitted for this function.
631 ///
632 /// A *nested* function's lookup declares the binding early (see
633 /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
634 /// prologue is still needed — the binding existing is not the same as it being
635 /// initialised.
636 self_name_initialized: bool,
637 /// Whether the code emitted so far leaves the program's result on the stack.
638 /// The reference tracks this for the hidden `<ret>` local of an eval script.
639 leaves_value: bool,
640 /// Statement nesting depth, used to tell top-level statements apart.
641 stmt_depth: u32,
642 /// Function declarations waiting to be instantiated at scope entry, as
643 /// (target slot, constant pool index). The reference emits these from
644 /// `instantiate_hoisted_definitions` rather than at the statement, because a
645 /// declaration is visible before it is reached.
646 hoisted: Vec<(u64, HoistTarget, u32)>,
647 /// Function declarations whose bodies are compiled only once the enclosing scope
648 /// has finished hoisting, as (owning block, declaration).
649 ///
650 /// Compiling a body at the declaration makes the result depend on source order: in
651 /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
652 /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
653 /// names first and the bodies second is what removes that dependence.
654 deferred_funcs: Vec<(u64, Box<ast::Function>)>,
655 /// The source position of the node being compiled. Every instruction emitted
656 /// takes it, which is how the position table that feeds stack traces is built.
657 cur_pos: Option<Position>,
658 /// One position per entry in `insns`, index-aligned.
659 insn_pos: Vec<Option<Position>>,
660}
661
662/// Where a hoisted function declaration is stored.
663#[derive(Debug, Clone)]
664enum HoistTarget {
665 Arg(u32),
666 Loc(u32),
667 /// A global, which the resolver looks up by name.
668 Global(String),
669}
670
671impl FnState {
672 /// Whether this function suspends: a generator or an async function.
673 ///
674 /// A suspending function's `return` is a `return_async` and its body starts with an
675 /// `initial_yield`, so almost every statement that touches control flow asks this.
676 fn is_suspending(&self) -> bool {
677 self.kind.is_generator() || self.kind.is_async()
678 }
679
680 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
681 FnState {
682 span: None,
683 name: name.into(),
684 kind,
685 strict: false,
686 args: Vec::new(),
687 vars: Vec::new(),
688 closure_vars: Vec::new(),
689 cpool: Vec::new(),
690 atoms: Vec::new(),
691 blocks: Vec::new(),
692 current_block: 0,
693 created_in_block: NO_PARENT,
694 var_block: Vec::new(),
695 no_value: false,
696 label_since_insn: false,
697 discard_value: false,
698 body_block: 0,
699 block_heads: Vec::new(),
700 jump_targets: Vec::new(),
701 insns: Vec::new(),
702 labels: Vec::new(),
703 var_ref_count: 0,
704 line: 1,
705 column: 1,
706 is_script: false,
707 is_module: false,
708 is_arrow: false,
709 defined_args: 0,
710 param_prologue: Vec::new(),
711 ctor_kind: CtorKind::None,
712 class_ctor_pending: None,
713 needs_this_local: false,
714 needs_arguments_local: false,
715 needs_new_target_local: false,
716 has_this_prologue: false,
717 needs_home_object_local: false,
718 needs_active_func_local: false,
719 with_names: Vec::new(),
720 emitting_with_guard: false,
721 self_name: None,
722 has_direct_eval: false,
723 body_start: (0, 0),
724 has_parameter_expressions: false,
725 simple_parameter_list: true,
726 in_params: false,
727 needs_param_arguments: false,
728 created_in_params: false,
729 eval_sites: Vec::new(),
730 pending_eval_sites: Vec::new(),
731 has_await: false,
732 module: None,
733 self_name_initialized: false,
734 leaves_value: false,
735 stmt_depth: 0,
736 hoisted: Vec::new(),
737 deferred_funcs: Vec::new(),
738 cur_pos: None,
739 insn_pos: Vec::new(),
740 }
741 }
742
743 /// The scope a declaration lands in: a script's top-level declarations are
744 /// globals, everything else gets a slot.
745 /// Whether a binding declared *now* becomes a property of the global object.
746 ///
747 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
748 /// The `var` case is decided by the keyword rather than by the cursor position:
749 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
750 /// binding as a `var i` in the body, even though the head has its own block.
751 fn declares_globally(&self, def: &VarDef) -> bool {
752 // A module's top-level declarations are *module*-scoped: they live in the module
753 // record, never on the global object. Two modules can both declare `var x`
754 // without seeing each other, which is the whole point.
755 if self.is_module {
756 return false;
757 }
758 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
759 }
760}
761
762/// The compiler's entry point.
763pub struct Compiler {
764 /// The text being compiled, kept so each function can record its own slice for
765 /// `Function.prototype.toString`.
766 source: Option<String>,
767 module: bool,
768 /// Whether the program itself is the body of an `async` function.
769 ///
770 /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
771 /// completion value is wrapped so a returned promise is not adopted.
772 async_body: bool,
773 /// Enclosing functions, outermost first. The last entry is the current one.
774 stack: Vec<FnState>,
775 /// The private names visible at this point, innermost class body last.
776 ///
777 /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
778 /// to the class body: a method, an arrow inside it and a class nested inside that arrow
779 /// all resolve against the same entries, and the parser accepts exactly that set
780 /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
781 /// class's names the moment a method started.
782 private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
783 /// Whether the expression [`Compiler::expr`] is about to compile is the one its
784 /// statement asked to discard.
785 ///
786 /// `FnState::discard_value` says "the statement's value is thrown away", which is only
787 /// ever true of the statement's own expression — an assignment nested inside it, as in
788 /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
789 /// keeping the answer here is what tells the two apart; without it the nested store
790 /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
791 /// function threw `undefined is not a function`.
792 discard_root: bool,
793}
794
795/// How a use site of a private name compiles.
796///
797/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
798/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
799/// of a setter-only accessor pair.
800#[derive(Clone, Copy, PartialEq, Eq)]
801enum PrivateKind {
802 /// `#x = 1`: an own property keyed by the symbol in the binding.
803 Field,
804 /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
805 Method,
806 /// `get #a() {}`: the binding holds the getter, and a read calls it.
807 Getter,
808 /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
809 /// the same `TypeError` as reading an uninitialised `const`.
810 Setter,
811}
812
813/// What the compiler knows about one `#name` where it is used.
814#[derive(Clone)]
815struct PrivateUse {
816 kind: PrivateKind,
817 /// `#a<set>` when the class defines a setter for this name.
818 ///
819 /// A second binding, not a second field of the first: the reference stores the setter
820 /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
821 setter: Option<String>,
822}
823
824/// The class-scope bindings one class body needs, in declaration order.
825#[derive(Default)]
826struct ClassPlan {
827 /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
828 /// at class entry, in member order.
829 bindings: Vec<String>,
830 /// The private names, for the use sites inside the body.
831 uses: std::collections::HashMap<String, PrivateUse>,
832 /// Computed field keys, by element index, so the emission pass does not have to redo the
833 /// per-half counter that names them.
834 computed: std::collections::HashMap<usize, String>,
835 /// Whether the instance initialiser has to add the brand to `this`.
836 instance_brand: bool,
837 /// Whether the constructor itself has to carry the brand.
838 static_brand: bool,
839}
840
841impl ClassPlan {
842 /// Walk a class body once and decide every class-scope binding it needs.
843 ///
844 /// Order is the reference's: a member's binding is created when the member is parsed, so
845 /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
846 /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
847 /// the disassembly stops matching even when every instruction is right.
848 fn build(class: &Class) -> ClassPlan {
849 let mut plan = ClassPlan::default();
850 let mut instance_keys = 0usize;
851 let mut static_keys = 0usize;
852 for (index, element) in class.elements.iter().enumerate() {
853 match element {
854 ClassElement::Method {
855 key: PropName::Private(ident),
856 kind,
857 is_static,
858 ..
859 } => {
860 let name = format!("#{}", ident.name);
861 let first = !plan.uses.contains_key(&name);
862 if first {
863 plan.bindings.push(name.clone());
864 plan.uses.insert(
865 name.clone(),
866 PrivateUse {
867 kind: match kind {
868 MethodKind::Get => PrivateKind::Getter,
869 MethodKind::Set => PrivateKind::Setter,
870 _ => PrivateKind::Method,
871 },
872 setter: None,
873 },
874 );
875 }
876 match kind {
877 MethodKind::Set => {
878 let binding = format!("{name}<set>");
879 plan.bindings.push(binding.clone());
880 if let Some(use_) = plan.uses.get_mut(&name) {
881 use_.setter = Some(binding);
882 }
883 }
884 // A getter is what makes the name readable, so a pair that started
885 // as a setter becomes readable once the getter arrives.
886 MethodKind::Get => {
887 if let Some(use_) = plan.uses.get_mut(&name) {
888 use_.kind = PrivateKind::Getter;
889 }
890 }
891 _ => {}
892 }
893 if *is_static {
894 plan.static_brand = true;
895 } else {
896 plan.instance_brand = true;
897 }
898 }
899 ClassElement::Method {
900 key: PropName::Computed(_),
901 ..
902 } => {}
903 ClassElement::Method { .. } => {}
904 ClassElement::Field {
905 key: PropName::Private(ident),
906 ..
907 } => {
908 let name = format!("#{}", ident.name);
909 if !plan.uses.contains_key(&name) {
910 plan.bindings.push(name.clone());
911 plan.uses.insert(
912 name,
913 PrivateUse {
914 kind: PrivateKind::Field,
915 setter: None,
916 },
917 );
918 }
919 }
920 ClassElement::Field {
921 key: PropName::Computed(_),
922 is_static,
923 ..
924 } => {
925 let index_in_half = if *is_static {
926 static_keys += 1;
927 static_keys - 1
928 } else {
929 instance_keys += 1;
930 instance_keys - 1
931 };
932 let binding = computed_field_binding(index_in_half, *is_static);
933 plan.bindings.push(binding.clone());
934 plan.computed.insert(index, binding);
935 }
936 ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
937 }
938 }
939 plan
940 }
941
942 /// How a private name used inside the body compiles, or `None` if no enclosing class
943 /// declares it.
944 fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
945 compiler
946 .private_scopes
947 .iter()
948 .rev()
949 .find_map(|scope| scope.get(name))
950 }
951}
952
953impl Compiler {
954 /// The exact source text of a function, for `Function.prototype.toString`.
955 ///
956 /// §20.2.3.5 requires the *original* text: a function must stringify back to what
957 /// was written, comments and odd spacing included. Slicing the recorded span out of
958 /// the whole source is the only way to get that — rebuilding it from the AST would
959 /// normalise the text, and answering `[native code]` for a script function (which is
960 /// what this engine used to do) makes the result useless for feature detection and
961 /// for libraries that read their own source.
962 ///
963 /// Top-level bodies have no single expression span, so their `source` stays `None`
964 /// and `toString` falls back to the calling convention the spec allows.
965 fn function_source(
966 &self,
967 span: Option<(usize, usize)>,
968 line: u32,
969 column: u32,
970 ) -> Option<String> {
971 let source = self.source.as_ref()?;
972 let span = span?;
973 let bytes = source.as_bytes();
974 let start = span.0;
975 let end = span.1;
976 if start >= bytes.len() || end > bytes.len() || start >= end {
977 let _ = (line, column);
978 return None;
979 }
980 Some(source.get(start..end)?.to_string())
981 }
982}
983
984/// Compile a script.
985pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
986 Compiler::new(false).compile(program)
987}
988
989/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
990/// the original source.
991///
992/// The separate entry point rather than a parameter on [`compile_script`] because the
993/// tests and the disassembler compile from an AST they built themselves and have no
994/// source to give; they keep the `None` behaviour they already relied on.
995pub fn compile_script_with_source(
996 program: &Program,
997 source: &str,
998) -> Result<CompiledFunction, SyntaxError> {
999 let mut compiler = Compiler::new(false);
1000 compiler.source = Some(source.to_string());
1001 compiler.compile(program)
1002}
1003
1004/// [`compile_script_with_source`] for a module.
1005pub fn compile_module_with_source(
1006 program: &Program,
1007 source: &str,
1008) -> Result<CompiledFunction, SyntaxError> {
1009 let mut compiler = Compiler::new(true);
1010 compiler.source = Some(source.to_string());
1011 compiler.compile(program)
1012}
1013
1014/// Compile a script whose top level is the body of an `async` function.
1015///
1016/// The body is an ordinary script in every other way — it still reports a completion value
1017/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1018/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1019/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1020/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1021/// documents.
1022pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1023 Compiler::for_suspensible_script().compile(program)
1024}
1025
1026/// Compile a module.
1027pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1028 Compiler::new(true).compile(program)
1029}
1030
1031impl Compiler {
1032 /// Create a compiler.
1033 pub fn new(module: bool) -> Compiler {
1034 Compiler {
1035 source: None,
1036 module,
1037 async_body: false,
1038 stack: Vec::new(),
1039 private_scopes: Vec::new(),
1040 discard_root: false,
1041 }
1042 }
1043
1044 /// Create a compiler for a script whose top level is an `async` function body.
1045 fn for_suspensible_script() -> Compiler {
1046 Compiler {
1047 source: None,
1048 module: false,
1049 async_body: true,
1050 stack: Vec::new(),
1051 private_scopes: Vec::new(),
1052 discard_root: false,
1053 }
1054 }
1055
1056 /// Compile a whole program into its top-level function.
1057 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1058 let mut state = FnState::new("<eval>", FunctionKind::Normal);
1059 // A module body is *not* a script: it has no completion value, so no hidden
1060 // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1061 // is having no `arguments` of its own and no receiver — see `is_module`.
1062 state.is_script = !self.module;
1063 state.is_module = self.module;
1064 if self.module {
1065 state.module = Some(ModuleMeta::default());
1066 }
1067 state.strict = program.strict || self.module;
1068 state.line = program.span.start.line;
1069 state.column = program.span.start.column;
1070 // Locals are numbered in declaration order; `<ret>` is always slot 0.
1071 //
1072 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1073 // slot that only appears in one of the two arrays shifts every later
1074 // binding's block and silently loses the temporal-dead-zone marking for
1075 // the script's own blocks. A function frame has no `<ret>`, which is why
1076 // the misalignment only showed up at the top level.
1077 if !self.module {
1078 state.vars.push(VarDef::var("<ret>"));
1079 state.var_block.push(FUNCTION_SCOPE);
1080 }
1081 self.stack.push(state);
1082 // The body is its own scope, keyed by the position of the program.
1083 // The script body needs a key no statement can produce. Statement keys are
1084 // source offsets, and the program's own start offset is `0` — which is also
1085 // the offset of the first statement, so a top-level `{ let x }` or
1086 // `for (let i …)` used to share the body's block and lose its scope.
1087 let body_key = SCRIPT_BODY;
1088 self.push_block(body_key, NO_PARENT);
1089 self.state().body_block = body_key;
1090 // A module body opens with a re-entry guard. The host evaluates a module exactly
1091 // once, so the guard never fires in practice — but the reference emits it, and a
1092 // module function called a second time (through `eval` of its own source, say)
1093 // must not run its body again.
1094 let module_guard = self.module.then(|| self.new_label());
1095 if let Some(body) = module_guard {
1096 // The guard wraps the *hoisting* too: a second evaluation of the same module
1097 // body must not even re-create its function declarations.
1098 self.emit(Opcode::PushThis, &[]);
1099 self.emit_jump(Opcode::IfFalse, body, &[]);
1100 }
1101 self.hoist(&program.body, body_key)?;
1102 // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1103 // come before the guard's `return_undef`: the reference's jump target sits past
1104 // both, and a second evaluation therefore re-creates nothing.
1105 self.emit_scope_enter(body_key);
1106 if let Some(body) = module_guard {
1107 self.emit(Opcode::ReturnUndef, &[]);
1108 self.place_label(body);
1109 }
1110 // Through `stmts` rather than the loop, so a `using` region at the top level of an
1111 // eval'd body or a module gets its disposal epilogue like any other block.
1112 self.stmts(&program.body)?;
1113 if self.module {
1114 // A module has no completion value; its body simply ends.
1115 self.emit(Opcode::Undefined, &[]);
1116 self.emit(Opcode::ReturnAsync, &[]);
1117 // Top-level `await` makes the body an async function, so the host runs it as
1118 // a coroutine and waits. Without this the `await` opcode would suspend in a
1119 // body that nothing knows how to resume — which is what "a generator body ran
1120 // as an ordinary call" was reporting.
1121 if self.cur().has_await {
1122 self.state().kind = FunctionKind::Async;
1123 }
1124 } else if self.async_body {
1125 // An async body reports its completion value the same way, but through an
1126 // object: the function answers a promise, and resolving that promise *with*
1127 // the completion value would adopt a promise completion instead of reporting
1128 // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1129 // resolve to `{value: <promise>}` rather than to `7`.
1130 //
1131 // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1132 // value in an object so that promises can be safely returned").
1133 self.emit(Opcode::Object, &[]);
1134 self.emit(Opcode::Dup, &[]);
1135 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1136 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1137 self.emit(Opcode::Return, &[]);
1138 self.state().kind = FunctionKind::Async;
1139 } else {
1140 // The program's value is whatever the last expression statement stored in
1141 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1142 // case into a single `set_loc0`.
1143 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1144 self.emit(Opcode::Return, &[]);
1145 }
1146 Ok(self.finish_current())
1147 }
1148
1149 // -- emitting ----------------------------------------------------------
1150
1151 fn state(&mut self) -> &mut FnState {
1152 self.stack.last_mut().expect("a function is being compiled")
1153 }
1154
1155 fn cur(&self) -> &FnState {
1156 self.stack.last().expect("a function is being compiled")
1157 }
1158
1159 fn emit(&mut self, op: Opcode, operands: &[Op]) {
1160 self.state().label_since_insn = false;
1161 let pos = self.cur().cur_pos;
1162 self.state().insns.push(Insn::Fixed {
1163 op,
1164 operands: operands.to_vec(),
1165 });
1166 self.state().insn_pos.push(pos);
1167 }
1168
1169 /// Reset the script's hidden return value to `undefined`.
1170 ///
1171 /// Called at the start of every statement that does not itself produce the
1172 /// program's value, which is how the reference keeps `if`/loop results from
1173 /// leaking into an eval result.
1174 fn reset_value(&mut self) {
1175 if !self.cur().is_script {
1176 return;
1177 }
1178 self.emit(Opcode::Undefined, &[]);
1179 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1180 self.state().leaves_value = false;
1181 }
1182
1183 /// Whether `name` is a local or argument slot rather than a global.
1184 fn is_slot(&self, name: &str) -> bool {
1185 self.cur().vars.iter().any(|v| v.name == name)
1186 || self.cur().args.iter().any(|a| a.name == name)
1187 }
1188
1189 /// `with (object) body`
1190 ///
1191 /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1192 /// what makes the object reachable from a closure created inside the block, and it
1193 /// is also what lets an `eval` find it: the runtime collects the active `With`
1194 /// locals of every frame and resolves names against them before the realm.
1195 ///
1196 /// Inside the block every name reference is spelled as "look in the with objects
1197 /// first", innermost outwards, and falls through to the ordinary access. The test is
1198 /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1199 /// Record asks.
1200 fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1201 let name = self.next_with_name();
1202 // The object expression is evaluated *outside* the scope it introduces, so no
1203 // wrapper may be emitted for the names it mentions.
1204 let saved = std::mem::take(&mut self.state().with_names);
1205 self.expr(object)?;
1206 self.state().with_names = saved;
1207 self.emit(Opcode::ToObject, &[]);
1208 self.declare_hidden_local(&name, VarKind::With);
1209 // Pushed before the store so the store itself is not guarded by an *outer*
1210 // `with` — the object being stored is the new one, not something to look up.
1211 self.state().with_names.push(name.clone());
1212 self.emit_var(VarAction::Put, &name);
1213 let result = self.stmt(body);
1214 self.state().with_names.pop();
1215 result
1216 }
1217
1218 /// A hidden-local name for one `with` block, distinct from every enclosing one.
1219 fn next_with_name(&self) -> String {
1220 let depth = self.cur().with_names.len();
1221 if depth == 0 {
1222 "<with>".to_string()
1223 } else {
1224 format!("<with{depth}>")
1225 }
1226 }
1227
1228 /// Declare a hidden local that must stay a *local* even in a script.
1229 ///
1230 /// A script's `var` is a property of the global object, but the `with` object is not
1231 /// part of the source program's name space at all — it only exists for the compiler
1232 /// and the runtime — so it goes straight into the frame's slot list.
1233 fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1234 let state = self.state();
1235 if state.vars.iter().any(|v| v.name == name) {
1236 return;
1237 }
1238 state.var_block.push(FUNCTION_SCOPE);
1239 state.vars.push(VarDef {
1240 kind,
1241 ..VarDef::var(name)
1242 });
1243 }
1244
1245 /// Emit a name access, guarded by every active `with` object.
1246 ///
1247 /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1248 /// the read itself; the outer guards and the plain access are what the `if_false`
1249 /// jumps to, so the innermost object wins.
1250 fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1251 let names = self.cur().with_names.clone();
1252 let done = self.new_label();
1253 let mut starts = Vec::new();
1254 // Innermost object first: the last `with` opened is the one that shadows the
1255 // others, so its guard has to be the first chance to satisfy the name.
1256 for with_name in names.iter().rev() {
1257 let next = self.new_label();
1258 // `in` takes the key then the object.
1259 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1260 self.emit_var(VarAction::Get, with_name);
1261 self.emit(Opcode::In, &[]);
1262 self.emit_jump(Opcode::IfFalse, next, &[]);
1263 starts.push(next);
1264 match action {
1265 // A store keeps the value under the receiver, which is where
1266 // `put_field` expects it.
1267 VarAction::Put | VarAction::PutInit => {
1268 self.emit_var(VarAction::Get, with_name);
1269 self.emit(Opcode::Swap, &[]);
1270 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
1271 }
1272 _ => {
1273 self.emit_var(VarAction::Get, with_name);
1274 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1275 self.emit(Opcode::GetArrayEl, &[]);
1276 }
1277 }
1278 self.emit_jump(Opcode::Goto, done, &[]);
1279 self.place_label(next);
1280 }
1281 self.emit_var(action, name);
1282 self.place_label(done);
1283 }
1284
1285 fn emit_var(&mut self, action: VarAction, name: &str) {
1286 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1287 // stores and keeps the value in one instruction. The reference does this
1288 // in a post-pass; folding it at emit time keeps instruction indices
1289 // stable, which matters because labels are recorded as indices.
1290 //
1291 // Only slots have a `set_` form: a global is stored with `put_var` and
1292 // read with `get_var`, and the reference does not fold those.
1293 //
1294 // A label between the two cancels the fold. `set_x v` leaves the value on
1295 // the stack, which is only equivalent when the read immediately follows the
1296 // store; when a jump target sits in between, the store must *consume* the
1297 // value and the read must fetch it afresh. A loop head is exactly that
1298 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1299 // condition re-reads it — and folding across the label would make the
1300 // condition compare whatever the previous iteration left on the stack.
1301 if action == VarAction::Get {
1302 let is_slot = self.is_slot(name);
1303 let at_label = std::mem::take(&mut self.state().label_since_insn);
1304 //
1305 // `arguments` is excluded because the reference treats it as a special
1306 // binding: it is initialised once and read many times, and folding its
1307 // initialisation into a `set_` would leave the object on the stack where
1308 // the reference leaves nothing.
1309 if is_slot
1310 && name != "arguments"
1311 && !at_label
1312 && let Some(Insn::Var {
1313 action: previous,
1314 name: previous_name,
1315 ..
1316 }) = self.state().insns.last_mut()
1317 && *previous == VarAction::Put
1318 && previous_name == name
1319 {
1320 *previous = VarAction::Set;
1321 return;
1322 }
1323 }
1324 // Inside a `with`, every name lookup consults the with objects first. The
1325 // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
1326 let guarded = !self.cur().with_names.is_empty()
1327 && !self.cur().with_names.iter().any(|hidden| hidden == name)
1328 && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1329 && !self.state().emitting_with_guard;
1330 if guarded {
1331 self.state().emitting_with_guard = true;
1332 self.emit_with_guarded(action, name);
1333 self.state().emitting_with_guard = false;
1334 return;
1335 }
1336 let block = self.cur().current_block;
1337 self.state().label_since_insn = false;
1338 let pos = self.cur().cur_pos;
1339 let in_params = self.cur().in_params;
1340 self.state().insns.push(Insn::Var {
1341 action,
1342 name: name.to_string(),
1343 block,
1344 in_params,
1345 });
1346 self.state().insn_pos.push(pos);
1347 }
1348
1349 fn new_label(&mut self) -> Label {
1350 let state = self.state();
1351 state.labels.push(None);
1352 Label(state.labels.len() as u32 - 1)
1353 }
1354
1355 fn place_label(&mut self, label: Label) {
1356 let index = self.cur().insns.len();
1357 self.state().label_since_insn = true;
1358 self.state().labels[label.0 as usize] = Some(index);
1359 }
1360
1361 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1362 let mut operands = vec![Op::Label(label)];
1363 operands.extend_from_slice(extra);
1364 self.emit(op, &operands);
1365 }
1366
1367 // -- scopes ------------------------------------------------------------
1368
1369 /// Start a new lexical scope inside `parent`.
1370 fn push_block(&mut self, key: u64, parent: u64) {
1371 let state = self.state();
1372 if !state.blocks.iter().any(|b| b.key == key) {
1373 state.blocks.push(Block { key, parent });
1374 }
1375 state.current_block = key;
1376 }
1377
1378 /// Emit the code that runs when a lexical scope is entered.
1379 ///
1380 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1381 /// so entering its block marks it uninitialised. Hoisted function
1382 /// declarations are created here instead, which is why a call before the
1383 /// declaration still works.
1384 ///
1385 /// The order is not obvious: bindings are emitted in *reverse* declaration
1386 /// order, because the reference walks its scope chain, which is built by
1387 /// prepending.
1388 fn emit_scope_enter(&mut self, block: u64) {
1389 // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1390 // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1391 // so entering an outer scope threw away every nested block's function
1392 // declarations: `function h(){ { function k(){} } return k; }` answered
1393 // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1394 // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1395 // in a block is also a `var` of the enclosing function), and it is what makes the
1396 // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1397 let mut hoisted = std::mem::take(&mut self.state().hoisted);
1398 let mut rest = Vec::with_capacity(hoisted.len());
1399 let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1400 for (owner, target, pool_index) in hoisted.drain(..) {
1401 if owner == block {
1402 mine.push((target, pool_index));
1403 } else {
1404 rest.push((owner, target, pool_index));
1405 }
1406 }
1407 self.state().hoisted = rest;
1408 mine.sort_by_key(|(target, _)| match target {
1409 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1410 HoistTarget::Global(_) => u32::MAX,
1411 });
1412 for (target, pool_index) in mine {
1413 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1414 match target {
1415 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1416 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1417 HoistTarget::Global(name) => {
1418 // A global binding lives in a reference cell, so the store
1419 // goes through `put_var_ref` while reads use `get_var`.
1420 let block = self.cur().current_block;
1421 let pos = self.cur().cur_pos;
1422 let in_params = self.cur().in_params;
1423 self.state().insns.push(Insn::Var {
1424 action: VarAction::PutRef,
1425 name,
1426 block,
1427 in_params,
1428 });
1429 self.state().insn_pos.push(pos);
1430 }
1431 }
1432 }
1433 for index in self.block_vars_reversed(block) {
1434 self.emit(
1435 Opcode::SetLocUninitialized,
1436 &[Op::Slot(Slot::Loc(index as u32))],
1437 );
1438 }
1439 }
1440
1441 /// Emit the code that runs when a lexical scope is exited.
1442 ///
1443 /// A captured binding has to be closed: detaching its reference cell freezes
1444 /// the value the binding had when the block ended, which is what a closure
1445 /// created inside the block must keep seeing.
1446 fn emit_scope_leave(&mut self, block: u64) {
1447 for index in self.block_vars_reversed(block) {
1448 if self.cur().vars[index].is_captured {
1449 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1450 }
1451 }
1452 }
1453
1454 /// Locals declared in `block`, in reverse declaration order.
1455 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1456 let state = self.cur();
1457 let mut out: Vec<usize> = (0..state.vars.len())
1458 .filter(|index| {
1459 state.var_block.get(*index).copied() == Some(block)
1460 && state.vars[*index].is_lexical
1461 // A derived constructor's `this` is lexical but is not initialised by
1462 // entering the scope: `check_ctor` proves it, so its dead-zone marker
1463 // was emitted with the constructor's own prologue.
1464 && state.vars[*index].name != "this"
1465 })
1466 .collect();
1467 out.reverse();
1468 out
1469 }
1470
1471 /// Declare a local, even at the top level of a script.
1472 ///
1473 /// A `catch` parameter is always a local: the reference puts it in the
1474 /// function's own variable list (`1: catch e`), never in the global object,
1475 /// because it only exists while the handler runs.
1476 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1477 let state = self.state();
1478 let index = state.vars.len() as u32;
1479 // A `catch` parameter belongs to a scope even though it is not lexical: the
1480 // runtime instantiates it per handler entry, but it never sits in the
1481 // temporal dead zone.
1482 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1483 state.current_block
1484 } else {
1485 0
1486 };
1487 state.var_block.push(block);
1488 state.vars.push(def);
1489 index
1490 }
1491
1492 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1493 if self.cur().is_module
1494 && self.cur().current_block == self.cur().body_block
1495 && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1496 {
1497 // Only the body's own block: a `let` inside a module-level `{}` is still an
1498 // ordinary local of that block, not a module variable.
1499 //
1500 // A `using` binding is excluded on purpose, and the reference excludes it in
1501 // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1502 // "'using' variables are currently not exported in modules"): a module-level
1503 // `using` is an ordinary *local* of the module body function, not a module
1504 // cell. Two things follow, and both are what the reference does — `export {a}`
1505 // of a `using` binding is "exported variable 'a' does not exist", and
1506 // disposal works, because the disposal epilogue addresses locals by slot.
1507 //
1508 // The hidden dispose-method variable is excluded for a stronger reason: it is
1509 // *always* a local (`add_scope_var` in the reference), and it must sit
1510 // immediately after its value so `using_dispose` can find it at `slot + 1`.
1511 return self.declare_module(name, &def);
1512 }
1513 if self.cur().declares_globally(&def) {
1514 self.declare_global(name, &def);
1515 return 0;
1516 }
1517 let state = self.state();
1518 let index = state.vars.len() as u32;
1519 let block = if def.is_lexical {
1520 state.current_block
1521 } else {
1522 0
1523 };
1524 state.var_block.push(block);
1525 state.vars.push(def);
1526 index
1527 }
1528
1529 /// Declare a `using` binding and its cached dispose method, returning both slots.
1530 ///
1531 /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1532 /// `(value, value + 1)` — the reference does the same and documents the constraint.
1533 fn declare_using(&mut self, name: &str) -> (u32, u32) {
1534 let mut def = VarDef::lexical(name);
1535 def.kind = VarKind::Using;
1536 let value = self.declare(name, def);
1537 let mut method = VarDef::lexical(using_method_name(name));
1538 method.kind = VarKind::UsingMethod;
1539 let method_slot = self.declare(&using_method_name(name), method);
1540 (value, method_slot)
1541 }
1542
1543 /// The slot a `using` binding's dispose method lives in.
1544 fn using_method_slot(&self, name: &str) -> Option<u32> {
1545 let hidden = using_method_name(name);
1546 self.cur()
1547 .vars
1548 .iter()
1549 .position(|var| var.name == hidden)
1550 .map(|index| index as u32)
1551 }
1552
1553 // -- statements --------------------------------------------------------
1554
1555 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1556 self.stmt_labelled(stmt, &[])
1557 }
1558
1559 /// Compile a statement that a chain of labels names.
1560 ///
1561 /// Only a loop consumes `labels`; every other statement ignores them (the
1562 /// parser has already rejected a label on a statement that cannot use it).
1563 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1564 // Only a *top-level* expression statement supplies the program's value.
1565 let saved = self.cur().leaves_value;
1566 self.state().leaves_value =
1567 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1568 self.state().stmt_depth += 1;
1569 let result = self.stmt_inner(stmt, labels);
1570 self.state().stmt_depth -= 1;
1571 // A nested statement never contributes the program's value, so the flag
1572 // the wrapper set above is what survives.
1573 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1574 self.state().leaves_value = produced;
1575 let _ = saved;
1576 result
1577 }
1578
1579 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1580 match &stmt.kind {
1581 StmtKind::Empty | StmtKind::Debugger => {}
1582 StmtKind::Expr(expr) => {
1583 // The statement's first token is a position the reference records: an
1584 // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1585 // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1586 // is why an error from a construct with no position of its own (`[...it]`
1587 // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1588 let saved = self.cur().cur_pos;
1589 self.state().cur_pos = Some(expr.span.start);
1590 // An expression statement's value is thrown away — except in a
1591 // script, where it becomes the program's result. `assign` reads this
1592 // and clears it, so a nested assignment still produces a value.
1593 self.state().discard_value = !self.cur().is_script;
1594 let result = self.expr(expr);
1595 self.state().discard_value = false;
1596 result?;
1597 if std::mem::take(&mut self.state().no_value) {
1598 // A store whose value was discarded left nothing to drop.
1599 } else if self.cur().is_script {
1600 // The program's value lands in the hidden `<ret>` local.
1601 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1602 } else {
1603 self.emit(Opcode::Drop, &[]);
1604 }
1605 // Restored last: the trailing `drop` is part of the statement, and in the
1606 // reference it simply inherits whatever the expression last recorded.
1607 self.state().cur_pos = saved;
1608 }
1609 StmtKind::Block(body) => {
1610 // The block's declarations were hoisted with its enclosing
1611 // statement list, so there is nothing left to declare here.
1612 let key = stmt.span.start.offset as u64;
1613 let parent = self.cur().current_block;
1614 self.push_block(key, parent);
1615 self.emit_scope_enter(key);
1616 // A block is where a `using` region lives, so its statements have to go
1617 // through `stmts`: that is what emits the disposal epilogue.
1618 self.stmts(body)?;
1619 self.emit_scope_leave(key);
1620 self.state().current_block = parent;
1621 }
1622 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1623 // A function declaration was already instantiated when its scope was
1624 // entered, so the statement itself emits nothing.
1625 StmtKind::FuncDecl(_) => {}
1626 StmtKind::If { test, cons, alt } => {
1627 self.reset_value();
1628 let else_label = self.new_label();
1629 let end_label = self.new_label();
1630 self.expr(test)?;
1631 self.emit_jump(Opcode::IfFalse, else_label, &[]);
1632 self.stmt(cons)?;
1633 if alt.is_some() {
1634 self.emit_jump(Opcode::Goto, end_label, &[]);
1635 }
1636 self.place_label(else_label);
1637 if let Some(alt) = alt {
1638 self.stmt(alt)?;
1639 self.place_label(end_label);
1640 }
1641 }
1642 StmtKind::While { test, body } => {
1643 self.reset_value();
1644 let top = self.new_label();
1645 let end = self.new_label();
1646 self.place_label(top);
1647 self.expr(test)?;
1648 // The condition's false branch and `break` share one target,
1649 // which is why a `while` loop needs only one end label.
1650 self.emit_jump(Opcode::IfFalse, end, &[]);
1651 self.loop_body(body, labels, top, end)?;
1652 self.emit_jump(Opcode::Goto, top, &[]);
1653 self.place_label(end);
1654 }
1655 StmtKind::DoWhile { body, test } => {
1656 self.reset_value();
1657 let top = self.new_label();
1658 let cont = self.new_label();
1659 let end = self.new_label();
1660 self.place_label(top);
1661 // `continue` in a `do…while` runs the test, so it lands on `cont`
1662 // rather than on the loop head.
1663 self.loop_body(body, labels, cont, end)?;
1664 self.place_label(cont);
1665 self.expr(test)?;
1666 self.emit_jump(Opcode::IfTrue, top, &[]);
1667 self.place_label(end);
1668 }
1669 StmtKind::For {
1670 init,
1671 test,
1672 update,
1673 body,
1674 } => {
1675 self.reset_value();
1676 let for_key = stmt.span.start.offset as u64;
1677 let for_parent = self.cur().current_block;
1678 self.push_block(for_key, for_parent);
1679 self.emit_scope_enter(for_key);
1680 if let Some(init) = init {
1681 match init {
1682 ForInit::VarDecl(decl) => {
1683 self.var_decl(decl)?;
1684 }
1685 ForInit::Expr(expr) => {
1686 // The head's value is discarded. Saying so lets an
1687 // assignment store with `put` instead of `dup`+`put`, which
1688 // is what the reference emits — and the difference matters:
1689 // a `dup`/`drop` pair around the store gives the peephole a
1690 // chance to fold the store into the *condition's* read.
1691 self.state().discard_value = true;
1692 let result = self.expr(expr);
1693 self.state().discard_value = false;
1694 result?;
1695 if !std::mem::take(&mut self.state().no_value) {
1696 self.emit(Opcode::Drop, &[]);
1697 }
1698 }
1699 }
1700 }
1701 // A `let`/`const` in the head gets a *fresh binding per iteration*,
1702 // so a closure made in the body captures that iteration's value
1703 // instead of sharing one. The reference expresses this with
1704 // `close_loc`, which swaps in a new reference cell holding the
1705 // current value; the three points below are the ones it uses — after
1706 // the initialiser, before the update, and after the loop.
1707 let loop_bindings = match init {
1708 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1709 let mut names: Vec<String> = Vec::new();
1710 for declarator in &decl.declarators {
1711 let mut idents = Vec::new();
1712 declarator.target.bound_names(&mut idents);
1713 names.extend(idents.into_iter().map(|ident| ident.name));
1714 }
1715 names
1716 }
1717 _ => Vec::new(),
1718 };
1719 // The reference also closes right after the initialiser, so the first
1720 // iteration's closures get their own cell rather than sharing the one
1721 // the initialiser wrote into.
1722 for name in &loop_bindings {
1723 let pos = self.cur().cur_pos;
1724 self.state().insns.push(Insn::CloseCaptured {
1725 name: name.clone(),
1726 block: for_key,
1727 });
1728 self.state().insn_pos.push(pos);
1729 }
1730 let top = self.new_label();
1731 let cont = self.new_label();
1732 let end = self.new_label();
1733 self.place_label(top);
1734 if let Some(test) = test {
1735 self.expr(test)?;
1736 self.emit_jump(Opcode::IfFalse, end, &[]);
1737 }
1738 // `continue` runs the update expression first, so it lands on
1739 // `cont`, which sits just before the update.
1740 self.loop_body(body, labels, cont, end)?;
1741 self.place_label(cont);
1742 // Each iteration ends with a fresh cell, so the closures the body just
1743 // created keep the cell they captured and the update writes to a new
1744 // one. Without this every closure in the loop shares one binding.
1745 let binding_block = for_key;
1746 for name in &loop_bindings {
1747 let pos = self.cur().cur_pos;
1748 self.state().insns.push(Insn::CloseCaptured {
1749 name: name.clone(),
1750 block: binding_block,
1751 });
1752 self.state().insn_pos.push(pos);
1753 }
1754 if let Some(update) = update {
1755 self.state().discard_value = true;
1756 let result = self.expr(update);
1757 self.state().discard_value = false;
1758 result?;
1759 if !std::mem::take(&mut self.state().no_value) {
1760 self.emit(Opcode::Drop, &[]);
1761 }
1762 }
1763 self.emit_jump(Opcode::Goto, top, &[]);
1764 self.place_label(end);
1765 self.emit_scope_leave(for_key);
1766 self.state().current_block = for_parent;
1767 }
1768 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1769 StmtKind::Throw(expr) => {
1770 self.expr(expr)?;
1771 self.emit(Opcode::Throw, &[]);
1772 }
1773 StmtKind::Break(_) | StmtKind::Continue(_) => {
1774 // Labels and loops are wired up in a later milestone; a bare
1775 // break/continue jumps to the innermost enclosing target, which
1776 // the loop helpers register.
1777 self.control_transfer(stmt)?;
1778 }
1779 StmtKind::Labeled { label, body } => {
1780 self.labeled(label, body, stmt)?;
1781 }
1782 StmtKind::Switch {
1783 discriminant,
1784 cases,
1785 } => {
1786 self.switch(discriminant, cases, stmt)?;
1787 }
1788 StmtKind::Try {
1789 block,
1790 handler,
1791 finalizer,
1792 } => {
1793 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1794 }
1795 StmtKind::ForIn { left, right, body } => {
1796 self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1797 }
1798 StmtKind::ForOf {
1799 left,
1800 right,
1801 body,
1802 is_await,
1803 } => {
1804 let kind = if *is_await {
1805 ForLoopKind::AwaitOf
1806 } else {
1807 ForLoopKind::Of
1808 };
1809 self.for_in_of(stmt, left, right, body, kind, labels)?;
1810 }
1811 StmtKind::With { object, body } => self.with_stmt(object, body)?,
1812 StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1813 // `import` emits nothing: hoisting already bound its names, and the host
1814 // fills their cells before the body runs.
1815 StmtKind::Import(_) => {}
1816 StmtKind::Export(decl) => self.export_stmt(decl)?,
1817 }
1818 Ok(())
1819 }
1820
1821 /// Compile `return`, running every enclosing finalizer on the way out.
1822 ///
1823 /// `nip_catch` is what makes this possible: it discards everything on the stack
1824 /// down to and including the `catch` offset while keeping the return value on
1825 /// top, so the frame the finalizer sees has the same shape as on the normal
1826 /// path.
1827 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1828 let mut has_value = value.is_some();
1829 if let Some(expr) = value {
1830 // `return f(x)` is a tail call *only* when nothing has to happen to the
1831 // value afterwards. A `finally` or an open iterator in scope forces the
1832 // normal path, because the cleanup has to run after the call returns —
1833 // which is exactly what a tail call refuses to do.
1834 let plain = self
1835 .cur()
1836 .jump_targets
1837 .iter()
1838 .all(|target| target.finally_label.is_none() && !target.has_iterator);
1839 if plain && self.expr_if_tail_call(expr)? {
1840 return Ok(());
1841 }
1842 self.expr(expr)?;
1843 }
1844 // `return v` in an *async generator* awaits `v` before anything else happens —
1845 // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
1846 // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
1847 // exactly that reason ("the await must be done before handling the finally in case
1848 // it raises an exception").
1849 if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
1850 self.emit(Opcode::Await, &[]);
1851 self.state().has_await = true;
1852 }
1853 has_value = self.emit_unwind_for_return(has_value);
1854 // A generator or async function does not return to its caller: it either
1855 // finishes, and the value becomes `{value, done: true}`, or it suspends.
1856 // `return_async` is the "finished" half, and it reads the value off the stack
1857 // rather than carrying it, which is what the resume machinery expects.
1858 if self.cur().is_suspending() {
1859 if !has_value {
1860 self.emit(Opcode::Undefined, &[]);
1861 }
1862 self.emit(Opcode::ReturnAsync, &[]);
1863 return Ok(());
1864 }
1865 if has_value {
1866 self.emit(Opcode::Return, &[]);
1867 } else {
1868 self.emit(Opcode::ReturnUndef, &[]);
1869 }
1870 Ok(())
1871 }
1872
1873 /// Close an iterator: the reference's `emit_iterator_close`.
1874 ///
1875 /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
1876 /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
1877 /// sequence, and three details in it are load-bearing:
1878 ///
1879 /// * the iterator object is compared against `undefined` first, because a loop that
1880 /// ran to completion clears that slot rather than closing an exhausted iterator;
1881 /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
1882 /// * `preserve_completion` keeps whatever was underneath (the return value of the
1883 /// function being left), which is why one branch ends on `nip` and the other on `drop`.
1884 fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
1885 if !is_async {
1886 if preserve_completion {
1887 self.emit(Opcode::Rot3r, &[]);
1888 self.emit(Opcode::Undefined, &[]);
1889 }
1890 self.emit(Opcode::IteratorClose, &[]);
1891 return;
1892 }
1893 if preserve_completion {
1894 // `iter next completion -> completion iter`
1895 self.emit(Opcode::Nip, &[]);
1896 self.emit(Opcode::Swap, &[]);
1897 } else {
1898 // `iter next catch_offset -> iter`
1899 self.emit(Opcode::Drop, &[]);
1900 self.emit(Opcode::Drop, &[]);
1901 }
1902 let done = self.new_label();
1903 let no_return = self.new_label();
1904 self.emit(Opcode::Dup, &[]);
1905 self.emit(Opcode::IsUndefined, &[]);
1906 self.emit_jump(Opcode::IfTrue, done, &[]);
1907 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
1908 self.emit(Opcode::Dup, &[]);
1909 self.emit(Opcode::IsUndefinedOrNull, &[]);
1910 self.emit_jump(Opcode::IfTrue, no_return, &[]);
1911 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
1912 self.emit(Opcode::Await, &[]);
1913 self.state().has_await = true;
1914 self.emit_jump(Opcode::Goto, done, &[]);
1915 self.place_label(no_return);
1916 self.emit(Opcode::Drop, &[]);
1917 self.place_label(done);
1918 self.emit(Opcode::Drop, &[]);
1919 }
1920
1921 /// Emit the finalizer/iterator cleanup for leaving the current position with a
1922 /// return, and report whether a value is now on the stack for it to carry.
1923 ///
1924 /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
1925 /// enclosing `finally` at once, and the two used to be separate — the `yield` path
1926 /// simply emitted `return_async`, so `it.return()` ended the generator without ever
1927 /// running `finally` blocks the body was sitting inside.
1928 fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
1929 let targets = self.cur().jump_targets.clone();
1930 for target in targets.iter().rev() {
1931 if target.finally_label.is_none() && !target.has_iterator {
1932 continue;
1933 }
1934 if !has_value {
1935 // The cleanup expects a value to pass through; with nothing to
1936 // return, `undefined` stands in.
1937 self.emit(Opcode::Undefined, &[]);
1938 has_value = true;
1939 }
1940 self.emit(Opcode::NipCatch, &[]);
1941 if target.has_iterator {
1942 // Rewind to the loop's own slots and hand the close a dummy catch offset:
1943 // the loop is being abandoned, so there is nothing left to catch.
1944 self.emit_iterator_close(target.is_async_iterator, true);
1945 } else if let Some(finally) = target.finally_label {
1946 self.emit_jump(Opcode::Gosub, finally, &[]);
1947 }
1948 }
1949 has_value
1950 }
1951
1952 /// Compile a statement list, stopping at the first statement that cannot
1953 /// fall through.
1954 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1955 for (index, stmt) in body.iter().enumerate() {
1956 // A `using` declaration is not just a binding: everything after it, to the end
1957 // of the list, runs inside its disposal region. Compiling the rest of the list
1958 // recursively is what gives nested regions their innermost-first order.
1959 if Self::using_declaration(stmt).is_some() {
1960 return self.using_region(stmt, &body[index + 1..]);
1961 }
1962 self.stmt(stmt)?;
1963 if Self::terminates(stmt) {
1964 break;
1965 }
1966 }
1967 Ok(())
1968 }
1969
1970 /// The declaration a `using` statement carries, if it is one.
1971 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
1972 match &stmt.kind {
1973 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
1974 _ => None,
1975 }
1976 }
1977
1978 /// Compile `decl` and then the rest of its block, disposing when the block ends.
1979 ///
1980 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
1981 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
1982 /// exception — and this engine already funnels all of those through `catch` plus
1983 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
1984 /// `return` and `break` dispose without knowing anything about `using`.
1985 ///
1986 /// ```text
1987 /// <declaration> value -> x, method -> x+1
1988 /// catch CATCH <- an exception in the rest lands here
1989 /// REST:
1990 /// <the rest of the block>
1991 /// drop <- the catch offset, on the fall-through path
1992 /// undefined; gosub DISPOSE; drop
1993 /// goto END
1994 /// CATCH:
1995 /// using_dispose x <- merges the failure into the pending exception
1996 /// throw
1997 /// DISPOSE:
1998 /// using_dispose_init
1999 /// using_dispose x
2000 /// using_dispose_end <- rethrows if a dispose failed
2001 /// ret
2002 /// END:
2003 /// ```
2004 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2005 let Some(decl) = Self::using_declaration(stmt) else {
2006 unreachable!("using_region is only called for a using declaration");
2007 };
2008 // `using` binds exactly one name and has no pattern form, which the parser
2009 // enforces; the region still has to know *which* slot to dispose.
2010 let name = decl
2011 .declarators
2012 .first()
2013 .and_then(|declarator| match &declarator.target.kind {
2014 PatternKind::Ident(ident) => Some(ident.name.clone()),
2015 _ => None,
2016 });
2017 self.stmt(stmt)?;
2018 let Some(name) = name else {
2019 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2020 // must not make the compiler panic.
2021 return self.stmts(rest);
2022 };
2023 let Some(value_slot) = self.using_value_slot(&name) else {
2024 // Declared globally, which the parser rules out for a script; a module's
2025 // top level is a scope, and there the disposal stays a known gap.
2026 return self.stmts(rest);
2027 };
2028 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2029 // exit path already disposed.
2030 let live = !rest.last().is_some_and(Self::terminates);
2031 self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
2032 }
2033
2034 /// The slot a `using` binding's value lives in.
2035 fn using_value_slot(&self, name: &str) -> Option<u32> {
2036 self.cur()
2037 .vars
2038 .iter()
2039 .position(|var| var.name == name && var.kind == VarKind::Using)
2040 .map(|index| index as u32)
2041 }
2042
2043 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2044 ///
2045 /// Shared between a `using` statement — which owns the rest of its block — and a
2046 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2047 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2048 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2049 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2050 /// target with a `finally_label` is what makes `return` and `break` dispose without
2051 /// knowing anything about `using`.
2052 ///
2053 /// ```text
2054 /// catch CATCH <- an exception inside lands here
2055 /// <inside>
2056 /// drop <- the catch offset, on the fall-through path
2057 /// undefined; gosub DISPOSE; drop
2058 /// goto END
2059 /// CATCH:
2060 /// using_dispose slot <- merges the failure into the pending exception
2061 /// throw
2062 /// DISPOSE:
2063 /// using_dispose_init
2064 /// using_dispose slot
2065 /// using_dispose_end <- rethrows if a dispose failed
2066 /// ret
2067 /// END:
2068 /// ```
2069 fn using_region_around(
2070 &mut self,
2071 value_slot: u32,
2072 live: bool,
2073 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2074 ) -> Result<(), SyntaxError> {
2075 let catch_label = self.new_label();
2076 let end_label = self.new_label();
2077 let dispose_label = self.new_label();
2078
2079 self.emit_jump(Opcode::Catch, catch_label, &[]);
2080 self.push_jump_target(JumpTarget {
2081 names: Vec::new(),
2082 break_label: None,
2083 continue_label: None,
2084 // The catch offset is the one thing on the stack that leaving has to remove.
2085 drop_count: 1,
2086 finally_label: Some(dispose_label),
2087 is_regular_stmt: false,
2088 has_iterator: false,
2089 is_async_iterator: false,
2090 });
2091 inside(self)?;
2092 self.pop_jump_target();
2093
2094 if live {
2095 self.emit(Opcode::Drop, &[]);
2096 self.emit(Opcode::Undefined, &[]);
2097 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2098 self.emit(Opcode::Drop, &[]);
2099 self.emit_jump(Opcode::Goto, end_label, &[]);
2100 }
2101
2102 // An exception unwinds to here with the thrown value on the stack, which is exactly
2103 // the shape `using_dispose` expects as its error state.
2104 self.place_label(catch_label);
2105 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2106 self.emit(Opcode::Throw, &[]);
2107
2108 self.place_label(dispose_label);
2109 // Inside the subroutine the return value and the `gosub` return address are both
2110 // live, and neither an outer finalizer nor another region may run before this one
2111 // has finished.
2112 self.push_jump_target(JumpTarget {
2113 names: Vec::new(),
2114 break_label: None,
2115 continue_label: None,
2116 drop_count: 2,
2117 finally_label: None,
2118 is_regular_stmt: false,
2119 has_iterator: false,
2120 is_async_iterator: false,
2121 });
2122 self.emit(Opcode::UsingDisposeInit, &[]);
2123 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2124 self.emit(Opcode::UsingDisposeEnd, &[]);
2125 self.pop_jump_target();
2126 self.emit(Opcode::Ret, &[]);
2127 self.place_label(end_label);
2128 Ok(())
2129 }
2130
2131 /// Declare every name a statement list introduces, before compiling any of
2132 /// it, so a reference that appears textually before a declaration still
2133 /// resolves.
2134 ///
2135 /// Declarations are walked in source order because that is the order the
2136 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2137 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2138 /// declarations hoist out to the function scope; lexical names belong to the
2139 /// block they were written in, which `block` records.
2140 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2141 let saved = self.cur().current_block;
2142 self.state().current_block = block;
2143 let result = self.hoist_list(body);
2144 // Only now is every binding of this scope known, so the deferred function
2145 // bodies can be compiled against the finished list. Compiled at its own
2146 // declaration instead, a body that names a `var` written further down would
2147 // have resolved that name as a global.
2148 if result.is_ok() {
2149 let deferred = std::mem::take(&mut self.state().deferred_funcs);
2150 let mut outcome = Ok(());
2151 for (owner, func) in deferred {
2152 let previous = self.cur().current_block;
2153 self.state().current_block = owner;
2154 outcome = self.func_decl(&func);
2155 self.state().current_block = previous;
2156 if outcome.is_err() {
2157 break;
2158 }
2159 }
2160 self.state().current_block = saved;
2161 return outcome;
2162 }
2163 // `current_block` is restored by the caller for a block statement, since
2164 // it needs it set while compiling; only clean up on the hoist path.
2165 self.state().current_block = saved;
2166 result
2167 }
2168
2169 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2170 for stmt in body {
2171 self.hoist_stmt(stmt)?;
2172 }
2173 Ok(())
2174 }
2175
2176 /// Whether a statement always transfers control away, making everything after
2177 /// it in the same list unreachable.
2178 ///
2179 /// The reference drops such statements in `skip_dead_code`, so `return 1;
2180 /// let x = 2;` compiles to the same bytecode as `return 1;`.
2181 fn terminates(stmt: &Stmt) -> bool {
2182 matches!(
2183 stmt.kind,
2184 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2185 )
2186 }
2187
2188 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2189 match &stmt.kind {
2190 StmtKind::VarDecl(decl) => {
2191 for declarator in &decl.declarators {
2192 let mut names = Vec::new();
2193 declarator.target.bound_names(&mut names);
2194 for name in names {
2195 let text = name.name.clone();
2196 if decl.kind == VarDeclKind::Var {
2197 let def = VarDef::var(text.clone());
2198 self.declare_var(&text, def);
2199 } else if decl.kind.is_using() {
2200 // Two adjacent slots: the resource, then the dispose method
2201 // snapshotted at declaration. `using_dispose` reads them as a
2202 // pair `(slot, slot + 1)`, so nothing may be declared between
2203 // them — which is why both are declared here, in one step,
2204 // rather than the method being added at emission time.
2205 self.declare_using(&text);
2206 } else {
2207 let def = if decl.kind == VarDeclKind::Const {
2208 VarDef::constant(text.clone())
2209 } else {
2210 VarDef::lexical(text.clone())
2211 };
2212 self.declare(&text, def);
2213 }
2214 }
2215 }
2216 }
2217 StmtKind::FuncDecl(func) => {
2218 if let Some(name) = &func.name {
2219 // A function declaration is a `var` binding that happens to
2220 // hold a function, not a lexical one.
2221 let def = VarDef::var(name.name.clone());
2222 self.declare_var(&name.name.clone(), def);
2223 }
2224 // The function object is created when the scope is entered, so it
2225 // exists before the declaration is reached. Its body is compiled
2226 // *after* this scope's hoisting finishes, so a name it uses resolves
2227 // even when the `var` that declares it comes later in the source.
2228 let owner = self.cur().current_block;
2229 self.state().deferred_funcs.push((owner, func.clone()));
2230 }
2231 StmtKind::ClassDecl(class) => {
2232 if let Some(name) = &class.name {
2233 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2234 }
2235 }
2236 // A module's imports are bound before any of its code runs, and its exports
2237 // declare the very bindings they export — so both hoist the declarations
2238 // their `StmtKind` arm will later emit code for.
2239 StmtKind::Import(decl) => self.hoist_import(decl)?,
2240 StmtKind::Export(decl) => self.hoist_export(decl)?,
2241 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2242 StmtKind::If { cons, alt, .. } => {
2243 self.hoist_stmt(cons)?;
2244 if let Some(alt) = alt {
2245 self.hoist_stmt(alt)?;
2246 }
2247 }
2248 StmtKind::While { body, .. }
2249 | StmtKind::DoWhile { body, .. }
2250 | StmtKind::Labeled { body, .. }
2251 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2252 StmtKind::For { init, body, .. } => {
2253 // A `for` head gets its own scope even when it declares nothing,
2254 // because `let` in the head is scoped to the loop.
2255 let key = stmt.span.start.offset as u64;
2256 let parent = self.cur().current_block;
2257 self.push_block(key, parent);
2258 if let Some(init) = init
2259 && let ForInit::VarDecl(decl) = init
2260 {
2261 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2262 }
2263 self.hoist_stmt(body)?;
2264 self.state().current_block = parent;
2265 }
2266 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2267 let key = stmt.span.start.offset as u64;
2268 let parent = self.cur().current_block;
2269 self.push_block(key, parent);
2270 if let ForHead::VarDecl(decl) = left {
2271 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2272 }
2273 self.hoist_stmt(body)?;
2274 self.state().current_block = parent;
2275 }
2276 StmtKind::Try {
2277 block,
2278 handler,
2279 finalizer,
2280 } => {
2281 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2282 let try_parent = self.cur().current_block;
2283 if let Some(handler) = handler {
2284 // The catch parameter belongs to the function scope, not to a
2285 // block: it is a `catch` binding rather than a `let`, so it is
2286 // never in the temporal dead zone and `emit_scope_enter` must
2287 // not mark it uninitialised. It still has to be declared before
2288 // the handler body is hoisted, so it takes the slot the
2289 // reference gives it (bindings are numbered in source order).
2290 if let Some(pattern) = &handler.param {
2291 // The parameter gets its own scope, so entering the handler
2292 // does not have to re-declare it. It is not lexical, so it
2293 // is never marked uninitialised.
2294 let key = Self::try_block_key(stmt, TryPart::Param);
2295 let parent = self.cur().current_block;
2296 self.push_block(key, parent);
2297 // A destructuring parameter binds several names, one slot each,
2298 // in the order they are written. The reference declares those as
2299 // `let`s rather than as one `catch` binding — its dump prints
2300 // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2301 // so the kind follows the shape of the parameter.
2302 //
2303 // Neither form is in the dead zone: the stores run as the handler
2304 // is entered, so both use the unchecked `put_loc`.
2305 let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2306 let mut names = Vec::new();
2307 pattern.bound_names(&mut names);
2308 for name in names {
2309 let def = VarDef {
2310 name: name.name.clone(),
2311 is_const: false,
2312 is_lexical: destructures,
2313 kind: if destructures {
2314 crate::bytecode::VarKind::LexicalCatch
2315 } else {
2316 crate::bytecode::VarKind::Catch
2317 },
2318 is_captured: false,
2319 scope_level: 0,
2320 scope_next: None,
2321 };
2322 self.declare_local(&name.name.clone(), def);
2323 }
2324 // The handler body nests inside the parameter's scope, so the
2325 // body's bindings chain on to the parameter (the reference
2326 // prints `let y [next:1]`, pointing at `e`).
2327 self.state().current_block = key;
2328 }
2329 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2330 // Back to the block the `try` itself lives in, so the finalizer
2331 // is a sibling of the handler rather than nested in it.
2332 self.state().current_block = try_parent;
2333 }
2334 if let Some(finalizer) = finalizer {
2335 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2336 }
2337 }
2338 StmtKind::Switch { cases, .. } => {
2339 let key = stmt.span.start.offset as u64;
2340 let parent = self.cur().current_block;
2341 self.push_block(key, parent);
2342 for case in cases {
2343 self.hoist_list(&case.body)?;
2344 }
2345 self.state().current_block = parent;
2346 }
2347 _ => {}
2348 }
2349 Ok(())
2350 }
2351
2352 /// Hoist a nested statement list, which is its own lexical scope.
2353 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2354 let parent = self.cur().current_block;
2355 self.push_block(key, parent);
2356 self.hoist_list(body)?;
2357 self.state().current_block = parent;
2358 Ok(())
2359 }
2360
2361 /// A block key for one part of a `try` statement.
2362 ///
2363 /// The three parts are three separate scopes, so they cannot share the key a
2364 /// statement's own offset would give them: the try block, the handler body and
2365 /// the finalizer would then look like one scope, and their `let` bindings would
2366 /// be marked uninitialised only on entering the first of them.
2367 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2368 (stmt.span.start.offset as u64) * 4 + part as u64
2369 }
2370
2371 /// Declare a `var`: it lives in the function's own scope, not the block's.
2372 fn declare_var(&mut self, name: &str, def: VarDef) {
2373 if self.cur().is_module {
2374 self.declare_module(name, &def);
2375 return;
2376 }
2377 if self.cur().declares_globally(&def) {
2378 self.declare_global(name, &def);
2379 return;
2380 }
2381 let state = self.state();
2382 // A binding of the *parameter* scope does not count: the body's `var` of the
2383 // same name is a different binding and needs a slot of its own.
2384 if state.vars.iter().enumerate().any(|(index, v)| {
2385 v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2386 }) {
2387 return;
2388 }
2389 // A `var` belongs to the function scope, never to the enclosing block.
2390 state.var_block.push(FUNCTION_SCOPE);
2391 state.vars.push(def);
2392 }
2393
2394 /// Declare `name` as a binding of the parameter scope, returning its slot.
2395 fn declare_param_var(&mut self, name: &str) -> u32 {
2396 declare_param_var_at(self.state(), name)
2397 }
2398
2399 /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2400 ///
2401 /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2402 /// so each points at the one declared before it and the oldest ends the chain with
2403 /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2404 /// runtime walks when it instantiates them.
2405 fn declare_param_binding(&mut self, name: &str) -> u32 {
2406 let state = self.state();
2407 let previous = state
2408 .vars
2409 .iter()
2410 .enumerate()
2411 .rev()
2412 .find(|(index, var)| {
2413 state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2414 })
2415 .map(|(index, _)| index as i32);
2416 let index = state.vars.len() as u32;
2417 state.var_block.push(PARAM_SCOPE);
2418 let mut def = VarDef::lexical(name);
2419 // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2420 // the function's, and its bindings are initialised one by one rather than all at
2421 // once — which is exactly what the dead zone needs.
2422 def.scope_level = 1;
2423 def.scope_next = Some(previous.unwrap_or(-2));
2424 state.vars.push(def);
2425 index
2426 }
2427
2428 /// The slot of a parameter-list binding, if the list has one by that name.
2429 fn param_binding_slot(&self, name: &str) -> Option<u32> {
2430 let state = self.cur();
2431 state
2432 .vars
2433 .iter()
2434 .enumerate()
2435 .position(|(index, var)| {
2436 var.name == name
2437 && var.is_lexical
2438 && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2439 })
2440 .map(|index| index as u32)
2441 }
2442
2443 /// Every parameter-list binding, in declaration order.
2444 fn param_binding_names(&self) -> Vec<String> {
2445 let state = self.cur();
2446 state
2447 .vars
2448 .iter()
2449 .enumerate()
2450 .filter(|(index, var)| {
2451 var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2452 })
2453 .map(|(_, var)| var.name.clone())
2454 .collect()
2455 }
2456
2457 /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2458 fn body_var_slot(&self, name: &str) -> Option<u32> {
2459 let state = self.cur();
2460 state
2461 .vars
2462 .iter()
2463 .enumerate()
2464 .find(|(index, var)| {
2465 var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2466 })
2467 .map(|(index, _)| index as u32)
2468 }
2469
2470 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2471 /// one.
2472 ///
2473 /// With parameter expressions the reference creates two: an unmapped one in the
2474 /// argument scope, for the defaults and anything they close over, and the body's own.
2475 /// They are separate bindings, which is what makes
2476 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2477 /// report 1 from `p` and 2 from the body.
2478 fn provide_param_arguments(&mut self) {
2479 if !self.cur().has_parameter_expressions {
2480 return;
2481 }
2482 let mentioned = self.cur().needs_param_arguments
2483 || self
2484 .cur()
2485 .insns
2486 .iter()
2487 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2488 if !mentioned {
2489 return;
2490 }
2491 let slot = self.declare_param_var("arguments");
2492 let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2493 0
2494 } else {
2495 1
2496 };
2497 self.prepend_initialiser_to(
2498 slot,
2499 Insn::Fixed {
2500 op: Opcode::SpecialObject,
2501 operands: vec![Op::Int(magic)],
2502 },
2503 );
2504 }
2505
2506 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2507 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2508 let current = self.stack.len() - 1;
2509 let init = [
2510 producer,
2511 Insn::Fixed {
2512 op: Opcode::PutLoc,
2513 operands: vec![Op::Slot(Slot::Loc(slot))],
2514 },
2515 ];
2516 let inserted = init.len();
2517 for (index, instruction) in init.into_iter().enumerate() {
2518 self.stack[current].insns.insert(index, instruction);
2519 }
2520 for placed in self.stack[current].labels.iter_mut().flatten() {
2521 *placed += inserted;
2522 }
2523 self.state().label_since_insn = false;
2524 }
2525
2526 /// Give the function an `arguments` binding if its body mentions one.
2527 ///
2528 /// The check runs on the *instruction* stream rather than the AST: by this point
2529 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2530 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2531 /// would renumber every later local slot and stop the bytecode matching the
2532 /// reference, which only adds the binding when the body uses it.
2533 ///
2534 /// `arguments` is a local, initialised at the top of the body by
2535 /// `special_object`; that is the reference's shape, so the disassembly agrees.
2536 fn provide_arguments(&mut self) {
2537 let current = self.stack.len() - 1;
2538 if self.stack[current].is_script || self.stack[current].is_module {
2539 // A module has no `arguments` binding; referring to it is a ReferenceError,
2540 // which is exactly what an unbound name produces.
2541 return;
2542 }
2543 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2544 // function, which is why `() => arguments` sees the caller's arguments.
2545 if self.stack[current].is_arrow {
2546 if self.mentions("arguments") {
2547 self.ensure_enclosing_arguments();
2548 }
2549 return;
2550 }
2551 // Only a *body* mention needs the body's binding: the parameter list has one of
2552 // its own (see [`Compiler::provide_param_arguments`]).
2553 //
2554 // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2555 // `Var`, so without this the body got no binding at all — the name resolved to
2556 // the global object and `delete` answered `true` for a binding that cannot be
2557 // deleted. The reference answers `false`.
2558 let mentioned = self.cur().insns.iter().any(|insn| match insn {
2559 Insn::Var {
2560 name, in_params, ..
2561 } => name == "arguments" && !*in_params,
2562 Insn::DeleteVar { name } => name == "arguments",
2563 _ => false,
2564 });
2565 // A mention that resolves to the body's *own* lexical `arguments` is not a request
2566 // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
2567 // implicit binding is not created at all. Providing it anyway was worse than useless:
2568 // its prologue store resolved past the shadowing `let` and landed on the **global**,
2569 // so `function f(p = eval("var arguments")) { let arguments; }` defined
2570 // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
2571 // test262's `fn-body-cntns-arguments-lex-bind` family).
2572 //
2573 // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
2574 // var *is* the binding, and the implicit arguments object is initialised into it at
2575 // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
2576 // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
2577 // `typeof arguments` `"undefined"`.
2578 if self
2579 .cur()
2580 .vars
2581 .iter()
2582 .any(|var| var.name == "arguments" && var.needs_check())
2583 {
2584 return;
2585 }
2586 if !mentioned && !self.cur().needs_arguments_local {
2587 return;
2588 }
2589 // The request may have come only from a parameter-list arrow, in which case the
2590 // parameter scope's binding already answers for it and the body needs none.
2591 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2592 return;
2593 }
2594 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
2595 //
2596 // With parameter expressions the list and the body are separate environments, so
2597 // an assignment to a parameter cannot be reflected into `arguments` at all — the
2598 // arguments object is unmapped whatever the mode, which is why the reference emits
2599 // `special_object 0` here even in sloppy code.
2600 // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
2601 // object unmapped whatever the mode — §10.4.4 keys the decision on
2602 // `IsSimpleParameterList`, not on strictness alone.
2603 let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
2604 0
2605 } else {
2606 1
2607 };
2608 // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
2609 // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
2610 // The only storage both sides can see is a reference cell, so every parameter the
2611 // object maps gets one — even a parameter no closure captured. Without this the
2612 // slot holds a plain copy and the mapping has nothing to write through.
2613 if magic == 1 {
2614 for arg in &mut self.stack[current].args {
2615 arg.is_captured = true;
2616 }
2617 }
2618 self.prepend_binding("arguments", magic);
2619 }
2620
2621 /// Whether a *body* instruction refers to `arguments`.
2622 fn body_mentions_arguments(&self) -> bool {
2623 self.cur()
2624 .insns
2625 .iter()
2626 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2627 }
2628
2629 /// Whether the function body's instruction stream refers to `name`.
2630 fn mentions(&self, name: &str) -> bool {
2631 let current = self.stack.len() - 1;
2632 // A binding of the parameter scope does not answer for the body: the body's own
2633 // `arguments` (or self-name) still has to be provided for it.
2634 if self.stack[current]
2635 .vars
2636 .iter()
2637 .enumerate()
2638 .any(|(index, v)| {
2639 v.name == name
2640 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2641 })
2642 {
2643 return false;
2644 }
2645 self.stack[current]
2646 .insns
2647 .iter()
2648 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2649 }
2650
2651 /// Bind the name a named function expression uses to refer to itself.
2652 ///
2653 /// The value is `special_object 2`, the function currently running, so the binding
2654 /// is the closure itself and not a copy. It is a local of this function, which is
2655 /// what keeps `g` out of the enclosing scope.
2656 /// Give the function a local `this`, for an arrow inside it to capture.
2657 fn provide_this_local(&mut self) {
2658 let current = self.stack.len() - 1;
2659 if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2660 return;
2661 }
2662 if !self.stack[current]
2663 .vars
2664 .iter()
2665 .any(|var| var.name == "this")
2666 {
2667 self.declare_hidden_local("this", VarKind::Normal);
2668 }
2669 self.prepend_initialiser(
2670 "this",
2671 Insn::Fixed {
2672 op: Opcode::PushThis,
2673 operands: vec![],
2674 },
2675 );
2676 }
2677
2678 /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2679 /// to read through `super`.
2680 fn provide_home_object_local(&mut self) {
2681 let current = self.stack.len() - 1;
2682 if !self.stack[current].needs_home_object_local {
2683 return;
2684 }
2685 if !self.stack[current]
2686 .vars
2687 .iter()
2688 .any(|var| var.name == HOME_OBJECT)
2689 {
2690 self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2691 }
2692 self.prepend_initialiser(
2693 HOME_OBJECT,
2694 Insn::Fixed {
2695 op: Opcode::SpecialObject,
2696 operands: vec![Op::Int(4)],
2697 },
2698 );
2699 }
2700
2701 fn provide_self_name(&mut self) {
2702 let current = self.stack.len() - 1;
2703 let Some(name) = self.stack[current].self_name.clone() else {
2704 return;
2705 };
2706 if self.stack[current].self_name_initialized {
2707 return;
2708 }
2709 // Either the body refers to the name, or a nested function already forced the
2710 // binding into existence while being resolved. A direct `eval` can name it
2711 // without mentioning it, so its presence is a third reason: in strict mode
2712 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2713 // that only happens if the binding exists.
2714 let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2715 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2716 return;
2717 }
2718 self.stack[current].self_name_initialized = true;
2719 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2720 }
2721
2722 /// Insert `special_object magic` plus the store to `name` at the top of the body.
2723 ///
2724 /// Prepending shifts every label that has been placed, so they are all moved by
2725 /// the number of instructions inserted.
2726 fn prepend_binding(&mut self, name: &str, magic: i32) {
2727 self.prepend_binding_with(name, magic, VarKind::Normal);
2728 }
2729
2730 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2731 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2732 let current = self.stack.len() - 1;
2733 // A function-expression's own name is immutable in strict mode, which is what
2734 // makes `f = 1` inside a strict body throw instead of being dropped.
2735 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2736 self.declare_var(
2737 name,
2738 VarDef {
2739 kind,
2740 is_const,
2741 ..VarDef::var(name)
2742 },
2743 );
2744 let init = [
2745 Insn::Fixed {
2746 op: Opcode::SpecialObject,
2747 operands: vec![Op::Int(magic)],
2748 },
2749 Insn::Var {
2750 // An initialisation, not an assignment: sloppy mode drops stores to a
2751 // function-expression's own name, and the prologue is what puts the
2752 // value there in the first place.
2753 action: if kind == VarKind::FunctionName {
2754 VarAction::PutInit
2755 } else {
2756 VarAction::Put
2757 },
2758 name: name.to_string(),
2759 block: 0,
2760 in_params: false,
2761 },
2762 ];
2763 let inserted = init.len();
2764 for (index, instruction) in init.into_iter().enumerate() {
2765 self.stack[current].insns.insert(index, instruction);
2766 }
2767 for placed in self.stack[current].labels.iter_mut().flatten() {
2768 *placed += inserted;
2769 }
2770 // A store sits at the insertion point now, so the `put`/`get` fold must not
2771 // reach across it.
2772 self.stack[current].label_since_insn = true;
2773 }
2774
2775 /// Record a top-level script declaration as a global.
2776 ///
2777 /// A script's top-level `var`/`let`/`function` create properties of the
2778 /// global object, not slots in the script's frame, so they show up as closure
2779 /// variables instead.
2780 fn declare_global(&mut self, name: &str, def: &VarDef) {
2781 let state = self.state();
2782 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2783 // The name was already referenced, from a function compiled before this
2784 // declaration was reached — `function a(){ b() } function b(){}` resolves
2785 // `b` while `b` is still unknown, and that guess has to be corrected here.
2786 // Leaving it as a plain global meant the declaration was never registered,
2787 // so the binding did not exist at run time and `a()` threw
2788 // `b is not defined`.
2789 if matches!(existing.closure_type, ClosureType::Global) {
2790 existing.closure_type = ClosureType::GlobalDecl;
2791 existing.is_const = def.is_const;
2792 existing.is_lexical = def.is_lexical;
2793 }
2794 return;
2795 }
2796 state.closure_vars.push(ClosureVar {
2797 name: name.to_string(),
2798 is_const: def.is_const,
2799 is_lexical: def.is_lexical,
2800 closure_type: ClosureType::GlobalDecl,
2801 var_idx: 0,
2802 });
2803 }
2804
2805 /// Record a module-level declaration as a module variable.
2806 ///
2807 /// The binding is a closure variable of the module body, so reads and writes are
2808 /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
2809 /// *who fills the cell*: the module record does, before the body runs, and an import
2810 /// points its cell at the exporting module's, which is what makes bindings live and
2811 /// cycles work.
2812 fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
2813 let state = self.state();
2814 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2815 // The name may have been referenced before this declaration was hoisted,
2816 // which resolved it as a plain global. Correct that here, the way
2817 // `declare_global` does.
2818 if matches!(existing.closure_type, ClosureType::Global) {
2819 existing.closure_type = ClosureType::ModuleDecl;
2820 existing.is_const = def.is_const;
2821 existing.is_lexical = def.is_lexical;
2822 }
2823 return 0;
2824 }
2825 state.closure_vars.push(ClosureVar {
2826 name: name.to_string(),
2827 is_const: def.is_const,
2828 is_lexical: def.is_lexical,
2829 closure_type: ClosureType::ModuleDecl,
2830 var_idx: 0,
2831 });
2832 0
2833 }
2834
2835 /// Declare a module variable and answer its closure-variable index.
2836 ///
2837 /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
2838 /// module variable is not one. The import table needs the real index instead, because
2839 /// that is the position the host writes the cell into.
2840 fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
2841 self.declare_module(name, def);
2842 self.cur()
2843 .closure_vars
2844 .iter()
2845 .position(|c| c.name == name)
2846 .map(|index| index as u32)
2847 .unwrap_or(0)
2848 }
2849
2850 /// Declare one imported binding as a module variable.
2851 ///
2852 /// Returns the closure-variable index, which is what the import table records: the
2853 /// host writes the exporter's cell into that slot before the body runs.
2854 fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
2855 let state = self.state();
2856 if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
2857 // Keep the slot, fix the kind: the name may already have been referenced.
2858 state.closure_vars[index].closure_type = ClosureType::ModuleImport;
2859 state.closure_vars[index].is_const = is_const;
2860 return index as u32;
2861 }
2862 state.closure_vars.push(ClosureVar {
2863 name: name.to_string(),
2864 // An imported binding cannot be assigned: `x = 1` on an import is a
2865 // `TypeError` at run time, which the const flag is what produces.
2866 is_const: true,
2867 // Lexical, so reads go through `get_var_ref_check`: before linking has filled
2868 // the cell an import is in its dead zone, and reading it there must say so
2869 // rather than answer `undefined`.
2870 is_lexical: true,
2871 closure_type: ClosureType::ModuleImport,
2872 var_idx: 0,
2873 });
2874 state.closure_vars.len() as u32 - 1
2875 }
2876
2877 /// Emit the code an `export` needs.
2878 ///
2879 /// Only `export default <expr>` has any: everything else is a table entry whose
2880 /// binding is declared elsewhere. The expression is stored into the hidden
2881 /// `*default*` variable rather than returned, because the module body has no value
2882 /// to speak of.
2883 fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2884 match &decl.kind {
2885 ExportKind::Declaration(stmt) => self.stmt(stmt),
2886 ExportKind::Default(expr) => {
2887 // `export default class Foo {}`: evaluate the declaration (which binds
2888 // `Foo`), then copy its value into the hidden `*default*` binding, because a
2889 // class declaration is a *statement* and `expr` cannot be compiled as one.
2890 if let ExprKind::Class(class) = &expr.kind
2891 && class.name.is_some()
2892 {
2893 self.stmt(&Stmt {
2894 kind: StmtKind::ClassDecl(class.clone()),
2895 span: expr.span,
2896 })?;
2897 let Some(name) = &class.name else {
2898 return Ok(());
2899 };
2900 self.emit_var(VarAction::Get, &name.name);
2901 let index = self.declare_export_default();
2902 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2903 return Ok(());
2904 }
2905 // A named default function/class is already a module binding; the export
2906 // points at it and there is nothing to evaluate.
2907 if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
2908 return Ok(());
2909 }
2910 self.expr(expr)?;
2911 // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
2912 // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
2913 // name is observable — `imported.default.name` — and without this an
2914 // anonymous `export default class {}` arrived with the empty name.
2915 self.set_name_if_anonymous(expr, &Wtf8::new("default"));
2916 let index = self.declare_export_default();
2917 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2918 Ok(())
2919 }
2920 ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
2921 }
2922 }
2923
2924 /// A module name as the string it denotes.
2925 fn module_name_text(name: &ModuleName) -> &str {
2926 match name {
2927 ModuleName::Ident(ident) => &ident.name,
2928 ModuleName::Str(text) => text,
2929 }
2930 }
2931
2932 /// Bind `import`'s local names and record where each one comes from.
2933 ///
2934 /// Nothing is emitted: an import is not an instruction, it is a promise that the
2935 /// binding's cell will be filled before the body runs. The cell lands in the module's
2936 /// environment at a fixed index, and the host fills it from the exporter's cell —
2937 /// which is why a cyclic import can bind before the other module has evaluated.
2938 fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
2939 let request = self.module_request(&decl.source, &decl.attributes);
2940 for specifier in &decl.specifiers {
2941 let (local, name, is_star) = match specifier {
2942 ImportSpecifier::Default(ident) => {
2943 (ident.name.clone(), "default".to_string(), false)
2944 }
2945 ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
2946 ImportSpecifier::Named { imported, local } => (
2947 local.name.clone(),
2948 Self::module_name_text(imported).to_string(),
2949 false,
2950 ),
2951 };
2952 // `import * as ns` is *not* a live binding of another module's variable —
2953 // it is a value of its own, which is why the reference declares it like a
2954 // module variable and the host stores the namespace object in that cell.
2955 let var_idx = if is_star {
2956 // `const`: a namespace object is a value, and the binding is immutable.
2957 self.declare_module_var(&local, &VarDef::constant(local.clone()))
2958 } else {
2959 self.declare_import(&local, true)
2960 };
2961 self.module_meta().imports.push(ImportEntry {
2962 module: request,
2963 name,
2964 var_idx,
2965 is_star,
2966 });
2967 }
2968 Ok(())
2969 }
2970
2971 /// Record what an `export` offers, declaring the binding it exports.
2972 ///
2973 /// `export var x = 1` is a declaration like any other; only the table entry is extra.
2974 fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2975 match &decl.kind {
2976 ExportKind::Declaration(stmt) => {
2977 // The inner declaration keeps its own hoisting, then every name it binds
2978 // becomes an export of the same name.
2979 self.hoist_stmt(stmt)?;
2980 let mut names = Vec::new();
2981 Self::declared_names(stmt, &mut names);
2982 for name in names {
2983 let var_idx = self.module_binding_index(&name);
2984 self.exports_local(&name, var_idx);
2985 }
2986 }
2987 ExportKind::Default(expr) => {
2988 // The reference puts a default export in a hidden `*default*` variable,
2989 // so `export default function f(){}` can export a *value* while `f` stays
2990 // a binding of the module.
2991 if let ExprKind::Function(func) = &expr.kind
2992 && let Some(name) = &func.name
2993 {
2994 let text = name.name.clone();
2995 self.hoist_stmt(&Stmt {
2996 kind: StmtKind::FuncDecl(func.clone()),
2997 span: expr.span,
2998 })?;
2999 let var_idx = self.module_binding_index(&text);
3000 self.module_meta().exports.push(ExportEntry::Local {
3001 export_name: "default".to_string(),
3002 var_idx,
3003 });
3004 return Ok(());
3005 }
3006 if let ExprKind::Class(class) = &expr.kind
3007 && class.name.is_some()
3008 {
3009 // `export default class Foo {}` binds `Foo` in the module scope **and**
3010 // stores the class into the hidden `*default*` binding — it is a
3011 // declaration *and* a value, unlike `export default class {}` which is
3012 // only a value.
3013 //
3014 // Pointing the `default` export straight at `Foo` looked simpler and was
3015 // wrong twice over: `module_binding_index` did not find the lexical
3016 // binding the hoist had just made, so it declared a second one that
3017 // nothing ever wrote, and `export_stmt` then had no code to emit for the
3018 // declaration either. `imported.default` came out `undefined` and `Foo`
3019 // was not in scope inside its own module.
3020 self.hoist_stmt(&Stmt {
3021 kind: StmtKind::ClassDecl(class.clone()),
3022 span: expr.span,
3023 })?;
3024 let var_idx = self.declare_export_default();
3025 self.exports_local("default", var_idx);
3026 return Ok(());
3027 }
3028 let var_idx = self.declare_export_default();
3029 self.module_meta().exports.push(ExportEntry::Local {
3030 export_name: "default".to_string(),
3031 var_idx,
3032 });
3033 }
3034 ExportKind::Named {
3035 specifiers,
3036 source,
3037 attributes,
3038 } => match source {
3039 Some(source) => {
3040 let request = self.module_request(source, attributes);
3041 for specifier in specifiers {
3042 self.module_meta().exports.push(ExportEntry::Indirect {
3043 export_name: Self::module_name_text(&specifier.exported).to_string(),
3044 module: request,
3045 import_name: Self::module_name_text(&specifier.local).to_string(),
3046 });
3047 }
3048 }
3049 None => {
3050 for specifier in specifiers {
3051 let local = Self::module_name_text(&specifier.local).to_string();
3052 let export_name = Self::module_name_text(&specifier.exported).to_string();
3053 // `export { x }` where `x` is itself an **import** re-exports the
3054 // binding the import names, not a binding of this module
3055 // (§16.2.1.6.3: a local export whose local name is imported resolves
3056 // through the imported module). Recording it as a local made two
3057 // modules that both forward one import look like two different
3058 // bindings, and the name was reported ambiguous
3059 // (`import-and-export-propagates-binding`;
3060 // `namespace-unambiguous-if-import-star-as-and-export`).
3061 let closure_names: Vec<String> = self
3062 .cur()
3063 .closure_vars
3064 .iter()
3065 .map(|var| var.name.clone())
3066 .collect();
3067 let forwarded = self
3068 .module_meta()
3069 .imports
3070 .iter()
3071 .filter(|entry| {
3072 closure_names
3073 .get(entry.var_idx as usize)
3074 .is_some_and(|name| *name == local)
3075 })
3076 .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3077 .find(|(_, name, is_star)| !is_star || name.is_empty());
3078 if let Some((request, name, is_star)) = forwarded {
3079 // A namespace import has no export *name* of its own; the
3080 // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3081 // which is what the marker below records.
3082 let import_name = if is_star {
3083 "*namespace*".to_string()
3084 } else {
3085 name
3086 };
3087 self.module_meta().exports.push(ExportEntry::Indirect {
3088 export_name,
3089 module: request,
3090 import_name,
3091 });
3092 continue;
3093 }
3094 let var_idx = self.module_binding_index(&local);
3095 self.module_meta().exports.push(ExportEntry::Local {
3096 export_name,
3097 var_idx,
3098 });
3099 }
3100 }
3101 },
3102 ExportKind::All {
3103 source,
3104 exported,
3105 attributes,
3106 } => {
3107 let request = self.module_request(source, attributes);
3108 match exported {
3109 Some(name) => {
3110 self.module_meta().exports.push(ExportEntry::StarAs {
3111 export_name: Self::module_name_text(name).to_string(),
3112 module: request,
3113 });
3114 }
3115 None => {
3116 self.module_meta()
3117 .exports
3118 .push(ExportEntry::Star { module: request });
3119 }
3120 }
3121 }
3122 }
3123 Ok(())
3124 }
3125
3126 /// The names a declaration binds, which is what `export <decl>` exports.
3127 fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3128 match &stmt.kind {
3129 StmtKind::VarDecl(decl) => {
3130 for declarator in &decl.declarators {
3131 let mut names = Vec::new();
3132 declarator.target.bound_names(&mut names);
3133 out.extend(names.into_iter().map(|name| name.name));
3134 }
3135 }
3136 StmtKind::FuncDecl(func) => {
3137 if let Some(name) = &func.name {
3138 out.push(name.name.clone());
3139 }
3140 }
3141 StmtKind::ClassDecl(class) => {
3142 if let Some(name) = &class.name {
3143 out.push(name.name.clone());
3144 }
3145 }
3146 _ => {}
3147 }
3148 }
3149
3150 /// The closure-variable index of a module binding, declaring it if the name was
3151 /// exported without being declared here.
3152 ///
3153 /// `export { x }` where `x` is not declared in the module is a link-time
3154 /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3155 fn module_binding_index(&mut self, name: &str) -> u32 {
3156 if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3157 return index as u32;
3158 }
3159 self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3160 }
3161
3162 fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3163 self.module_meta().exports.push(ExportEntry::Local {
3164 export_name: export_name.to_string(),
3165 var_idx,
3166 });
3167 }
3168
3169 /// The hidden `*default*` binding `export default <expr>` stores into.
3170 fn declare_export_default(&mut self) -> u32 {
3171 const DEFAULT: &str = "*default*";
3172 if let Some(index) = self
3173 .cur()
3174 .closure_vars
3175 .iter()
3176 .position(|c| c.name == DEFAULT)
3177 {
3178 return index as u32;
3179 }
3180 self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3181 }
3182
3183 /// The module tables, which only the top-level state has.
3184 fn module_meta(&mut self) -> &mut ModuleMeta {
3185 self.state()
3186 .module
3187 .as_mut()
3188 .expect("module tables are only touched while compiling a module")
3189 }
3190
3191 /// The index of `specifier`'s request, adding it if it is new.
3192 ///
3193 /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3194 /// JSON and once as text is two modules with two different contents, which is exactly
3195 /// what `hello_module.js` does.
3196 fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3197 let attributes: Vec<(String, String)> = attributes
3198 .iter()
3199 .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3200 .collect();
3201 let meta = self.module_meta();
3202 if let Some(index) = meta
3203 .requests
3204 .iter()
3205 .position(|request| request.specifier == specifier && request.attributes == attributes)
3206 {
3207 return index as u32;
3208 }
3209 meta.requests.push(ModuleRequest {
3210 specifier: specifier.to_string(),
3211 attributes,
3212 });
3213 meta.requests.len() as u32 - 1
3214 }
3215
3216 /// Compile a loop body with a `break`/`continue` target pushed for it.
3217 fn loop_body(
3218 &mut self,
3219 body: &Stmt,
3220 labels: &[String],
3221 continue_label: Label,
3222 break_label: Label,
3223 ) -> Result<(), SyntaxError> {
3224 self.push_jump_target(JumpTarget {
3225 names: labels.to_vec(),
3226 break_label: Some(break_label),
3227 continue_label: Some(continue_label),
3228 // A loop leaves nothing of its own on the value stack.
3229 drop_count: 0,
3230 finally_label: None,
3231 is_regular_stmt: false,
3232 has_iterator: false,
3233 is_async_iterator: false,
3234 });
3235 let result = self.stmt(body);
3236 self.pop_jump_target();
3237 result
3238 }
3239
3240 fn push_jump_target(&mut self, target: JumpTarget) {
3241 self.state().jump_targets.push(target);
3242 }
3243
3244 fn pop_jump_target(&mut self) {
3245 self.state().jump_targets.pop();
3246 }
3247
3248 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3249 let (label, is_break) = match &stmt.kind {
3250 StmtKind::Break(label) => (label.as_ref(), true),
3251 StmtKind::Continue(label) => (label.as_ref(), false),
3252 _ => unreachable!("control_transfer is only called for break and continue"),
3253 };
3254
3255 // Walk outward from the innermost construct. Everything considered before
3256 // the match is a construct control is leaving, and leaving it has a cost:
3257 // its stack slots go, and its finalizer runs.
3258 let targets = self.cur().jump_targets.clone();
3259 for target in targets.iter().rev() {
3260 let destination = match (label, is_break) {
3261 // An unlabelled `break` skips a labelled non-loop statement: `break`
3262 // may name one, but the bare form only means "leave the loop".
3263 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3264 (None, false) => target.continue_label,
3265 (Some(name), true) => target
3266 .break_label
3267 .filter(|_| target.names.contains(&name.name)),
3268 (Some(name), false) => target
3269 .continue_label
3270 .filter(|_| target.names.contains(&name.name)),
3271 };
3272
3273 if let Some(destination) = destination {
3274 self.emit_jump(Opcode::Goto, destination, &[]);
3275 return Ok(());
3276 }
3277
3278 // Closing the iterator consumes the three slots the loop keeps on the
3279 // stack (iterator, next method, catch offset), so those are not dropped
3280 // again below.
3281 let mut remaining = target.drop_count;
3282 if target.has_iterator {
3283 self.emit_iterator_close(target.is_async_iterator, false);
3284 remaining = remaining.saturating_sub(3);
3285 }
3286 for _ in 0..remaining {
3287 self.emit(Opcode::Drop, &[]);
3288 }
3289 if let Some(finally) = target.finally_label {
3290 // The finalizer runs as a subroutine and is handed a dummy return
3291 // value, which is dropped afterwards to keep the stack the depth it
3292 // had before.
3293 self.emit(Opcode::Undefined, &[]);
3294 self.emit_jump(Opcode::Gosub, finally, &[]);
3295 self.emit(Opcode::Drop, &[]);
3296 }
3297 }
3298
3299 // The parser rejects a break/continue with no target, so reaching here
3300 // means the compiler's own bookkeeping is wrong.
3301 Err(SyntaxError::new(
3302 if is_break {
3303 "break has no enclosing loop or switch"
3304 } else {
3305 "continue has no enclosing loop"
3306 },
3307 stmt.span,
3308 ))
3309 }
3310
3311 /// Compile a labelled statement.
3312 ///
3313 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3314 /// that loop's targets, so the chain is collected and handed to the loop. A
3315 /// label on a non-loop statement only provides a `break` target, because
3316 /// `continue` may not target it.
3317 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3318 let mut names = vec![label.name.clone()];
3319 let mut inner = body;
3320 while let StmtKind::Labeled {
3321 label: next,
3322 body: deeper,
3323 } = &inner.kind
3324 {
3325 names.push(next.name.clone());
3326 inner = deeper;
3327 }
3328 if Self::is_loop(inner) {
3329 return self.stmt_labelled(inner, &names);
3330 }
3331 let end = self.new_label();
3332 self.push_jump_target(JumpTarget {
3333 names,
3334 break_label: Some(end),
3335 continue_label: None,
3336 drop_count: 0,
3337 finally_label: None,
3338 is_regular_stmt: true,
3339 has_iterator: false,
3340 is_async_iterator: false,
3341 });
3342 let result = self.stmt(inner);
3343 self.pop_jump_target();
3344 result?;
3345 self.place_label(end);
3346 let _ = stmt;
3347 Ok(())
3348 }
3349
3350 /// Whether a statement is a loop, i.e. a valid target for `continue`.
3351 fn is_loop(stmt: &Stmt) -> bool {
3352 matches!(
3353 stmt.kind,
3354 StmtKind::While { .. }
3355 | StmtKind::DoWhile { .. }
3356 | StmtKind::For { .. }
3357 | StmtKind::ForIn { .. }
3358 | StmtKind::ForOf { .. }
3359 )
3360 }
3361
3362 /// Compile `switch`.
3363 ///
3364 /// The discriminant is evaluated once and stays on the value stack while the
3365 /// clauses compare against copies of it, so it is dropped at the end — which is
3366 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3367 /// clause's body jumps over the *next* clause's tests straight into its body.
3368 ///
3369 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3370 /// the next run's tests. Only the last run's miss reaches the `default` body, or
3371 /// the end of the switch when there is no `default`. That failure path can point
3372 /// backwards (`default` written first), so the runs and their labels are worked
3373 /// out before any code is emitted.
3374 fn switch(
3375 &mut self,
3376 discriminant: &Expr,
3377 cases: &[SwitchCase],
3378 stmt: &Stmt,
3379 ) -> Result<(), SyntaxError> {
3380 self.reset_value();
3381 // The discriminant is evaluated outside the switch's block scope, before
3382 // any `case` clause exists.
3383 self.expr(discriminant)?;
3384
3385 let switch_key = stmt.span.start.offset as u64;
3386 let switch_parent = self.cur().current_block;
3387 self.push_block(switch_key, switch_parent);
3388 self.emit_scope_enter(switch_key);
3389
3390 let break_label = self.new_label();
3391 self.push_jump_target(JumpTarget {
3392 names: Vec::new(),
3393 break_label: Some(break_label),
3394 // `switch` is a valid `break` target but not a `continue` target.
3395 continue_label: None,
3396 // The discriminant stays on the value stack for the whole statement, so
3397 // a `break` aimed further out has to discard it.
3398 drop_count: 1,
3399 finally_label: None,
3400 is_regular_stmt: false,
3401 has_iterator: false,
3402 is_async_iterator: false,
3403 });
3404
3405 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3406 // its label to the clause after it, so both tests reach the same body.
3407 let mut runs: Vec<(usize, usize)> = Vec::new();
3408 let mut scan = 0;
3409 while scan < cases.len() {
3410 if cases[scan].test.is_some() {
3411 let mut last = scan;
3412 while last + 1 < cases.len()
3413 && cases[last].test.is_some()
3414 && cases[last].body.is_empty()
3415 && cases[last + 1].test.is_some()
3416 {
3417 last += 1;
3418 }
3419 runs.push((scan, last));
3420 scan = last + 1;
3421 } else {
3422 scan += 1;
3423 }
3424 }
3425
3426 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3427 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3428 let default_at = cases.iter().position(|case| case.test.is_none());
3429 // Where the last run sends control when nothing matched.
3430 let miss_target = match default_at {
3431 Some(index) => body_labels[index],
3432 None => break_label,
3433 };
3434
3435 // When `default` comes first, control has to jump over it to reach the
3436 // tests. It only needs to when some clause actually has a test; otherwise
3437 // the default body is the entry point.
3438 let mut entry = None;
3439 if default_at == Some(0) && !runs.is_empty() {
3440 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3441 entry = Some(run_labels[0]);
3442 }
3443
3444 let mut index = 0;
3445 let mut run = 0;
3446 let result = (|| -> Result<(), SyntaxError> {
3447 while index < cases.len() {
3448 if cases[index].test.is_some() {
3449 let (first, last) = runs[run];
3450 // Reaching these tests from the preceding body is a
3451 // fallthrough, which continues inside the body and skips them.
3452 if index > 0 {
3453 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3454 }
3455 if let Some(label) = entry.take() {
3456 self.place_label(label);
3457 }
3458 self.place_label(run_labels[run]);
3459
3460 for (offset, case) in cases[first..=last].iter().enumerate() {
3461 let test = case.test.as_ref().unwrap();
3462 self.emit(Opcode::Dup, &[]);
3463 self.expr(test)?;
3464 self.emit(Opcode::StrictEq, &[]);
3465 if first + offset < last {
3466 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3467 } else {
3468 // Hand over to the next run's tests, or give up.
3469 let next = match runs.get(run + 1) {
3470 Some(_) => run_labels[run + 1],
3471 None => miss_target,
3472 };
3473 self.emit_jump(Opcode::IfFalse, next, &[]);
3474 }
3475 }
3476
3477 self.place_label(body_labels[index]);
3478 for case in &cases[first..=last] {
3479 self.stmts(&case.body)?;
3480 }
3481 index = last + 1;
3482 run += 1;
3483 } else {
3484 // `default`: control arrives here either by falling through or
3485 // because every test missed.
3486 self.place_label(body_labels[index]);
3487 self.stmts(&cases[index].body)?;
3488 index += 1;
3489 }
3490 }
3491 Ok(())
3492 })();
3493
3494 if result.is_ok() {
3495 self.place_label(break_label);
3496 // Discard the discriminant now that no test needs it.
3497 self.emit(Opcode::Drop, &[]);
3498 }
3499
3500 self.pop_jump_target();
3501 self.emit_scope_leave(switch_key);
3502 self.state().current_block = switch_parent;
3503 result
3504 }
3505
3506 /// Compile `try`/`catch`/`finally`.
3507 ///
3508 /// The shape is an exception table built out of `catch` instructions, each of
3509 /// which records where control goes if the instructions that follow raise:
3510 ///
3511 /// ```text
3512 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
3513 /// <guarded block>
3514 /// drop <- discard the catch offset
3515 /// undefined; gosub FINALLY; drop
3516 /// goto END
3517 /// HANDLER:
3518 /// <bind the catch parameter>
3519 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
3520 /// <handler body>
3521 /// drop; undefined; gosub FINALLY; drop; goto END
3522 /// CATCH2:
3523 /// gosub FINALLY; throw <- run the finalizer, then let the error out
3524 /// FINALLY:
3525 /// <finalizer>
3526 /// ret <- return to the `gosub`
3527 /// END:
3528 /// ```
3529 ///
3530 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3531 /// of the finalizer serves the normal path, the handler path and the
3532 /// propagating-exception path.
3533 ///
3534 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3535 /// runs with `ret_value` on the stack, and the normal path has no value to
3536 /// keep, so it pushes one to keep the stack depth identical on every path.
3537 fn try_stmt(
3538 &mut self,
3539 stmt: &Stmt,
3540 block: &[Stmt],
3541 handler: &Option<CatchClause>,
3542 finalizer: Option<&[Stmt]>,
3543 ) -> Result<(), SyntaxError> {
3544 self.reset_value();
3545
3546 let catch_label = self.new_label();
3547 let catch2_label = self.new_label();
3548 let finally_label = self.new_label();
3549 let end_label = self.new_label();
3550
3551 self.emit_jump(Opcode::Catch, catch_label, &[]);
3552
3553 // The guarded block. `break` may not target it, so its entry exists purely
3554 // to unwind: a jump out has to discard the catch offset and run the
3555 // finalizer.
3556 self.push_jump_target(JumpTarget {
3557 names: Vec::new(),
3558 break_label: None,
3559 continue_label: None,
3560 drop_count: 1,
3561 finally_label: Some(finally_label),
3562 is_regular_stmt: false,
3563 has_iterator: false,
3564 is_async_iterator: false,
3565 });
3566
3567 let block_key = Self::try_block_key(stmt, TryPart::Block);
3568 let block_parent = self.cur().current_block;
3569 self.push_block(block_key, block_parent);
3570 self.emit_scope_enter(block_key);
3571 self.stmts(block)?;
3572 self.emit_scope_leave(block_key);
3573 self.state().current_block = block_parent;
3574 // A guarded block that ends in a `return`/`throw` never reaches the
3575 // epilogue, so the reference does not emit one.
3576 self.pop_jump_target();
3577 let block_live = !block.last().is_some_and(Self::terminates);
3578
3579 if block_live {
3580 self.emit(Opcode::Drop, &[]);
3581 self.emit(Opcode::Undefined, &[]);
3582 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3583 self.emit(Opcode::Drop, &[]);
3584 self.emit_jump(Opcode::Goto, end_label, &[]);
3585 }
3586
3587 if let Some(handler) = handler {
3588 self.place_label(catch_label);
3589 // The thrown value is on top of the stack: bind it, or discard it for
3590 // `catch { }`.
3591 match &handler.param {
3592 Some(pattern) => {
3593 // The stores resolve the names, so they have to run inside the
3594 // parameter's own scope; otherwise a same-named `catch` further out
3595 // could win. A `catch` binding is never in the dead zone, so the store
3596 // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3597 let param_key = Self::try_block_key(stmt, TryPart::Param);
3598 let param_parent = self.cur().current_block;
3599 self.push_block(param_key, param_parent);
3600 self.destructure(pattern, Some(VarDeclKind::Var))?;
3601 self.state().current_block = param_parent;
3602 }
3603 None => self.emit(Opcode::Drop, &[]),
3604 }
3605 self.emit_jump(Opcode::Catch, catch2_label, &[]);
3606
3607 self.push_jump_target(JumpTarget {
3608 names: Vec::new(),
3609 break_label: None,
3610 continue_label: None,
3611 drop_count: 1,
3612 finally_label: Some(finally_label),
3613 is_regular_stmt: false,
3614 has_iterator: false,
3615 is_async_iterator: false,
3616 });
3617 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3618 let catch_parent = self.cur().current_block;
3619 self.push_block(catch_key, catch_parent);
3620 self.emit_scope_enter(catch_key);
3621 self.stmts(&handler.body)?;
3622 self.emit_scope_leave(catch_key);
3623 self.state().current_block = catch_parent;
3624 self.pop_jump_target();
3625 let handler_live = !handler.body.last().is_some_and(Self::terminates);
3626
3627 if handler_live {
3628 self.emit(Opcode::Drop, &[]);
3629 self.emit(Opcode::Undefined, &[]);
3630 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3631 self.emit(Opcode::Drop, &[]);
3632 self.emit_jump(Opcode::Goto, end_label, &[]);
3633 }
3634
3635 // An error raised inside the handler still has to run the finalizer.
3636 self.place_label(catch2_label);
3637 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3638 self.emit(Opcode::Throw, &[]);
3639 } else {
3640 // `try`/`finally` with no handler: the finalizer runs, then the error
3641 // keeps propagating.
3642 self.place_label(catch_label);
3643 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3644 self.emit(Opcode::Throw, &[]);
3645 }
3646
3647 self.place_label(finally_label);
3648 // Inside the finalizer, leaving has a different cost: the return value and
3649 // the `gosub` return address are both on the stack, and neither finalizer nor
3650 // any outer one may run before the block has finished.
3651 self.push_jump_target(JumpTarget {
3652 names: Vec::new(),
3653 break_label: None,
3654 continue_label: None,
3655 drop_count: 2,
3656 finally_label: None,
3657 is_regular_stmt: false,
3658 has_iterator: false,
3659 is_async_iterator: false,
3660 });
3661 if let Some(finalizer) = finalizer {
3662 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3663 let finally_parent = self.cur().current_block;
3664 self.push_block(finally_key, finally_parent);
3665 self.emit_scope_enter(finally_key);
3666 self.stmts(finalizer)?;
3667 self.emit_scope_leave(finally_key);
3668 self.state().current_block = finally_parent;
3669 }
3670 self.pop_jump_target();
3671 self.emit(Opcode::Ret, &[]);
3672 self.place_label(end_label);
3673 Ok(())
3674 }
3675
3676 /// Compile `for`/`in` and `for`/`of`.
3677 ///
3678 /// Both keep an enumeration record on the value stack for the whole loop, which
3679 /// is what makes leaving early expensive: the record has to be dropped, or the
3680 /// iterator closed. The layout is
3681 ///
3682 /// ```text
3683 /// <iterated expression>
3684 /// for_in_start | for_of_start <- pushes the record
3685 /// goto TEST
3686 /// NEXT:
3687 /// <bind the loop variable>
3688 /// <body>
3689 /// TEST:
3690 /// for_in_next | for_of_next 0
3691 /// if_false NEXT <- not finished: next iteration
3692 /// drop <- finished: discard the leftover value
3693 /// BREAK:
3694 /// drop | iterator_close <- the one cleanup `break` also uses
3695 /// ```
3696 ///
3697 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3698 /// normal exit share one copy — which is why `break` inside the loop emits nothing
3699 /// of its own, and only a jump that passes *through* the loop pays for its record.
3700 fn for_in_of(
3701 &mut self,
3702 stmt: &Stmt,
3703 left: &ForHead,
3704 right: &Expr,
3705 body: &Stmt,
3706 kind: ForLoopKind,
3707 labels: &[String],
3708 ) -> Result<(), SyntaxError> {
3709 self.reset_value();
3710
3711 let loop_key = stmt.span.start.offset as u64;
3712 let loop_parent = self.cur().current_block;
3713 self.push_block(loop_key, loop_parent);
3714 self.emit_scope_enter(loop_key);
3715
3716 // The iterated expression is evaluated inside the loop's scope, after the
3717 // bindings exist in the temporal dead zone.
3718 self.expr(right)?;
3719
3720 let next = self.new_label();
3721 let test = self.new_label();
3722 let break_target = self.new_label();
3723
3724 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3725 match kind {
3726 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3727 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3728 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3729 }
3730 self.emit_jump(Opcode::Goto, test, &[]);
3731
3732 self.push_jump_target(JumpTarget {
3733 // `outer: for (x of xs) … break outer` needs the name here. Without it the
3734 // loop had no label to break to, and the compiler reported "break has no
3735 // enclosing loop" for a loop that was plainly enclosing it.
3736 names: labels.to_vec(),
3737 break_label: Some(break_target),
3738 continue_label: Some(test),
3739 // Passing through the loop has to dispose of its record. A `for`/`of`
3740 // record is three slots, and closing the iterator consumes all of them.
3741 drop_count: if has_iterator { 3 } else { 1 },
3742 finally_label: None,
3743 is_regular_stmt: false,
3744 has_iterator,
3745 is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3746 });
3747
3748 self.place_label(next);
3749 self.bind_loop_variable(left)?;
3750
3751 // The reference marks the body with its own label here. Nothing jumps to it
3752 // once the loop is laid out, but it is not decoration: a label between the
3753 // store and the body is why `put_loc v; get_loc v` does *not* fold into
3754 // `set_loc v` when the body starts by reading the loop variable.
3755 let body_label = self.new_label();
3756 self.place_label(body_label);
3757 // `for (using x of …)` disposes once per iteration, so the body is a disposal
3758 // region rather than the whole loop: the resource is the element that this
3759 // iteration produced.
3760 let using_slot = match left {
3761 ForHead::VarDecl(decl) if decl.kind.is_using() => {
3762 decl.declarators
3763 .first()
3764 .and_then(|declarator| match &declarator.target.kind {
3765 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3766 _ => None,
3767 })
3768 }
3769 _ => None,
3770 };
3771 match using_slot {
3772 Some(slot) => {
3773 let live = !Self::terminates(body);
3774 self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3775 }
3776 None => self.stmt(body)?,
3777 }
3778
3779 // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
3780 // binding each iteration**, so a closure the body creates keeps that iteration's
3781 // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
3782 // a new reference cell holding the current value.
3783 //
3784 // The position is the *end* of the body, not the start: closing before the body
3785 // would leave the closures pointing at the cell the next `put_loc` overwrites, and
3786 // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
3787 for name in Self::loop_binding_names(left) {
3788 let pos = self.cur().cur_pos;
3789 self.state().insns.push(Insn::CloseCaptured {
3790 name,
3791 block: loop_key,
3792 });
3793 self.state().insn_pos.push(pos);
3794 }
3795 self.place_label(test);
3796 match kind {
3797 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3798 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3799 ForLoopKind::AwaitOf => {
3800 // The reference's shape: step, `await` the result, then unpack it.
3801 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3802 self.emit(Opcode::Await, &[]);
3803 self.state().has_await = true;
3804 self.emit(Opcode::IteratorGetValueDone, &[]);
3805 }
3806 }
3807 self.emit_jump(Opcode::IfFalse, next, &[]);
3808 // The loop is finished; `for_xx_next` left an `undefined` behind.
3809 self.emit(Opcode::Drop, &[]);
3810
3811 self.pop_jump_target();
3812 self.place_label(break_target);
3813 if has_iterator {
3814 // A loop that ran to completion finds its iterator slot already cleared (see
3815 // `iterator_get_value_done`), so this closes only an iterator abandoned by a
3816 // `break` that jumped here.
3817 self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
3818 } else {
3819 self.emit(Opcode::Drop, &[]);
3820 }
3821
3822 self.emit_scope_leave(loop_key);
3823 self.state().current_block = loop_parent;
3824 Ok(())
3825 }
3826
3827 /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
3828 /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
3829 fn loop_binding_names(left: &ForHead) -> Vec<String> {
3830 let ForHead::VarDecl(decl) = left else {
3831 return Vec::new();
3832 };
3833 if decl.kind == VarDeclKind::Var {
3834 return Vec::new();
3835 }
3836 let mut names = Vec::new();
3837 for declarator in &decl.declarators {
3838 let mut idents = Vec::new();
3839 declarator.target.bound_names(&mut idents);
3840 names.extend(idents.into_iter().map(|ident| ident.name));
3841 }
3842 names
3843 }
3844
3845 /// Store the value `for_xx_next` left on the stack into the loop variable.
3846 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3847 // A declaration *initialises* the binding, which is what takes a `let` out of
3848 // the temporal dead zone, so the store is the unchecked form. Assigning to a
3849 // binding declared elsewhere is an ordinary write and keeps its check.
3850 let (pattern, action) = match left {
3851 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3852 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3853 };
3854 match &pattern.kind {
3855 PatternKind::Ident(name) => {
3856 // `for (using x of …)` validates and snapshots each iteration's value
3857 // before the body runs, which is what makes a non-disposable element fail
3858 // on the iteration that produced it rather than at the end of the loop.
3859 if let ForHead::VarDecl(decl) = left
3860 && decl.kind.is_using()
3861 {
3862 let method_slot = self
3863 .using_method_slot(&name.name)
3864 .expect("a using binding was declared during hoisting");
3865 self.emit(
3866 Opcode::UsingCheck,
3867 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3868 );
3869 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3870 }
3871 self.emit_var(action, &name.name);
3872 Ok(())
3873 }
3874 // Every other target stores through the same path an assignment pattern
3875 // uses, which is what makes `for (a[0] in obj)` write each key into the
3876 // property instead of refusing the loop outright.
3877 _ => self.destructure(
3878 pattern,
3879 match left {
3880 ForHead::VarDecl(decl) => Some(decl.kind),
3881 ForHead::Assign(_) => None,
3882 },
3883 ),
3884 }
3885 }
3886
3887 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3888 for declarator in &decl.declarators {
3889 let Some(init) = &declarator.init else {
3890 // `var x;` stays `undefined`. A lexical binding is different: it
3891 // has to be *initialised* to leave the temporal dead zone, so the
3892 // compiler supplies an explicit `undefined`.
3893 if decl.kind.is_lexical() {
3894 // A lexical binding has to be *initialised* to leave the temporal
3895 // dead zone, and a destructuring one is no different — `let {a}`
3896 // with no initialiser is a syntax error, but `let [a] = []` still
3897 // needs `a` to be initialised from an empty source, which the
3898 // pattern does on its own.
3899 self.emit(Opcode::Undefined, &[]);
3900 self.destructure(&declarator.target, Some(decl.kind))?;
3901 }
3902 continue;
3903 };
3904 match &declarator.target.kind {
3905 PatternKind::Ident(name) => {
3906 self.expr(init)?;
3907 self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
3908 if decl.kind.is_using() {
3909 // `using_check` validates the value and snapshots its dispose
3910 // method: `value -> value, method`. The snapshot is what makes a
3911 // later change to `Symbol.dispose` irrelevant, and validating here
3912 // is what keeps the body from running at all when the value is not
3913 // disposable.
3914 let method_slot = self
3915 .using_method_slot(&name.name)
3916 .expect("a using binding was declared during hoisting");
3917 self.emit(
3918 Opcode::UsingCheck,
3919 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3920 );
3921 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3922 self.emit_var(VarAction::PutInit, &name.name);
3923 continue;
3924 }
3925 // A declaration statement produces no value, so nothing is
3926 // duplicated onto the stack.
3927 match decl.kind {
3928 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3929 _ => self.emit_var(VarAction::PutInit, &name.name),
3930 }
3931 }
3932 _ => {
3933 // A destructuring declaration keeps nothing on the stack: the
3934 // pattern consumes the initialiser.
3935 self.expr(init)?;
3936 self.destructure(&declarator.target, Some(decl.kind))?;
3937 }
3938 }
3939 }
3940 Ok(())
3941 }
3942
3943 /// Bind a destructuring pattern from the value on top of the stack.
3944 ///
3945 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
3946 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
3947 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
3948 /// *assignment*, where a member expression is a legal target and the store is an
3949 /// ordinary property write.
3950 ///
3951 /// The value is consumed. An assignment expression's own result is the right-hand
3952 /// side, which the caller keeps separately — the spec does not make the pattern's
3953 /// last store produce it.
3954 fn destructure(
3955 &mut self,
3956 pattern: &Pattern,
3957 decl: Option<VarDeclKind>,
3958 ) -> Result<(), SyntaxError> {
3959 match &pattern.kind {
3960 PatternKind::Ident(name) => {
3961 match decl {
3962 Some(VarDeclKind::Var) | None => {
3963 self.emit_var(VarAction::Put, &name.name);
3964 }
3965 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
3966 }
3967 Ok(())
3968 }
3969 PatternKind::Assign { target, default } => {
3970 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
3971 // keeps `null`.
3972 //
3973 // The shape is the reference's: test for `undefined`, and when the value is
3974 // present fall **through** to a single store both paths share. The
3975 // alternatives — branching to the store on each side — need a second store
3976 // and a jump between them, which is what the dump used to show.
3977 let has_value = self.new_label();
3978 self.emit(Opcode::Dup, &[]);
3979 self.emit(Opcode::IsUndefined, &[]);
3980 self.emit_jump(Opcode::IfFalse, has_value, &[]);
3981 self.emit(Opcode::Drop, &[]);
3982 self.expr(default)?;
3983 // `var {f = function(){}} = {}` names the function `f`, like a plain
3984 // `var f = function(){}` does. Both pattern forms do it:
3985 // `BindingInitialization` names the value for a *binding* target, and since
3986 // ES2018 `DestructuringAssignmentEvaluation` does the same, so
3987 // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
3988 // no name to give, which is why only an identifier qualifies.
3989 if let PatternKind::Ident(name) = &target.kind {
3990 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
3991 }
3992 self.place_label(has_value);
3993 self.destructure(target, decl)
3994 }
3995 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
3996 PatternKind::Object { properties, rest } => {
3997 self.destructure_object(properties, rest, decl, pattern)
3998 }
3999 PatternKind::Member(member) if decl.is_none() => {
4000 // An assignment pattern may store into a property. The value is on the
4001 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4002 // put the three in the order `put_array_el`/`put_field` expect.
4003 self.expr(&member.object)?;
4004 match &member.property {
4005 MemberProp::Ident(name) => {
4006 // `value obj` -> `obj value`, the order `put_field` takes.
4007 // Nothing needs to be left behind: a pattern element's value is
4008 // consumed by its own store.
4009 self.emit(Opcode::Swap, &[]);
4010 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4011 }
4012 MemberProp::Computed(index) => {
4013 self.expr(index)?;
4014 // `value obj key` -> `obj key value`.
4015 self.emit(Opcode::Rot3l, &[]);
4016 self.emit(Opcode::PutArrayEl, &[]);
4017 }
4018 MemberProp::Private(name) => {
4019 // `value obj` -> `obj value`, and the store half of the assignment is
4020 // the same one `obj.#x = value` uses — only without `insert2`,
4021 // because a pattern element's value is not wanted back.
4022 let binding = format!("#{}", name.name);
4023 let (kind, setter) = self.private_use(&binding, member.span)?;
4024 self.emit(Opcode::Swap, &[]);
4025 self.private_store(&binding, kind, setter.as_deref())?;
4026 }
4027 }
4028 Ok(())
4029 }
4030 PatternKind::Rest(inner) => self.destructure(inner, decl),
4031 PatternKind::Invalid(expr) => {
4032 Err(SyntaxError::new("invalid assignment target", expr.span))
4033 }
4034 _ => Err(SyntaxError::new(
4035 "this destructuring target is not supported by the compiler yet",
4036 pattern.span,
4037 )),
4038 }
4039 }
4040
4041 /// `[…]` on the left: drain an iterator, binding one target per element.
4042 fn destructure_array(
4043 &mut self,
4044 elements: &[Option<PatternElement>],
4045 rest: &Option<Box<RestElement>>,
4046 decl: Option<VarDeclKind>,
4047 ) -> Result<(), SyntaxError> {
4048 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4049 // pattern accepts any iterable and closes the iterator when the pattern ends
4050 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4051 // first because it is on top.
4052 self.emit(Opcode::ForOfStart, &[]);
4053 for element in elements {
4054 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4055 self.emit(Opcode::Drop, &[]);
4056 match element {
4057 Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
4058 Some(PatternElement::Property { span, .. }) => {
4059 return Err(SyntaxError::new(
4060 "a property pattern is not a valid array element",
4061 *span,
4062 ));
4063 }
4064 // An elision skips the value, which is already on the stack.
4065 None => self.emit(Opcode::Drop, &[]),
4066 }
4067 }
4068 if let Some(rest) = rest {
4069 // The remaining values go into a fresh array. The target and its running
4070 // index stay on the stack above the iterator, which is what the operand of
4071 // `for_of_next` accounts for: two values sit above the iterator triple.
4072 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4073 self.emit(Opcode::Push0, &[]);
4074 let top = self.new_label();
4075 self.place_label(top);
4076 self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
4077 let done = self.new_label();
4078 self.emit_jump(Opcode::IfTrue, done, &[]);
4079 self.emit(Opcode::DefineArrayEl, &[]);
4080 self.emit(Opcode::Inc, &[]);
4081 self.emit_jump(Opcode::Goto, top, &[]);
4082 self.place_label(done);
4083 self.emit(Opcode::Drop, &[]);
4084 self.emit(Opcode::Drop, &[]);
4085 self.destructure_rest(rest, decl)?;
4086 }
4087 self.emit(Opcode::IteratorClose, &[]);
4088 Ok(())
4089 }
4090
4091 /// `{…}` on the left: read properties off one boxed source object.
4092 fn destructure_object(
4093 &mut self,
4094 properties: &[Option<PatternElement>],
4095 rest: &Option<Box<RestElement>>,
4096 decl: Option<VarDeclKind>,
4097 pattern: &Pattern,
4098 ) -> Result<(), SyntaxError> {
4099 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4100 // aside for the rest element below.
4101 self.emit(Opcode::ToObject, &[]);
4102 let mut taken: Vec<Wtf8> = Vec::new();
4103 // Whether any key was computed, which a rest element cannot exclude.
4104 let mut computed = false;
4105 for property in properties {
4106 let Some(PatternElement::Property {
4107 key, value, span, ..
4108 }) = property
4109 else {
4110 return Err(SyntaxError::new(
4111 "a bare pattern is not a valid object property",
4112 properties
4113 .iter()
4114 .flatten()
4115 .map(|element| match element {
4116 PatternElement::Pattern(pattern) => pattern.span,
4117 PatternElement::Property { span, .. } => *span,
4118 })
4119 .next()
4120 .unwrap_or(pattern.span),
4121 ));
4122 };
4123 // Every read needs the source twice: to read from, and to keep for the next
4124 // property. `get_field2` is that duplicate-and-read in one instruction, but it
4125 // leaves the copy *under* the value, so it is only usable when whatever
4126 // consumes the value tolerates that. See [`reads_with_get_field2`].
4127 let nested = reads_with_get_field2(decl, value);
4128 if !nested {
4129 self.emit(Opcode::Dup, &[]);
4130 }
4131 match key {
4132 PropName::Literal(literal) => {
4133 let name = self.property_key_text(literal, *span)?;
4134 taken.push(name.clone());
4135 self.emit(
4136 if nested {
4137 Opcode::GetField2
4138 } else {
4139 Opcode::GetField
4140 },
4141 &[Op::Atom(Atom::from_wtf8(&name))],
4142 );
4143 }
4144 PropName::Computed(index) => {
4145 // A computed key has no name to exclude ahead of time, so a rest
4146 // element that has to skip it is refused below rather than silently
4147 // copying the property into the rest object.
4148 computed = true;
4149 self.expr(index)?;
4150 self.emit(Opcode::GetArrayEl, &[]);
4151 }
4152 PropName::Private(_) => {
4153 return Err(SyntaxError::new(
4154 "private fields are not supported by the compiler yet",
4155 value.span,
4156 ));
4157 }
4158 }
4159 self.destructure(value, decl)?;
4160 }
4161 match rest {
4162 Some(rest) => {
4163 if computed {
4164 return Err(SyntaxError::new(
4165 "a computed key with a rest element is not supported by the compiler yet",
4166 Self::rest_span(rest),
4167 ));
4168 }
4169 // `target src exclude`: the exclusion list is an array of the keys the
4170 // literal part already took, so the rest object gets only the others.
4171 self.emit(Opcode::Object, &[]);
4172 self.emit(Opcode::Swap, &[]);
4173 for name in &taken {
4174 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4175 }
4176 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4177 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4178 self.emit(Opcode::Drop, &[]);
4179 self.emit(Opcode::Drop, &[]);
4180 self.destructure_rest(rest, decl)?;
4181 }
4182 // The source was only kept for a rest element.
4183 None => self.emit(Opcode::Drop, &[]),
4184 }
4185 Ok(())
4186 }
4187
4188 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4189 fn destructure_rest(
4190 &mut self,
4191 rest: &RestElement,
4192 decl: Option<VarDeclKind>,
4193 ) -> Result<(), SyntaxError> {
4194 match rest {
4195 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4196 // `[...a.b] = c` stores into a property.
4197 RestElement::Member(member) => {
4198 let pattern = Pattern {
4199 kind: PatternKind::Member(member.clone()),
4200 span: member.span,
4201 };
4202 self.destructure(&pattern, decl)
4203 }
4204 }
4205 }
4206
4207 /// The source range of a rest element, for error messages.
4208 fn rest_span(rest: &RestElement) -> Span {
4209 match rest {
4210 RestElement::Pattern(pattern) => pattern.span,
4211 RestElement::Member(member) => member.span,
4212 }
4213 }
4214
4215 /// Compile a function declaration and queue it for instantiation at scope
4216 /// entry.
4217 ///
4218 /// A declaration is visible before the statement that declares it, so the
4219 /// code that creates the function object belongs at the top of the enclosing
4220 /// scope, not at the declaration.
4221 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4222 let name = func.name.as_ref().expect("a declaration has a name");
4223 let function = self.compile_function(func)?;
4224 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4225 let target = self.hoist_target(&name.name);
4226 let block = self.cur().current_block;
4227 self.state().hoisted.push((block, target, pool_index));
4228 Ok(())
4229 }
4230
4231 /// Where a name lives, for a hoisted declaration.
4232 fn hoist_target(&self, name: &str) -> HoistTarget {
4233 let state = self.cur();
4234 if let Some(index) = state.args.iter().position(|a| a.name == name) {
4235 return HoistTarget::Arg(index as u32);
4236 }
4237 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4238 return HoistTarget::Loc(index as u32);
4239 }
4240 // A global function declaration is not a slot at all.
4241 HoistTarget::Global(name.to_string())
4242 }
4243
4244 // -- expressions -------------------------------------------------------
4245
4246 /// Compile one expression, recording where its instructions sit.
4247 ///
4248 /// The position is the node's operator when it has one and its first token
4249 /// otherwise, and it is restored on the way out so a parent's own instructions —
4250 /// which are emitted *after* its children — are blamed on the parent. Without the
4251 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4252 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4253 // `discard_value` belongs to the *statement* that is about to be compiled, so it
4254 // may only be honoured by that statement's own top-level expression. Taking it here
4255 // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4256 // the argument list is a different expression — it must still leave its value on the
4257 // stack. Without this the argument vanished, and `call` then consumed the callee as
4258 // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4259 // function).
4260 self.discard_root = std::mem::take(&mut self.state().discard_value);
4261 let saved = self.cur().cur_pos;
4262 // Only the node kinds the reference calls `emit_source_pos` for record a position:
4263 // the operator a node exists for, and a variable *read*, which the reference
4264 // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4265 // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4266 // start, a parenthesised group, an anonymous function expression — leaves the
4267 // previous position in place, because a table entry the reference never writes is
4268 // one we must not write either: the instruction that inherits a position (the
4269 // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4270 // report a more recent token than the reference does.
4271 let pos = expr.op_pos.or(match &expr.kind {
4272 ExprKind::Ident(ident) => Some(ident.span.start),
4273 _ => None,
4274 });
4275 match pos {
4276 Some(pos) => self.state().cur_pos = Some(pos),
4277 // A node the reference records nothing for: its own instructions stay
4278 // unpositioned, so they inherit whatever was written last — which is what an
4279 // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4280 // enclosing position instead would blame them on a token the reference has not
4281 // reached yet: a spread's `iterator_open` reports the expression it follows, and
4282 // a template's `to_propkey` the interpolation.
4283 None => self.state().cur_pos = None,
4284 }
4285 // Note a direct `eval` call before compiling it, because the *whole* function
4286 // is affected: an eval can name any binding the function declares, so every one
4287 // of them has to live in a cell for a closure it creates to capture it.
4288 if Self::is_direct_eval(expr) {
4289 // Every enclosing function is affected too: the eval sees the whole scope
4290 // chain, and a closure it creates can capture a binding of any of them.
4291 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
4292 // cell, because the closure the eval builds outlives the loop iteration.
4293 for state in &mut self.stack {
4294 state.has_direct_eval = true;
4295 }
4296 let block = self.cur().current_block;
4297 let in_params = self.cur().in_params;
4298 self.state()
4299 .pending_eval_sites
4300 .push((expr.span, block, in_params));
4301 }
4302 let result = self.expr_inner(expr);
4303 self.discard_root = false;
4304 self.state().cur_pos = saved;
4305 result
4306 }
4307
4308 /// Record which bindings are in scope at a direct `eval` call.
4309 ///
4310 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4311 /// resolves names from a string at run time, so the only chance to pin down *which*
4312 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4313 /// its block is the current block, an enclosing one, or the function scope.
4314 fn materialize_eval_sites(&mut self) {
4315 let pending = std::mem::take(&mut self.state().pending_eval_sites);
4316 for (span, site_block, in_params) in pending {
4317 self.resolve_eval_site(span, site_block, in_params);
4318 }
4319 }
4320
4321 /// Resolve the bindings visible at one `eval` call.
4322 fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
4323 /// How near a binding is: function distance first, then block depth, then the
4324 /// later declaration (which shadows the earlier one in the same block).
4325 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4326
4327 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4328 // walked, innermost function first: a direct `eval` sees every enclosing
4329 // function's bindings, and none of them can be resolved at run time because the
4330 // runtime only has names to go on.
4331 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4332 let deepest = self.stack.len() - 1;
4333 for (level, state) in self.stack.iter().enumerate().rev() {
4334 let owner = (deepest - level) as u32;
4335 // The innermost function's block is the one the call sat in, which is not
4336 // the block the compiler is in now; the enclosing functions are still at
4337 // the point where this one was created.
4338 let here = if level == deepest {
4339 site_block
4340 } else {
4341 state.current_block
4342 };
4343 // The chain of live blocks, innermost first, with a depth for each. The walk
4344 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4345 // block can start at source offset zero.
4346 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4347 let mut block = here;
4348 while let Some(parent) = state
4349 .blocks
4350 .iter()
4351 .find(|candidate| candidate.key == block)
4352 .map(|candidate| candidate.parent)
4353 .filter(|parent| *parent != NO_PARENT)
4354 .filter(|parent| parent != &block)
4355 {
4356 live.push((parent, live.len()));
4357 block = parent;
4358 }
4359 let depth_of = |key: u64| {
4360 live.iter()
4361 .find(|(candidate, _)| *candidate == key)
4362 .map(|(_, depth)| *depth)
4363 // The function scope is the outermost depth there is. A binding of a
4364 // block this site is not inside lands here too, which pushes it
4365 // behind every live one — the right answer: it is out of scope.
4366 .unwrap_or(live.len())
4367 };
4368 for (index, arg) in state.args.iter().enumerate() {
4369 bindings.push((
4370 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4371 EvalVisible {
4372 name: arg.name.clone(),
4373 is_arg: true,
4374 index: index as u32,
4375 owner,
4376 },
4377 ));
4378 }
4379 // A parameter list cannot see the body, so a body `var` is not a binding the
4380 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4381 // not let that eval write the body's `c`.
4382 let hides_body = if level == deepest {
4383 site_in_params
4384 } else {
4385 state.created_in_params
4386 };
4387 for (index, var) in state.vars.iter().enumerate() {
4388 let block = state
4389 .var_block
4390 .get(index)
4391 .copied()
4392 .unwrap_or(FUNCTION_SCOPE);
4393 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4394 continue;
4395 }
4396 bindings.push((
4397 (
4398 owner as usize,
4399 depth_of(block),
4400 std::cmp::Reverse(index as u32),
4401 ),
4402 EvalVisible {
4403 name: var.name.clone(),
4404 is_arg: false,
4405 index: index as u32,
4406 owner,
4407 },
4408 ));
4409 }
4410 }
4411 // Innermost function first, then innermost block, then the later declaration
4412 // (which shadows the earlier one within a block).
4413 bindings.sort_by_key(|(priority, _)| *priority);
4414 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4415 self.state().eval_sites.push(EvalSite {
4416 line: span.start.line,
4417 column: span.start.column,
4418 bindings,
4419 });
4420 }
4421
4422 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4423 ///
4424 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4425 /// a bare identifier callee counts.
4426 fn is_direct_eval(expr: &Expr) -> bool {
4427 matches!(
4428 &expr.kind,
4429 ExprKind::Call { callee, .. }
4430 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4431 )
4432 }
4433
4434 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4435 match &expr.kind {
4436 ExprKind::Number(value) => self.push_number(*value),
4437 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4438 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4439 ExprKind::Null => self.emit(Opcode::Null, &[]),
4440 ExprKind::String(text) => self.push_string(text),
4441 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4442 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4443 ExprKind::This => self.this_expression(),
4444 ExprKind::NewTarget => self.new_target_expression(),
4445 ExprKind::Paren(inner) => self.expr(inner)?,
4446 ExprKind::Binary { op, left, right } => {
4447 self.expr(left)?;
4448 self.expr(right)?;
4449 self.emit(binary_opcode(*op), &[]);
4450 }
4451 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4452 ExprKind::Unary {
4453 op: UnaryOp::Minus,
4454 argument,
4455 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4456 let ExprKind::Number(value) = argument.unparen().kind else {
4457 unreachable!("matched above")
4458 };
4459 // The reference folds a negative literal only when the negation is
4460 // exact in the integer range: `-1` becomes `push_minus1` and
4461 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4462 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4463 // `-Infinity`, not `Infinity` — and folding a fraction would change
4464 // which instruction the reference emits.
4465 let negated = -value;
4466 // `-2147483648` is deliberately excluded: its magnitude is one past
4467 // `i32::MAX`, so the reference sends it through the constant pool and
4468 // negates at run time instead.
4469 if value > 0.0
4470 && negated == negated.trunc()
4471 && negated >= -(i32::MAX as f64)
4472 && negated < 0.0
4473 {
4474 self.push_number(negated);
4475 } else {
4476 self.push_number(value);
4477 self.emit(Opcode::Neg, &[]);
4478 }
4479 }
4480 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4481 ExprKind::Conditional { test, cons, alt } => {
4482 let else_label = self.new_label();
4483 let end_label = self.new_label();
4484 self.expr(test)?;
4485 self.emit_jump(Opcode::IfFalse, else_label, &[]);
4486 self.expr(cons)?;
4487 self.emit_jump(Opcode::Goto, end_label, &[]);
4488 self.place_label(else_label);
4489 self.expr(alt)?;
4490 self.place_label(end_label);
4491 }
4492 ExprKind::Assign { op, target, value } => {
4493 let discard = std::mem::take(&mut self.discard_root);
4494 self.assign(*op, target, value, discard)?
4495 }
4496 ExprKind::Update {
4497 op,
4498 argument,
4499 prefix,
4500 } => self.update(*op, argument, *prefix)?,
4501 ExprKind::Sequence(items) => {
4502 for (index, item) in items.iter().enumerate() {
4503 self.expr(item)?;
4504 if index + 1 != items.len() {
4505 self.emit(Opcode::Drop, &[]);
4506 }
4507 }
4508 }
4509 ExprKind::Call { .. } => self.chain_link_top(expr)?,
4510 ExprKind::Member { .. } => self.chain_link_top(expr)?,
4511 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4512 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4513 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4514 ExprKind::Template(template) => self.template_literal(template)?,
4515 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4516 ExprKind::New { callee, arguments } => {
4517 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4518 // The `dup` is not redundant: `call_constructor` takes the
4519 // constructor twice, once as the target and once as `new.target`,
4520 // which is what makes `new.target === C` inside the body.
4521 self.expr(callee)?;
4522 self.emit(Opcode::Dup, &[]);
4523 let args = arguments.as_deref().unwrap_or(&[]);
4524 if Self::has_spread(args) {
4525 // `C C array`: the duplicated callee is already both the target
4526 // and `new.target`, so no reordering is needed before `apply 1`.
4527 self.argument_array(args)?;
4528 self.emit(Opcode::Apply, &[Op::Int(1)]);
4529 return Ok(());
4530 }
4531 for argument in args {
4532 self.expr(argument)?;
4533 }
4534 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4535 }
4536 ExprKind::Class(class) => self.class_definition(class, true)?,
4537 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4538 ExprKind::Yield { argument, delegate } => {
4539 self.yield_expression(argument.as_deref(), *delegate)?
4540 }
4541 ExprKind::Await(argument) => self.await_expression(argument)?,
4542 ExprKind::RegExp { pattern, flags } => {
4543 // A literal is compiled *here*, at parse time, not when the line runs. The
4544 // spec is explicit that an invalid pattern is an early error (§12.9.4:
4545 // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
4546 // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
4547 // also validates `\p{…}` names: 163 conformance cases are patterns that have
4548 // to be rejected before any code runs.
4549 //
4550 // This is the whole reason the engine lives in its own crate rather than
4551 // inside `quickjs-pure`: the compiler could not depend on the interpreter
4552 // (`pure` depends on `compile`), but both need this.
4553 // The lexer already rejected an unknown or repeated flag, so an unparsable
4554 // flag string here would be a bug in the lexer rather than in the script;
4555 // fall back to the default flags instead of inventing a second message.
4556 let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
4557 let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
4558 SyntaxError::new(
4559 format!("invalid regular expression: {}", error.message),
4560 expr.span,
4561 )
4562 })?;
4563 // The tree is thrown away and rebuilt when the literal first runs: keeping it
4564 // would mean serialising the syntax tree into the function's constant pool,
4565 // and a literal is created once per evaluation of its expression anyway.
4566 let _ = parsed;
4567 // The pattern and its flags travel as two string constants; `regexp` builds
4568 // the object. A dedicated opcode (rather than a call to the constructor) is
4569 // what the reference does too, so that a literal never goes through the
4570 // public `RegExp` function and its string-coercion rules.
4571 self.push_string(&Wtf8::new(pattern));
4572 self.push_string(&Wtf8::new(flags));
4573 self.emit(Opcode::Regexp, &[]);
4574 }
4575 ExprKind::Arrow(func) => {
4576 let function = self.compile_function(func)?;
4577 let index = self.push_constant(Constant::Function(Box::new(function)));
4578 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4579 }
4580 ExprKind::Function(func) => {
4581 let function = self.compile_function_with_name(func, true)?;
4582 let index = self.push_constant(Constant::Function(Box::new(function)));
4583 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4584 }
4585 // `import.meta`: the host fills a per-module object at link time.
4586 ExprKind::ImportMeta => {
4587 self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
4588 }
4589 // `import("x")` compiles to a two-slot push followed by one opcode: the
4590 // specifier, then the options object. Both are evaluated, in that order, because
4591 // §13.3.10.1 numbers them that way and their side effects are observable — the
4592 // absent second argument is a literal `undefined`, which evaluates to nothing.
4593 ExprKind::ImportCall(specifier, options) => {
4594 self.expr(specifier)?;
4595 match options {
4596 Some(options) => self.expr(options)?,
4597 None => {
4598 self.emit(Opcode::Undefined, &[]);
4599 }
4600 }
4601 self.emit(Opcode::Import, &[]);
4602 }
4603 ExprKind::PrivateIn { name, object } => {
4604 // `#x in o`: the object, then the binding, then one opcode which decides what
4605 // to do with the second operand. A field's binding holds a symbol and the
4606 // answer is an own-property test; a method's holds a function and the answer
4607 // is a brand check — both live in `private_in`, so the compiler emits the
4608 // same instruction for either.
4609 self.expr(object)?;
4610 self.emit_var(VarAction::Get, &format!("#{}", name.name));
4611 self.emit(Opcode::PrivateIn, &[]);
4612 }
4613 _ => {
4614 return Err(SyntaxError::new(
4615 "this expression form is not supported by the compiler yet",
4616 expr.span,
4617 ));
4618 }
4619 }
4620 Ok(())
4621 }
4622
4623 /// Build one array holding the evaluated call arguments, which is how a call
4624 /// containing a spread is compiled: the reference does the same, building the
4625 /// list on the stack and handing it to `apply`.
4626 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4627 let elements: Vec<Option<ArrayElement>> = arguments
4628 .iter()
4629 .map(|argument| match &argument.unparen().kind {
4630 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
4631 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
4632 })
4633 .collect();
4634 self.array_literal(&elements, Span::default())
4635 }
4636
4637 /// Whether any argument is a spread, which is what selects the `apply` form.
4638 fn has_spread(arguments: &[Expr]) -> bool {
4639 arguments
4640 .iter()
4641 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
4642 }
4643
4644 /// Compile `a${x}b`.
4645 ///
4646 /// A template is a `+` chain built left to right: the leading chunk (or an empty
4647 /// string when the template starts with a substitution), then for each
4648 /// substitution its value, `to_propkey` and `add`, then the following chunk when
4649 /// it is not empty. `to_propkey` is what makes a number or object substitute the
4650 /// way `ToString` would while leaving the result a string for `add` to
4651 /// concatenate.
4652 ///
4653 /// The chunk is an atom rather than a constant-pool string, because a non-empty
4654 /// chunk always lands where a value is pushed and `push_atom_value` is the
4655 /// instruction the reference uses for it; the empty first chunk has its own
4656 /// zero-byte form.
4657 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
4658 let first = template.quasis.first();
4659 match first.and_then(|quasi| quasi.cooked.clone()) {
4660 Some(text) if !text.is_empty() => {
4661 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4662 }
4663 // Either the template begins with a substitution, or the chunk is
4664 // empty — in both cases the chain needs a string to start from.
4665 _ => self.emit(Opcode::PushEmptyString, &[]),
4666 }
4667 for (index, expression) in template.expressions.iter().enumerate() {
4668 self.expr(expression)?;
4669 self.emit(Opcode::ToPropkey, &[]);
4670 self.emit(Opcode::Add, &[]);
4671 if let Some(text) = template
4672 .quasis
4673 .get(index + 1)
4674 .and_then(|quasi| quasi.cooked.clone())
4675 && !text.is_empty()
4676 {
4677 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4678 self.emit(Opcode::Add, &[]);
4679 }
4680 }
4681 Ok(())
4682 }
4683
4684 /// Compile an object literal.
4685 ///
4686 /// The object is built in place: `object` pushes it, and each property leaves it
4687 /// on the stack with one field more, so no temporary is needed and later
4688 /// properties can overwrite earlier ones.
4689 ///
4690 /// The instruction depends on *how* the property was written, not on what kind
4691 /// of value it holds:
4692 ///
4693 /// | source | instruction |
4694 /// |---|---|
4695 /// | `{ a: v }` | `define_field a` |
4696 /// | `{ __proto__: v }` | `set_proto` |
4697 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4698 /// | `{ m() {} }` | `define_method m,4` |
4699 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4700 /// | `{ [k]() {} }` | `define_method_computed 4` |
4701 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4702 ///
4703 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
4704 /// key itself, which is why the trailing `drop` is absent there too.
4705 /// `tag`…``: a call whose first argument is the call site's template object.
4706 ///
4707 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
4708 /// array beside it, so `String.raw` can read the source text back. It is a constant
4709 /// because its contents never change; the reference builds one per call site and
4710 /// reuses it, while this builds one per evaluation, which only `tag` code that
4711 /// compares template objects across calls could tell apart.
4712 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
4713 let cooked = quasi
4714 .quasis
4715 .iter()
4716 .map(|chunk| chunk.cooked.clone())
4717 .collect();
4718 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
4719 let index = self.push_constant(Constant::Template { cooked, raw });
4720 let count = quasi.expressions.len() + 1;
4721 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
4722 if let ExprKind::Member {
4723 object, property, ..
4724 } = &tag.unparen().kind
4725 {
4726 self.expr(object)?;
4727 match property {
4728 MemberProp::Ident(name) => {
4729 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
4730 }
4731 MemberProp::Computed(key) => {
4732 self.expr(key)?;
4733 self.emit(Opcode::GetArrayEl2, &[]);
4734 }
4735 MemberProp::Private(name) => {
4736 let binding = format!("#{}", name.name);
4737 let (kind, _) = self.private_use(&binding, tag.span)?;
4738 self.private_callee(&binding, kind)?;
4739 }
4740 }
4741 self.emit(Opcode::PushConst, &[Op::Const(index)]);
4742 for expression in &quasi.expressions {
4743 self.expr(expression)?;
4744 }
4745 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
4746 return Ok(());
4747 }
4748 self.expr(tag)?;
4749 self.emit(Opcode::PushConst, &[Op::Const(index)]);
4750 for expression in &quasi.expressions {
4751 self.expr(expression)?;
4752 }
4753 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
4754 Ok(())
4755 }
4756
4757 fn object_literal(
4758 &mut self,
4759 properties: &[ObjectProperty],
4760 span: Span,
4761 ) -> Result<(), SyntaxError> {
4762 self.emit(Opcode::Object, &[]);
4763 for property in properties {
4764 match property {
4765 ObjectProperty::Spread(value) => {
4766 // `copy_data_properties` takes the target, the source and an
4767 // exclusion list; a literal `null` means "exclude nothing".
4768 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
4769 // exclusion list by stack offset.
4770 self.expr(spread_argument(value))?;
4771 self.emit(Opcode::Null, &[]);
4772 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4773 self.emit(Opcode::Drop, &[]);
4774 self.emit(Opcode::Drop, &[]);
4775 }
4776 ObjectProperty::Property {
4777 key,
4778 value,
4779 kind,
4780 shorthand,
4781 span: property_span,
4782 } => match key {
4783 PropName::Computed(key_expr) => {
4784 self.expr(key_expr)?;
4785 match kind {
4786 PropertyKind::Value => {
4787 self.emit(Opcode::ToPropkey, &[]);
4788 self.expr(value)?;
4789 self.set_name_if_anonymous_computed(value);
4790 self.emit(Opcode::DefineArrayEl, &[]);
4791 // `define_array_el` leaves the object and the key;
4792 // the key is no longer needed.
4793 self.emit(Opcode::Drop, &[]);
4794 }
4795 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4796 self.emit_method_function(value)?;
4797 self.emit(
4798 Opcode::DefineMethodComputed,
4799 &[Op::Int(define_method_flags(*kind))],
4800 );
4801 }
4802 }
4803 }
4804 PropName::Literal(key) => {
4805 let name = self.property_key_text(key, *property_span)?;
4806 match kind {
4807 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4808 self.emit_method_function(value)?;
4809 self.emit(
4810 Opcode::DefineMethod,
4811 &[
4812 Op::Atom(Atom::from_wtf8(&name)),
4813 Op::Int(define_method_flags(*kind)),
4814 ],
4815 );
4816 }
4817 PropertyKind::Value => {
4818 self.expr(value)?;
4819 // `{__proto__: x}` sets the prototype instead of
4820 // creating a property; the shorthand `{__proto__}`
4821 // is an ordinary property and does not.
4822 if name == "__proto__" && !shorthand {
4823 self.emit(Opcode::SetProto, &[]);
4824 } else {
4825 self.set_name_if_anonymous(value, &name);
4826 self.emit(
4827 Opcode::DefineField,
4828 &[Op::Atom(Atom::from_wtf8(&name))],
4829 );
4830 }
4831 }
4832 }
4833 }
4834 PropName::Private(_) => {
4835 return Err(SyntaxError::new(
4836 "private names are not valid in object literals",
4837 *property_span,
4838 ));
4839 }
4840 },
4841 }
4842 }
4843 let _ = span;
4844 Ok(())
4845 }
4846
4847 /// Emit the function a method/accessor property defines.
4848 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
4849 self.expr(value)
4850 }
4851
4852 /// The name a literal property key contributes.
4853 ///
4854 /// String keys are used as written. A numeric key is converted the way
4855 /// `ToString` would convert it, because the atom is made from that spelling:
4856 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
4857 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
4858 match key {
4859 PropKey::Str(text) => Ok(text.clone()),
4860 PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
4861 }
4862 }
4863
4864 /// Compile an optional chain.
4865 ///
4866 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
4867 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
4868 /// `undefined`. So the chain is compiled with one end label and every guard
4869 /// jumps to it. The parser hands us the extent of that spine as an
4870 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
4871 /// exactly the scope the label has to cover.
4872 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
4873 let end = self.new_label();
4874 self.chain_link(inner, end)?;
4875 self.place_label(end);
4876 Ok(())
4877 }
4878
4879 /// A member access or call reached from outside any optional chain.
4880 ///
4881 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
4882 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
4883 /// still created because [`Self::chain_link`] takes it, and placing it at the
4884 /// end is a no-op that keeps a single code path.
4885 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4886 let end = self.new_label();
4887 self.chain_link(expr, end)?;
4888 self.place_label(end);
4889 Ok(())
4890 }
4891
4892 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
4893 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
4894 match &expr.kind {
4895 ExprKind::Member {
4896 object,
4897 property,
4898 optional,
4899 } => {
4900 // `super.x` is not a lookup on a value: it starts at the home object's
4901 // prototype and keeps `this` as the receiver, so it cannot go through
4902 // `chain_link` and the ordinary field read.
4903 if matches!(object.unparen().kind, ExprKind::SuperProp) {
4904 self.super_base();
4905 match property {
4906 MemberProp::Ident(name) => self.emit(
4907 Opcode::PushAtomValue,
4908 &[Op::Atom(Atom::from_text(&name.name))],
4909 ),
4910 MemberProp::Computed(index) => self.expr(index)?,
4911 MemberProp::Private(_) => {
4912 return Err(SyntaxError::new(
4913 "private fields are not supported by the compiler yet",
4914 expr.span,
4915 ));
4916 }
4917 }
4918 self.emit(Opcode::GetSuperValue, &[]);
4919 return Ok(());
4920 }
4921 self.chain_link(object, end)?;
4922 if *optional {
4923 self.optional_guard(end);
4924 }
4925 match property {
4926 // `.length` has its own opcode. The reference emits it for every
4927 // object, not just arrays, so a name-based rule is right and
4928 // cheaper than the generic field read.
4929 MemberProp::Ident(name) if name.name == "length" => {
4930 self.emit(Opcode::GetLength, &[]);
4931 }
4932 MemberProp::Ident(name) => {
4933 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
4934 }
4935 MemberProp::Computed(index) => {
4936 self.expr(index)?;
4937 self.emit(Opcode::GetArrayEl, &[]);
4938 }
4939 MemberProp::Private(name) => {
4940 // The binding comes from the class scope, so a read from outside the
4941 // class cannot name it at all. `?.` checks the object, not the field:
4942 // `o?.#x` guards on `o` being nullish.
4943 let binding = format!("#{}", name.name);
4944 let (kind, _) = self.private_use(&binding, expr.span)?;
4945 self.private_load(&binding, kind, expr.span)?;
4946 }
4947 }
4948 Ok(())
4949 }
4950 ExprKind::Call {
4951 callee,
4952 arguments,
4953 optional,
4954 } => {
4955 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
4956 // cannot: it reads the function and then calls it with no
4957 // receiver at all. The reference's answer is to keep the object
4958 // under the function value — `get_field2` reads a field and leaves
4959 // its base in place — and to use `call_method`, which takes the
4960 // receiver from the stack. Missing this does not just cost an
4961 // instruction, it loses the `this` binding.
4962 if let ExprKind::Member {
4963 object,
4964 property,
4965 optional: member_optional,
4966 } = &callee.unparen().kind
4967 {
4968 // `super.m()` reads the method off the home object's prototype but
4969 // calls it with `this`, so the receiver goes under the read instead of
4970 // being replaced by it.
4971 if matches!(object.unparen().kind, ExprKind::SuperProp) {
4972 self.super_base();
4973 match property {
4974 MemberProp::Ident(name) => self.emit(
4975 Opcode::PushAtomValue,
4976 &[Op::Atom(Atom::from_text(&name.name))],
4977 ),
4978 MemberProp::Computed(index) => self.expr(index)?,
4979 MemberProp::Private(_) => {
4980 return Err(SyntaxError::new(
4981 "private fields are not supported by the compiler yet",
4982 expr.span,
4983 ));
4984 }
4985 }
4986 // The two-output form would drop the receiver; this one replaces
4987 // the prototype and the key, leaving `this` underneath.
4988 self.emit(Opcode::GetArrayEl, &[]);
4989 if Self::has_spread(arguments) {
4990 self.argument_array(arguments)?;
4991 self.emit(Opcode::Perm3, &[]);
4992 self.emit(Opcode::Apply, &[Op::Int(0)]);
4993 return Ok(());
4994 }
4995 for argument in arguments {
4996 self.expr(argument)?;
4997 }
4998 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4999 return Ok(());
5000 }
5001 self.chain_link(object, end)?;
5002 if *member_optional {
5003 self.optional_guard(end);
5004 }
5005 match property {
5006 MemberProp::Ident(name) => {
5007 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5008 }
5009 MemberProp::Computed(index) => {
5010 self.expr(index)?;
5011 // The key is not needed after the read, so this is the
5012 // two-output form: object, value.
5013 self.emit(Opcode::GetArrayEl2, &[]);
5014 }
5015 MemberProp::Private(name) => {
5016 // The receiver is already under the callee, which is exactly the
5017 // shape `call_method` and `apply` want — so nothing is dropped.
5018 let binding = format!("#{}", name.name);
5019 let (kind, _) = self.private_use(&binding, expr.span)?;
5020 self.private_callee(&binding, kind)?;
5021 }
5022 }
5023 if Self::has_spread(arguments) {
5024 // Stack is `obj func`; the array goes on top, then `perm3`
5025 // reorders to the `func this array` that `apply` wants.
5026 self.argument_array(arguments)?;
5027 self.emit(Opcode::Perm3, &[]);
5028 self.emit(Opcode::Apply, &[Op::Int(0)]);
5029 return Ok(());
5030 }
5031 for argument in arguments {
5032 self.expr(argument)?;
5033 }
5034 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5035 return Ok(());
5036 }
5037 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5038 // with `get_field2` so the base stays under it, and on the short-circuit
5039 // path pushes an extra `undefined` as a placeholder receiver — the call
5040 // then throws, which is what calling a missing optional chain should do.
5041 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5042 && let ExprKind::Member {
5043 object,
5044 property,
5045 optional: member_optional,
5046 } = &inner.unparen().kind
5047 {
5048 let call = self.new_label();
5049 // A guard target of its own: the outer `end` skips the whole
5050 // expression, and a short-circuited receiver still has to reach the
5051 // call so that calling it throws.
5052 let short = self.new_label();
5053 self.chain_link(object, end)?;
5054 if *member_optional {
5055 self.optional_guard(short);
5056 }
5057 match property {
5058 MemberProp::Ident(name) => {
5059 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5060 }
5061 MemberProp::Computed(index) => {
5062 self.expr(index)?;
5063 self.emit(Opcode::GetArrayEl2, &[]);
5064 }
5065 MemberProp::Private(name) => {
5066 let binding = format!("#{}", name.name);
5067 let (kind, _) = self.private_use(&binding, expr.span)?;
5068 self.private_callee(&binding, kind)?;
5069 }
5070 }
5071 self.emit_jump(Opcode::Goto, call, &[]);
5072 self.place_label(short);
5073 self.emit(Opcode::Undefined, &[]);
5074 self.place_label(call);
5075 if Self::has_spread(arguments) {
5076 self.argument_array(arguments)?;
5077 self.emit(Opcode::Perm3, &[]);
5078 self.emit(Opcode::Apply, &[Op::Int(0)]);
5079 return Ok(());
5080 }
5081 for argument in arguments {
5082 self.expr(argument)?;
5083 }
5084 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5085 return Ok(());
5086 }
5087 self.chain_link(callee, end)?;
5088 if *optional {
5089 self.optional_guard(end);
5090 }
5091 if Self::has_spread(arguments) {
5092 // `func array -> func undefined array`, which is the plain-call
5093 // form of `apply`: the receiver is `undefined`.
5094 self.argument_array(arguments)?;
5095 self.emit(Opcode::Undefined, &[]);
5096 self.emit(Opcode::Swap, &[]);
5097 self.emit(Opcode::Apply, &[Op::Int(0)]);
5098 return Ok(());
5099 }
5100 for argument in arguments {
5101 self.expr(argument)?;
5102 }
5103 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5104 Ok(())
5105 }
5106 _ => self.expr(expr),
5107 }
5108 }
5109
5110 /// Compile `expr` as a tail call when it is one, reporting whether it was.
5111 ///
5112 /// `tail_call` reuses the current frame instead of pushing a new one, so a
5113 /// tail-recursive function runs in constant stack space. It also has to be the
5114 /// *last* thing the function does, which is why only a `return` reaches here.
5115 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5116 let ExprKind::Call {
5117 callee,
5118 arguments,
5119 optional: false,
5120 } = &expr.unparen().kind
5121 else {
5122 return Ok(false);
5123 };
5124 // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5125 // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5126 // as an ordinary call costs the one frame the optimisation was saving and keeps the
5127 // semantics — the alternative was reaching the spread expression below and failing
5128 // with "this expression form is not supported", which is how `return super.m(...a)`
5129 // stopped compiling. Checked before anything is emitted, because the decision cannot
5130 // be taken back once `super_base` or a `get_field2` is on the stack.
5131 if Self::has_spread(arguments) {
5132 return Ok(false);
5133 }
5134 let end = self.new_label();
5135 if let ExprKind::Member {
5136 object,
5137 property,
5138 optional: false,
5139 } = &callee.unparen().kind
5140 {
5141 // `super.m()` in tail position is still an ordinary method call with `this`
5142 // as the receiver; only the read of the method differs.
5143 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5144 self.super_base();
5145 match property {
5146 MemberProp::Ident(name) => self.emit(
5147 Opcode::PushAtomValue,
5148 &[Op::Atom(Atom::from_text(&name.name))],
5149 ),
5150 MemberProp::Computed(index) => self.expr(index)?,
5151 MemberProp::Private(_) => return Ok(false),
5152 }
5153 self.emit(Opcode::GetArrayEl, &[]);
5154 for argument in arguments {
5155 self.expr(argument)?;
5156 }
5157 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5158 self.place_label(end);
5159 return Ok(true);
5160 }
5161 self.chain_link(object, end)?;
5162 match property {
5163 MemberProp::Ident(name) => {
5164 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5165 }
5166 MemberProp::Computed(index) => {
5167 self.expr(index)?;
5168 self.emit(Opcode::GetArrayEl2, &[]);
5169 }
5170 MemberProp::Private(_) => return Ok(false),
5171 }
5172 for argument in arguments {
5173 self.expr(argument)?;
5174 }
5175 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5176 self.place_label(end);
5177 return Ok(true);
5178 }
5179 self.chain_link(callee, end)?;
5180 for argument in arguments {
5181 self.expr(argument)?;
5182 }
5183 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5184 self.place_label(end);
5185 Ok(true)
5186 }
5187
5188 /// The `?.` guard: keep the value if it is neither null nor undefined,
5189 /// otherwise replace it with `undefined` and leave the whole chain.
5190 fn optional_guard(&mut self, end: Label) {
5191 let cont = self.new_label();
5192 self.emit(Opcode::Dup, &[]);
5193 self.emit(Opcode::IsUndefinedOrNull, &[]);
5194 self.emit_jump(Opcode::IfFalse, cont, &[]);
5195 self.emit(Opcode::Drop, &[]);
5196 self.emit(Opcode::Undefined, &[]);
5197 self.emit_jump(Opcode::Goto, end, &[]);
5198 self.place_label(cont);
5199 }
5200
5201 fn push_number(&mut self, value: f64) {
5202 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5203 // goes into the constant pool.
5204 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5205 let int = value as i32;
5206 if (-1..=7).contains(&int) {
5207 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5208 return;
5209 }
5210 if (-128..=127).contains(&int) {
5211 self.emit(Opcode::PushI8, &[Op::Int(int)]);
5212 return;
5213 }
5214 if (-32768..=32767).contains(&int) {
5215 self.emit(Opcode::PushI16, &[Op::Int(int)]);
5216 return;
5217 }
5218 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5219 return;
5220 }
5221 let index = self.push_constant(Constant::Number(value));
5222 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5223 }
5224
5225 /// Push a `BigInt` literal.
5226 ///
5227 /// A value that fits an `i32` uses the immediate form, which is what the reference
5228 /// emits too; anything larger goes into the constant pool, because the operand of
5229 /// `push_bigint` is only four bytes wide.
5230 fn push_bigint(&mut self, digits: &str, radix: u32) {
5231 if radix == 10
5232 && let Ok(value) = digits.parse::<i64>()
5233 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5234 {
5235 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5236 return;
5237 }
5238 let index = self.push_constant(Constant::BigInt {
5239 digits: digits.to_string(),
5240 radix,
5241 });
5242 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5243 }
5244
5245 fn push_string(&mut self, text: &Wtf8) {
5246 if text.is_empty() {
5247 self.emit(Opcode::PushEmptyString, &[]);
5248 return;
5249 }
5250 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5251 }
5252
5253 /// Name an anonymous function from the binding it is assigned to.
5254 ///
5255 /// `var f = function(){}` produces a function whose `name` is `f`, which the
5256 /// runtime cannot know without being told: the function object is created
5257 /// before the store. `set_name` carries the name across.
5258 fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5259 if value.is_anonymous_function_definition() {
5260 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5261 }
5262 }
5263
5264 /// The same, for a computed key: the name comes from the value on the stack
5265 /// rather than from an atom, so a different instruction carries it.
5266 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5267 if value.is_anonymous_function_definition() {
5268 self.emit(Opcode::SetNameComputed, &[]);
5269 }
5270 }
5271
5272 /// Compile a function body that exists only in the compiler's head — a class's
5273 /// implicit constructor or its field initialiser.
5274 ///
5275 /// Everything structural is the same as a written function: a fresh `FnState`, its
5276 /// own body block, and resolution while the frame is still on the stack. Only the
5277 /// statements differ.
5278 fn compile_synthetic_function(
5279 &mut self,
5280 name: &str,
5281 strict: bool,
5282 span: Span,
5283 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5284 ) -> Result<CompiledFunction, SyntaxError> {
5285 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5286 state.span = Some((span.start.offset as usize, span.end.offset as usize));
5287 state.strict = strict;
5288 state.created_in_block = self.cur().current_block;
5289 state.with_names = self.cur().with_names.clone();
5290 state.line = span.start.line;
5291 state.column = span.start.column;
5292 let depth = self.stack.len();
5293 self.stack.push(state);
5294 let body_key = span.start.offset as u64;
5295 self.push_block(body_key, NO_PARENT);
5296 self.state().body_block = body_key;
5297 let result = (|| {
5298 self.emit_scope_enter(body_key);
5299 body(self)?;
5300 if self.end_is_reachable() {
5301 self.emit(Opcode::ReturnUndef, &[]);
5302 }
5303 Ok(())
5304 })();
5305 if result.is_err() {
5306 self.stack.truncate(depth);
5307 return result.map(|()| unreachable!());
5308 }
5309 Ok(self.finish_current())
5310 }
5311
5312 /// The implicit return of a class constructor.
5313 ///
5314 /// A constructor that falls off the end initialises its instance fields first, and a
5315 /// derived one returns `this` — which is what makes `new D()` the object `super()`
5316 /// built rather than `undefined`.
5317 fn emit_class_constructor_tail(&mut self) {
5318 match self.cur().ctor_kind {
5319 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5320 // Nothing to install: a base constructor did it in its prologue and a derived
5321 // one at each `super()` site, which is where `this` first exists.
5322 CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5323 CtorKind::Derived => {
5324 // `get_loc_check` rather than `get_loc`: reaching the end without ever
5325 // running `super()` is a ReferenceError, not `undefined`.
5326 self.emit_var(VarAction::Get, "this");
5327 self.emit(Opcode::Return, &[]);
5328 }
5329 }
5330 }
5331
5332 /// `yield expr` / `yield* expr`.
5333 ///
5334 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5335 /// it to the caller and parks the frame. On resume the stack holds the value the
5336 /// caller passed *and* a "magic" number saying which method resumed it — `next`
5337 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5338 /// `if_false <continue>` asks whether this was an ordinary `next`:
5339 ///
5340 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5341 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5342 /// and uses the value sitting under the magic number.
5343 ///
5344 /// A `throw` never reaches here: the interpreter unwinds instead (see
5345 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5346 fn yield_expression(
5347 &mut self,
5348 argument: Option<&Expr>,
5349 delegate: bool,
5350 ) -> Result<(), SyntaxError> {
5351 if delegate {
5352 return self.yield_star(argument);
5353 }
5354 // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5355 // does the same for the `return(v)` that can resume it — which is why an async
5356 // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5357 // generator's is just `yield`.
5358 let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5359 match argument {
5360 Some(value) => self.expr(value)?,
5361 None => self.emit(Opcode::Undefined, &[]),
5362 }
5363 if is_async {
5364 self.emit(Opcode::Await, &[]);
5365 self.state().has_await = true;
5366 }
5367 self.emit(Opcode::Yield, &[]);
5368 let resume = self.new_label();
5369 self.emit_jump(Opcode::IfFalse, resume, &[]);
5370 // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5371 // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5372 // finished the generator and never ran the `finally`.
5373 if is_async {
5374 self.emit(Opcode::Await, &[]);
5375 }
5376 self.emit_unwind_for_return(true);
5377 self.emit(Opcode::ReturnAsync, &[]);
5378 self.place_label(resume);
5379 // Nothing is emitted here: the value the caller passed to `next` *is* the value
5380 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5381 // it through the ordinary expression-statement discard.
5382 Ok(())
5383 }
5384
5385 /// `yield* iterable`.
5386 ///
5387 /// The shape is the reference's, and it is a fall-through chain rather than a
5388 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5389 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5390 /// the inner iterator and finishes, `throw` forwards the exception into it and
5391 /// continues only if it has a `throw` method.
5392 ///
5393 /// The stack is `iter next catch value` throughout, `catch` being the offset
5394 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5395 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5396 match argument {
5397 Some(value) => self.expr(value)?,
5398 // The parser rejects a bare `yield*`, so this is unreachable in practice.
5399 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5400 }
5401 // `for await of` is the same protocol as `for of` with two differences that matter
5402 // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5403 // every `next()` result is a promise the delegate has to await.
5404 let is_async = self.cur().kind.is_async();
5405 self.emit(
5406 if is_async {
5407 Opcode::ForAwaitOfStart
5408 } else {
5409 Opcode::ForOfStart
5410 },
5411 &[],
5412 );
5413 self.emit(Opcode::Drop, &[]);
5414 self.emit(Opcode::Undefined, &[]);
5415 self.emit(Opcode::Undefined, &[]);
5416 let next = self.new_label();
5417 let resume = self.new_label();
5418 let finished = self.new_label();
5419 let rethrow = self.new_label();
5420 let throw_no_method = self.new_label();
5421 let done = self.new_label();
5422 self.place_label(next);
5423 self.emit(Opcode::IteratorNext, &[]);
5424 if is_async {
5425 self.emit(Opcode::Await, &[]);
5426 self.state().has_await = true;
5427 }
5428 self.emit(Opcode::IteratorCheckObject, &[]);
5429 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5430 self.emit_jump(Opcode::IfTrue, done, &[]);
5431 // The suspension. `resume` is both the label the return path jumps back to in order
5432 // to yield one more value and where the caller's answer arrives, as the value
5433 // followed by the magic number.
5434 //
5435 // The two forms differ in what they hand the suspension: `yield_star` takes the
5436 // result object itself, `async_yield_star` takes `.value`, because an async
5437 // generator awaits and re-wraps whatever it yields.
5438 self.place_label(resume);
5439 if is_async {
5440 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5441 self.emit(Opcode::AsyncYieldStar, &[]);
5442 } else {
5443 self.emit(Opcode::YieldStar, &[]);
5444 }
5445 self.emit(Opcode::Dup, &[]);
5446 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5447 self.emit(Opcode::Drop, &[]);
5448 self.emit_jump(Opcode::Goto, next, &[]);
5449
5450 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5451 self.place_label(rethrow);
5452 self.emit(Opcode::PushI32, &[Op::Int(2)]);
5453 self.emit(Opcode::StrictEq, &[]);
5454 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5455 // A `return` closes the inner iterator; if it had none, the delegate simply
5456 // finishes with the requested value. In an async generator both the call and its
5457 // result are awaited, because the inner `return` may itself be async.
5458 if is_async {
5459 self.emit(Opcode::Await, &[]);
5460 }
5461 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5462 self.emit_jump(Opcode::IfTrue, finished, &[]);
5463 if is_async {
5464 self.emit(Opcode::Await, &[]);
5465 }
5466 self.emit(Opcode::IteratorCheckObject, &[]);
5467 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5468 self.emit_jump(Opcode::IfFalse, resume, &[]);
5469 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5470 self.place_label(finished);
5471 self.emit(Opcode::Nip, &[]);
5472 self.emit(Opcode::Nip, &[]);
5473 self.emit(Opcode::Nip, &[]);
5474 // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5475 // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5476 // awaits the value in an async generator and then runs the same `finally`/iterator
5477 // unwinding a written `return` would. Skipping the unwinding made
5478 // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5479 if is_async {
5480 self.emit(Opcode::Await, &[]);
5481 }
5482 self.emit_unwind_for_return(true);
5483 self.emit(Opcode::ReturnAsync, &[]);
5484
5485 // `throw(e)`: forward it into the inner iterator.
5486 self.place_label(throw_no_method);
5487 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5488 let no_throw = self.new_label();
5489 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5490 if is_async {
5491 self.emit(Opcode::Await, &[]);
5492 }
5493 self.emit(Opcode::IteratorCheckObject, &[]);
5494 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5495 self.emit_jump(Opcode::IfFalse, resume, &[]);
5496 self.emit_jump(Opcode::Goto, done, &[]);
5497 // No `throw` method: close the iterator, then report the spec's TypeError. The
5498 // `if_true` before the `await` is the reference's shape — the flag it consumes is
5499 // what `iterator_call` leaves behind, and a close that *did* find no `return`
5500 // method has nothing to await.
5501 self.place_label(no_throw);
5502 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5503 let no_close = self.new_label();
5504 self.emit_jump(Opcode::IfTrue, no_close, &[]);
5505 if is_async {
5506 self.emit(Opcode::Await, &[]);
5507 }
5508 self.place_label(no_close);
5509 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5510
5511 // The inner iterator finished: the delegate's value is the `yield*` expression's
5512 // value, so it is left on the stack for whatever consumes it.
5513 self.place_label(done);
5514 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5515 self.emit(Opcode::Nip, &[]);
5516 self.emit(Opcode::Nip, &[]);
5517 self.emit(Opcode::Nip, &[]);
5518 Ok(())
5519 }
5520
5521 /// `await expr`: exactly one instruction.
5522 ///
5523 /// No resume-magic branch follows it. The reference's `await` leaves a single value
5524 /// on the stack and completion is signalled by the `return_async` at the end of the
5525 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5526 /// reference never emits, and a `for await` loop — which reaches `await` through the
5527 /// same opcode — would then spill a value the loop's unpacking does not expect.
5528 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5529 self.expr(argument)?;
5530 self.emit(Opcode::Await, &[]);
5531 self.state().has_await = true;
5532 Ok(())
5533 }
5534
5535 /// The `super` base: the receiver followed by the home object's prototype.
5536 ///
5537 /// Everything `super` does needs both. A *read* starts at the prototype but reports
5538 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5539 /// prototype but calls it with the receiver.
5540 fn super_base(&mut self) {
5541 self.this_expression();
5542 self.home_object();
5543 self.emit(Opcode::GetSuper, &[]);
5544 }
5545
5546 /// `[[HomeObject]]` as `super` sees it.
5547 ///
5548 /// A method, a constructor and a field initialiser each carry one — `set_home_object`
5549 /// put it there — so for them the special object *is* the answer. An arrow and a
5550 /// static block have none: they read the enclosing function's, which has to be
5551 /// materialised into a local, exactly as `this` is for an arrow.
5552 ///
5553 /// The name matches what the reference stores, so the disassembly agrees; it is not a
5554 /// name any program can write.
5555 fn home_object(&mut self) {
5556 if !self.cur().is_arrow {
5557 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
5558 return;
5559 }
5560 if let Some(target) = self.enclosing_function() {
5561 self.state_at(target).needs_home_object_local = true;
5562 self.declare_at(target, HOME_OBJECT);
5563 }
5564 self.emit_var(VarAction::Get, HOME_OBJECT);
5565 }
5566
5567 /// `super(args)`: construct the parent class and adopt the result as `this`.
5568 ///
5569 /// The parent is the prototype of the constructor that is running, which is exactly
5570 /// what `extends` set up. `new.target` is passed through unchanged so that
5571 /// `new.target` inside the parent is the class actually being constructed.
5572 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5573 self.active_func_expression();
5574 self.emit(Opcode::GetSuper, &[]);
5575 self.new_target_expression();
5576 if Self::has_spread(arguments) {
5577 self.argument_array(arguments)?;
5578 self.emit(Opcode::Apply, &[Op::Int(1)]);
5579 } else {
5580 for argument in arguments {
5581 self.expr(argument)?;
5582 }
5583 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
5584 }
5585 // The value stays on the stack: `super()` is an expression, and a derived
5586 // constructor's `this` may only be initialised once.
5587 self.emit(Opcode::Dup, &[]);
5588 self.emit_var(VarAction::PutInitChecked, "this");
5589 // Instance fields are installed here, not at the top of the body: a derived
5590 // constructor has no `this` to install them on until `super()` returns. The
5591 // reference emits the same call at every `super()` site.
5592 self.call_field_initialiser();
5593 Ok(())
5594 }
5595
5596 /// `this` as a local, which every class constructor and field initialiser needs.
5597 ///
5598 /// The reference materialises the receiver into a local rather than reading
5599 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
5600 /// and a field initialiser has to see the final value.
5601 fn begin_this_local(&mut self) {
5602 self.declare_hidden_local("this", VarKind::Normal);
5603 self.emit(Opcode::PushThis, &[]);
5604 self.emit_var(VarAction::Put, "this");
5605 // The store is already at the top of the body, so `provide_this_local` has
5606 // nothing left to prepend. Without this the initialiser ended up with
5607 // `push_this; put_loc0 this` twice whenever the class also held a field
5608 // initialiser whose body read `this` through an arrow.
5609 self.state().has_this_prologue = true;
5610 }
5611
5612 /// Compile a constructor the class wrote.
5613 ///
5614 /// The flags have to be in place before the body is compiled, but
5615 /// `compile_function_with_name` creates its own state — so the caller's state is
5616 /// marked instead and the new one inherits it. That is the same trick the parameter
5617 /// prologue uses, and it keeps one code path for both.
5618 fn compile_class_constructor(
5619 &mut self,
5620 func: &ast::Function,
5621 has_heritage: bool,
5622 ) -> Result<CompiledFunction, SyntaxError> {
5623 let saved = self.cur().ctor_kind;
5624 self.state().class_ctor_pending = Some(if has_heritage {
5625 CtorKind::Derived
5626 } else {
5627 CtorKind::Base
5628 });
5629 let result = self.compile_function_with_name(func, false);
5630 self.state().ctor_kind = saved;
5631 self.state().class_ctor_pending = None;
5632 result
5633 }
5634
5635 /// The constructor a class gets when it does not declare one.
5636 ///
5637 /// A base class's is empty; a derived class's forwards every argument to the parent
5638 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
5639 /// instance field initialiser afterwards when the class has fields, which is why the
5640 /// initialiser is captured rather than inlined.
5641 fn compile_implicit_constructor(
5642 &mut self,
5643 class: &Class,
5644 has_heritage: bool,
5645 ) -> Result<CompiledFunction, SyntaxError> {
5646 self.compile_synthetic_function(
5647 "",
5648 true,
5649 Span::new(class.body_end, class.body_end),
5650 |compiler| {
5651 if has_heritage {
5652 // A derived constructor's `this` does not exist until `super()` returns,
5653 // so it starts in the dead zone and `init_ctor` fills it.
5654 compiler.declare("this", VarDef::lexical("this"));
5655 compiler.emit(
5656 Opcode::SetLocUninitialized,
5657 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5658 );
5659 compiler.emit(Opcode::InitCtor, &[]);
5660 compiler.emit(
5661 Opcode::PutLocCheckInit,
5662 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5663 );
5664 } else {
5665 compiler.begin_this_local();
5666 compiler.emit(Opcode::CheckCtor, &[]);
5667 }
5668 compiler.call_field_initialiser();
5669 // A derived constructor returns `this`, the object `super()` built. Without
5670 // this the implicit constructor fell through to `return_undef`, and `new B()`
5671 // handed back the empty object `construct` had made instead of the one the
5672 // parent constructor initialised.
5673 if has_heritage {
5674 compiler.emit_var(VarAction::Get, "this");
5675 compiler.emit(Opcode::Return, &[]);
5676 }
5677 Ok(())
5678 },
5679 )
5680 }
5681
5682 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
5683 ///
5684 /// A class with no instance fields leaves the binding `undefined`, and calling it
5685 /// would throw; the reference emits the same guard rather than branching at compile
5686 /// time because a class can be extended by a subclass whose fields still have to run.
5687 fn call_field_initialiser(&mut self) {
5688 let skip = self.new_label();
5689 self.emit_var(VarAction::Get, "<class_fields_init>");
5690 self.emit(Opcode::Dup, &[]);
5691 self.emit_jump(Opcode::IfFalse, skip, &[]);
5692 self.emit_var(VarAction::Get, "this");
5693 self.emit(Opcode::Swap, &[]);
5694 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5695 self.place_label(skip);
5696 self.emit(Opcode::Drop, &[]);
5697 }
5698
5699 /// The function that defines one class's fields on `this`, and runs its static blocks.
5700 ///
5701 /// `define_field` rather than `put_field`: a field is an own property created
5702 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
5703 /// `x = 1` field must not call the setter.
5704 ///
5705 /// One function serves the whole class: it is called once per instance (or once, for
5706 /// the static half) and walks the members in source order. Static blocks are compiled
5707 /// into the same function because they *are* part of the same sequence — `static a =
5708 /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
5709 /// different values, so the two kinds cannot be split apart.
5710 fn compile_field_initialiser(
5711 &mut self,
5712 items: &[StaticInitItem<'_>],
5713 span: Span,
5714 instance: bool,
5715 add_brand: bool,
5716 ) -> Result<CompiledFunction, SyntaxError> {
5717 self.compile_synthetic_function("", true, span, |compiler| {
5718 if instance {
5719 // An instance initialiser always carries a `<home_object>` local, because the
5720 // brand block below reads it — even when that block turns out to be dead. The
5721 // reference has the same artefact, and the store is visible in its dump.
5722 let current = compiler.stack.len() - 1;
5723 compiler.stack[current].needs_home_object_local = true;
5724 }
5725 compiler.begin_this_local();
5726 if instance {
5727 // `this` gets the brand the prototype created, before any field is defined —
5728 // which is what makes `#m()` usable from inside a field initialiser.
5729 //
5730 // The reference always emits `push_false; if_false L; this; home; add_brand;
5731 // L:` and patches the `push_false` to `push_true` from the class parse when
5732 // the class has private methods; either way the branch folds, but the *mark*
5733 // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
5734 // `this` local from being fused into a `set_loc`.
5735 let skip = compiler.new_label();
5736 if add_brand {
5737 compiler.emit(Opcode::PushTrue, &[]);
5738 } else {
5739 compiler.emit(Opcode::PushFalse, &[]);
5740 }
5741 compiler.emit_jump(Opcode::IfFalse, skip, &[]);
5742 compiler.emit_var(VarAction::Get, "this");
5743 compiler.emit_var(VarAction::Get, HOME_OBJECT);
5744 compiler.emit(Opcode::AddBrand, &[]);
5745 compiler.place_label(skip);
5746 }
5747 for item in items {
5748 match item {
5749 StaticInitItem::Field(key, value) => {
5750 // A private field is *defined*, not assigned: `define_private_field`
5751 // reads `obj symbol value`, and its point is that it fails on a
5752 // receiver that is not this class's — which `put_field` would not.
5753 //
5754 // The three shapes are the reference's: `define_field <atom>` for a
5755 // static name, `define_array_el` for a key that is only known at run
5756 // time (`obj key value`), `define_private_field` for `#x`, and a
5757 // computed key is read from its binding rather than recomputed.
5758 compiler.emit_var(VarAction::Get, "this");
5759 match key {
5760 FieldKey::Private(binding) | FieldKey::Computed(binding) => {
5761 compiler.emit_var(VarAction::Get, binding);
5762 }
5763 FieldKey::Literal(_) => {}
5764 }
5765 match value {
5766 Some(value) => compiler.expr(value)?,
5767 None => compiler.emit(Opcode::Undefined, &[]),
5768 }
5769 match key {
5770 FieldKey::Literal(literal) => {
5771 let text = compiler.property_key_text(literal, span)?;
5772 compiler
5773 .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
5774 }
5775 FieldKey::Computed(_) => {
5776 compiler.emit(Opcode::DefineArrayEl, &[]);
5777 // `define_array_el` leaves `obj key`; the key is consumed by
5778 // the copy the pattern machinery wants, so both go.
5779 compiler.emit(Opcode::Drop, &[]);
5780 }
5781 FieldKey::Private(_) => {
5782 compiler.emit(Opcode::DefinePrivateField, &[]);
5783 }
5784 }
5785 compiler.emit(Opcode::Drop, &[]);
5786 }
5787 StaticInitItem::Block { body, body_start } => {
5788 let block = compiler.compile_static_block(body, *body_start)?;
5789 let index = compiler.push_constant(Constant::Function(Box::new(block)));
5790 // `this fclosure`, so `call_method` finds the receiver below the
5791 // callee: the block runs with `this` bound to the class.
5792 compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
5793 compiler.emit_var(VarAction::Get, "this");
5794 compiler.emit(Opcode::Swap, &[]);
5795 compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
5796 // Nothing the block evaluates is wanted; its effects are the point.
5797 compiler.emit(Opcode::Drop, &[]);
5798 }
5799 }
5800 }
5801 Ok(())
5802 })
5803 }
5804
5805 /// Compile a `static { … }` body into the function the class calls for it.
5806 ///
5807 /// Shaped like an arrow, because that is the one function form with no `this`,
5808 /// `new.target` or `arguments` of its own: all three reach the enclosing static
5809 /// initialiser, and through it the class. `arguments` never gets that far — the parser
5810 /// rejects the reference — but `this` and `super` both depend on it.
5811 ///
5812 /// The body is hoisted like a function body's, because the reference parses it as one:
5813 /// `var` inside a block is a local of the block's function, not of whatever encloses
5814 /// the class.
5815 fn compile_static_block(
5816 &mut self,
5817 body: &[Stmt],
5818 body_start: Position,
5819 ) -> Result<CompiledFunction, SyntaxError> {
5820 let mut state = FnState::new(String::new(), FunctionKind::Normal);
5821 // Class bodies are strict, so a static block is too.
5822 state.strict = true;
5823 // The one property that makes this an arrow: nothing of its own to bind `this` to,
5824 // so `this` and `super` come from the initialiser that calls it.
5825 state.is_arrow = true;
5826 state.created_in_block = self.cur().current_block;
5827 state.with_names = self.cur().with_names.clone();
5828 state.line = body_start.line;
5829 state.column = body_start.column;
5830 let depth = self.stack.len();
5831 self.stack.push(state);
5832 let body_key = body_start.offset as u64;
5833 self.push_block(body_key, NO_PARENT);
5834 self.state().body_block = body_key;
5835 let result = (|| {
5836 self.hoist(body, body_key)?;
5837 self.emit_scope_enter(body_key);
5838 for statement in body {
5839 self.stmt(statement)?;
5840 }
5841 if self.end_is_reachable() {
5842 self.emit(Opcode::ReturnUndef, &[]);
5843 }
5844 Ok(())
5845 })();
5846 if result.is_err() {
5847 self.stack.truncate(depth);
5848 return result.map(|()| unreachable!());
5849 }
5850 Ok(self.finish_current())
5851 }
5852
5853 /// Compile a class, leaving the constructor on the stack when `keep`.
5854 ///
5855 /// The shape follows the reference: the class body is its own scope holding the
5856 /// class's *inner* name as a `const` — which is what lets a method refer to the
5857 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
5858 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
5859 /// on the top of the stack: the prototype for instance members, the constructor
5860 /// itself for `static` ones, which is why a static member costs an extra `swap`.
5861 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
5862 let parent_block = self.cur().current_block;
5863 let key = class.span.start.offset as u64;
5864 self.push_block(key, parent_block);
5865 let name = class.name.as_ref().map(|ident| ident.name.clone());
5866 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
5867 // resolves `E` without a global lookup. An *unnamed* class expression has no such
5868 // binding, and `define_class` is handed the empty name.
5869 if let Some(name) = &name {
5870 self.declare(name, VarDef::constant(name.clone()));
5871 }
5872 self.emit_scope_enter(key);
5873
5874 // The heritage clause is evaluated outside the class's own scope: it cannot see
5875 // the class binding it is about to initialise.
5876 let saved_block = self.cur().current_block;
5877 self.state().current_block = parent_block;
5878 match &class.super_class {
5879 Some(parent) => self.expr(parent)?,
5880 None => self.emit(Opcode::Undefined, &[]),
5881 }
5882 self.state().current_block = saved_block;
5883 let has_heritage = class.super_class.is_some();
5884
5885 // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
5886 // lands after the heritage's code — which is where the reference puts it, because it
5887 // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
5888 // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
5889 // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
5890 // came out in the opposite order from the reference's.
5891 //
5892 // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
5893 // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
5894 // a const accepts — so the old comment's worry ("a const would refuse the second
5895 // store") did not apply: there is no second store.
5896 // Every `#name` the class declares gets a `const` binding in the class scope, and so
5897 // does every computed field key. That is how the reference does it
5898 // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
5899 // what makes a private name resolve like any other class-scope variable — including
5900 // through a nested function's closure — while remaining invisible outside.
5901 //
5902 // All of them are declared *before* `<class_fields_init>`, in member order, because
5903 // that is when the reference's parser creates them.
5904 let plan = ClassPlan::build(class);
5905 // The body's private names are visible from here to the end of the class, and shadow
5906 // any outer class's of the same spelling. Pushed *before* the constructor is compiled
5907 // — it is compiled first because `define_class` consumes it, but its body can name
5908 // `#x` like any other member's.
5909 self.private_scopes.push(plan.uses.clone());
5910 let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
5911 for binding in &plan.bindings {
5912 class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
5913 }
5914 let fci = self.declare(
5915 "<class_fields_init>",
5916 VarDef::constant("<class_fields_init>"),
5917 );
5918 // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
5919 // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
5920 // members' bindings follow in reverse.
5921 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
5922 for slot in class_slots.iter().rev() {
5923 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
5924 }
5925
5926 // The constructor is compiled before `define_class` because that instruction
5927 // consumes it; a class without one gets the implicit version.
5928 let constructor = class.elements.iter().find_map(|element| match element {
5929 ClassElement::Method {
5930 kind: MethodKind::Constructor,
5931 func,
5932 ..
5933 } => Some(&**func),
5934 _ => None,
5935 });
5936 // A constructor is compiled differently from a method: it owns `this`. The flags
5937 // go on the *enclosing* state because a constructor is a nested function and
5938 // `compile_function_with_name` starts a fresh one.
5939 let ctor = match constructor {
5940 Some(func) => self.compile_class_constructor(func, has_heritage)?,
5941 None => self.compile_implicit_constructor(class, has_heritage)?,
5942 };
5943 // A closure, not the bare constant: the constructor captures
5944 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
5945 // has to hold the cell rather than a copy of its value.
5946 //
5947 // The pool slot is left unassigned for now, because the reference gives the
5948 // constructor the *last* index of the members' range: `js_parse_class` emits a
5949 // `push_const` whose operand is patched at the end of the class parse, after every
5950 // method has taken a slot. Emitting the members first and the constant second is how
5951 // the numbering comes out the same; the instruction itself stays where it is.
5952 let ctor_insn = self.cur().insns.len();
5953 self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
5954 let flags = if has_heritage { 1 } else { 0 };
5955 self.emit(
5956 Opcode::DefineClass,
5957 &[
5958 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
5959 Op::Int(flags),
5960 ],
5961 );
5962
5963 // Instance fields and static fields are two different functions: the first runs
5964 // per instance from the constructor, the second runs once, here.
5965 let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
5966 let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
5967 for (index, element) in class.elements.iter().enumerate() {
5968 match element {
5969 ClassElement::Method {
5970 key: member_key,
5971 is_static,
5972 kind,
5973 func,
5974 span,
5975 } => {
5976 if *kind == MethodKind::Constructor {
5977 continue;
5978 }
5979 // `static(x)` is a *method* named `static`, not a static method; the
5980 // parser already decided which by putting it in `kind`.
5981 if *is_static {
5982 self.emit(Opcode::Swap, &[]);
5983 }
5984 // A computed key is evaluated *here*, before the method's closure
5985 // exists, and stays under it: `define_method_computed` pops
5986 // `function, key, object`, so the stack has to read
5987 // `[class, prototype, key, function]`. Evaluating the key after the
5988 // `fclosure` and swapping the two put the prototype *below* the
5989 // closure, which defined the method on the function and lost the
5990 // prototype: `class C { [k]() {} }` left `C` undefined. The order is
5991 // also the spec's — a class body evaluates every element's name before
5992 // that element's function.
5993 if let PropName::Computed(key) = member_key {
5994 self.expr(key)?;
5995 }
5996 let function = self.compile_function_with_name(func, true)?;
5997 let index = self.push_constant(Constant::Function(Box::new(function)));
5998 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5999 match member_key {
6000 // A private method is not a property of the prototype: it is a
6001 // closure in the class scope, which is why nothing outside can reach
6002 // it and why a use site has to brand-check. `set_name` gives the
6003 // function its `name` (`#m`), which an accessor does not get — the
6004 // reference leaves that commented out.
6005 PropName::Private(ident) => {
6006 let name = format!("#{}", ident.name);
6007 // `set_home_object` first: the brand check reads the function's
6008 // home object, and for a method that is the prototype.
6009 self.emit(Opcode::SetHomeObject, &[]);
6010 let binding = if *kind == MethodKind::Set {
6011 format!("{name}<set>")
6012 } else {
6013 name.clone()
6014 };
6015 if *kind == MethodKind::Method {
6016 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6017 }
6018 self.emit_var(VarAction::PutInit, &binding);
6019 }
6020 PropName::Computed(_) => {
6021 self.emit(
6022 Opcode::DefineMethodComputed,
6023 &[Op::Int(class_method_flags(*kind))],
6024 );
6025 }
6026 PropName::Literal(literal) => {
6027 let text = self.property_key_text(literal, *span)?;
6028 self.emit(
6029 Opcode::DefineMethod,
6030 &[
6031 Op::Atom(Atom::from_wtf8(&text)),
6032 Op::Int(class_method_flags(*kind)),
6033 ],
6034 );
6035 }
6036 }
6037 if *is_static {
6038 self.emit(Opcode::Swap, &[]);
6039 }
6040 }
6041 ClassElement::Field {
6042 key: field_key,
6043 is_static,
6044 value,
6045 ..
6046 } => {
6047 // A private field's *symbol* is created here, at the member, and stored
6048 // in its binding: the field's property is keyed by it, so it has to exist
6049 // before any initialiser runs, and a fresh one per class body is what
6050 // makes two classes that both write `#x` independent.
6051 //
6052 // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6053 // whose `toString` has a side effect must not run again per instance.
6054 let key = match field_key {
6055 PropName::Private(ident) => {
6056 let binding = format!("#{}", ident.name);
6057 if *is_static {
6058 self.emit(Opcode::Swap, &[]);
6059 }
6060 self.emit(
6061 Opcode::PrivateSymbol,
6062 &[Op::Atom(Atom::from_text(&binding))],
6063 );
6064 self.emit_var(VarAction::PutInit, &binding);
6065 if *is_static {
6066 self.emit(Opcode::Swap, &[]);
6067 }
6068 FieldKey::Private(binding)
6069 }
6070 PropName::Computed(expression) => {
6071 let binding = plan
6072 .computed
6073 .get(&index)
6074 .cloned()
6075 .expect("every computed key got a binding");
6076 if *is_static {
6077 self.emit(Opcode::Swap, &[]);
6078 }
6079 self.expr(expression)?;
6080 self.emit(Opcode::ToPropkey, &[]);
6081 self.emit_var(VarAction::PutInit, &binding);
6082 if *is_static {
6083 self.emit(Opcode::Swap, &[]);
6084 }
6085 FieldKey::Computed(binding)
6086 }
6087 PropName::Literal(literal) => FieldKey::Literal(literal),
6088 };
6089 if *is_static {
6090 static_items.push(StaticInitItem::Field(key, value.as_deref()));
6091 } else {
6092 instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6093 }
6094 }
6095 ClassElement::StaticBlock {
6096 body, body_start, ..
6097 } => static_items.push(StaticInitItem::Block {
6098 body,
6099 body_start: *body_start,
6100 }),
6101 }
6102 }
6103
6104 // Now that every member has its slot, the constructor can have the next one and the
6105 // `fclosure` above can name it.
6106 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6107 match self.state().insns.get_mut(ctor_insn) {
6108 Some(Insn::Fixed { operands, .. }) => {
6109 operands[0] = Op::Const(ctor_index);
6110 }
6111 // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6112 // loudly beats emitting a `fclosure` of slot 4294967295.
6113 _ => {
6114 return Err(SyntaxError::new(
6115 "the class constructor's fclosure went missing",
6116 class.span,
6117 ));
6118 }
6119 }
6120
6121 // The instance brand: a symbol created once on the prototype, which every instance
6122 // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6123 // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6124 // copy is created. The prototype is on top of the stack at this point.
6125 if plan.instance_brand {
6126 self.emit(Opcode::Dup, &[]);
6127 self.emit(Opcode::Null, &[]);
6128 self.emit(Opcode::Swap, &[]);
6129 self.emit(Opcode::AddBrand, &[]);
6130 }
6131
6132 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6133 // class has no instance fields. The constructor calls it only when it is defined.
6134 //
6135 // A class with private *methods* but no fields still needs one, because adding the
6136 // brand to each new instance is the initialiser's job.
6137 if instance_fields.is_empty() && !plan.instance_brand {
6138 self.emit(Opcode::Undefined, &[]);
6139 } else {
6140 let initialiser = self.compile_field_initialiser(
6141 &instance_fields,
6142 class.span,
6143 true,
6144 plan.instance_brand,
6145 )?;
6146 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6147 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6148 // `set_home_object` reads `obj func`, so the prototype stays where it is.
6149 self.emit(Opcode::SetHomeObject, &[]);
6150 }
6151 self.emit_var(VarAction::PutInit, "<class_fields_init>");
6152 // The prototype has done its job: every instance member is defined on it. What
6153 // is left under it is the constructor.
6154 self.emit(Opcode::Drop, &[]);
6155
6156 // The static brand, for `static #m() {}`: same opcode, but the home object is the
6157 // constructor itself, so the symbol lands on the class and the class carries it.
6158 if plan.static_brand {
6159 self.emit(Opcode::Dup, &[]);
6160 self.emit(Opcode::Dup, &[]);
6161 self.emit(Opcode::AddBrand, &[]);
6162 }
6163
6164 // The class binding is initialised *before* static fields run, so a static field
6165 // can refer to the class by name (`static y = S.x`).
6166 // `set_loc` leaves the constructor on the stack, which is what the static field
6167 // call and the outer store both consume.
6168 //
6169 // Only when there *is* such a binding: an anonymous class expression declares no
6170 // class-scope name, and asking for one by the empty string resolved to nothing —
6171 // which made `var x = class {}` assign `undefined` and put a bogus global store in
6172 // the instruction stream.
6173 if let Some(name) = &name {
6174 self.emit_var(VarAction::SetInit, name);
6175 }
6176 if !static_items.is_empty() {
6177 // The static half has no brand prologue of its own: the constructor got its
6178 // brand above, before this runs.
6179 let initialiser =
6180 self.compile_field_initialiser(&static_items, class.span, false, false)?;
6181 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6182 self.emit(Opcode::Dup, &[]);
6183 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6184 self.emit(Opcode::SetHomeObject, &[]);
6185 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6186 self.emit(Opcode::Drop, &[]);
6187 }
6188 // The body is over, and with it this class's private names.
6189 let _ = self.private_scopes.pop();
6190 self.emit_scope_leave(key);
6191 self.state().current_block = parent_block;
6192 if keep {
6193 // A class *expression* is its own value; the class-scope binding was only
6194 // ever an alias for it.
6195 return Ok(());
6196 }
6197 // A declaration stores into the binding the enclosing statement declared.
6198 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6199 Ok(())
6200 }
6201
6202 fn push_this(&mut self) {
6203 self.emit(Opcode::PushThis, &[]);
6204 }
6205
6206 /// `this`, which an arrow does not have of its own.
6207 ///
6208 /// The reference gives the enclosing function a local named `this`, initialised from
6209 /// `push_this` at the top of its body, and the arrow then reads it as a captured
6210 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6211 /// the arrow is called with none.
6212 fn this_expression(&mut self) {
6213 // In a class constructor `this` is a local: a derived constructor only gets one
6214 // when `super()` returns, and reading the raw receiver would give the *outer*
6215 // one instead.
6216 if self.cur().ctor_kind != CtorKind::None {
6217 self.emit_var(VarAction::Get, "this");
6218 return;
6219 }
6220 if !self.cur().is_arrow {
6221 self.push_this();
6222 return;
6223 }
6224 // An arrow at the **top level** of a script or module has no enclosing function,
6225 // but it still inherits `this` — the script's or module's own. Falling through to
6226 // `emit_var(Get, "this")` without a target made that a *global* lookup, so
6227 // `var f = () => typeof this` at top level reported
6228 // `ReferenceError: 'this' is not defined` instead of `"object"`
6229 // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
6230 // is the test262 case that reaches it, through a native `forEach`).
6231 //
6232 // The script state is the bottom of the stack, so it is the fallback target. Its
6233 // own `provide_this_local` then prepends the `push_this` the arrow reads.
6234 let target = self.enclosing_function().unwrap_or(0);
6235 self.state_at(target).needs_this_local = true;
6236 self.declare_at(target, "this");
6237 self.emit_var(VarAction::Get, "this");
6238 }
6239
6240 /// `new.target`, which an arrow likewise does not own.
6241 fn new_target_expression(&mut self) {
6242 if !self.cur().is_arrow {
6243 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6244 return;
6245 }
6246 if let Some(target) = self.enclosing_function() {
6247 self.state_at(target).needs_new_target_local = true;
6248 self.declare_at(target, NEW_TARGET);
6249 }
6250 self.emit_var(VarAction::Get, NEW_TARGET);
6251 }
6252
6253 /// `this.active_func`: the function `super()` resolves against.
6254 ///
6255 /// In a constructor or a method that is the function being run, so the special object
6256 /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6257 /// a closure variable — see [`FnState::needs_active_func_local`].
6258 fn active_func_expression(&mut self) {
6259 if !self.cur().is_arrow {
6260 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6261 return;
6262 }
6263 if let Some(target) = self.enclosing_function() {
6264 self.state_at(target).needs_active_func_local = true;
6265 self.declare_at(target, ACTIVE_FUNC);
6266 }
6267 self.emit_var(VarAction::Get, ACTIVE_FUNC);
6268 }
6269
6270 /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6271 fn provide_active_func_local(&mut self) {
6272 let current = self.stack.len() - 1;
6273 if !self.stack[current].needs_active_func_local {
6274 return;
6275 }
6276 if !self.stack[current]
6277 .vars
6278 .iter()
6279 .any(|var| var.name == ACTIVE_FUNC)
6280 {
6281 self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6282 }
6283 self.prepend_initialiser(
6284 ACTIVE_FUNC,
6285 Insn::Fixed {
6286 op: Opcode::SpecialObject,
6287 operands: vec![Op::Int(2)],
6288 },
6289 );
6290 }
6291
6292 /// Give the function a local `new.target`, for an arrow inside it to capture.
6293 fn provide_new_target_local(&mut self) {
6294 let current = self.stack.len() - 1;
6295 if !self.stack[current].needs_new_target_local {
6296 return;
6297 }
6298 if !self.stack[current]
6299 .vars
6300 .iter()
6301 .any(|var| var.name == NEW_TARGET)
6302 {
6303 self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6304 }
6305 self.prepend_initialiser(
6306 NEW_TARGET,
6307 Insn::Fixed {
6308 op: Opcode::SpecialObject,
6309 operands: vec![Op::Int(3)],
6310 },
6311 );
6312 }
6313
6314 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6315 /// function.
6316 fn ensure_enclosing_arguments(&mut self) {
6317 // An arrow created in a parameter list needs the *parameter* scope's
6318 // `arguments`, not the body's: the two are separate bindings and the arrow was
6319 // born before the body existed.
6320 let from_params = self.cur().created_in_params;
6321 if let Some(target) = self.enclosing_function() {
6322 self.state_at(target).needs_arguments_local = true;
6323 if from_params {
6324 self.state_at(target).needs_param_arguments = true;
6325 // Declare it now, not at the enclosing function's `finish_current`: the
6326 // arrow resolves its own `arguments` before that runs, and a binding that
6327 // does not exist yet resolves as a global.
6328 declare_param_var_at(&mut self.stack[target], "arguments");
6329 }
6330 self.declare_at(target, "arguments");
6331 }
6332 }
6333
6334 /// The innermost enclosing frame that is a real function — an arrow inherits from it
6335 /// rather than starting a scope of its own.
6336 fn enclosing_function(&self) -> Option<usize> {
6337 (0..self.stack.len())
6338 .rev()
6339 .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
6340 }
6341
6342 fn state_at(&mut self, index: usize) -> &mut FnState {
6343 &mut self.stack[index]
6344 }
6345
6346 /// Declare a `var` binding directly in a specific frame.
6347 fn declare_at(&mut self, index: usize, name: &str) {
6348 let state = &mut self.stack[index];
6349 if state.vars.iter().any(|var| var.name == name) {
6350 return;
6351 }
6352 state.var_block.push(FUNCTION_SCOPE);
6353 state.vars.push(VarDef::var(name));
6354 }
6355
6356 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6357 /// the reference calls a `special_object` gets initialised on entry.
6358 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6359 let current = self.stack.len() - 1;
6360 let init = [
6361 producer,
6362 Insn::Var {
6363 action: VarAction::Put,
6364 name: name.to_string(),
6365 block: 0,
6366 // A prologue initialiser runs before the body proper, but it is body
6367 // code: `this` and `arguments` are provided for it, not by it.
6368 in_params: false,
6369 },
6370 ];
6371 let inserted = init.len();
6372 for (index, instruction) in init.into_iter().enumerate() {
6373 self.stack[current].insns.insert(index, instruction);
6374 }
6375 for placed in self.stack[current].labels.iter_mut().flatten() {
6376 *placed += inserted;
6377 }
6378 self.stack[current].label_since_insn = true;
6379 }
6380
6381 fn push_constant(&mut self, constant: Constant) -> u32 {
6382 let state = self.state();
6383 let index = state.cpool.len() as u32;
6384 state.cpool.push(constant);
6385 index
6386 }
6387
6388 /// Compile `a && b`, `a || b`, `a ?? b`.
6389 ///
6390 /// A run of the *same* operator shares one end label, so `a || b || c` tests
6391 /// `a` once and jumps past everything when it is truthy, instead of falling
6392 /// into `b`'s test. The parser builds such a run left-associated —
6393 /// `((a || b) || c)` — so the operands are collected off the left spine.
6394 ///
6395 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6396 /// `||`'s label, because the inner chain really does end before `&&` begins.
6397 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6398 let mut operands = Vec::new();
6399 collect_same_operator(op, left, &mut operands);
6400 operands.push(right);
6401
6402 let end = self.new_label();
6403 // Every operand but the last decides whether the chain stops here.
6404 let last = operands.pop().expect("the right operand is always present");
6405 for operand in operands {
6406 self.expr(operand)?;
6407 self.emit(Opcode::Dup, &[]);
6408 match op {
6409 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6410 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6411 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6412 // `0 || b` is `b`. The dedicated test keeps the value unless it is
6413 // null-ish, so the jump is taken on `false`.
6414 LogicalOp::Coalesce => {
6415 self.emit(Opcode::IsUndefinedOrNull, &[]);
6416 self.emit_jump(Opcode::IfFalse, end, &[]);
6417 }
6418 }
6419 self.emit(Opcode::Drop, &[]);
6420 }
6421 self.expr(last)?;
6422 self.place_label(end);
6423 Ok(())
6424 }
6425
6426 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6427 match op {
6428 UnaryOp::Typeof => {
6429 // `typeof x` must not throw on an undeclared name.
6430 if let ExprKind::Ident(name) = &argument.kind {
6431 self.emit_var(VarAction::GetUndef, &name.name);
6432 } else {
6433 self.expr(argument)?;
6434 }
6435 self.emit(Opcode::Typeof, &[]);
6436 }
6437 UnaryOp::Delete => {
6438 // `delete obj.prop` really deletes, and answers whether it could.
6439 // Deleting a *binding* is always `false`: a local, an argument and a
6440 // declared global are all non-configurable, which the reference encodes
6441 // as a constant `push_false` rather than a runtime check. Only a
6442 // property access has anything to do at run time.
6443 // `delete super.x` is not a delete at all: the spec refuses it, and the
6444 // reference encodes the refusal as a `throw_error`. The receiver and the
6445 // key are still evaluated first, which is what keeps the evaluation order
6446 // of the operand intact.
6447 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6448 // nothing to delete, and a failed delete is not the same as a skipped
6449 // one. The reference emits the guards so they land on a `drop; push_true`
6450 // tail, which is what this reproduces.
6451 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6452 && let ExprKind::Member {
6453 object, property, ..
6454 } = &inner.unparen().kind
6455 {
6456 let end = self.new_label();
6457 let done = self.new_label();
6458 self.chain_link(object, end)?;
6459 match property {
6460 MemberProp::Ident(name) => self.emit(
6461 Opcode::PushAtomValue,
6462 &[Op::Atom(Atom::from_text(&name.name))],
6463 ),
6464 MemberProp::Computed(index) => self.expr(index)?,
6465 MemberProp::Private(_) => {
6466 return Err(SyntaxError::new(
6467 "deleting a private field is not allowed",
6468 argument.span,
6469 ));
6470 }
6471 }
6472 self.emit(Opcode::Delete, &[]);
6473 self.emit_jump(Opcode::Goto, done, &[]);
6474 self.place_label(end);
6475 self.emit(Opcode::Drop, &[]);
6476 self.emit(Opcode::PushTrue, &[]);
6477 self.place_label(done);
6478 return Ok(());
6479 }
6480 if let ExprKind::Member { object, .. } = &argument.unparen().kind
6481 && matches!(object.unparen().kind, ExprKind::SuperProp)
6482 {
6483 self.super_base();
6484 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6485 return Ok(());
6486 }
6487 // Parentheses are transparent to `delete`: `(x)` is still a Reference to
6488 // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
6489 // does, and `delete (a().b)` still evaluates `a()`. Matching on the
6490 // unparenthesised operand is what keeps both — matching on `argument.kind`
6491 // sent every parenthesised form to the "not a Reference" arm, which cost
6492 // `delete(__variable) === false` in test262's `S12.2_A2`.
6493 match &argument.unparen().kind {
6494 ExprKind::Member {
6495 object, property, ..
6496 } => {
6497 self.expr(object)?;
6498 match property {
6499 MemberProp::Ident(name) => {
6500 self.emit(
6501 Opcode::PushAtomValue,
6502 &[Op::Atom(Atom::from_text(&name.name))],
6503 );
6504 }
6505 MemberProp::Computed(index) => self.expr(index)?,
6506 MemberProp::Private(_) => {
6507 return Err(SyntaxError::new(
6508 "deleting a private field is not allowed",
6509 argument.span,
6510 ));
6511 }
6512 }
6513 self.emit(Opcode::Delete, &[]);
6514 }
6515 ExprKind::Ident(name) => {
6516 // `delete name`: a declared global, a local and an argument all
6517 // answer `false`, but an *implicit* global (`x = 1` with no
6518 // declaration) is a configurable property of the global object
6519 // and really goes away. Which of those a name is only the
6520 // resolver knows, so the decision waits for it.
6521 let pos = self.cur().cur_pos;
6522 self.state().insns.push(Insn::DeleteVar {
6523 name: name.name.clone(),
6524 });
6525 self.state().insn_pos.push(pos);
6526 }
6527 // §13.5.1.2 step 2: an operand that is **not** a Reference Record
6528 // answers `true` — there is nothing to delete, and "nothing needed
6529 // deleting" is success. `delete !0`, `delete (1 + 2)` and
6530 // `delete typeof 0` are all `true`, and the operand is still evaluated
6531 // (which is why it is `Drop`ed rather than skipped:
6532 // `delete f()` must call `f`).
6533 //
6534 // Answering `false` here is the C reference's old behaviour and was
6535 // wrong in an observable way: test262's
6536 // `dynamic-import/assignment-expression/logical-and-expr` builds a
6537 // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
6538 // half turned the whole `&&` into `false`, so the import asked for a
6539 // module named "false".
6540 _ => {
6541 self.expr(argument)?;
6542 self.emit(Opcode::Drop, &[]);
6543 self.emit(Opcode::PushTrue, &[]);
6544 }
6545 }
6546 }
6547 UnaryOp::Void => {
6548 self.expr(argument)?;
6549 self.emit(Opcode::Drop, &[]);
6550 self.emit(Opcode::Undefined, &[]);
6551 }
6552 UnaryOp::Minus => {
6553 self.expr(argument)?;
6554 self.emit(Opcode::Neg, &[]);
6555 }
6556 UnaryOp::Plus => {
6557 self.expr(argument)?;
6558 self.emit(Opcode::Plus, &[]);
6559 }
6560 UnaryOp::Not => {
6561 self.expr(argument)?;
6562 self.emit(Opcode::Lnot, &[]);
6563 }
6564 UnaryOp::BitNot => {
6565 self.expr(argument)?;
6566 self.emit(Opcode::Not, &[]);
6567 }
6568 }
6569 Ok(())
6570 }
6571
6572 /// Compile an assignment.
6573 ///
6574 /// Three operator families, three shapes:
6575 ///
6576 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
6577 /// the value is kept, because `put_field`/`put_array_el` consume both the
6578 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
6579 /// the pair it wants and leaves a copy on top.
6580 /// * **compound** `+=` … — read the place, apply the operator, store. A member
6581 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
6582 /// index) underneath the value precisely so the store can follow.
6583 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
6584 /// right-hand side. The test *keeps* the current value and skips the store
6585 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
6586 /// `a` is already truthy.
6587 fn assign(
6588 &mut self,
6589 op: AssignOp,
6590 target: &Pattern,
6591 value: &Expr,
6592 discard: bool,
6593 ) -> Result<(), SyntaxError> {
6594 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
6595 // about, so it is set only when this assignment *is* that expression.
6596 let keep = !discard;
6597 match &target.kind {
6598 PatternKind::Ident(name) => {
6599 // A *simple* store is blamed on the identifier, not on the `=`: a
6600 // strict-mode `not_def = 1` raises when the name is written, which the
6601 // reference reports at the name's column. A compound store is blamed on
6602 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
6603 // which the reference reports at the `+=`), so only the simple case
6604 // moves the position.
6605 let saved = self.cur().cur_pos;
6606 let name_pos = Some(name.span.start);
6607 if matches!(op, AssignOp::Assign) {
6608 self.state().cur_pos = name_pos;
6609 }
6610 // A *compound* store reads the binding before it combines, and that read
6611 // is blamed on the identifier: `not_def += 2` fails while reading
6612 // `not_def`, so the position is the name's, not the `+=`'s. The
6613 // combination that follows is blamed on the operator, which is why
6614 // `cur_pos` is put back to the operator position before it is emitted.
6615 self.state().cur_pos = name_pos;
6616 match op {
6617 AssignOp::Assign => {
6618 self.expr(value)?;
6619 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
6620 // A discarded store to a *slot* consumes its value, so no copy
6621 // is needed. A global store goes through `put_var`, which the
6622 // reference always pairs with a `dup` — matching it keeps the
6623 // bytecode identical. Getting this wrong is not only an extra
6624 // instruction: a stray copy gives the peephole a chance to fold
6625 // the store into an unrelated later read.
6626 let slot = self.is_slot(&name.name);
6627 if keep || !slot {
6628 self.emit(Opcode::Dup, &[]);
6629 }
6630 self.state().no_value = !keep && slot;
6631 self.emit_var(VarAction::Put, &name.name);
6632 }
6633 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6634 let end = self.new_label();
6635 self.emit_var(VarAction::Get, &name.name);
6636 self.state().cur_pos = saved;
6637 self.emit(Opcode::Dup, &[]);
6638 self.emit_logical_test(op);
6639 self.emit_jump(logical_jump(op), end, &[]);
6640 self.emit(Opcode::Drop, &[]);
6641 self.expr(value)?;
6642 self.emit(Opcode::Dup, &[]);
6643 self.emit_var(VarAction::Put, &name.name);
6644 self.place_label(end);
6645 }
6646 _ => {
6647 self.emit_var(VarAction::Get, &name.name);
6648 self.expr(value)?;
6649 self.state().cur_pos = saved;
6650 self.emit(compound_opcode(op), &[]);
6651 self.emit(Opcode::Dup, &[]);
6652 self.emit_var(VarAction::Put, &name.name);
6653 }
6654 }
6655 self.state().cur_pos = saved;
6656 Ok(())
6657 }
6658 PatternKind::Member(member) => {
6659 // `super.x = v` is not a store through a value: it starts at the home
6660 // object's prototype but writes to `this`, so it goes through
6661 // `put_super_value` rather than `put_field`. The receiver, prototype, key
6662 // and value are handed over together.
6663 if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
6664 return self.assign_super(member, op, value);
6665 }
6666 // A store is blamed on the selector punctuator (`.` or `[`), the same
6667 // token a load is blamed on — the reference records `put_field obj.a`
6668 // at the `.`, so a setter that throws reports that column and not the
6669 // `=` of the assignment it sits in. The inner expressions restore their
6670 // own positions, so the selector's sticks for the store instructions.
6671 let saved = self.cur().cur_pos;
6672 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6673 self.expr(&member.object)?;
6674 match &member.property {
6675 MemberProp::Ident(property) => {
6676 let atom = Atom::from_text(&property.name);
6677 match op {
6678 AssignOp::Assign => {
6679 self.expr(value)?;
6680 // `put_field` consumes the object and the value, so
6681 // without `insert2` nothing is left over for the
6682 // statement to drop.
6683 self.state().no_value = !keep;
6684 if keep {
6685 self.emit(Opcode::Insert2, &[]);
6686 }
6687 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6688 }
6689 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6690 // `get_field2` leaves the object under the value, so
6691 // the keep path has an object to dispose of. The store
6692 // path must jump *over* that cleanup: falling into it
6693 // would `nip` a stack that only holds the value.
6694 let (keep_label, end) = (self.new_label(), self.new_label());
6695 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6696 self.emit(Opcode::Dup, &[]);
6697 self.emit_logical_test(op);
6698 self.emit_jump(logical_jump(op), keep_label, &[]);
6699 self.emit(Opcode::Drop, &[]);
6700 self.expr(value)?;
6701 self.emit(Opcode::Insert2, &[]);
6702 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6703 self.emit_jump(Opcode::Goto, end, &[]);
6704 self.place_label(keep_label);
6705 self.emit(Opcode::Nip, &[]);
6706 self.place_label(end);
6707 }
6708 _ => {
6709 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6710 self.expr(value)?;
6711 self.emit(compound_opcode(op), &[]);
6712 self.state().no_value = !keep;
6713 if keep {
6714 self.emit(Opcode::Insert2, &[]);
6715 }
6716 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6717 }
6718 }
6719 }
6720 MemberProp::Computed(index) => {
6721 self.expr(index)?;
6722 match op {
6723 AssignOp::Assign => {
6724 self.expr(value)?;
6725 self.state().no_value = !keep;
6726 if keep {
6727 self.emit(Opcode::Insert3, &[]);
6728 }
6729 self.emit(Opcode::PutArrayEl, &[]);
6730 }
6731 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6732 let (keep_label, end) = (self.new_label(), self.new_label());
6733 self.emit(Opcode::GetArrayEl3, &[]);
6734 self.emit(Opcode::Dup, &[]);
6735 self.emit_logical_test(op);
6736 self.emit_jump(logical_jump(op), keep_label, &[]);
6737 self.emit(Opcode::Drop, &[]);
6738 self.expr(value)?;
6739 self.emit(Opcode::Insert3, &[]);
6740 self.emit(Opcode::PutArrayEl, &[]);
6741 self.emit_jump(Opcode::Goto, end, &[]);
6742 self.place_label(keep_label);
6743 // Both the object and the index are left over.
6744 self.emit(Opcode::Nip, &[]);
6745 self.emit(Opcode::Nip, &[]);
6746 self.place_label(end);
6747 }
6748 _ => {
6749 self.emit(Opcode::GetArrayEl3, &[]);
6750 self.expr(value)?;
6751 self.emit(compound_opcode(op), &[]);
6752 self.state().no_value = !keep;
6753 if keep {
6754 self.emit(Opcode::Insert3, &[]);
6755 }
6756 self.emit(Opcode::PutArrayEl, &[]);
6757 }
6758 }
6759 }
6760 MemberProp::Private(name) => {
6761 // `obj value` is on the stack, and every private store wants exactly
6762 // that. A top-level private name cannot be assigned (the parser rejects
6763 // `#x = 1`), so the only way here is `this.#x = …` inside the class.
6764 //
6765 // The reference emits `insert2` whether or not the value is wanted,
6766 // so this does too: the copy left behind is the assignment expression's
6767 // value, and a discarded one is simply never read.
6768 let binding = format!("#{}", name.name);
6769 let (kind, setter) = self.private_use(&binding, member.span)?;
6770 match op {
6771 AssignOp::Assign => {
6772 self.expr(value)?;
6773 if keep {
6774 self.emit(Opcode::Insert2, &[]);
6775 }
6776 self.private_store(&binding, kind, setter.as_deref())?;
6777 self.state().no_value = !keep;
6778 }
6779 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6780 let (keep_label, end) = (self.new_label(), self.new_label());
6781 self.emit(Opcode::Dup, &[]);
6782 self.private_load(&binding, kind, member.span)?;
6783 self.emit(Opcode::Dup, &[]);
6784 self.emit_logical_test(op);
6785 self.emit_jump(logical_jump(op), keep_label, &[]);
6786 self.emit(Opcode::Drop, &[]);
6787 self.expr(value)?;
6788 self.emit(Opcode::Insert2, &[]);
6789 self.private_store(&binding, kind, setter.as_deref())?;
6790 self.emit_jump(Opcode::Goto, end, &[]);
6791 self.place_label(keep_label);
6792 self.emit(Opcode::Nip, &[]);
6793 self.place_label(end);
6794 }
6795 _ => {
6796 self.emit(Opcode::Dup, &[]);
6797 self.private_load(&binding, kind, member.span)?;
6798 self.expr(value)?;
6799 self.emit(compound_opcode(op), &[]);
6800 self.emit(Opcode::Insert2, &[]);
6801 self.private_store(&binding, kind, setter.as_deref())?;
6802 }
6803 }
6804 }
6805 }
6806 self.state().cur_pos = saved;
6807 Ok(())
6808 }
6809 // A destructuring assignment: the right-hand side is the expression's own
6810 // value, so it is evaluated once and kept under the pattern's stores.
6811 PatternKind::Array { .. } | PatternKind::Object { .. } => {
6812 self.expr(value)?;
6813 if keep {
6814 self.emit(Opcode::Dup, &[]);
6815 }
6816 self.destructure(target, None)?;
6817 self.state().no_value = !keep;
6818 Ok(())
6819 }
6820 _ => Err(SyntaxError::new(
6821 "this assignment target is not supported by the compiler yet",
6822 target.span,
6823 )),
6824 }
6825 }
6826
6827 /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
6828 ///
6829 /// The stack has to carry four values — receiver, prototype, key, value — because
6830 /// `put_super_value` takes them together; the receiver is what makes a setter found on
6831 /// the prototype run with `this`, and the key has to survive until the store, which is
6832 /// why a compound form converts it to a property key once and `dup3`s rather than
6833 /// evaluating it twice.
6834 fn assign_super(
6835 &mut self,
6836 member: &MemberPattern,
6837 op: AssignOp,
6838 value: &Expr,
6839 ) -> Result<(), SyntaxError> {
6840 let saved = self.cur().cur_pos;
6841 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6842 self.super_base();
6843 match &member.property {
6844 MemberProp::Ident(property) => self.emit(
6845 Opcode::PushAtomValue,
6846 &[Op::Atom(Atom::from_text(&property.name))],
6847 ),
6848 MemberProp::Computed(index) => self.expr(index)?,
6849 MemberProp::Private(_) => {
6850 return Err(SyntaxError::new(
6851 "private fields are not supported by the compiler yet",
6852 member.span,
6853 ));
6854 }
6855 }
6856 match op {
6857 AssignOp::Assign => {
6858 // The key is only converted once, by `put_super_value` itself, so a
6859 // computed key's `toString` runs exactly once.
6860 self.expr(value)?;
6861 self.emit(Opcode::Insert4, &[]);
6862 self.emit(Opcode::PutSuperValue, &[]);
6863 }
6864 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6865 let (keep_label, end) = (self.new_label(), self.new_label());
6866 self.emit(Opcode::ToPropkey, &[]);
6867 self.emit(Opcode::Dup3, &[]);
6868 self.emit(Opcode::GetSuperValue, &[]);
6869 self.emit(Opcode::Dup, &[]);
6870 self.emit_logical_test(op);
6871 self.emit_jump(logical_jump(op), keep_label, &[]);
6872 self.emit(Opcode::Drop, &[]);
6873 self.expr(value)?;
6874 self.emit(Opcode::Insert4, &[]);
6875 self.emit(Opcode::PutSuperValue, &[]);
6876 self.emit_jump(Opcode::Goto, end, &[]);
6877 self.place_label(keep_label);
6878 // The prototype and the key are still under the value that was read.
6879 self.emit(Opcode::Nip, &[]);
6880 self.emit(Opcode::Nip, &[]);
6881 self.emit(Opcode::Nip, &[]);
6882 self.place_label(end);
6883 }
6884 _ => {
6885 self.emit(Opcode::ToPropkey, &[]);
6886 self.emit(Opcode::Dup3, &[]);
6887 self.emit(Opcode::GetSuperValue, &[]);
6888 self.expr(value)?;
6889 self.emit(compound_opcode(op), &[]);
6890 self.emit(Opcode::Insert4, &[]);
6891 self.emit(Opcode::PutSuperValue, &[]);
6892 }
6893 }
6894 // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
6895 // is still on the stack when the store finishes, and the expression statement is
6896 // what disposes of it — the same arrangement as `put_field`, reached from the other
6897 // side: there the store consumes the value (`no_value`), here it leaves it
6898 // (`keep` already false, so nothing tells the statement otherwise).
6899 self.state().cur_pos = saved;
6900 Ok(())
6901 }
6902
6903 /// The test a logical assignment applies to the current value.
6904 ///
6905 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
6906 /// assign, while `0 ||= b` must not.
6907 fn emit_logical_test(&mut self, op: AssignOp) {
6908 if op == AssignOp::Coalesce {
6909 self.emit(Opcode::IsUndefinedOrNull, &[]);
6910 }
6911 }
6912
6913 /// The private name `#name` this use site resolves against.
6914 ///
6915 /// The parser has already rejected a name no enclosing class declares, so a miss here
6916 /// means the compiler lost track of a class scope — which is worth a real error rather
6917 /// than an `unwrap`.
6918 fn private_use(
6919 &self,
6920 binding: &str,
6921 span: Span,
6922 ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
6923 ClassPlan::find(self, binding)
6924 .map(|use_| (use_.kind, use_.setter.clone()))
6925 .ok_or_else(|| {
6926 SyntaxError::new(
6927 format!("the private name '{binding}' is out of scope here"),
6928 span,
6929 )
6930 })
6931 }
6932
6933 /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
6934 ///
6935 /// The three readable kinds take three different instructions, because a private name
6936 /// holds three different things — a symbol, a method function, a getter function — and
6937 /// only the first one is a property read at all.
6938 fn private_load(
6939 &mut self,
6940 binding: &str,
6941 kind: PrivateKind,
6942 span: Span,
6943 ) -> Result<(), SyntaxError> {
6944 match kind {
6945 PrivateKind::Field => {
6946 self.emit_var(VarAction::Get, binding);
6947 self.emit(Opcode::GetPrivateField, &[]);
6948 }
6949 PrivateKind::Method => {
6950 self.emit_var(VarAction::Get, binding);
6951 self.emit(Opcode::CheckBrand, &[]);
6952 // `check_brand` reads `obj func` and leaves both; the method itself is what
6953 // `this.#m` evaluates to.
6954 self.emit(Opcode::Nip, &[]);
6955 }
6956 PrivateKind::Getter => {
6957 self.emit_var(VarAction::Get, binding);
6958 self.emit(Opcode::CheckBrand, &[]);
6959 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6960 }
6961 // `#a` is declared but never filled when only a setter exists, so reading it is
6962 // the same refusal as assigning to a `const`. The reference reports it with the
6963 // generic read-only wording and leaves the better message as a `XXX`.
6964 PrivateKind::Setter => self.emit(
6965 Opcode::ThrowError,
6966 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6967 ),
6968 }
6969 let _ = span;
6970 Ok(())
6971 }
6972
6973 /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
6974 fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
6975 match kind {
6976 // A method *is* the callee, so only the check goes in between.
6977 PrivateKind::Method => {
6978 self.emit_var(VarAction::Get, binding);
6979 self.emit(Opcode::CheckBrand, &[]);
6980 }
6981 _ => self.private_load(binding, kind, Span::default())?,
6982 }
6983 Ok(())
6984 }
6985
6986 /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
6987 /// wanted back.
6988 ///
6989 /// A getter/setter pair is a *method call*, not a property store: the reference reads
6990 /// the setter out of its own binding and calls it with the receiver, which is why the
6991 /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
6992 /// keeps the assignment's value for an expression context.
6993 fn private_store(
6994 &mut self,
6995 binding: &str,
6996 kind: PrivateKind,
6997 setter: Option<&str>,
6998 ) -> Result<(), SyntaxError> {
6999 match kind {
7000 PrivateKind::Field => {
7001 self.emit_var(VarAction::Get, binding);
7002 self.emit(Opcode::PutPrivateField, &[]);
7003 }
7004 PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
7005 Some(setter) => {
7006 self.emit_var(VarAction::Get, setter);
7007 // `obj func value` -> `value obj func` for the check, and back again for
7008 // the call, which wants `obj func arg`.
7009 self.emit(Opcode::Swap, &[]);
7010 self.emit(Opcode::Rot3r, &[]);
7011 self.emit(Opcode::CheckBrand, &[]);
7012 self.emit(Opcode::Rot3l, &[]);
7013 self.emit(Opcode::CallMethod, &[Op::Int(1)]);
7014 // The setter's return value is discarded; the assignment's own value is
7015 // whatever the caller left underneath.
7016 self.emit(Opcode::Drop, &[]);
7017 }
7018 None => self.emit(
7019 Opcode::ThrowError,
7020 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7021 ),
7022 },
7023 }
7024 Ok(())
7025 }
7026
7027 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
7028 let instruction = match (op, prefix) {
7029 (UpdateOp::Increment, true) => Opcode::Inc,
7030 (UpdateOp::Increment, false) => Opcode::PostInc,
7031 (UpdateOp::Decrement, true) => Opcode::Dec,
7032 (UpdateOp::Decrement, false) => Opcode::PostDec,
7033 };
7034 if let ExprKind::Member {
7035 object,
7036 property,
7037 optional: _,
7038 } = &argument.kind
7039 {
7040 // `o.x++` needs the receiver twice, so the last link is read with the
7041 // `get_*2`/`get_*3` form that keeps it, and the update is written back
7042 // with `put_field`/`put_array_el`. The reordering in between is what puts
7043 // the old value below the receiver for a postfix update and the new one
7044 // above it for a prefix one:
7045 //
7046 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
7047 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
7048 //
7049 // This mirrors the reference instruction for instruction.
7050 self.expr(object)?;
7051 match property {
7052 MemberProp::Ident(name) => {
7053 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
7054 self.emit(instruction, &[]);
7055 self.emit(
7056 if prefix {
7057 Opcode::Insert2
7058 } else {
7059 Opcode::Perm3
7060 },
7061 &[],
7062 );
7063 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
7064 }
7065 MemberProp::Computed(index) => {
7066 self.expr(index)?;
7067 self.emit(Opcode::GetArrayEl3, &[]);
7068 self.emit(instruction, &[]);
7069 self.emit(
7070 if prefix {
7071 Opcode::Insert3
7072 } else {
7073 Opcode::Perm4
7074 },
7075 &[],
7076 );
7077 self.emit(Opcode::PutArrayEl, &[]);
7078 }
7079 MemberProp::Private(name) => {
7080 // The receiver is duplicated and the read keeps it, exactly as `get_field2`
7081 // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
7082 // `perm3` -> `old obj new` -> store.
7083 let binding = format!("#{}", name.name);
7084 let (kind, setter) = self.private_use(&binding, argument.span)?;
7085 self.emit(Opcode::Dup, &[]);
7086 self.private_load(&binding, kind, argument.span)?;
7087 self.emit(instruction, &[]);
7088 self.emit(
7089 if prefix {
7090 Opcode::Insert2
7091 } else {
7092 Opcode::Perm3
7093 },
7094 &[],
7095 );
7096 self.private_store(&binding, kind, setter.as_deref())?;
7097 }
7098 }
7099 return Ok(());
7100 }
7101 let ExprKind::Ident(name) = &argument.kind else {
7102 return Err(SyntaxError::new(
7103 "increment of a non-variable is not supported by the compiler yet",
7104 argument.span,
7105 ));
7106 };
7107 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
7108 // reference's `inc_loc` folds those three into one, but it does so only in some
7109 // positions (a `for` update and not a bare statement, and never for a lexical
7110 // binding), so emitting it unconditionally would move *away* from its output.
7111 // The instruction is equivalent either way; matching the reference matters more
7112 // than saving two instructions.
7113 let _ = !std::mem::take(&mut self.state().discard_value);
7114 self.emit_var(VarAction::Get, &name.name);
7115 self.emit(instruction, &[]);
7116 if prefix {
7117 self.emit(Opcode::Dup, &[]);
7118 }
7119 self.emit_var(VarAction::Put, &name.name);
7120 Ok(())
7121 }
7122
7123 /// Compile an array literal.
7124 ///
7125 /// The reference splits this into three phases, and the split is load-bearing
7126 /// rather than an optimisation detail:
7127 ///
7128 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
7129 /// the array in one instruction.
7130 /// 2. **Everything up to the first spread** is appended with explicit indices
7131 /// (`define_field <index>`), because a hole has no element to pass to
7132 /// `array_from`. A hole here is what makes `length` need fixing up: an
7133 /// explicit index does not extend the array the way a pushed element does.
7134 /// 3. **From the first spread on** the index lives on the stack, so `append` and
7135 /// `define_array_el` can consume it and `inc` advances it.
7136 ///
7137 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
7138 /// forces phase 2, and `[...a]` forces phase 3.
7139 fn array_literal(
7140 &mut self,
7141 elements: &[Option<ArrayElement>],
7142 span: Span,
7143 ) -> Result<(), SyntaxError> {
7144 let _ = span;
7145 let mut index: u32 = 0;
7146 let mut cursor = 0usize;
7147
7148 // Phase 1: a leading run of plain elements, at most 32 of them.
7149 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
7150 if index >= 32 {
7151 break;
7152 }
7153 self.expr(element)?;
7154 index += 1;
7155 cursor += 1;
7156 }
7157 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
7158
7159 // Phase 2: explicit indices, up to the first spread.
7160 let mut need_length = false;
7161 while let Some(element) = elements.get(cursor) {
7162 if matches!(element, Some(ArrayElement::Spread(_))) {
7163 break;
7164 }
7165 need_length = true;
7166 if let Some(ArrayElement::Expr(expression)) = element {
7167 self.expr(expression)?;
7168 self.emit_define_index(index);
7169 need_length = false;
7170 }
7171 index += 1;
7172 cursor += 1;
7173 }
7174
7175 if cursor >= elements.len() {
7176 if need_length {
7177 // `define_field` cannot set `length`, which is not configurable.
7178 self.emit(Opcode::Dup, &[]);
7179 self.push_number(index as f64);
7180 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7181 }
7182 return Ok(());
7183 }
7184
7185 // Phase 3: the index moves onto the stack for the spreading tail.
7186 //
7187 // `need_length` deliberately carries over from phase 2: a hole before the
7188 // first spread still has to be reflected in `length`, and only the final
7189 // check can do it because the array is not finished until the tail is
7190 // appended.
7191 self.push_number(index as f64);
7192 while let Some(element) = elements.get(cursor) {
7193 match element {
7194 Some(ArrayElement::Spread(expression)) => {
7195 // `append` copies an iterable and leaves the next index behind,
7196 // so no `inc` is needed here.
7197 self.expr(spread_argument(expression))?;
7198 self.emit(Opcode::Append, &[]);
7199 }
7200 None | Some(ArrayElement::Expr(_)) => {
7201 need_length = true;
7202 if let Some(ArrayElement::Expr(expression)) = element {
7203 self.expr(expression)?;
7204 self.emit(Opcode::DefineArrayEl, &[]);
7205 need_length = false;
7206 }
7207 self.emit(Opcode::Inc, &[]);
7208 }
7209 }
7210 cursor += 1;
7211 }
7212 if need_length {
7213 self.emit(Opcode::Dup1, &[]);
7214 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7215 } else {
7216 self.emit(Opcode::Drop, &[]);
7217 }
7218 Ok(())
7219 }
7220
7221 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
7222 fn emit_define_index(&mut self, index: u32) {
7223 self.emit(
7224 Opcode::DefineField,
7225 &[Op::Atom(Atom::from_text(&index.to_string()))],
7226 );
7227 }
7228
7229 // -- functions ---------------------------------------------------------
7230
7231 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
7232 self.compile_function_with_name(func, false)
7233 }
7234
7235 /// Compile a function, recording whether it is a *named function expression*.
7236 ///
7237 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
7238 /// must not leak outside. The reference does that by declaring `g` as a local of
7239 /// the function itself and initialising it with `special_object 2` (the current
7240 /// function), which is why this has to be known at compile time.
7241 fn compile_function_with_name(
7242 &mut self,
7243 func: &ast::Function,
7244 is_expression: bool,
7245 ) -> Result<CompiledFunction, SyntaxError> {
7246 let kind = match (func.is_generator, func.is_async) {
7247 (false, false) => FunctionKind::Normal,
7248 (true, false) => FunctionKind::Generator,
7249 (false, true) => FunctionKind::Async,
7250 (true, true) => FunctionKind::AsyncGenerator,
7251 };
7252 let mut state = FnState::new(
7253 func.name
7254 .as_ref()
7255 .map(|n| n.name.clone())
7256 .unwrap_or_default(),
7257 kind,
7258 );
7259 // The function's own mode, recorded by the parser. Inheriting the enclosing
7260 // function's instead let a nested `"use strict"` directive be ignored, so the
7261 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
7262 state.strict = func.strict;
7263 // A function defined inside a `with` block keeps seeing that object: the guard
7264 // chain names the enclosing `<with>` locals, which resolve outward into closure
7265 // variables exactly like any other captured binding.
7266 state.with_names = self.cur().with_names.clone();
7267 state.is_arrow = func.is_arrow;
7268 state.created_in_block = self.cur().current_block;
7269 // A default anywhere in the parameter list is what gives the function two
7270 // variable environments. The reference decides this the same way: it scans the
7271 // parenthesis for a top-level `=`, so a destructured name without a default
7272 // stays a plain function-scope binding.
7273 state.in_params = false;
7274 // The reference scans the parenthesis for *any* `=`, including one nested inside
7275 // a pattern, so `function f({a = 1})` has parameter expressions even though the
7276 // parameter itself carries no initialiser.
7277 state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7278 // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
7279 // flag above this looks at the *shape* of each parameter, not just for `=`.
7280 state.simple_parameter_list = func
7281 .params
7282 .iter()
7283 .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
7284 // A function born inside a parameter list inherits the prohibition: it must not
7285 // see the body bindings of the function it was created in.
7286 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
7287 // A class constructor knows what it is only because the class told it.
7288 if let Some(kind) = self.cur().class_ctor_pending {
7289 state.ctor_kind = kind;
7290 }
7291 // A named *expression* binds its own name; a declaration's name is already
7292 // bound in the enclosing scope.
7293 state.self_name = if is_expression && !func.is_arrow {
7294 func.name.as_ref().map(|n| n.name.clone())
7295 } else {
7296 None
7297 };
7298 // Keep the written range so `Function.prototype.toString` can answer with the
7299 // original text rather than `[native code]`.
7300 //
7301 // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
7302 // accessor and generator prefixes, and for a method it must not include the name
7303 // or a leading `static`. `params_span` is exactly that boundary.
7304 // A *method* keeps the old `[native code]` answer: its reported text is defined
7305 // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
7306 // the comments in between kept verbatim), and reconstructing that from a byte
7307 // span got it wrong in more cases than it got right. A plain function and an
7308 // arrow are the shapes libraries actually introspect, and those are exact.
7309 // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
7310 // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
7311 // so the same slice works for every form. (`Params_span` is the boundary that
7312 // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
7313 // `source_span` is set only where the reported text is not the function's own
7314 // range — a class's constructor reports the whole class definition.
7315 let reported = func.source_span.unwrap_or(func.span);
7316 state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
7317 state.line = func.span.start.line;
7318 state.column = func.span.start.column;
7319 // A function body has no hidden `<ret>` local; the value comes back on
7320 // the stack. Only a script keeps one.
7321 // Parameters are positional, so even a pattern occupies one argument slot. A
7322 // simple name is that slot itself; anything else (a pattern, a default, a rest
7323 // parameter) takes an anonymous slot and is unpicked into locals at the top of
7324 // the body, which is the only way one argument can bind several names.
7325 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
7326 // `.length` stops at the first parameter that can be substituted: a default
7327 // fills a missing argument in, and a rest parameter absorbs the rest.
7328 let mut defined_args = func.params.len() as u32;
7329 for (index, param) in func.params.iter().enumerate() {
7330 match simple_parameter(param) {
7331 Some(name) => state.args.push(VarDef::var(name.name.clone())),
7332 None => {
7333 state.args.push(VarDef::var(ANONYMOUS_BINDING));
7334 prologue.push((index, param.clone()));
7335 }
7336 }
7337 }
7338 // A default anywhere before the end also ends the count, which the loop above
7339 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
7340 for (position, param) in func.params.iter().enumerate() {
7341 if matches!(
7342 param.kind,
7343 PatternKind::Assign { .. } | PatternKind::Rest(_)
7344 ) {
7345 defined_args = position as u32;
7346 break;
7347 }
7348 }
7349 state.defined_args = defined_args;
7350 state.param_prologue = prologue;
7351 let depth = self.stack.len();
7352 self.stack.push(state);
7353 let result = self.compile_function_body(func);
7354 if result.is_err() {
7355 // A failed compile must not leave its `FnState` behind. Every caller
7356 // reads `self.state()` as "the function being compiled", so a leftover
7357 // frame silently retargets all later bookkeeping at a dead function.
7358 self.stack.truncate(depth);
7359 }
7360 result
7361 }
7362
7363 /// The body of a function, with its frame already pushed.
7364 fn compile_function_body(
7365 &mut self,
7366 func: &ast::Function,
7367 ) -> Result<CompiledFunction, SyntaxError> {
7368 let body_key = func.params_span.end.offset as u64;
7369 // Where the body begins, in source order. The runtime needs this to tell a
7370 // closure created by a default expression from one the body creates — the two see
7371 // different variable environments — and a bytecode offset would not survive the
7372 // instruction shuffling that building the frame does. Positions are in source
7373 // order, so a comparison answers it.
7374 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7375 self.push_block(body_key, NO_PARENT);
7376 self.state().body_block = body_key;
7377 // An arrow with an expression body has no statements; the expression is
7378 // its `return`. Building the statement here keeps one code path below, and
7379 // matters for correctness beyond convenience: returning early with the new
7380 // `FnState` still on the stack would leave the compiler looking at the
7381 // wrong function, which surfaces as an unrelated underflow later.
7382 let concise = match &func.body {
7383 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
7384 StmtKind::Return(Some(Box::new((**value).clone()))),
7385 value.span,
7386 )),
7387 js_parse::ast::FunctionBody::Block(_) => None,
7388 };
7389 let body: &[Stmt] = match &concise {
7390 Some(stmt) => std::slice::from_ref(stmt),
7391 None => func
7392 .body
7393 .statements()
7394 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
7395 };
7396 let prologue = std::mem::take(&mut self.state().param_prologue);
7397 let has_param_scope = self.cur().has_parameter_expressions;
7398 // The parameter scope's own bindings, declared in source order.
7399 //
7400 // With parameter expressions the list gets a variable environment of its own, and
7401 // every name it binds is a `let` there. That is what puts the *list* in the
7402 // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
7403 // and `function f(x = y, y){}` does the same, where a single shared environment
7404 // would answer `undefined` to both.
7405 if has_param_scope {
7406 let mut declared: Vec<String> = Vec::new();
7407 for param in &func.params {
7408 let mut names = Vec::new();
7409 param.bound_names(&mut names);
7410 for name in names {
7411 if declared.contains(&name.name) {
7412 continue;
7413 }
7414 declared.push(name.name.clone());
7415 self.declare_param_binding(&name.name);
7416 }
7417 }
7418 }
7419 // A pattern parameter binds its names as function-scope locals, so they have to
7420 // exist — and be unpicked from the argument — before the body runs. With a
7421 // parameter scope these are the *second* environment: the pattern fills the
7422 // parameter's copy, and the body's binding is filled from it afterwards.
7423 for (_, pattern) in &prologue {
7424 let mut names = Vec::new();
7425 pattern.bound_names(&mut names);
7426 for name in names {
7427 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
7428 }
7429 }
7430 self.hoist(body, body_key)?;
7431 // A constructor's prologue is not a parameter unpacking but the `this` binding:
7432 // a base constructor takes the receiver, a derived one starts in the dead zone
7433 // because only `super()` may produce it.
7434 match self.cur().ctor_kind {
7435 CtorKind::None => {}
7436 CtorKind::Base => {
7437 self.begin_this_local();
7438 self.emit(Opcode::CheckCtor, &[]);
7439 // Instance fields are installed at the top of a base constructor's body,
7440 // before any statement — `class C { x = 1; constructor() { this.x } }` sees
7441 // `1`. This used to be emitted at the *tail*, which made every field read
7442 // `undefined` inside the constructor that declared it.
7443 self.call_field_initialiser();
7444 }
7445 CtorKind::Derived => {
7446 self.declare("this", VarDef::lexical("this"));
7447 let slot = self.cur().vars.len() as u32 - 1;
7448 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7449 self.emit(Opcode::CheckCtor, &[]);
7450 }
7451 }
7452 // Entering the parameter list: everything it binds starts in the dead zone.
7453 // The order is the reference's — it walks the scope chain, which is prepended, so
7454 // the bindings come out newest first.
7455 for name in self.param_binding_names().into_iter().rev() {
7456 if let Some(slot) = self.param_binding_slot(&name) {
7457 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7458 }
7459 }
7460 // The whole parameter list is one scope, and nothing in the body exists yet, so
7461 // every name it mentions resolves against the parameter bindings and outward.
7462 self.state().in_params = has_param_scope;
7463 for (index, param) in func.params.iter().enumerate() {
7464 if let Some(pattern) = prologue_pattern(&prologue, index) {
7465 // A destructuring parameter *initialises* its bindings: with a parameter
7466 // scope they are the list's own `let`s, which is why the stores skip the
7467 // dead-zone check, and why the reference reads their properties with
7468 // `get_field2` — a `let` needs no reference.
7469 let kind = if has_param_scope {
7470 VarDeclKind::Let
7471 } else {
7472 VarDeclKind::Var
7473 };
7474 match &pattern.kind {
7475 // `...rest` collects what is left rather than reading one slot.
7476 PatternKind::Rest(inner) => {
7477 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7478 self.destructure(inner, Some(kind))?;
7479 }
7480 _ => {
7481 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7482 self.destructure(pattern, Some(kind))?;
7483 }
7484 }
7485 continue;
7486 }
7487 // A plain name binds straight from its argument slot. With a parameter scope
7488 // the slot is also copied into the parameter binding, which is what a later
7489 // default (or a closure made among the defaults) reads.
7490 let Some(name) = simple_parameter(param) else {
7491 continue;
7492 };
7493 let target = self.param_binding_slot(&name.name);
7494 if matches!(param.kind, PatternKind::Rest(_)) {
7495 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7496 if let Some(slot) = target {
7497 self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
7498 }
7499 // `put_arg` rather than `set_arg`: the array is the last thing on the
7500 // stack and nothing keeps it. Named by hand because a name in the
7501 // parameter list resolves to the parameter binding, and this store has to
7502 // reach the *argument* — that is what the body reads.
7503 self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
7504 continue;
7505 }
7506 if let PatternKind::Assign { default, .. } = ¶m.kind {
7507 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7508 let has_value = self.new_label();
7509 self.emit(Opcode::Dup, &[]);
7510 self.emit(Opcode::IsUndefined, &[]);
7511 self.emit_jump(Opcode::IfFalse, has_value, &[]);
7512 self.emit(Opcode::Drop, &[]);
7513 self.expr(default)?;
7514 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
7515 // The argument slot keeps the substituted value, because the *body* reads
7516 // the slot rather than the parameter binding — so this store is named
7517 // explicitly, like the rest parameter's.
7518 self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7519 self.place_label(has_value);
7520 if let Some(slot) = target {
7521 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7522 }
7523 continue;
7524 }
7525 if let Some(slot) = target {
7526 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7527 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7528 }
7529 }
7530 // Copy the parameter scope into the body. A plain parameter needs nothing: the
7531 // body reads its argument slot, and the list kept the two in step. A name a
7532 // pattern bound has no argument slot of its own, so the body gets a `var` filled
7533 // from the parameter's copy — and *that* is why an assignment inside a default
7534 // does not reach the body.
7535 if has_param_scope {
7536 for (_, pattern) in &prologue {
7537 let mut names = Vec::new();
7538 pattern.bound_names(&mut names);
7539 for name in names {
7540 let Some(slot) = self.param_binding_slot(&name.name) else {
7541 continue;
7542 };
7543 let Some(body) = self.body_var_slot(&name.name) else {
7544 continue;
7545 };
7546 self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
7547 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
7548 }
7549 }
7550 }
7551 // The parameter list is over; from here on a direct `eval` belongs to the body.
7552 self.state().in_params = false;
7553 // Entering the body's own scope comes *after* the parameter list: the body's
7554 // `let`s are not in existence while the defaults run, and the reference emits
7555 // their `set_loc_uninitialized` only once the parameters are bound.
7556 self.emit_scope_enter(body_key);
7557 // A generator starts suspended: `initial_yield` parks the body so that creating one
7558 // runs no body code until the first `next()`.
7559 //
7560 // It comes *after* the parameter unpacking, not before, because a parameter
7561 // initialiser is not body code — `function* g(a = sideEffect())` must run
7562 // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
7563 // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
7564 // until the first `next()` and 29 test262 cases that check for a synchronous throw
7565 // saw none at all.
7566 //
7567 // An async function does **not** get one. Its body runs synchronously up to the
7568 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
7569 // before its caller's next statement — so an `initial_yield` here would park the
7570 // body before it started, which is not fixable at run time: the suspension looks
7571 // exactly like a real `await`.
7572 if self.cur().kind.is_generator() {
7573 self.emit(Opcode::InitialYield, &[]);
7574 }
7575 // Through `stmts`: the body is a block, and a `using` declaration in it is a
7576 // disposal region.
7577 self.stmts(body)?;
7578 // The implicit return only exists if control can actually get here: an
7579 // infinite loop never falls off the end.
7580 if self.end_is_reachable() {
7581 if self.cur().is_suspending() {
7582 // Falling off the end finishes the generator with `undefined`, and the
7583 // value is what tells the resume machinery "completed" rather than
7584 // "suspended".
7585 self.emit(Opcode::Undefined, &[]);
7586 self.emit(Opcode::ReturnAsync, &[]);
7587 } else {
7588 self.emit_class_constructor_tail();
7589 }
7590 }
7591 // Resolution runs while this function is still on the stack: capturing a
7592 // variable from an enclosing function means reaching into that
7593 // function's state, which requires the whole chain to be present.
7594 Ok(self.finish_current())
7595 }
7596
7597 /// Put every binding of a function that contains a direct `eval` into a cell.
7598 ///
7599 /// A direct eval can name any binding in scope, and any closure it creates has to
7600 /// keep sharing that binding after the function returns — `for (let i …)
7601 /// eval("push(() => i)")` collects one closure per iteration and each must read its
7602 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
7603 /// a cell. Doing this unconditionally for such functions is the cheap, honest
7604 /// answer: the alternative is knowing at compile time which names a string will
7605 /// mention.
7606 fn capture_everything_for_eval(&mut self) {
7607 let current = self.stack.len() - 1;
7608 if !self.stack[current].has_direct_eval {
7609 return;
7610 }
7611 for arg in &mut self.stack[current].args {
7612 arg.is_captured = true;
7613 }
7614 for var in &mut self.stack[current].vars {
7615 var.is_captured = true;
7616 }
7617 }
7618
7619 /// Whether the current position in the instruction stream can be reached.
7620 ///
7621 /// A walk over the control-flow graph, using labels as instruction indices.
7622 /// The reference does the same thing to decide whether an implicit
7623 /// `return_undef` is needed.
7624 fn end_is_reachable(&self) -> bool {
7625 let state = self.cur();
7626 reachable_instructions(state, state.insns.len())[state.insns.len()]
7627 }
7628
7629 /// Resolve and assemble the function on top of the compiler stack, then pop
7630 /// it.
7631 fn finish_current(&mut self) -> CompiledFunction {
7632 self.provide_param_arguments();
7633 self.provide_arguments();
7634 self.provide_this_local();
7635 self.provide_new_target_local();
7636 self.provide_home_object_local();
7637 self.provide_active_func_local();
7638 self.provide_self_name();
7639 self.materialize_eval_sites();
7640 self.capture_everything_for_eval();
7641 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
7642 // Captured bindings need a reference cell; the count goes in the header so
7643 // the runtime knows how many cells to allocate on entry.
7644 let current = self.stack.len() - 1;
7645 let captured = self.stack[current]
7646 .args
7647 .iter()
7648 .filter(|a| a.is_captured)
7649 .count()
7650 + self.stack[current]
7651 .vars
7652 .iter()
7653 .filter(|v| v.is_captured)
7654 .count();
7655 self.stack[current].var_ref_count = captured as u32;
7656 // The scope chain is only final now that every binding is known.
7657 rebuild_scope_chain(&mut self.stack[current]);
7658 let (code, stack_size, positions) =
7659 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
7660 let _ = &mut resolved;
7661 let mut state = self.stack.pop().expect("a function is being compiled");
7662 CompiledFunction {
7663 name: state.name,
7664 kind: state.kind,
7665 strict: state.strict,
7666 is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
7667 is_arrow: state.is_arrow,
7668 has_parameter_expressions: state.has_parameter_expressions,
7669 simple_parameter_list: state.simple_parameter_list,
7670 body_start: state.body_start,
7671 args: state.args,
7672 defined_args: state.defined_args,
7673 vars: state.vars,
7674 closure_vars: state.closure_vars,
7675 cpool: state.cpool,
7676 atoms: state.atoms,
7677 code,
7678 stack_size,
7679 var_ref_count: state.var_ref_count,
7680 positions,
7681 source: self.function_source(state.span, state.line, state.column),
7682 line: state.line,
7683 column: state.column,
7684 filename: None,
7685 eval_sites: state.eval_sites,
7686 module: state.module.take().map(Box::new),
7687 }
7688 }
7689}
7690
7691/// Assign each binding a scope level and rebuild the scope chains.
7692///
7693/// Levels are numbered in the order the blocks appear, with 0 reserved for the
7694/// function scope where `var` and hoisted functions live. Every binding outside
7695/// level 0 gets a `scope_next` link to the next binding visible from the same
7696/// point, so walking a block's chain enumerates exactly the bindings live there.
7697///
7698/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
7699/// point at `b`, which is declared later in the source but earlier in the chain.
7700fn rebuild_scope_chain(state: &mut FnState) {
7701 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
7702 // real block that happens to start at offset zero keeps its own level instead of
7703 // being merged into the function scope.
7704 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
7705 for block in &state.blocks {
7706 if !levels.contains(&block.key) {
7707 levels.push(block.key);
7708 }
7709 }
7710 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
7711 let parent_level = |level: usize| -> usize {
7712 if level == 0 {
7713 return 0;
7714 }
7715 let key = levels[level];
7716 let parent = state
7717 .blocks
7718 .iter()
7719 .find(|b| b.key == key)
7720 .map(|b| b.parent)
7721 .unwrap_or(FUNCTION_SCOPE);
7722 level_of(parent)
7723 };
7724
7725 // Own bindings per level, in declaration order.
7726 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
7727 let keys: Vec<u64> = (0..state.vars.len())
7728 .map(|index| {
7729 state
7730 .var_block
7731 .get(index)
7732 .copied()
7733 .unwrap_or(FUNCTION_SCOPE)
7734 })
7735 .collect();
7736 for (index, key) in keys.into_iter().enumerate() {
7737 // The parameter scope is not a block: it is a level of its own with no parent,
7738 // assigned below. Letting it land in level 0 would chain the body's bindings onto
7739 // it, which the reference does not do — the two environments are siblings.
7740 if key == PARAM_SCOPE {
7741 continue;
7742 }
7743 let level = level_of(key);
7744 state.vars[index].scope_level = level as u32;
7745 // A `catch` parameter is part of the runtime scope chain even though it is
7746 // not lexical: the handler's own bindings chain on to it, which is why the
7747 // reference prints `let y [next:1]` with `e` at 1.
7748 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
7749 {
7750 own[level].push(index);
7751 }
7752 }
7753
7754 // A scope's chain is its own bindings in reverse declaration order followed
7755 // by the enclosing scope's chain.
7756 let mut head = vec![-1i32; levels.len()];
7757 for level in 0..levels.len() {
7758 let inherited = if level == 0 {
7759 -1
7760 } else {
7761 head[parent_level(level)]
7762 };
7763 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
7764 head[level] = chain.first().map_or(inherited, |first| *first as i32);
7765 for (position, &index) in chain.iter().enumerate() {
7766 let next = chain
7767 .get(position + 1)
7768 .map_or(inherited, |next| *next as i32);
7769 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
7770 }
7771 }
7772 state.block_heads = head;
7773
7774 // The parameter list is a scope of its own, and it has no parent: the reference pops
7775 // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
7776 // the `-1` a block uses. A level past every real block keeps it out of the walk above
7777 // — nothing but the dump reads it — and the links run newest-to-oldest through the
7778 // bindings themselves, which is the order `set_loc_uninitialized` walks.
7779 let param_level = levels.len() as u32;
7780 let mut previous: Option<usize> = None;
7781 for index in 0..state.vars.len() {
7782 if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
7783 {
7784 continue;
7785 }
7786 state.vars[index].scope_level = param_level;
7787 state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
7788 previous = Some(index);
7789 }
7790}
7791
7792/// This is where names become slots and where the temporal dead zone shows up in
7793/// the instruction stream: a read of a `let`/`const` binding compiles to
7794/// `get_loc_check`, which throws if the binding is still uninitialised.
7795///
7796/// The peephole pass from the reference implementation is applied at the end,
7797/// for the same reason it is applied to resolved bytecode there: the patterns are
7798/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
7799/// resolution. Deleted instructions stay in the list as `None` so that label
7800/// indices remain valid; [`Assembler`] maps them to byte offsets.
7801/// A resolved instruction and the source position it came from.
7802type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
7803
7804/// A resolved instruction paired with its position, which is what `assemble` consumes.
7805type PositionedInsn = (Opcode, Vec<Op>);
7806
7807fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
7808 let current = stack.len() - 1;
7809 // Dead-code elimination, on the symbolic form where labels are still
7810 // instruction indices. A `break` inside a loop leaves the trailing `goto`
7811 // unreachable, and a `return` leaves everything after it unreachable; the
7812 // reference drops both. Doing it here means the emitter never has to think
7813 // about reachability.
7814 strip_empty_gosubs(stack, current);
7815 eliminate_dead_code(stack, current);
7816 let insns = std::mem::take(&mut stack[current].insns);
7817 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
7818 // `insns`, and every arm below pushes exactly one instruction, so the positions
7819 // stay aligned with `out`.
7820 let positions = std::mem::take(&mut stack[current].insn_pos);
7821 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
7822 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
7823 for (index, insn) in insns.iter().enumerate() {
7824 let pos = positions.get(index).copied().flatten();
7825 out_pos.push(pos);
7826 match insn {
7827 Insn::Fixed { op, operands } => {
7828 let operands = operands
7829 .iter()
7830 .map(|operand| match operand {
7831 Op::Atom(atom) => {
7832 Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
7833 }
7834 other => other.clone(),
7835 })
7836 .collect();
7837 out.push(Some((*op, operands)));
7838 }
7839 Insn::Var {
7840 action,
7841 name,
7842 block,
7843 in_params,
7844 } => {
7845 // Both reads and writes in the parameter list address the parameter
7846 // scope. That is what puts the list in the temporal dead zone — a read of
7847 // a later parameter is `get_loc_check` on an uninitialised slot — and it
7848 // is also what keeps an assignment made inside a default away from the
7849 // body, which sees a separate environment.
7850 let slot = resolve_slot(stack, current, name, *block, *in_params);
7851 // A store to the name of a named function expression is special: the
7852 // reference drops it in sloppy mode and throws in strict mode, because
7853 // the binding is immutable but only *checked* when the body is strict.
7854 // The same rule applies when the name is reached through a closure:
7855 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
7856 // the store in the arrow too, not just in the function that owns the
7857 // binding. Reaching the owner means walking the chain of closure
7858 // entries, which is what `self_name_binding` does.
7859 let self_name = matches!(action, VarAction::Put | VarAction::Set)
7860 .then(|| {
7861 // A local of this function is the common case and needs no
7862 // chain walk; only an access that resolves elsewhere can be
7863 // pointing at an enclosing function's name binding.
7864 if let Slot::Loc(index) = slot {
7865 stack[current]
7866 .vars
7867 .get(index as usize)
7868 .filter(|var| var.kind == VarKind::FunctionName)
7869 .map(|var| var.is_const)
7870 } else {
7871 self_name_binding(stack, current, name, *block)
7872 }
7873 })
7874 .flatten();
7875 if let Some(is_const) = self_name {
7876 out.push(Some(if is_const {
7877 (
7878 Opcode::ThrowError,
7879 vec![
7880 Op::AtomId(intern_atom(&mut stack[current], name)),
7881 Op::Int(0),
7882 ],
7883 )
7884 } else {
7885 (Opcode::Drop, Vec::new())
7886 }));
7887 continue;
7888 }
7889 out.push(Some(variable_instruction(stack, current, *action, slot)));
7890 }
7891 Insn::CloseCaptured { name, block } => {
7892 // The block matters: a loop variable is scoped to the `for` head's own
7893 // block, so resolving it against block 0 would miss it entirely and
7894 // silently emit nothing.
7895 let slot = resolve_slot(stack, current, name, *block, false);
7896 // Only a local with a reference cell has anything to close. A global
7897 // or a never-captured local resolves to no instruction at all, which
7898 // keeps the bytecode identical to the reference's.
7899 if let Slot::Loc(index) = slot
7900 && stack[current]
7901 .vars
7902 .get(index as usize)
7903 .is_some_and(|v| v.is_captured)
7904 {
7905 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
7906 } else {
7907 out.push(None);
7908 }
7909 }
7910 Insn::DeleteVar { name } => {
7911 // A binding — a local, an argument, or a declared global — cannot be
7912 // deleted, and the reference encodes that as a constant `push_false`.
7913 // Only an implicit global needs the runtime lookup.
7914 if matches!(
7915 resolve_slot(stack, current, name, 0, false),
7916 Slot::Global(_)
7917 ) {
7918 let atom = intern_atom(&mut stack[current], name);
7919 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
7920 } else {
7921 out.push(Some((Opcode::PushFalse, Vec::new())));
7922 }
7923 }
7924 Insn::Dead => out.push(None),
7925 }
7926 }
7927 // Which label (if any) sits on each instruction, so the jump patterns can
7928 // tell whether they would cross a jump target.
7929 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
7930 for (id, placed) in stack[current].labels.iter().enumerate() {
7931 if let Some(index) = *placed
7932 && index < label_at.len()
7933 && label_at[index].is_none()
7934 {
7935 label_at[index] = Some(id as u32);
7936 }
7937 }
7938 if std::env::var_os("QJS_DEBUG").is_some() {
7939 eprintln!("--- peephole entry ---");
7940 for (i, e) in out.iter().enumerate() {
7941 eprintln!("{i}: {e:?}");
7942 }
7943 eprintln!("label_at: {label_at:?}");
7944 }
7945 peephole(&mut out, &label_at, &stack[current].labels);
7946 (out, out_pos)
7947}
7948
7949/// Find where `name` lives, capturing it in an enclosing function when needed.
7950///
7951/// The search runs outward through the enclosing functions' states, which are
7952/// still on the compiler stack while a nested function is resolved. Finding the
7953/// name in an enclosing function is what creates a closure reference, and every
7954/// function in between has to forward it — a function can only reach its own
7955/// parent's frame.
7956///
7957/// A name declared nowhere is a global. The reference does *not* look it up by
7958/// name from the inner function: the top-level function gets one `[global]`
7959/// entry and every nested function gets a `[global_ref<n>]` pointing at its
7960/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
7961/// rather than `[global]`.
7962/// The lexical blocks enclosing `block`, innermost first.
7963fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
7964 let mut chain = Vec::new();
7965 let mut current = Some(block);
7966 while let Some(key) = current {
7967 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
7968 // explicitly (rather than on "no block with this key") is what keeps a block
7969 // that happens to sit at offset zero from being mistaken for the terminator.
7970 if key == NO_PARENT || chain.contains(&key) {
7971 break;
7972 }
7973 chain.push(key);
7974 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
7975 }
7976 chain
7977}
7978
7979/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
7980///
7981/// The binding may be several functions away: an arrow nested in `function myfunc`
7982/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
7983/// means following `Ref` entries down and then reading the owning function's var table.
7984fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
7985 let state = stack.get(current)?;
7986 // A parameter shadows everything and is never a function-expression name.
7987 if state.args.iter().any(|arg| arg.name == name) {
7988 return None;
7989 }
7990 // A local of this very function: the answer is in its var table.
7991 if let Some(index) = local_slot_index(state, name, block) {
7992 let var = state.vars.get(index)?;
7993 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7994 }
7995 // Otherwise the name lives further out, and the closure entry says how to get
7996 // there. `Local` names the owner's slot directly; `Ref` names the next level's
7997 // closure entry, so the walk continues downwards.
7998 let mut level = current;
7999 let mut index = state
8000 .closure_vars
8001 .iter()
8002 .position(|closure| closure.name == name)?;
8003 loop {
8004 let state = stack.get(level)?;
8005 let closure = state.closure_vars.get(index)?;
8006 match closure.closure_type {
8007 ClosureType::Local => {
8008 let owner = stack.get(level.checked_sub(1)?)?;
8009 let var = owner.vars.get(closure.var_idx as usize)?;
8010 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8011 }
8012 ClosureType::Arg => return None,
8013 ClosureType::Ref => {
8014 level -= 1;
8015 index = closure.var_idx as usize;
8016 }
8017 // A global is never a function-expression name.
8018 ClosureType::Global
8019 | ClosureType::GlobalDecl
8020 | ClosureType::GlobalRef
8021 | ClosureType::ModuleDecl
8022 | ClosureType::ModuleImport => return None,
8023 }
8024 }
8025}
8026
8027/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
8028fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
8029 block_chain(state, block).into_iter().find_map(|scope| {
8030 state.vars.iter().enumerate().find_map(|(index, var)| {
8031 (var.name == name && state.var_block.get(index).copied() == Some(scope))
8032 .then_some(index)
8033 })
8034 })
8035}
8036
8037/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
8038fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
8039 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
8040 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
8041 }) {
8042 return index as u32;
8043 }
8044 state.var_block.push(PARAM_SCOPE);
8045 state.vars.push(VarDef::var(name));
8046 state.vars.len() as u32 - 1
8047}
8048
8049/// The name a parameter binds straight from its argument slot, if it has one.
8050///
8051/// A plain name does — with or without a default, and with or without `...`. Everything
8052/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
8053/// reference names the argument in the first case and leaves it `<null>` in the second,
8054/// so both the dump and the closures that capture the argument depend on this.
8055fn simple_parameter(param: &Pattern) -> Option<&Ident> {
8056 match ¶m.kind {
8057 PatternKind::Ident(name) => Some(name),
8058 PatternKind::Assign { target, .. } => match &target.kind {
8059 PatternKind::Ident(name) => Some(name),
8060 _ => None,
8061 },
8062 PatternKind::Rest(inner) => match &inner.kind {
8063 PatternKind::Ident(name) => Some(name),
8064 _ => None,
8065 },
8066 _ => None,
8067 }
8068}
8069
8070/// The pattern a parameter list has to unpick, if `index` is one of them.
8071fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
8072 prologue
8073 .iter()
8074 .find(|(at, _)| *at == index)
8075 .map(|(_, pattern)| pattern)
8076}
8077
8078fn pattern_has_default(pattern: &Pattern) -> bool {
8079 match &pattern.kind {
8080 PatternKind::Assign { .. } => true,
8081 PatternKind::Rest(inner) => pattern_has_default(inner),
8082 PatternKind::Array { elements, rest } => {
8083 elements.iter().flatten().any(element_has_default)
8084 || rest.as_deref().is_some_and(rest_has_default)
8085 }
8086 PatternKind::Object { properties, rest } => {
8087 properties.iter().flatten().any(element_has_default)
8088 || rest.as_deref().is_some_and(rest_has_default)
8089 }
8090 _ => false,
8091 }
8092}
8093
8094fn element_has_default(element: &PatternElement) -> bool {
8095 match element {
8096 PatternElement::Pattern(pattern) => pattern_has_default(pattern),
8097 PatternElement::Property { value, .. } => pattern_has_default(value),
8098 }
8099}
8100
8101fn rest_has_default(rest: &RestElement) -> bool {
8102 match rest {
8103 RestElement::Pattern(pattern) => pattern_has_default(pattern),
8104 RestElement::Member(_) => false,
8105 }
8106}
8107
8108/// Whether a function-scope binding is visible to the parameter list.
8109///
8110/// The parameter list runs before the body, so the body's `var`s and function
8111/// declarations do not exist yet — a name that only the body declares has to resolve
8112/// outward instead. What *does* exist by then is the compiler's own prologue: the
8113/// self-name of a named function expression (bound by `special_object 2` before anything
8114/// else), `this` and `new.target`. Those stay visible, which is what makes
8115/// `function f(a = this)` and `var f = function f(a = f)` work.
8116///
8117/// `arguments` is handled separately, as a binding of the parameter scope itself: with
8118/// parameter expressions the reference creates two of them, and the one the parameter
8119/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
8120fn visible_in_params(var: &VarDef) -> bool {
8121 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
8122}
8123
8124fn resolve_slot(
8125 stack: &mut [FnState],
8126 current: usize,
8127 name: &str,
8128 block: u64,
8129 in_params: bool,
8130) -> Slot {
8131 // The parameter list's own bindings. They are consulted first because they shadow
8132 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
8133 // `a` in the parameter scope, so a closure made there reads the parameter even after
8134 // the body assigns to its own `a`.
8135 if in_params
8136 && let Some(index) = stack[current]
8137 .vars
8138 .iter()
8139 .enumerate()
8140 .position(|(index, var)| {
8141 var.name == name
8142 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
8143 })
8144 {
8145 return Slot::Loc(index as u32);
8146 }
8147 // A name can be bound more than once: two `catch` parameters in nested
8148 // handlers are two slots. The binding that wins is the one whose scope encloses
8149 // the access, and among those the innermost — so the blocks are walked outward
8150 // and the first binding found on the way is the one that counts. A binding in
8151 // no block (`var`) is reachable from anywhere, which is why the function scope
8152 // is the end of the walk.
8153 //
8154 // The block walk comes *before* the argument slots, because a block may shadow a
8155 // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
8156 // slot is only the answer once nothing nearer claims the name.
8157 let chain = block_chain(&stack[current], block);
8158 for scope in &chain {
8159 let found = stack[current]
8160 .vars
8161 .iter()
8162 .enumerate()
8163 .find(|(index, var)| {
8164 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
8165 })
8166 .map(|(index, _)| index);
8167 if let Some(index) = found {
8168 return Slot::Loc(index as u32);
8169 }
8170 }
8171 // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
8172 // its own slot, and `var` of the same name in the body is the same binding.
8173 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
8174 return Slot::Arg(index as u32);
8175 }
8176 // Function-scope bindings — `var` and function declarations — are recorded with
8177 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
8178 // them. They are reachable from anywhere in the function, which is exactly what
8179 // the sentinel means.
8180 //
8181 // This pass is *only* for those. A lexical binding has to be found through the
8182 // chain or not at all, and looking a name up without its block is precisely how
8183 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
8184 // block leaked out of it.
8185 let function_scoped = stack[current]
8186 .vars
8187 .iter()
8188 .enumerate()
8189 .find(|(index, var)| {
8190 var.name == name
8191 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
8192 && (!in_params || visible_in_params(var))
8193 })
8194 .map(|(index, _)| index);
8195 if let Some(index) = function_scoped {
8196 return Slot::Loc(index as u32);
8197 }
8198 if let Some(index) = stack[current]
8199 .closure_vars
8200 .iter()
8201 .position(|c| c.name == name)
8202 {
8203 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
8204 }
8205
8206 for owner in (0..current).rev() {
8207 // The nested function was created inside one of this frame's blocks, and the
8208 // outermost visible binding is the innermost block on that chain — not whatever
8209 // comes first in the variable table. `function f(){ class S{} }` has two `S`
8210 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
8211 // the class body is the one a method may see.
8212 let entry = stack
8213 .get(owner + 1)
8214 .map(|s| s.created_in_block)
8215 .unwrap_or(0);
8216 let lexical = block_chain(&stack[owner], entry)
8217 .into_iter()
8218 .find_map(|scope| {
8219 stack[owner]
8220 .vars
8221 .iter()
8222 .enumerate()
8223 .find(|(index, var)| {
8224 var.name == name
8225 && stack[owner].var_block.get(*index).copied() == Some(scope)
8226 })
8227 .map(|(index, _)| index)
8228 });
8229 // A function born in a parameter list sees that list's bindings, not the body's:
8230 // the parameter scope is the environment it was created in.
8231 let in_param_scope = stack
8232 .get(owner + 1)
8233 .is_some_and(|child| child.created_in_params)
8234 .then(|| {
8235 stack[owner]
8236 .vars
8237 .iter()
8238 .enumerate()
8239 .position(|(index, var)| {
8240 var.name == name
8241 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
8242 })
8243 })
8244 .flatten();
8245 let found = if let Some(index) = in_param_scope {
8246 let var = &stack[owner].vars[index];
8247 Some(Found::Local(
8248 ClosureType::Local,
8249 index as u32,
8250 var.is_const,
8251 var.needs_check(),
8252 ))
8253 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
8254 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
8255 } else if let Some(index) = lexical {
8256 let var = &stack[owner].vars[index];
8257 Some(Found::Local(
8258 ClosureType::Local,
8259 index as u32,
8260 var.is_const,
8261 var.needs_check(),
8262 ))
8263 } else if let Some(index) = stack[owner]
8264 .vars
8265 .iter()
8266 .enumerate()
8267 .find_map(|(index, var)| {
8268 // A function created inside a parameter list must not see the body of the
8269 // function it was born in; see [`FnState::created_in_params`].
8270 let hidden = stack
8271 .get(owner + 1)
8272 .is_some_and(|child| child.created_in_params);
8273 (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
8274 })
8275 {
8276 let var = &stack[owner].vars[index];
8277 Some(Found::Local(
8278 ClosureType::Local,
8279 index as u32,
8280 var.is_const,
8281 var.needs_check(),
8282 ))
8283 } else if stack[owner].self_name.as_deref() == Some(name) {
8284 // A named function expression's own name. The reference declares it here,
8285 // on the first lookup that fails, rather than up front — and that is what
8286 // makes it reachable from a *nested* function: the nested lookup is what
8287 // walks out and creates the binding. A direct reference in the body is
8288 // caught the same way, which is why `provide_self_name` only has to add
8289 // the prologue.
8290 let strict = stack[owner].strict;
8291 stack[owner].var_block.push(FUNCTION_SCOPE);
8292 stack[owner].vars.push(VarDef {
8293 kind: VarKind::FunctionName,
8294 // In strict mode the name is immutable, so a store raises; sloppy
8295 // mode drops the store instead (see `variable_instruction`).
8296 is_const: strict,
8297 ..VarDef::var(name)
8298 });
8299 let index = stack[owner].vars.len() as u32 - 1;
8300 Some(Found::Local(ClosureType::Local, index, strict, false))
8301 } else if let Some(index) = stack[owner]
8302 .closure_vars
8303 .iter()
8304 .position(|c| c.name == name)
8305 {
8306 let closure = &stack[owner].closure_vars[index];
8307 Some(match closure.closure_type {
8308 // `GlobalRef` belongs here too: it is a *global* reached through this
8309 // frame's reference table, so treating it as a `Ref` to a local cell makes
8310 // the reader look for a cell no frame ever fills. That is how a second
8311 // function using `eval` in its parameter list read `undefined` after a
8312 // sibling had already made `eval` a closure entry.
8313 ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
8314 Found::Global(index as u32)
8315 }
8316 // A module variable is a cell in the *module's* environment, which is
8317 // the module body's parent as far as a nested function is concerned — so
8318 // it is captured as a plain reference, not looked up as a global.
8319 ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
8320 ClosureType::Ref,
8321 index as u32,
8322 closure.is_const,
8323 closure.is_lexical,
8324 ),
8325 _ => Found::Local(
8326 ClosureType::Ref,
8327 index as u32,
8328 closure.is_const,
8329 closure.is_lexical,
8330 ),
8331 })
8332 } else {
8333 None
8334 };
8335 let Some(found) = found else { continue };
8336
8337 let (is_const, is_lexical) = match found {
8338 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
8339 Found::Global(_) => (false, false),
8340 };
8341 // Mark the owner's binding as captured so it moves into a reference cell.
8342 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
8343 let slot = match found {
8344 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8345 _ => &mut stack[owner].vars[index as usize],
8346 };
8347 slot.is_captured = true;
8348 }
8349 // Forward the reference through every function in between.
8350 let mut previous = match found {
8351 Found::Local(kind, index, _, _) => (kind, index),
8352 Found::Global(index) => (ClosureType::Global, index),
8353 };
8354 for level in owner + 1..=current {
8355 let kind = match (previous.0, level) {
8356 // A global stays a global at *every* level. Without `GlobalRef` in
8357 // this arm the second nested function over the same global got a
8358 // `Ref` to a cell no frame ever held, so the innermost closure read
8359 // `undefined` — which is how a two-deep getter lost its outer
8360 // variable.
8361 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8362 ClosureType::GlobalRef
8363 }
8364 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8365 _ => ClosureType::Ref,
8366 };
8367 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8368 previous = (kind, index);
8369 }
8370 let index = previous.1;
8371 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8372 }
8373
8374 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8375 // creating a property. The top-level function holds the entry.
8376 let mut previous = (
8377 ClosureType::Global,
8378 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8379 );
8380 for level in 1..=current {
8381 let index = ensure_closure(
8382 stack,
8383 level,
8384 name,
8385 false,
8386 false,
8387 ClosureType::GlobalRef,
8388 previous.1,
8389 );
8390 previous = (ClosureType::GlobalRef, index);
8391 }
8392 Slot::Global(previous.1)
8393}
8394
8395/// What an outward search turned up.
8396#[derive(Debug, Clone, Copy)]
8397enum Found {
8398 /// A binding in an enclosing function, reachable through a closure of this
8399 /// type, with its const/lexical flags.
8400 Local(ClosureType, u32, bool, bool),
8401 /// A global, reached through the enclosing function's closure entry.
8402 Global(u32),
8403}
8404
8405/// Add a closure entry to `level` if it is not there yet.
8406fn ensure_closure(
8407 stack: &mut [FnState],
8408 level: usize,
8409 name: &str,
8410 is_const: bool,
8411 is_lexical: bool,
8412 closure_type: ClosureType,
8413 var_idx: u32,
8414) -> u32 {
8415 if let Some(index) = stack[level]
8416 .closure_vars
8417 .iter()
8418 .position(|c| c.name == name)
8419 {
8420 return index as u32;
8421 }
8422 stack[level].closure_vars.push(ClosureVar {
8423 name: name.to_string(),
8424 is_const,
8425 is_lexical,
8426 closure_type,
8427 var_idx: var_idx as u16,
8428 });
8429 stack[level].closure_vars.len() as u32 - 1
8430}
8431
8432fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
8433 match closure.closure_type {
8434 // A `global_ref` only says *how* the binding is found (through the
8435 // parent's closure table); the access itself is an ordinary global one.
8436 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
8437 ClosureType::GlobalDecl => Slot::GlobalDecl(index),
8438 // A module variable is a real cell in the module's environment, so it is reached
8439 // exactly like a captured local — the host, not the global object, is what fills
8440 // the slot.
8441 ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
8442 _ => Slot::VarRef(index),
8443 }
8444}
8445
8446/// Pick the opcode for one variable access.
8447///
8448/// The `_check` variants are what enforce the temporal dead zone. They are used
8449/// for every access to a `let`/`const` binding except its own initialisation —
8450/// which is exactly the operation that takes the binding out of the dead zone.
8451fn variable_instruction(
8452 stack: &[FnState],
8453 current: usize,
8454 action: VarAction,
8455 slot: Slot,
8456) -> (Opcode, Vec<Op>) {
8457 let lexical = match slot {
8458 Slot::Loc(index) => stack[current]
8459 .vars
8460 .get(index as usize)
8461 .is_some_and(|v| v.needs_check()),
8462 Slot::VarRef(index) => stack[current]
8463 .closure_vars
8464 .get(index as usize)
8465 .is_some_and(|c| c.is_lexical),
8466 _ => false,
8467 };
8468 let operand = vec![Op::Slot(slot)];
8469 match (action, slot) {
8470 (VarAction::Get, Slot::Loc(index)) => (
8471 if lexical {
8472 Opcode::GetLocCheck
8473 } else {
8474 Opcode::GetLoc
8475 },
8476 vec![Op::Slot(Slot::Loc(index))],
8477 ),
8478 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
8479 (VarAction::Get, Slot::VarRef(index)) => (
8480 if lexical {
8481 Opcode::GetVarRefCheck
8482 } else {
8483 Opcode::GetVarRef
8484 },
8485 vec![Op::Slot(Slot::VarRef(index))],
8486 ),
8487 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
8488 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
8489 // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
8490 // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
8491 // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
8492 // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
8493 // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
8494 // `ReferenceError`.
8495 (VarAction::GetUndef, Slot::Loc(index)) => (
8496 if lexical {
8497 Opcode::GetLocCheck
8498 } else {
8499 Opcode::GetLoc
8500 },
8501 vec![Op::Slot(Slot::Loc(index))],
8502 ),
8503 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
8504 (VarAction::GetUndef, Slot::VarRef(index)) => (
8505 if lexical {
8506 Opcode::GetVarRefCheck
8507 } else {
8508 Opcode::GetVarRef
8509 },
8510 vec![Op::Slot(Slot::VarRef(index))],
8511 ),
8512 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8513 (Opcode::GetVarUndef, operand)
8514 }
8515
8516 (VarAction::Put, Slot::Loc(_)) => (
8517 if lexical {
8518 Opcode::PutLocCheck
8519 } else {
8520 Opcode::PutLoc
8521 },
8522 operand,
8523 ),
8524 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
8525 (VarAction::Put, Slot::VarRef(_)) => (
8526 if lexical {
8527 Opcode::PutVarRefCheck
8528 } else {
8529 Opcode::PutVarRef
8530 },
8531 operand,
8532 ),
8533 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
8534 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8535 // Initialisation is what ends the dead zone, so it never checks.
8536 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8537 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
8538 // `this` in a derived constructor is always a local, so these cannot happen;
8539 // routing them to the ordinary forms keeps the match total without inventing
8540 // opcodes the reference does not have.
8541 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
8542 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8543 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8544 (Opcode::PutVarInit, operand)
8545 }
8546 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
8547 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8548 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8549 (Opcode::PutVarInit, operand)
8550 }
8551 (VarAction::Set, Slot::Loc(_)) => (
8552 if lexical {
8553 Opcode::SetLocCheck
8554 } else {
8555 Opcode::SetLoc
8556 },
8557 operand,
8558 ),
8559 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
8560 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
8561 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8562 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8563 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
8564 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8565 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
8566 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
8567 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8568 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
8569 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8570 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
8571 }
8572}
8573
8574/// The instruction-rewriting pass.
8575///
8576/// These are the reference implementation's patterns, restricted to the ones the
8577/// constructs this compiler supports can produce. Each entry is a comment on the
8578/// bytecode it removes, because the whole point is that the result is one
8579/// instruction shorter than the literal translation of the AST.
8580fn peephole(
8581 insns: &mut [Option<(Opcode, Vec<Op>)>],
8582 label_at: &[Option<u32>],
8583 placed: &[Option<usize>],
8584) {
8585 fold_dup_patterns(insns, label_at);
8586
8587 // `drop` before `return_undef` is dead: the return discards the whole frame
8588 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
8589 // consumes its own `drop`; removing the drop first would leave the `dup` and
8590 // produce a `set_` where the reference has a `put_`.
8591 for index in 0..insns.len() {
8592 if opcode_at(insns, index) != Some(Opcode::Drop) {
8593 continue;
8594 }
8595 // Skip over a run of drops, but stop at a jump target: removing code on
8596 // one side of a label would silently retarget the jump.
8597 let mut next = index + 1;
8598 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
8599 next += 1;
8600 }
8601 if is_label_at(label_at, next) {
8602 continue;
8603 }
8604 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
8605 for entry in &mut insns[index..next] {
8606 *entry = None;
8607 }
8608 }
8609 }
8610
8611 // The rewrites below all decide against one fixed snapshot, which is what the
8612 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
8613 // the pass, so a rule never observes what an earlier rule removed. Gathering
8614 // every deletion first and applying them together reproduces that.
8615 let snapshot: Vec<Option<Opcode>> = insns
8616 .iter()
8617 .map(|entry| entry.as_ref().map(|(op, _)| *op))
8618 .collect();
8619 // The next instruction that is still there. Holes left by dead-code
8620 // elimination are not instructions, so a rule looks past them.
8621 let next_op = |index: usize| -> Option<usize> {
8622 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
8623 };
8624
8625 let mut doomed = vec![false; insns.len()];
8626 for index in 0..insns.len() {
8627 // A constant pushed only to be dropped does nothing at all. This is what a
8628 // comma expression with a literal left operand compiles to — `(0, f)()` — and
8629 // the reference removes the pair rather than making the reader step over it.
8630 let constant = matches!(
8631 snapshot[index],
8632 Some(
8633 Opcode::Undefined
8634 | Opcode::Null
8635 | Opcode::PushMinus1
8636 | Opcode::Push0
8637 | Opcode::Push1
8638 | Opcode::Push2
8639 | Opcode::Push3
8640 | Opcode::Push4
8641 | Opcode::Push5
8642 | Opcode::Push6
8643 | Opcode::Push7
8644 | Opcode::PushTrue
8645 | Opcode::PushFalse
8646 | Opcode::PushI32
8647 )
8648 );
8649 if constant
8650 && let Some(next) = next_op(index)
8651 && snapshot[next] == Some(Opcode::Drop)
8652 {
8653 doomed[index] = true;
8654 doomed[next] = true;
8655 }
8656 }
8657 for (index, entry) in insns.iter_mut().enumerate() {
8658 if doomed[index] {
8659 *entry = None;
8660 }
8661 }
8662
8663 // A conditional whose destination is the very next instruction just pops its
8664 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
8665 // compiles to.
8666 //
8667 // Order matters, and it is the reference's order: this runs *before* the
8668 // folding below, on the instruction the conditional originally had. Folding
8669 // moves a conditional's destination, and the reference never re-examines it
8670 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
8671 // a conditional even though folding leaves it pointing at the next
8672 // instruction.
8673 for (index, entry) in insns.iter_mut().enumerate() {
8674 let Some((op, operands)) = entry.clone() else {
8675 continue;
8676 };
8677 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
8678 continue;
8679 }
8680 let Some(id) = label_id(&operands) else {
8681 continue;
8682 };
8683 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
8684 *entry = Some((Opcode::Drop, Vec::new()));
8685 }
8686 }
8687
8688 // A constant condition is decided here rather than at run time.
8689 fold_constant_conditions(insns);
8690 // The conditional folding below is about pairs of *real* branches, so it runs
8691 // before a jump to the next instruction is dropped: `do { … if (c) continue }
8692 // while (t)` puts `continue` exactly on the condition, and the reference inverts
8693 // the branch first and only then notices the jump goes nowhere.
8694 fold_conditional_jumps(insns, label_at, placed);
8695
8696 // A jump whose destination is the very next instruction does nothing, which is
8697 // what constant folding leaves behind for `while (1) { … }`.
8698 remove_jump_to_next(insns, placed);
8699
8700 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
8701 // a use of the same variable boils down to.
8702 for index in 0..insns.len() {
8703 let Some((put_op, _)) = insns[index].clone() else {
8704 continue;
8705 };
8706 if !is_foldable_put(put_op) {
8707 continue;
8708 }
8709 if is_label_at(label_at, index + 1) {
8710 continue;
8711 }
8712 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
8713 continue;
8714 };
8715 if get_op != get_form_of(put_op) {
8716 continue;
8717 }
8718 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
8719 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
8720 continue;
8721 }
8722 insns[index] = Some((set_form_of(put_op), get_operands));
8723 insns[index + 1] = None;
8724 }
8725}
8726
8727/// Drop `gosub`s that call an empty subroutine.
8728///
8729/// A `gosub` whose target starts with `ret` returns immediately, so the reference
8730/// drops the call. This is how `try`/`catch` without a `finally` loses its
8731/// finalizer plumbing: the finalizer block is empty, its first instruction is
8732/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
8733/// [`eliminate_dead_code`] then removes.
8734fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
8735 let state = &stack[current];
8736 let mut targets = Vec::new();
8737 for insn in &state.insns {
8738 if let Insn::Fixed { op, operands } = insn
8739 && *op == Opcode::Gosub
8740 && let Some(id) = label_id(operands)
8741 && let Some(target) = state.labels.get(id as usize).copied().flatten()
8742 {
8743 targets.push(target);
8744 }
8745 }
8746 let empty: Vec<usize> = targets
8747 .into_iter()
8748 .filter(|target| {
8749 stack[current]
8750 .insns
8751 .get(*target)
8752 .map(|insn| {
8753 matches!(
8754 insn,
8755 Insn::Fixed {
8756 op: Opcode::Ret,
8757 ..
8758 }
8759 )
8760 })
8761 .unwrap_or(false)
8762 })
8763 .collect();
8764 if empty.is_empty() {
8765 return;
8766 }
8767 for insn in stack[current].insns.iter_mut() {
8768 if let Insn::Fixed { op, operands } = insn
8769 && *op == Opcode::Gosub
8770 && let Some(id) = label_id(operands)
8771 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
8772 && empty.contains(&target)
8773 {
8774 *insn = Insn::Dead;
8775 }
8776 }
8777}
8778
8779/// Replace unreachable instructions with [`Insn::Dead`].
8780fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
8781 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
8782 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
8783 if !reachable[index] {
8784 *insn = Insn::Dead;
8785 }
8786 }
8787}
8788
8789/// Mark every instruction index reachable from the entry, plus the index one past
8790/// the last instruction.
8791///
8792/// `seen[len]` answers "can control reach the end of this function", and the
8793/// entries before it identify dead code. Both DCE and the implicit-return decision
8794/// read the same result, which keeps them from disagreeing.
8795fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
8796 let mut seen = vec![false; count + 1];
8797 let mut worklist = vec![0usize];
8798 while let Some(index) = worklist.pop() {
8799 if index > count || seen[index] {
8800 continue;
8801 }
8802 seen[index] = true;
8803 if index == count {
8804 continue;
8805 }
8806 let (op, operands) = match &state.insns[index] {
8807 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
8808 // A variable access never transfers control, and a removed
8809 // instruction is only reachable if it is already marked.
8810 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
8811 worklist.push(index + 1);
8812 continue;
8813 }
8814 };
8815 match op {
8816 // A return, a throw and a `ret` all leave this instruction stream: the
8817 // first two give control to the caller or the handler, and `ret`
8818 // returns to a `gosub` elsewhere.
8819 // A tail call leaves the function too: the callee's result becomes this
8820 // function's result, so nothing after it runs.
8821 Opcode::Return
8822 | Opcode::ReturnUndef
8823 | Opcode::ReturnAsync
8824 | Opcode::TailCall
8825 | Opcode::TailCallMethod
8826 | Opcode::Throw
8827 | Opcode::ThrowError
8828 | Opcode::Ret => {}
8829 // A `catch` records where exceptions from the code that follows go.
8830 // That code is not reachable through normal control flow, but it is
8831 // reachable — through the exception edge — so the walk has to follow
8832 // it, or dead-code elimination would delete every handler.
8833 Opcode::Catch => {
8834 if let Some(target) = placed_label(state, operands) {
8835 worklist.push(target);
8836 }
8837 worklist.push(index + 1);
8838 }
8839 // A `gosub` calls a subroutine and then continues, so both edges count.
8840 Opcode::Gosub => {
8841 if let Some(target) = placed_label(state, operands) {
8842 worklist.push(target);
8843 }
8844 worklist.push(index + 1);
8845 }
8846 Opcode::Goto => {
8847 if let Some(target) = placed_label(state, operands) {
8848 worklist.push(target);
8849 }
8850 }
8851 Opcode::IfTrue | Opcode::IfFalse => {
8852 if let Some(target) = placed_label(state, operands) {
8853 worklist.push(target);
8854 }
8855 worklist.push(index + 1);
8856 }
8857 _ => worklist.push(index + 1),
8858 }
8859 }
8860 seen
8861}
8862
8863/// The instruction index a jump operand points at, resolved through the label
8864/// placement table.
8865fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
8866 let id = label_id(operands)?;
8867 state.labels.get(id as usize).copied().flatten()
8868}
8869
8870/// The label an instruction refers to.
8871fn label_id(operands: &[Op]) -> Option<u32> {
8872 operands.iter().find_map(|operand| match operand {
8873 Op::Label(label) => Some(label.0),
8874 _ => None,
8875 })
8876}
8877
8878/// Turn `if_false L; goto M; L:` into `if_true M`.
8879///
8880/// A conditional whose alternate branch is an unconditional jump needs one jump,
8881/// not two. This is the shape `if (c) break;` produces, so folding it removes an
8882/// instruction and a label from every conditional `break`.
8883/// The boolean a constant-push instruction produces, or `None` if it is not one.
8884///
8885/// Only the operators whose truthiness is decided by the opcode are covered; a
8886/// constant that needs the constant pool (a string) is left alone, because reading it
8887/// would mean threading the pool through the peephole for a case the reference also
8888/// skips.
8889fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
8890 match op {
8891 // `push_0` returns -1 for zero, `push_1` 1, and so on.
8892 Opcode::PushMinus1 => Some(true),
8893 Opcode::Push0 => Some(false),
8894 Opcode::Push1
8895 | Opcode::Push2
8896 | Opcode::Push3
8897 | Opcode::Push4
8898 | Opcode::Push5
8899 | Opcode::Push6
8900 | Opcode::Push7 => Some(true),
8901 Opcode::PushTrue => Some(true),
8902 Opcode::PushFalse => Some(false),
8903 Opcode::Undefined | Opcode::Null => Some(false),
8904 Opcode::PushI32 => match operands.first() {
8905 Some(Op::Int(value)) => Some(*value != 0),
8906 _ => None,
8907 },
8908 _ => None,
8909 }
8910}
8911
8912/// Fold a branch on a constant condition.
8913///
8914/// `if (0) a() else b()` must not test anything at run time, and the reference
8915/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
8916/// which is why the bytecode for a `while (1)` loop has no condition at all.
8917///
8918/// Two instructions become one, so the slot the test occupied is left empty rather
8919/// than shifting everything after it: labels have already been resolved to indices.
8920fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
8921 for index in 0..insns.len() {
8922 let Some((push_op, push_operands)) = insns[index].clone() else {
8923 continue;
8924 };
8925 let Some(truth) = constant_truth(push_op, &push_operands) else {
8926 continue;
8927 };
8928 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
8929 continue;
8930 };
8931 let (destination, taken) = match branch_op {
8932 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
8933 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
8934 _ => continue,
8935 };
8936 let Some(destination) = destination else {
8937 continue;
8938 };
8939 insns[index] = if taken {
8940 // The branch is always taken, so it becomes an unconditional jump.
8941 Some((Opcode::Goto, vec![destination]))
8942 } else {
8943 // The branch never runs: both instructions disappear and control falls
8944 // through to what came after.
8945 None
8946 };
8947 insns[index + 1] = None;
8948 }
8949}
8950
8951/// Remove a jump whose destination is the instruction right after it.
8952///
8953/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
8954/// its test into nothing, and the loop-end jump then points at the following
8955/// instruction. The reference drops them, so `stack_size` and the listing agree.
8956fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
8957 for index in 0..insns.len() {
8958 let Some((op, operands)) = insns[index].clone() else {
8959 continue;
8960 };
8961 if !is_goto(op) {
8962 continue;
8963 }
8964 let Some(id) = label_id(&operands) else {
8965 continue;
8966 };
8967 // The next instruction that still exists, which is what "the instruction
8968 // after this jump" means once earlier folds have punched holes.
8969 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
8970 if placed.get(id as usize).copied().flatten() == next {
8971 insns[index] = None;
8972 }
8973 }
8974}
8975
8976fn fold_conditional_jumps(
8977 insns: &mut [Option<(Opcode, Vec<Op>)>],
8978 label_at: &[Option<u32>],
8979 placed: &[Option<usize>],
8980) {
8981 for index in 0..insns.len() {
8982 let Some((op, operands)) = insns[index].clone() else {
8983 continue;
8984 };
8985 let inverted = match op {
8986 Opcode::IfFalse => Opcode::IfTrue,
8987 Opcode::IfTrue => Opcode::IfFalse,
8988 _ => continue,
8989 };
8990 // Next must be an unconditional jump that is not itself a target, and the
8991 // instruction after it must be exactly where the conditional goes.
8992 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
8993 continue;
8994 };
8995 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
8996 continue;
8997 }
8998 // The conditional must land on the instruction *after* the jump. Several
8999 // labels can share a position, so this asks where *this* label was put
9000 // rather than what label happens to sit there.
9001 let Some(taken) = label_id(&operands) else {
9002 continue;
9003 };
9004 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
9005 continue;
9006 }
9007 let Some(destination) = next_operands.first().cloned() else {
9008 continue;
9009 };
9010 insns[index] = Some((inverted, vec![destination]));
9011 insns[index + 1] = None;
9012 }
9013}
9014
9015/// Whether a jump target is placed at this instruction index.
9016fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
9017 label_at.get(index).copied().flatten().is_some()
9018}
9019
9020fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9021 // `dup put_x(n)` -> `set_x(n)`
9022 // `dup put_x(n) drop` -> `put_x(n)`
9023 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
9024 for index in 0..insns.len() {
9025 if opcode_at(insns, index) != Some(Opcode::Dup) {
9026 continue;
9027 }
9028 if is_label_at(label_at, index + 1) {
9029 continue;
9030 }
9031 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
9032 continue;
9033 };
9034 if !is_foldable_put(put_op) {
9035 continue;
9036 }
9037 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
9038 continue;
9039 };
9040 let mut new_op = set_form_of(put_op);
9041 let mut end = index + 2;
9042 if is_label_at(label_at, end) {
9043 // The `put` has to stay as it is; only the `dup` can be folded.
9044 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
9045 insns[index + 1] = None;
9046 continue;
9047 }
9048 // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
9049 // Deleting it moves the label's target onto whatever follows, and the code that
9050 // jumps there arrives with a different stack than the fall-through path: that is
9051 // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
9052 // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
9053 // an empty stack. The store had already consumed the value it was supposed to
9054 // leave behind.
9055 if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
9056 new_op = put_op;
9057 end += 1;
9058 if opcode_at(insns, end) == Some(get_form_of(put_op))
9059 && !is_label_at(label_at, end)
9060 && insns[end]
9061 .as_ref()
9062 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
9063 {
9064 new_op = set_form_of(put_op);
9065 end += 1;
9066 }
9067 }
9068 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
9069 for entry in &mut insns[index + 1..end] {
9070 *entry = None;
9071 }
9072 }
9073}
9074
9075fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
9076 insns
9077 .get(index)
9078 .and_then(|entry| entry.as_ref())
9079 .map(|(op, _)| *op)
9080}
9081
9082/// The four `put_` families that have a `set_` twin. Deliberately not including
9083/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
9084/// these, and folding the others would produce instructions that do not exist.
9085fn is_foldable_put(op: Opcode) -> bool {
9086 matches!(
9087 op,
9088 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
9089 )
9090}
9091
9092fn set_form_of(op: Opcode) -> Opcode {
9093 match op {
9094 Opcode::PutLoc => Opcode::SetLoc,
9095 Opcode::PutLocCheck => Opcode::SetLocCheck,
9096 Opcode::PutArg => Opcode::SetArg,
9097 Opcode::PutVarRef => Opcode::SetVarRef,
9098 other => other,
9099 }
9100}
9101
9102fn get_form_of(op: Opcode) -> Opcode {
9103 match op {
9104 Opcode::PutLoc => Opcode::GetLoc,
9105 Opcode::PutLocCheck => Opcode::GetLocCheck,
9106 Opcode::PutArg => Opcode::GetArg,
9107 Opcode::PutVarRef => Opcode::GetVarRef,
9108 other => other,
9109 }
9110}
9111
9112/// Atom interning, per function.
9113///
9114/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
9115/// identifiers, so the array-index rule applies here rather than at the handful of
9116/// call sites that build property keys.
9117fn intern_atom(state: &mut FnState, name: &str) -> u32 {
9118 intern_atom_value(state, Atom::from_text(name))
9119}
9120
9121/// [`intern_atom`] for an operand that is already an [`Atom`].
9122///
9123/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
9124/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
9125/// would have looked up.
9126fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
9127 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
9128 return index as u32;
9129 }
9130 state.atoms.push(atom);
9131 state.atoms.len() as u32 - 1
9132}
9133
9134fn binary_opcode(op: BinaryOp) -> Opcode {
9135 match op {
9136 BinaryOp::Add => Opcode::Add,
9137 BinaryOp::Sub => Opcode::Sub,
9138 BinaryOp::Mul => Opcode::Mul,
9139 BinaryOp::Div => Opcode::Div,
9140 BinaryOp::Mod => Opcode::Mod,
9141 BinaryOp::Pow => Opcode::Pow,
9142 BinaryOp::BitOr => Opcode::Or,
9143 BinaryOp::BitXor => Opcode::Xor,
9144 BinaryOp::BitAnd => Opcode::And,
9145 BinaryOp::Shl => Opcode::Shl,
9146 BinaryOp::Shr => Opcode::Sar,
9147 BinaryOp::UShr => Opcode::Shr,
9148 BinaryOp::Lt => Opcode::Lt,
9149 BinaryOp::LtEq => Opcode::Lte,
9150 BinaryOp::Gt => Opcode::Gt,
9151 BinaryOp::GtEq => Opcode::Gte,
9152 BinaryOp::Eq => Opcode::Eq,
9153 BinaryOp::NotEq => Opcode::Neq,
9154 BinaryOp::StrictEq => Opcode::StrictEq,
9155 BinaryOp::StrictNotEq => Opcode::StrictNeq,
9156 BinaryOp::In => Opcode::In,
9157 BinaryOp::Instanceof => Opcode::Instanceof,
9158 }
9159}
9160
9161fn compound_opcode(op: AssignOp) -> Opcode {
9162 match op {
9163 AssignOp::Add => Opcode::Add,
9164 AssignOp::Sub => Opcode::Sub,
9165 AssignOp::Mul => Opcode::Mul,
9166 AssignOp::Div => Opcode::Div,
9167 AssignOp::Mod => Opcode::Mod,
9168 AssignOp::Pow => Opcode::Pow,
9169 AssignOp::Shl => Opcode::Shl,
9170 AssignOp::Shr => Opcode::Sar,
9171 AssignOp::UShr => Opcode::Shr,
9172 AssignOp::BitOr => Opcode::Or,
9173 AssignOp::BitXor => Opcode::Xor,
9174 AssignOp::BitAnd => Opcode::And,
9175 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
9176 }
9177}
9178
9179/// Encode the resolved instruction stream, choosing short forms where possible.
9180///
9181/// The peephole pass leaves holes in the instruction list so that label indices
9182/// stay valid. A label names an *instruction index*, and an index that was
9183/// deleted has to resolve to the next surviving instruction, which is what
9184/// [`resolve_label`] does before the byte offsets are known.
9185fn assemble(
9186 insns: &mut [Option<(Opcode, Vec<Op>)>],
9187 insn_pos: &[Option<Position>],
9188 state: &mut FnState,
9189) -> (Vec<u8>, u32, Vec<LineCol>) {
9190 // Compaction: surviving instructions in order, plus the index mapping.
9191 //
9192 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
9193 // point below where instructions are removed — otherwise a stack trace would point
9194 // at the wrong source line as soon as dead-code elimination kicked in.
9195 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
9196 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
9197 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
9198 for (original, entry) in insns.iter_mut().enumerate() {
9199 if let Some((op, operands)) = entry.take() {
9200 original_to_kept[original] = Some(kept.len());
9201 kept.push((op, operands));
9202 spans.push(insn_pos.get(original).copied().flatten());
9203 }
9204 }
9205
9206 if std::env::var_os("QJS_DEBUG").is_some() {
9207 eprintln!("--- assemble entry --- {kept:?}");
9208 }
9209 // How many labels are real, as opposed to the per-instruction ones allocated
9210 // just below. Only a real label marks a spot in the source program.
9211 let real_labels = state.labels.len();
9212
9213 // Give every surviving instruction a label of its own. Jump cleanup below
9214 // redirects jumps to arbitrary instructions, and a jump target has to be a
9215 // label; pre-allocating one per index means a redirect never has to invent
9216 // anything.
9217 let existing = state.labels.len();
9218 let base = kept.len();
9219 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
9220 for offset in 0..=kept.len() {
9221 state.labels.push(Some(0));
9222 index_label.push(Label((existing + offset) as u32));
9223 }
9224 // Point each pre-allocated label at its instruction, reusing the count from
9225 // `original_to_kept` so the mapping survives compaction.
9226 let place_index_labels = |state: &mut FnState,
9227 original_to_kept: &[Option<usize>],
9228 kept_len: usize,
9229 index_label: &[Label]| {
9230 for (original, mapped) in original_to_kept.iter().enumerate() {
9231 if let Some(kept_index) = mapped {
9232 let label = index_label[*kept_index].0 as usize;
9233 state.labels[label] = Some(original);
9234 }
9235 }
9236 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
9237 };
9238 place_index_labels(state, &original_to_kept, base, &index_label);
9239
9240 // Resolve every label to a kept index once; the placement table maps labels
9241 // to original indices, so a second hop lands in kept space.
9242 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
9243 for (id, placed) in state.labels.iter().enumerate() {
9244 let Some(original) = placed else { continue };
9245 label_kept[id] = if *original == usize::MAX {
9246 Some(base)
9247 } else {
9248 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
9249 };
9250 }
9251
9252 // Code after an unconditional transfer is unreachable, and the reference drops it
9253 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
9254 // scans forward until it finds a label something still jumps to, so a run of
9255 // dead instructions between a `throw` and the next live target disappears.
9256 //
9257 // The scan repeats because dropping a jump lowers the reference count of the
9258 // label it pointed at, which can strand what follows. Only a real label keeps an
9259 // instruction alive here; the per-instruction labels allocated above belong to
9260 // this pass, not to the program.
9261 loop {
9262 let mut references = vec![false; kept.len() + 1];
9263 for (_, operands) in &kept {
9264 if let Some(target) = target_kept_index(operands, &label_kept)
9265 && target < references.len()
9266 {
9267 references[target] = true;
9268 }
9269 }
9270 let mut doomed = vec![false; kept.len()];
9271 let mut any = false;
9272 for (index, (op, _)) in kept.iter().enumerate() {
9273 if !is_transfer(*op) {
9274 continue;
9275 }
9276 for next in index + 1..kept.len() {
9277 if references[next] {
9278 break;
9279 }
9280 doomed[next] = true;
9281 any = true;
9282 }
9283 }
9284 if !any {
9285 break;
9286 }
9287 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
9288 }
9289
9290 // A label that lands on an unconditional jump stands for wherever that jump
9291 // goes, so retarget it once and every jump to the label follows for free.
9292 // This is what makes `continue` in a `for` head reach the loop top instead of
9293 // stopping at the update's trailing jump.
9294 let folded: Vec<Option<usize>> = label_kept
9295 .iter()
9296 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
9297 .collect();
9298 label_kept = folded;
9299
9300 // Jump cleanup, in compacted index space. Two rewrites the reference also
9301 // applies while it resolves labels:
9302 // * a jump whose destination is the very next instruction does nothing;
9303 // * a jump to a jump is redirected to its final destination.
9304 // The second can expose the first, so this repeats until it settles.
9305 loop {
9306 let mut delete = vec![false; kept.len()];
9307 let mut changed = false;
9308 for index in 0..kept.len() {
9309 let (op, operands) = &kept[index];
9310 if !is_goto(*op) {
9311 continue;
9312 }
9313 let Some(immediate) = target_kept_index(operands, &label_kept) else {
9314 continue;
9315 };
9316 let target = follow_jump_chain(&kept, &label_kept, immediate);
9317 if target == index + 1 {
9318 delete[index] = true;
9319 changed = true;
9320 } else if matches!(
9321 kept.get(target).map(|(op, _)| *op),
9322 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
9323 ) {
9324 // Jumping straight to a return or throw is the same as doing it
9325 // here, so the jump becomes that instruction.
9326 kept[index] = (kept[target].0, Vec::new());
9327 changed = true;
9328 } else if target != immediate {
9329 // Redirect to the end of the chain.
9330 let label = index_label[target];
9331 kept[index].1 = vec![Op::Label(label)];
9332 changed = true;
9333 }
9334 }
9335 if !changed {
9336 break;
9337 }
9338 if !delete.iter().any(|deleted| *deleted) {
9339 break;
9340 }
9341 // Drop the deleted instructions and renumber everything.
9342 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9343 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9344 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9345 for (old, entry) in kept.into_iter().enumerate() {
9346 if delete[old] {
9347 continue;
9348 }
9349 moved[old] = Some(next.len());
9350 next.push(entry);
9351 next_spans.push(spans[old]);
9352 }
9353 for (id, slot) in label_kept.iter_mut().enumerate() {
9354 let Some(old) = *slot else { continue };
9355 *slot = match moved.get(old).copied().flatten() {
9356 Some(new) => Some(new),
9357 // The target was deleted: the jump now lands on whatever follows.
9358 None => (old..moved.len())
9359 .find_map(|i| moved[i])
9360 .or(Some(next.len())),
9361 };
9362 let _ = id;
9363 }
9364 kept = next;
9365 spans = next_spans;
9366 }
9367
9368 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9369 // jump to the next instruction and is deleted, leaving the label at the end with
9370 // nothing pointing at it. If that also strands the last instruction, it goes
9371 // too — which is how a `try` whose body always returns ends on its `ret` rather
9372 // than an implicit `return_undef`.
9373 // Which instructions something still jumps to. Reading the surviving jumps is
9374 // what the reference's reference counts amount to: once a jump has been folded
9375 // away the label it named is unreferenced, even though the program still has a
9376 // label there.
9377 let mut references = vec![false; kept.len() + 1];
9378 let _ = real_labels;
9379 for (_, operands) in &kept {
9380 if let Some(target) = target_kept_index(operands, &label_kept)
9381 && target < references.len()
9382 {
9383 references[target] = true;
9384 }
9385 }
9386 let mut end = kept.len();
9387 while end > 0 {
9388 let last = end - 1;
9389 let reachable = references[last] || end < kept.len();
9390 if reachable {
9391 break;
9392 }
9393 let after_transfer = last
9394 .checked_sub(1)
9395 .map(|previous| {
9396 matches!(
9397 kept[previous].0,
9398 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
9399 )
9400 })
9401 .unwrap_or(false);
9402 if !after_transfer {
9403 break;
9404 }
9405 end = last;
9406 }
9407 kept.truncate(end);
9408 spans.truncate(end);
9409
9410 // Choose an opcode for each instruction and its size, so label offsets can be
9411 // computed.
9412 let chosen = choose_opcodes(&kept, &label_kept);
9413 let offsets = instruction_offsets(&chosen);
9414 let offset = *offsets.last().unwrap_or(&0);
9415
9416 let mut code = Vec::with_capacity(offset);
9417 for (position, (_, operands)) in kept.iter().enumerate() {
9418 let op = chosen[position];
9419 code.push(op as u8);
9420 let operands = retarget_labels(operands, &label_kept, kept.len());
9421 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
9422 }
9423 let stack_size = compute_stack_size(&code);
9424 // Keep only the offsets where the position actually changes: a run of
9425 // instructions on one line is one table entry, and the runtime binary searches
9426 // the table for the frame's pc.
9427 //
9428 // The table always starts at pc 0 with the *function's own* position, because the
9429 // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
9430 // last_line_num)` from `fd->source_pos`, the token the function definition starts at
9431 // (`function`, `async`, a method's property name). An instruction before the first
9432 // recorded operator therefore reports the function's own start, which is what makes a
9433 // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
9434 let mut positions: Vec<LineCol> = vec![LineCol {
9435 pc: 0,
9436 line: state.line,
9437 column: state.column,
9438 }];
9439 let mut last: Option<Position> = None;
9440 for (index, span) in spans.iter().enumerate() {
9441 let Some(pos) = *span else { continue };
9442 if last == Some(pos) {
9443 continue;
9444 }
9445 last = Some(pos);
9446 if pos.line == state.line && pos.column == state.column {
9447 // Already the seed entry above.
9448 continue;
9449 }
9450 positions.push(LineCol {
9451 pc: offsets[index] as u32,
9452 line: pos.line,
9453 column: pos.column,
9454 });
9455 }
9456 (code, stack_size, positions)
9457}
9458
9459/// Whether an instruction always transfers control away, so anything after it in the
9460/// same stream is unreachable.
9461fn is_transfer(op: Opcode) -> bool {
9462 matches!(
9463 op,
9464 Opcode::Goto
9465 | Opcode::Goto8
9466 | Opcode::Goto16
9467 | Opcode::Return
9468 | Opcode::ReturnUndef
9469 | Opcode::Throw
9470 | Opcode::ThrowError
9471 | Opcode::Ret
9472 )
9473}
9474
9475/// Remove the marked instructions and renumber the label table so it keeps pointing
9476/// at the same instructions. A label whose instruction went away moves to whatever
9477/// follows it, since a jump is never left with nowhere to land.
9478fn drop_instructions(
9479 kept: Vec<(Opcode, Vec<Op>)>,
9480 spans: Vec<Option<Position>>,
9481 label_kept: &mut [Option<usize>],
9482 doomed: &[bool],
9483) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
9484 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9485 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9486 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9487 for (old, entry) in kept.into_iter().enumerate() {
9488 if doomed.get(old).copied().unwrap_or(false) {
9489 continue;
9490 }
9491 moved[old] = Some(result.len());
9492 result.push(entry);
9493 result_spans.push(spans[old]);
9494 }
9495 for slot in label_kept.iter_mut() {
9496 let Some(old) = *slot else { continue };
9497 *slot = match moved.get(old).copied().flatten() {
9498 Some(new) => Some(new),
9499 None => (old..moved.len())
9500 .find_map(|i| moved[i])
9501 .or(Some(result.len())),
9502 };
9503 }
9504 (result, result_spans)
9505}
9506
9507fn is_goto(op: Opcode) -> bool {
9508 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
9509}
9510
9511/// The kept index a jump operand points at.
9512fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
9513 let id = label_id(operands)?;
9514 label_kept.get(id as usize).copied().flatten()
9515}
9516
9517/// Follow a chain of unconditional jumps to its first real destination.
9518fn follow_jump_chain(
9519 kept: &[(Opcode, Vec<Op>)],
9520 label_kept: &[Option<usize>],
9521 start: usize,
9522) -> usize {
9523 let mut current = start;
9524 // `for(;;)` jumps to itself, so the walk has to be bounded.
9525 for _ in 0..kept.len() {
9526 let Some((op, operands)) = kept.get(current) else {
9527 return current;
9528 };
9529 if !is_goto(*op) {
9530 return current;
9531 }
9532 let Some(next) = target_kept_index(operands, label_kept) else {
9533 return current;
9534 };
9535 if next == current {
9536 return current;
9537 }
9538 current = next;
9539 }
9540 current
9541}
9542
9543/// Rewrite label operands from label ids to kept instruction indices.
9544fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
9545 operands
9546 .iter()
9547 .map(|operand| match operand {
9548 Op::Label(label) => {
9549 let target = label_kept
9550 .get(label.0 as usize)
9551 .copied()
9552 .flatten()
9553 .unwrap_or(kept_len);
9554 Op::Label(Label(target as u32))
9555 }
9556 other => other.clone(),
9557 })
9558 .collect()
9559}
9560
9561/// Encode the resolved instruction stream, choosing short forms where possible.
9562///
9563/// Compute the maximum value-stack depth by exploring the control-flow graph.
9564///
9565/// This is a breadth-first walk from the first instruction, tracking the stack
9566/// depth on entry to each instruction. Every instruction has at most two
9567/// successors (fall through, and a jump target), so a worklist over byte offsets
9568/// is enough. The reference does the same thing in `compute_stack_size`, which is
9569/// why the resulting numbers match exactly.
9570///
9571/// Instructions that pop a variable number of values (`call`, `array_from`, …)
9572/// encode that count in their operand, which is added to the static `n_pop`.
9573fn compute_stack_size(code: &[u8]) -> u32 {
9574 let mut depth_at = vec![u16::MAX; code.len()];
9575 // Each entry carries the enclosing `catch` levels, innermost last, because
9576 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
9577 // offset and forgets that level.
9578 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
9579 let mut max_depth = 0u32;
9580
9581 while let Some((pc, depth, catch_levels)) = worklist.pop() {
9582 if pc >= code.len() {
9583 continue;
9584 }
9585 if depth_at[pc] != u16::MAX {
9586 continue;
9587 }
9588 force_depth(&mut depth_at, pc, depth);
9589
9590 let Some(op) = Opcode::from_u8(code[pc]) else {
9591 break;
9592 };
9593 let info = op.info();
9594 let next = pc + info.size as usize;
9595 if next > code.len() {
9596 break;
9597 }
9598 let mut n_pop = info.n_pop as u32;
9599 let mut n_push = info.n_push as u32;
9600 // Variable-length forms carry their count in the operand.
9601 match info.format {
9602 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
9603 n_pop += read_u16(code, pc + 1) as u32;
9604 }
9605 crate::opcode::OpFormat::Npopx => {
9606 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
9607 }
9608 _ => {}
9609 }
9610 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
9611 // are the `set_` variant; the table already records that, so nothing to
9612 // adjust here.
9613 let _ = &mut n_push;
9614
9615 // The depth before this instruction's own push, which is what a `catch`
9616 // records as its level.
9617 let depth_before = depth;
9618 let mut depth = depth.saturating_sub(n_pop) + n_push;
9619 let mut catch_levels = catch_levels;
9620 if op == Opcode::NipCatch {
9621 // Discard everything above the innermost catch offset, keeping the value
9622 // on top: the frame the code after this sees is the same shape it would
9623 // have had if the `try` were not there.
9624 if let Some(base) = catch_levels.pop() {
9625 depth = base + 1;
9626 }
9627 }
9628 max_depth = max_depth.max(depth);
9629
9630 // Successors.
9631 let target = jump_target_of(code, pc, op);
9632 match op {
9633 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9634 if let Some(target) = target {
9635 worklist.push((target, depth, catch_levels));
9636 }
9637 }
9638 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
9639 if let Some(target) = target {
9640 worklist.push((target, depth, catch_levels.clone()));
9641 }
9642 worklist.push((next, depth, catch_levels));
9643 }
9644 // A `catch` records an exception edge to the handler. The handler is
9645 // entered with the thrown value on top of the stack, in the slot the
9646 // catch offset occupies on the normal path — which is why the handler's
9647 // first instruction can `put_loc` the exception away, and why the depth
9648 // is the same on both paths.
9649 Opcode::Catch => {
9650 if let Some(target) = target {
9651 // The handler is protected by the *enclosing* catch, not by this
9652 // one: an error raised inside it is what the handler's own
9653 // `catch` catches.
9654 worklist.push((target, depth, catch_levels.clone()));
9655 }
9656 catch_levels.push(depth_before);
9657 worklist.push((next, depth, catch_levels));
9658 }
9659 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
9660 // rewind past it too. Its level sits one slot higher than a `catch`'s:
9661 // the iterator and next-method slots occupy the offset's place.
9662 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
9663 if let Some(target) = target {
9664 worklist.push((target, depth, catch_levels.clone()));
9665 }
9666 catch_levels.push(depth_before + 1);
9667 worklist.push((next, depth, catch_levels));
9668 }
9669 // `gosub` calls a subroutine with the return address on top. The opcode
9670 // table records no push for it — `ret` is what pops the slot — so the
9671 // extra one is added here, where the depth of the subroutine's first
9672 // instruction is being computed.
9673 Opcode::Gosub => {
9674 if let Some(target) = target {
9675 worklist.push((target, depth + 1, catch_levels.clone()));
9676 }
9677 worklist.push((next, depth, catch_levels));
9678 }
9679 // `ret` goes back to a `gosub`; nothing here follows it.
9680 Opcode::Ret
9681 | Opcode::Return
9682 | Opcode::ReturnUndef
9683 | Opcode::Throw
9684 | Opcode::ThrowError => {}
9685 _ => worklist.push((next, depth, catch_levels)),
9686 }
9687 }
9688 max_depth
9689}
9690
9691/// Record the stack depth on entry to `pc`, keeping the deeper value if the
9692/// instruction is reachable more than once.
9693fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
9694 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
9695 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
9696 depth_at[pc] = clamped;
9697 }
9698}
9699
9700fn read_u16(code: &[u8], at: usize) -> u16 {
9701 let mut value = 0u16;
9702 for i in 0..2 {
9703 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
9704 }
9705 value
9706}
9707
9708/// The absolute target of a jump instruction, if it has one.
9709fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
9710 let info = op.info();
9711 let position = pc + 1;
9712 match info.format {
9713 crate::opcode::OpFormat::Label8 => {
9714 let offset = *code.get(position)? as i8 as i64;
9715 Some((position as i64 + offset) as usize)
9716 }
9717 crate::opcode::OpFormat::Label16 => {
9718 let offset = read_u16(code, position) as i16 as i64;
9719 Some((position as i64 + offset) as usize)
9720 }
9721 crate::opcode::OpFormat::Label => {
9722 let mut offset = 0i32;
9723 for i in 0..4 {
9724 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
9725 }
9726 Some((position as i64 + offset as i64) as usize)
9727 }
9728 _ => None,
9729 }
9730}
9731
9732fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
9733 use Opcode::*;
9734 match (op, operands.first()) {
9735 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
9736 op.short_form(*value as u32).unwrap_or(op)
9737 }
9738 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
9739 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
9740 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
9741 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
9742 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
9743 // A declared global is reached through its reference cell, so it shares
9744 // the `var_ref` encodings, short forms included.
9745 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
9746 op.short_form(*index).unwrap_or(op)
9747 }
9748 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
9749 op.short_form(*count as u32).unwrap_or(op)
9750 }
9751 _ => op,
9752 }
9753}
9754
9755/// The byte offset each instruction will start at, plus the total code size.
9756fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
9757 let mut offsets = Vec::with_capacity(chosen.len() + 1);
9758 let mut offset = 0usize;
9759 for op in chosen {
9760 offsets.push(offset);
9761 offset += op.size() as usize;
9762 }
9763 offsets.push(offset);
9764 offsets
9765}
9766
9767/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
9768/// the offset actually fits.
9769///
9770/// The choice is circular: an instruction's size decides the offsets of everything after
9771/// it, and the offsets decide whether a jump may be short. So this starts with every jump
9772/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
9773/// Shrinking only ever *shortens* distances, so the loop converges.
9774///
9775/// Doing it in one pass instead — which is what this used to do — silently truncated any
9776/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
9777/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
9778/// with four closures in its body simply stopped, with no error and no output past the
9779/// first iteration.
9780fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
9781 let mut chosen: Vec<Opcode> = kept
9782 .iter()
9783 .map(|(op, operands)| choose_short_form(*op, operands))
9784 .collect();
9785 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
9786 let candidates = |op: Opcode| match op {
9787 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
9788 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
9789 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
9790 _ => None,
9791 };
9792 loop {
9793 let offsets = instruction_offsets(&chosen);
9794 let mut changed = false;
9795 for index in 0..kept.len() {
9796 let (op, operands) = &kept[index];
9797 let Some((short, medium, has_medium)) = candidates(*op) else {
9798 continue;
9799 };
9800 if chosen[index] == short {
9801 continue;
9802 }
9803 let Some(target) = target_kept_index(operands, label_kept) else {
9804 continue;
9805 };
9806 let Some(&target_offset) = offsets.get(target) else {
9807 continue;
9808 };
9809 // A jump is relative to the byte after its opcode, which is the convention
9810 // `jump_target_of` decodes with.
9811 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
9812 if (-128..=127).contains(&relative) {
9813 chosen[index] = short;
9814 changed = true;
9815 } else if has_medium
9816 && chosen[index] == Opcode::Goto
9817 && (-32_768..=32_767).contains(&relative)
9818 {
9819 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
9820 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
9821 // the reference encodes them.
9822 chosen[index] = medium;
9823 changed = true;
9824 }
9825 }
9826 if !changed {
9827 return chosen;
9828 }
9829 }
9830}
9831
9832fn encode_operands(
9833 code: &mut Vec<u8>,
9834 op: Opcode,
9835 operands: &[Op],
9836 position: usize,
9837 offsets: &[usize],
9838) {
9839 use crate::opcode::OpFormat::*;
9840 let info = op.info();
9841 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
9842 let index = match slot {
9843 Slot::Arg(i)
9844 | Slot::Loc(i)
9845 | Slot::VarRef(i)
9846 | Slot::Global(i)
9847 | Slot::GlobalDecl(i) => i,
9848 };
9849 code.extend_from_slice(&(index as u16).to_be_bytes());
9850 };
9851 match info.format {
9852 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
9853 U8 | Const8 => {
9854 if let Some(value) = operands.first().and_then(operand_uint) {
9855 code.push(value as u8);
9856 }
9857 }
9858 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
9859 // like their wide counterparts, only one byte wide.
9860 Loc8 => {
9861 if let Some(Op::Slot(slot)) = operands.first() {
9862 let index = match slot {
9863 Slot::Arg(i)
9864 | Slot::Loc(i)
9865 | Slot::VarRef(i)
9866 | Slot::Global(i)
9867 | Slot::GlobalDecl(i) => *i,
9868 };
9869 code.push(index as u8);
9870 }
9871 }
9872 I8 => {
9873 if let Some(value) = operands.first().and_then(operand_int) {
9874 code.push(value as i8 as u8);
9875 }
9876 }
9877 U16 | Npop => {
9878 if let Some(value) = operands.first().and_then(operand_int) {
9879 code.extend_from_slice(&(value as u16).to_be_bytes());
9880 }
9881 }
9882 I16 => {
9883 if let Some(value) = operands.first().and_then(operand_int) {
9884 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
9885 }
9886 }
9887 I32 => {
9888 if let Some(value) = operands.first().and_then(operand_int) {
9889 code.extend_from_slice(&value.to_be_bytes());
9890 }
9891 }
9892 U32 | Const => {
9893 if let Some(value) = operands.first().and_then(operand_uint) {
9894 code.extend_from_slice(&value.to_be_bytes());
9895 }
9896 }
9897 Loc | Arg | VarRef => {
9898 if let Some(Op::Slot(slot)) = operands.first() {
9899 write_slot(code, *slot);
9900 }
9901 }
9902 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
9903 if let Some(Op::AtomId(index)) = operands.first() {
9904 code.extend_from_slice(&index.to_be_bytes());
9905 }
9906 // The trailing immediate means different things per format, and the
9907 // atom forms that carry a *label* have to resolve it like any other
9908 // jump, so they cannot share the `U8`/`U16` arms above.
9909 match info.format {
9910 AtomU8 | AtomLabelU8 => {
9911 if let Some(value) = operands.get(1).and_then(operand_uint) {
9912 code.push(value as u8);
9913 }
9914 }
9915 AtomU16 | AtomLabelU16 => {
9916 if let Some(value) = operands.get(1).and_then(operand_uint) {
9917 code.extend_from_slice(&(value as u16).to_be_bytes());
9918 }
9919 }
9920 _ => {}
9921 }
9922 }
9923 NpopU16 => {
9924 for operand in operands.iter().take(2) {
9925 if let Some(value) = operand_uint(operand) {
9926 code.extend_from_slice(&(value as u16).to_be_bytes());
9927 }
9928 }
9929 }
9930 Label | Label8 | Label16 | LabelU16 => {
9931 if let Some(Op::Label(label)) = operands.first() {
9932 // Labels were already remapped to kept-instruction indices.
9933 let Some(&target) = offsets.get(label.0 as usize) else {
9934 debug_assert!(false, "label {} is past the end", label.0);
9935 return;
9936 };
9937 let relative = target as i64 - (position as i64 + 1);
9938 match info.format {
9939 Label8 => code.push(relative as i8 as u8),
9940 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
9941 // `label_u16` stores the target followed by an unrelated u16.
9942 LabelU16 => {
9943 code.extend_from_slice(&(relative as i32).to_be_bytes());
9944 if let Some(value) = operands.get(1).and_then(operand_uint) {
9945 code.extend_from_slice(&(value as u16).to_be_bytes());
9946 }
9947 }
9948 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
9949 }
9950 }
9951 }
9952 }
9953}
9954
9955fn operand_int(op: &Op) -> Option<i32> {
9956 match op {
9957 Op::Int(value) => Some(*value),
9958 _ => None,
9959 }
9960}
9961
9962fn operand_uint(op: &Op) -> Option<u32> {
9963 match op {
9964 Op::Const(value) | Op::AtomId(value) => Some(*value),
9965 Op::Int(value) => Some(*value as u32),
9966 _ => None,
9967 }
9968}
9969
9970/// Disassemble a compiled function.
9971pub fn disassemble(function: &CompiledFunction) -> String {
9972 disasm::disassemble_program(function)
9973}