js_compile/compiler.rs
1//! The bytecode compiler.
2//!
3//! Compilation is a single walk over the AST that emits *symbolic* instructions
4//! (jump targets are label ids, variable references are names), followed by a
5//! resolution pass that turns them into final bytecode. Splitting it this way
6//! keeps the emitter readable: nothing has to know slot indices or byte offsets
7//! while it is still discovering them.
8//!
9//! Variable resolution follows the reference implementation's model:
10//!
11//! * every function has a flat table of arguments and locals;
12//! * block scopes form a chain through [`VarDef::scope_next`], which is what makes
13//! `let`/`const` bindings visible only inside their block and lets the runtime
14//! put them back into the temporal dead zone on entry;
15//! * a name that is not in the current function is looked up in the enclosing
16//! ones; if found, the variable is marked captured and reached through a
17//! closure reference;
18//! * a name found nowhere is a global, reached through a closure entry as well.
19//!
20//! Emission order and instruction choice deliberately mirror `quickjs.c`: the
21//! differential test compares disassembly with the reference opcode by opcode, so
22//! an unnecessary `dup` or a differently chosen short form shows up immediately.
23
24use crate::bytecode::LineCol;
25use crate::bytecode::{
26 ANONYMOUS_BINDING, Atom, ClosureType, ClosureVar, Constant, EvalPrivate, EvalPrivateKind,
27 EvalSite, EvalVisible, ExportEntry, Function as CompiledFunction, FunctionKind, ImportEntry,
28 ModuleMeta, ModuleRequest, VarDef, VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::Wtf8;
36use js_parse::ast::{self, *};
37
38/// A label id, local to the function being compiled.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Label(u32);
41
42/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
43///
44/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
45/// is why the brackets are part of the name; nothing a program writes can collide with it.
46const HOME_OBJECT: &str = "<home_object>";
47
48/// The local holding the function `super()` constructs from.
49///
50/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
51/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
52const ACTIVE_FUNC: &str = "this.active_func";
53
54/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
55const NEW_TARGET: &str = "new.target";
56
57/// Stand-in for a constant-pool index that is only known later in the instruction stream.
58///
59/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
60/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
61/// billion members is not a thing — and the compiler patches it before resolution runs, so a
62/// missed patch is a panic-free compiler error rather than a wrong jump.
63const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
64
65/// One step of a class's initialisation, in source order.
66///
67/// A static block is not a member the class keeps — it is a run of statements that executes
68/// at the point the class definition reaches it — so it belongs *inside* the initialiser
69/// function rather than alongside the fields as a separate pass. Merging the two is what
70/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
71/// same way the reference is.
72enum StaticInitItem<'a> {
73 /// `static x = value`, or `x = value` for the instance half.
74 Field(FieldKey<'a>, Option<&'a Expr>),
75 /// `static { … }`
76 Block {
77 body: &'a [Stmt],
78 /// Position of the `{`, which is where the reference puts the function.
79 body_start: Position,
80 },
81}
82
83/// The next template-site identity, process-wide.
84///
85/// A counter rather than something derived from the unit: two compilation units that both
86/// number their sites from zero would collide in the realm's registry, and a collision
87/// there is observable — it would hand the *same* template object to two unrelated sites.
88fn next_template_site() -> u32 {
89 static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
90 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
91}
92
93/// How one field names its property.
94///
95/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
96/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
97/// is fixed when the class is created. Keeping the expression here instead made
98/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
99/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
100/// `{1: "a"}`.
101enum FieldKey<'a> {
102 /// `x`, `"x"`, `0` — the property name is static text.
103 Literal(&'a PropKey),
104 /// `#x`: the class-scope binding that holds the private symbol.
105 Private(String),
106 /// `[expr]`: the class-scope binding that holds the evaluated key.
107 Computed(String),
108}
109
110/// The `var_block` sentinel for a binding that lives at function scope.
111///
112/// It has to be a value a *real* block key can never take. Block keys are source
113/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
114/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
115/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
116/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
117/// sentinel takes the slot below it.
118const FUNCTION_SCOPE: u64 = u64::MAX - 3;
119
120/// The `var_block` sentinel for a binding of the parameter list.
121///
122/// A function whose parameter list contains a default expression gets *two* variable
123/// environments: one for the parameters and one for the body, so a `var` in the body
124/// that shares a name with a parameter is a different binding. The parameter bindings
125/// therefore need a scope key of their own: reachable while the defaults are
126/// evaluated, invisible to the body, and never merged with a body `var` of the same
127/// name.
128///
129/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
130/// the closure and the body shared one slot, when only the parameters were in scope
131/// when it was created.
132const PARAM_SCOPE: u64 = u64::MAX - 4;
133
134/// The name of the hidden local a `using` declaration caches its dispose method in.
135///
136/// It has to be a name no source can produce, because a script may declare anything: the
137/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
138fn using_method_name(name: &str) -> String {
139 format!("<using.method {name}>")
140}
141
142/// The `blocks` parent sentinel for "this block has no enclosing block".
143///
144/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
145/// also the terminator the chain walk from the script body reached the file's
146/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
147/// leaked into the body scope.
148const NO_PARENT: u64 = u64::MAX - 2;
149
150/// The block key for a script body. Distinct from both sentinels and unreachable from
151/// any source offset.
152const SCRIPT_BODY: u64 = u64::MAX - 1;
153
154/// An operand of a symbolic instruction.
155#[derive(Debug, Clone, PartialEq)]
156enum Op {
157 /// An immediate integer.
158 Int(i32),
159 /// A jump target.
160 Label(Label),
161 /// A constant pool index.
162 Const(u32),
163 /// An atom, before interning.
164 Atom(Atom),
165 /// An interned atom, as an index into [`Function::atoms`].
166 AtomId(u32),
167 /// A resolved slot.
168 Slot(Slot),
169}
170
171/// Where a resolved variable lives.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum Slot {
174 Arg(u32),
175 Loc(u32),
176 VarRef(u32),
177 /// A global, by closure-var index.
178 Global(u32),
179 /// A global *declared* in this script. The reference keeps these bindings in
180 /// reference cells so that the script and any closure share one variable, so
181 /// a store goes through `put_var_ref` while a read uses `get_var`.
182 GlobalDecl(u32),
183}
184
185/// What a symbolic variable access does, which decides the final opcode.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187enum VarAction {
188 /// Read the value.
189 Get,
190 /// Read the value, yielding `undefined` for an undeclared global.
191 GetUndef,
192 /// Write, leaving nothing on the stack.
193 Put,
194 /// Write and initialise, leaving the value on the stack.
195 PutInit,
196 /// Write, leaving the value on the stack.
197 Set,
198 /// Initialise a binding that may only be initialised once, such as a derived
199 /// constructor's `this`.
200 PutInitChecked,
201 /// Initialise, leaving the value on the stack and without the `const` check.
202 ///
203 /// A class's own scope binding is a `const` that has to be initialised in the middle
204 /// of the definition — after the constructor exists but before the static fields run
205 /// — and the value has to survive for the outer store to use.
206 SetInit,
207 /// Write a binding that lives in a reference cell.
208 PutRef,
209}
210
211#[derive(Debug, Clone)]
212enum Insn {
213 /// A fully determined instruction.
214 Fixed { op: Opcode, operands: Vec<Op> },
215 /// A variable access, resolved in the second pass.
216 ///
217 /// `block` is the lexical block the access appears in, which is what makes
218 /// shadowing work: two bindings can share a name, and the one that wins is
219 /// whichever scope encloses the access.
220 Var {
221 action: VarAction,
222 name: String,
223 block: u64,
224 /// Whether the access was written in the parameter list; see
225 /// [`FnState::in_params`].
226 in_params: bool,
227 },
228 /// Close a binding *if* it turned out to be captured.
229 ///
230 /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
231 /// only known once the body has been compiled — a closure created there is the
232 /// thing that makes it necessary. The reference emits `close_loc` exactly in that
233 /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
234 /// of emitted blind.
235 CloseCaptured { name: String, block: u64 },
236 /// `delete name`, which can only answer `false` once the binding is known.
237 ///
238 /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
239 /// looks the name up on the global object, which is what distinguishes an implicit
240 /// global (configurable, deletable) from a declared one (a binding, always `false`).
241 DeleteVar { name: String },
242 /// An instruction that dead-code elimination removed. It keeps its slot so
243 /// that label indices stay valid, and resolves to no bytecode.
244 Dead,
245}
246
247/// Where `break` and `continue` jump to.
248///
249/// Targets are stacked as the compiler enters loops and labelled statements, so a
250/// bare `break` needs no analysis: it is simply the innermost target. A labelled
251/// one searches outward by name.
252#[derive(Debug, Clone)]
253struct JumpTarget {
254 /// The labels attached to this target. `l: for(;;)` gives one name; a bare
255 /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
256 /// same statement and `break a` must reach the same place as `break b`.
257 names: Vec<String>,
258 /// Where `break` lands. `None` for a construct `break` may only leave, not
259 /// target — a `try`, whose entry exists purely to unwind.
260 break_label: Option<Label>,
261 /// Where `continue` lands. `None` for anything that is not a loop.
262 continue_label: Option<Label>,
263 /// Stack slots to discard when control leaves this construct by a jump.
264 ///
265 /// Both `switch` and `try` leave something on the value stack for the duration
266 /// of the construct — the discriminant, or the `catch` offset — and a jump out
267 /// has to take it with it. A loop leaves nothing.
268 drop_count: u32,
269 /// The finalizer to run when control leaves this construct.
270 ///
271 /// Set on a `try` even when it has no `finally`: the label is always emitted and
272 /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
273 /// does not have to know whether a finalizer exists.
274 finally_label: Option<Label>,
275 /// Whether this is a labelled non-loop statement, which an unlabelled `break`
276 /// does not reach.
277 is_regular_stmt: bool,
278 /// Whether leaving this construct has to close an iterator.
279 ///
280 /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
281 /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
282 /// is dropped rather than closed.
283 has_iterator: bool,
284 /// Whether that iterator speaks the *async* protocol.
285 ///
286 /// An async close has to `await` the inner `return`, so it is an inline instruction
287 /// sequence rather than one opcode — the reference's `emit_iterator_close`.
288 is_async_iterator: bool,
289}
290
291/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
292///
293/// Both leave `source value` on the stack, so this is purely which spelling the reference
294/// picked, and it picked it by whether it had to build a *reference* for the target:
295///
296/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
297/// consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
298/// destructures);
299/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
300/// * a `var`, and any assignment target, go through `dup; get_field`, because the
301/// reference builds a reference for them — which is what `with` needs.
302fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
303 nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
304}
305
306/// Whether binding this pattern starts by boxing the value it was handed.
307fn nests_a_pattern(pattern: &Pattern) -> bool {
308 match &pattern.kind {
309 PatternKind::Array { .. } | PatternKind::Object { .. } => true,
310 PatternKind::Assign { target, .. } => nests_a_pattern(target),
311 _ => false,
312 }
313}
314
315/// `copy_data_properties` flags for an object-literal spread.
316///
317/// The byte packs three fields: the low bits are the stack offset of the source,
318/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
319/// as well as string keys. A spread passes a literal `null` exclusion list right
320/// below the source, so that field stays zero and only the source offset and the
321/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
322const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
323
324/// The expression a `...` introduces.
325///
326/// The parser marks the spread in two places — the element/property variant and an
327/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
328/// stepped through before the argument can be compiled.
329fn spread_argument(spread: &Expr) -> &Expr {
330 match &spread.kind {
331 ExprKind::Spread(inner) => inner,
332 _ => spread,
333 }
334}
335
336/// The flag byte `define_method` takes.
337///
338/// The low two bits pick value/getter/setter; bit 2 marks the property
339/// enumerable, which every object-literal method is.
340/// What kind of class constructor a function is being compiled as.
341///
342/// A constructor is not an ordinary method: a base one materialises `this` and refuses
343/// to run without `new`, and a derived one starts with `this` in the dead zone until
344/// `super()` produces it.
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346enum CtorKind {
347 /// Not a class constructor.
348 None,
349 /// A constructor of a class without `extends`.
350 Base,
351 /// A constructor of a class with `extends`.
352 Derived,
353}
354
355/// The flag byte `define_method` takes for a class member.
356///
357/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
358/// a class method is *not* — that is the whole difference from an object-literal method,
359/// and the reason `Object.keys(C.prototype)` stays empty.
360fn class_method_flags(kind: MethodKind) -> i32 {
361 match kind {
362 MethodKind::Constructor | MethodKind::Method => 0,
363 MethodKind::Get => 1,
364 MethodKind::Set => 2,
365 }
366}
367
368fn define_method_flags(kind: PropertyKind) -> i32 {
369 let base = match kind {
370 PropertyKind::Value | PropertyKind::Method => 0,
371 PropertyKind::Get => 1,
372 PropertyKind::Set => 2,
373 };
374 base | 4
375}
376
377/// Convert a numeric property key to the text an atom would be made from.
378///
379/// `PropertyKey` of a number is `ToString(number)`, the same conversion every other place
380/// uses — so this goes through [`crate::number::number_to_string`] rather than formatting
381/// the value here. It used to accept only `[1e-6, 1e21)` and reject the rest, on the
382/// theory that Rust's `{}` and JavaScript's spelling diverge at the extremes; they do, and
383/// that is exactly why the spec's own algorithm is the thing to call. `get 0.0000001() {}`
384/// binds the key `"1e-7"`, and the rejection made it a `SyntaxError` instead.
385///
386/// The `Result` is kept because the call sites are in a `?` chain, and a key conversion
387/// that could still fail (a non-finite value from a source literal, which the lexer does
388/// not produce) belongs on the same path as the rest of a property name's errors.
389fn numeric_key_text(value: f64, _span: Span) -> Result<String, SyntaxError> {
390 Ok(crate::number::number_to_string(value))
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 /// Whether this function has an `arguments` binding of its own.
568 ///
569 /// False for a class field initialiser and a static block: §15.7 puts them outside any
570 /// function, so `arguments` does not exist there and `eval('arguments')` inside one is a
571 /// `SyntaxError` rather than the caller's arguments object. The parser already enforces
572 /// that for written code; this carries the same fact to the `eval` call site, which has
573 /// to compile the eval'd source under the caller's restriction.
574 no_arguments_binding: bool,
575 /// The same, for `this.active_func`: the function `super()` constructs from.
576 ///
577 /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
578 /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
579 /// as a local of the enclosing function; an arrow that escaped the constructor
580 /// (`iter.return = () => super()`) then finds it in its closure even with the
581 /// constructor nowhere on the call stack.
582 needs_active_func_local: bool,
583 /// Hidden locals of the `with` blocks currently open, innermost last.
584 with_names: Vec<String>,
585 /// How many of [`FnState::with_names`] were already open when this function was
586 /// created, i.e. belong to an *enclosing* function.
587 ///
588 /// The distinction decides shadowing, and it is positional rather than lexical. A
589 /// `with` opened **inside** this function's body sits nearer than the function's own
590 /// environment, so it shadows even a `var` of this function:
591 /// `function f(){ with(o){ var v = 1 } }` writes `o.v`. A `with` opened **outside**
592 /// does not: `with(o){ function f(){ var v = 1 } }` writes `f`'s local `v`, because
593 /// `f`'s environment is the inner one. Treating both alike broke one family or the
594 /// other — `S12.10_A1.2` and `S12.10_A1.7` are these two cases.
595 inherited_with_names: usize,
596 /// Set while a with-guard is being emitted, so the guard's own accesses are not
597 /// wrapped in another guard.
598 emitting_with_guard: bool,
599 self_name: Option<String>,
600 /// Where the function body starts, in source order; see [`Function::body_start`].
601 body_start: (u32, u32),
602 /// Whether the body contains a *direct* `eval(...)` call.
603 ///
604 /// A direct eval sees every binding of the function that called it, including ones
605 /// no other code mentions. It also hands those bindings to any closure it creates,
606 /// which can outlive the function. Both need the bindings to live in cells, so this
607 /// flag makes the function treat all of them as captured.
608 has_direct_eval: bool,
609 /// Whether the parameter list contains a default expression, which is what gives
610 /// the function a second variable environment (see [`PARAM_SCOPE`]).
611 has_parameter_expressions: bool,
612 /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
613 simple_parameter_list: bool,
614 /// Whether the instructions being emitted belong to the parameter list.
615 ///
616 /// References made here must not see the body's `var`s: the body has not run yet,
617 /// and the reference's own model keeps the two scopes apart.
618 in_params: bool,
619 /// Whether an arrow created in this function's parameter list needs the parameter
620 /// scope's `arguments` binding.
621 needs_param_arguments: bool,
622 /// Whether this function was *created* inside a parameter list.
623 ///
624 /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
625 /// arrow too. The name reference is the arrow's, but the scope it must not see
626 /// belongs to the function the arrow was born in.
627 created_in_params: bool,
628 /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
629 ///
630 /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
631 /// final while the body is still being compiled: a named function expression declares
632 /// its own name binding *after* the body, and that binding is exactly what
633 /// `eval("myfunc = 1")` has to find.
634 eval_sites: Vec<EvalSite>,
635 /// Direct `eval` call sites seen so far: where, and the block that was current.
636 pending_eval_sites: Vec<(Span, u64, bool, Vec<EvalPrivate>, bool)>,
637 /// Whether this body contains `await`.
638 ///
639 /// For a *module* this decides whether its body is an async function: top-level
640 /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
641 /// to survive to the compiled function rather than being a local of the compiler.
642 has_await: bool,
643 /// The module tables, when this body is a module.
644 ///
645 /// Only the top-level state ever has one: `export` and `import` are top-level
646 /// statements, so nothing nested can add to these tables.
647 module: Option<ModuleMeta>,
648 /// Whether the self-name prologue (`special_object 2` then the store) has been
649 /// emitted for this function.
650 ///
651 /// A *nested* function's lookup declares the binding early (see
652 /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
653 /// prologue is still needed — the binding existing is not the same as it being
654 /// initialised.
655 self_name_initialized: bool,
656 /// Whether the code emitted so far leaves the program's result on the stack.
657 /// The reference tracks this for the hidden `<ret>` local of an eval script.
658 leaves_value: bool,
659 /// Statement nesting depth, used to tell top-level statements apart.
660 stmt_depth: u32,
661 /// Function declarations waiting to be instantiated at scope entry, as
662 /// (target slot, constant pool index). The reference emits these from
663 /// `instantiate_hoisted_definitions` rather than at the statement, because a
664 /// declaration is visible before it is reached.
665 hoisted: Vec<(u64, HoistTarget, u32)>,
666 /// Function declarations whose bodies are compiled only once the enclosing scope
667 /// has finished hoisting, as (owning block, declaration).
668 ///
669 /// Compiling a body at the declaration makes the result depend on source order: in
670 /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
671 /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
672 /// names first and the bodies second is what removes that dependence.
673 deferred_funcs: Vec<(u64, Box<ast::Function>)>,
674 /// The source position of the node being compiled. Every instruction emitted
675 /// takes it, which is how the position table that feeds stack traces is built.
676 cur_pos: Option<Position>,
677 /// One position per entry in `insns`, index-aligned.
678 insn_pos: Vec<Option<Position>>,
679}
680
681/// Where a hoisted function declaration is stored.
682#[derive(Debug, Clone)]
683enum HoistTarget {
684 Arg(u32),
685 Loc(u32),
686 /// A global, which the resolver looks up by name.
687 Global(String),
688}
689
690impl FnState {
691 /// Whether this function suspends: a generator or an async function.
692 ///
693 /// A suspending function's `return` is a `return_async` and its body starts with an
694 /// `initial_yield`, so almost every statement that touches control flow asks this.
695 fn is_suspending(&self) -> bool {
696 self.kind.is_generator() || self.kind.is_async()
697 }
698
699 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
700 FnState {
701 span: None,
702 name: name.into(),
703 kind,
704 strict: false,
705 args: Vec::new(),
706 vars: Vec::new(),
707 closure_vars: Vec::new(),
708 cpool: Vec::new(),
709 atoms: Vec::new(),
710 blocks: Vec::new(),
711 current_block: 0,
712 created_in_block: NO_PARENT,
713 var_block: Vec::new(),
714 no_value: false,
715 label_since_insn: false,
716 discard_value: false,
717 body_block: 0,
718 block_heads: Vec::new(),
719 jump_targets: Vec::new(),
720 insns: Vec::new(),
721 labels: Vec::new(),
722 var_ref_count: 0,
723 line: 1,
724 column: 1,
725 is_script: false,
726 is_module: false,
727 is_arrow: false,
728 defined_args: 0,
729 param_prologue: Vec::new(),
730 ctor_kind: CtorKind::None,
731 class_ctor_pending: None,
732 needs_this_local: false,
733 needs_arguments_local: false,
734 needs_new_target_local: false,
735 has_this_prologue: false,
736 needs_home_object_local: false,
737 no_arguments_binding: false,
738 needs_active_func_local: false,
739 with_names: Vec::new(),
740 inherited_with_names: 0,
741 emitting_with_guard: false,
742 self_name: None,
743 has_direct_eval: false,
744 body_start: (0, 0),
745 has_parameter_expressions: false,
746 simple_parameter_list: true,
747 in_params: false,
748 needs_param_arguments: false,
749 created_in_params: false,
750 eval_sites: Vec::new(),
751 pending_eval_sites: Vec::new(),
752 has_await: false,
753 module: None,
754 self_name_initialized: false,
755 leaves_value: false,
756 stmt_depth: 0,
757 hoisted: Vec::new(),
758 deferred_funcs: Vec::new(),
759 cur_pos: None,
760 insn_pos: Vec::new(),
761 }
762 }
763
764 /// The scope a declaration lands in: a script's top-level declarations are
765 /// globals, everything else gets a slot.
766 /// Whether a binding declared *now* becomes a property of the global object.
767 ///
768 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
769 /// The `var` case is decided by the keyword rather than by the cursor position:
770 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
771 /// binding as a `var i` in the body, even though the head has its own block.
772 fn declares_globally(&self, def: &VarDef) -> bool {
773 // A module's top-level declarations are *module*-scoped: they live in the module
774 // record, never on the global object. Two modules can both declare `var x`
775 // without seeing each other, which is the whole point.
776 if self.is_module {
777 return false;
778 }
779 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
780 }
781}
782
783/// The compiler's entry point.
784pub struct Compiler {
785 /// The text being compiled, kept so each function can record its own slice for
786 /// `Function.prototype.toString`.
787 source: Option<String>,
788 module: bool,
789 /// Whether the program itself is the body of an `async` function.
790 ///
791 /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
792 /// completion value is wrapped so a returned promise is not adopted.
793 async_body: bool,
794 /// Enclosing functions, outermost first. The last entry is the current one.
795 stack: Vec<FnState>,
796 /// The private names visible at this point, innermost class body last.
797 ///
798 /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
799 /// to the class body: a method, an arrow inside it and a class nested inside that arrow
800 /// all resolve against the same entries, and the parser accepts exactly that set
801 /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
802 /// class's names the moment a method started.
803 private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
804 /// Whether the expression [`Compiler::expr`] is about to compile is the one its
805 /// statement asked to discard.
806 ///
807 /// `FnState::discard_value` says "the statement's value is thrown away", which is only
808 /// ever true of the statement's own expression — an assignment nested inside it, as in
809 /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
810 /// keeping the answer here is what tells the two apart; without it the nested store
811 /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
812 /// function threw `undefined is not a function`.
813 discard_root: bool,
814}
815
816/// How a use site of a private name compiles.
817///
818/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
819/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
820/// of a setter-only accessor pair.
821#[derive(Clone, Copy, PartialEq, Eq)]
822enum PrivateKind {
823 /// `#x = 1`: an own property keyed by the symbol in the binding.
824 Field,
825 /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
826 Method,
827 /// `get #a() {}`: the binding holds the getter, and a read calls it.
828 Getter,
829 /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
830 /// the same `TypeError` as reading an uninitialised `const`.
831 Setter,
832}
833
834/// What the compiler knows about one `#name` where it is used.
835#[derive(Clone)]
836struct PrivateUse {
837 kind: PrivateKind,
838 /// `#a<set>` when the class defines a setter for this name.
839 ///
840 /// A second binding, not a second field of the first: the reference stores the setter
841 /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
842 setter: Option<String>,
843}
844
845/// The class-scope bindings one class body needs, in declaration order.
846#[derive(Default)]
847struct ClassPlan {
848 /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
849 /// at class entry, in member order.
850 bindings: Vec<String>,
851 /// The private names, for the use sites inside the body.
852 uses: std::collections::HashMap<String, PrivateUse>,
853 /// Computed field keys, by element index, so the emission pass does not have to redo the
854 /// per-half counter that names them.
855 computed: std::collections::HashMap<usize, String>,
856 /// Whether the instance initialiser has to add the brand to `this`.
857 instance_brand: bool,
858 /// Whether the constructor itself has to carry the brand.
859 static_brand: bool,
860}
861
862impl ClassPlan {
863 /// Walk a class body once and decide every class-scope binding it needs.
864 ///
865 /// Order is the reference's: a member's binding is created when the member is parsed, so
866 /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
867 /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
868 /// the disassembly stops matching even when every instruction is right.
869 fn build(class: &Class) -> ClassPlan {
870 let mut plan = ClassPlan::default();
871 let mut instance_keys = 0usize;
872 let mut static_keys = 0usize;
873 for (index, element) in class.elements.iter().enumerate() {
874 match element {
875 ClassElement::Method {
876 key: PropName::Private(ident),
877 kind,
878 is_static,
879 ..
880 } => {
881 let name = format!("#{}", ident.name);
882 let first = !plan.uses.contains_key(&name);
883 if first {
884 plan.bindings.push(name.clone());
885 plan.uses.insert(
886 name.clone(),
887 PrivateUse {
888 kind: match kind {
889 MethodKind::Get => PrivateKind::Getter,
890 MethodKind::Set => PrivateKind::Setter,
891 _ => PrivateKind::Method,
892 },
893 setter: None,
894 },
895 );
896 }
897 match kind {
898 MethodKind::Set => {
899 let binding = format!("{name}<set>");
900 plan.bindings.push(binding.clone());
901 if let Some(use_) = plan.uses.get_mut(&name) {
902 use_.setter = Some(binding);
903 }
904 }
905 // A getter is what makes the name readable, so a pair that started
906 // as a setter becomes readable once the getter arrives.
907 MethodKind::Get => {
908 if let Some(use_) = plan.uses.get_mut(&name) {
909 use_.kind = PrivateKind::Getter;
910 }
911 }
912 _ => {}
913 }
914 if *is_static {
915 plan.static_brand = true;
916 } else {
917 plan.instance_brand = true;
918 }
919 }
920 ClassElement::Method {
921 key: PropName::Computed(_),
922 ..
923 } => {}
924 ClassElement::Method { .. } => {}
925 ClassElement::Field {
926 key: PropName::Private(ident),
927 ..
928 } => {
929 let name = format!("#{}", ident.name);
930 if !plan.uses.contains_key(&name) {
931 plan.bindings.push(name.clone());
932 plan.uses.insert(
933 name,
934 PrivateUse {
935 kind: PrivateKind::Field,
936 setter: None,
937 },
938 );
939 }
940 }
941 ClassElement::Field {
942 key: PropName::Computed(_),
943 is_static,
944 ..
945 } => {
946 let index_in_half = if *is_static {
947 static_keys += 1;
948 static_keys - 1
949 } else {
950 instance_keys += 1;
951 instance_keys - 1
952 };
953 let binding = computed_field_binding(index_in_half, *is_static);
954 plan.bindings.push(binding.clone());
955 plan.computed.insert(index, binding);
956 }
957 ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
958 }
959 }
960 plan
961 }
962
963 /// How a private name used inside the body compiles, or `None` if no enclosing class
964 /// declares it.
965 fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
966 compiler
967 .private_scopes
968 .iter()
969 .rev()
970 .find_map(|scope| scope.get(name))
971 }
972}
973
974impl Compiler {
975 /// The exact source text of a function, for `Function.prototype.toString`.
976 ///
977 /// §20.2.3.5 requires the *original* text: a function must stringify back to what
978 /// was written, comments and odd spacing included. Slicing the recorded span out of
979 /// the whole source is the only way to get that — rebuilding it from the AST would
980 /// normalise the text, and answering `[native code]` for a script function (which is
981 /// what this engine used to do) makes the result useless for feature detection and
982 /// for libraries that read their own source.
983 ///
984 /// Top-level bodies have no single expression span, so their `source` stays `None`
985 /// and `toString` falls back to the calling convention the spec allows.
986 fn function_source(
987 &self,
988 span: Option<(usize, usize)>,
989 line: u32,
990 column: u32,
991 ) -> Option<String> {
992 let source = self.source.as_ref()?;
993 let span = span?;
994 let bytes = source.as_bytes();
995 let start = span.0;
996 let end = span.1;
997 if start >= bytes.len() || end > bytes.len() || start >= end {
998 let _ = (line, column);
999 return None;
1000 }
1001 Some(source.get(start..end)?.to_string())
1002 }
1003}
1004
1005/// Compile a script.
1006pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1007 Compiler::new(false).compile(program)
1008}
1009
1010/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
1011/// the original source.
1012///
1013/// The separate entry point rather than a parameter on [`compile_script`] because the
1014/// tests and the disassembler compile from an AST they built themselves and have no
1015/// source to give; they keep the `None` behaviour they already relied on.
1016pub fn compile_script_with_source(
1017 program: &Program,
1018 source: &str,
1019) -> Result<CompiledFunction, SyntaxError> {
1020 let mut compiler = Compiler::new(false);
1021 compiler.source = Some(source.to_string());
1022 compiler.compile(program)
1023}
1024
1025/// [`compile_script_with_source`] for a module.
1026pub fn compile_module_with_source(
1027 program: &Program,
1028 source: &str,
1029) -> Result<CompiledFunction, SyntaxError> {
1030 let mut compiler = Compiler::new(true);
1031 compiler.source = Some(source.to_string());
1032 compiler.compile(program)
1033}
1034
1035/// Compile a script whose top level is the body of an `async` function.
1036/// The body is an ordinary script in every other way — it still reports a completion value
1037/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1038/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1039/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1040/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1041/// documents.
1042pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1043 Compiler::for_suspensible_script().compile(program)
1044}
1045
1046/// Compile a module.
1047pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1048 Compiler::new(true).compile(program)
1049}
1050
1051/// Compile a direct `eval` body that inherits private names from its caller.
1052///
1053/// `class C { #m = 44; f() { return eval("this.#m") } }` is legal — private names are
1054/// lexically scoped and the eval runs inside the caller's scope — but the names live in the
1055/// *call site's* compilation unit, so they have to be handed over. Seeding them as the
1056/// outermost private scope is what lets the eval resolve `#m` to the caller's binding: the
1057/// read compiles as an ordinary name lookup of `#m`, which at run time finds the caller's
1058/// slot through the same `eval`-scope machinery every other inherited name uses.
1059///
1060/// `suspensible` selects the `{async: true}` form (`std.evalScript(s, {async: true})`), whose
1061/// body may `await`.
1062pub fn compile_eval_with_private(
1063 program: &Program,
1064 private: &[EvalPrivate],
1065 suspensible: bool,
1066) -> Result<CompiledFunction, SyntaxError> {
1067 let mut compiler = if suspensible {
1068 Compiler::for_suspensible_script()
1069 } else {
1070 Compiler::new(false)
1071 };
1072 if !private.is_empty() {
1073 let scope: std::collections::HashMap<String, PrivateUse> = private
1074 .iter()
1075 .map(|entry| {
1076 (
1077 entry.name.clone(),
1078 PrivateUse {
1079 kind: match entry.kind {
1080 EvalPrivateKind::Field => PrivateKind::Field,
1081 EvalPrivateKind::Method => PrivateKind::Method,
1082 EvalPrivateKind::Getter => PrivateKind::Getter,
1083 EvalPrivateKind::Setter => PrivateKind::Setter,
1084 },
1085 setter: entry.setter.clone(),
1086 },
1087 )
1088 })
1089 .collect();
1090 compiler.private_scopes.push(scope);
1091 }
1092 compiler.compile(program)
1093}
1094
1095impl Compiler {
1096 /// Create a compiler.
1097 pub fn new(module: bool) -> Compiler {
1098 Compiler {
1099 source: None,
1100 module,
1101 async_body: false,
1102 stack: Vec::new(),
1103 private_scopes: Vec::new(),
1104 discard_root: false,
1105 }
1106 }
1107
1108 /// Create a compiler for a script whose top level is an `async` function body.
1109 fn for_suspensible_script() -> Compiler {
1110 Compiler {
1111 source: None,
1112 module: false,
1113 async_body: true,
1114 stack: Vec::new(),
1115 private_scopes: Vec::new(),
1116 discard_root: false,
1117 }
1118 }
1119
1120 /// Compile a whole program into its top-level function.
1121 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1122 let mut state = FnState::new("<eval>", FunctionKind::Normal);
1123 // A module body is *not* a script: it has no completion value, so no hidden
1124 // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1125 // is having no `arguments` of its own and no receiver — see `is_module`.
1126 state.is_script = !self.module;
1127 state.is_module = self.module;
1128 if self.module {
1129 state.module = Some(ModuleMeta::default());
1130 }
1131 state.strict = program.strict || self.module;
1132 state.line = program.span.start.line;
1133 state.column = program.span.start.column;
1134 // Locals are numbered in declaration order; `<ret>` is always slot 0.
1135 //
1136 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1137 // slot that only appears in one of the two arrays shifts every later
1138 // binding's block and silently loses the temporal-dead-zone marking for
1139 // the script's own blocks. A function frame has no `<ret>`, which is why
1140 // the misalignment only showed up at the top level.
1141 if !self.module {
1142 state.vars.push(VarDef::var("<ret>"));
1143 state.var_block.push(FUNCTION_SCOPE);
1144 }
1145 self.stack.push(state);
1146 // The body is its own scope, keyed by the position of the program.
1147 // The script body needs a key no statement can produce. Statement keys are
1148 // source offsets, and the program's own start offset is `0` — which is also
1149 // the offset of the first statement, so a top-level `{ let x }` or
1150 // `for (let i …)` used to share the body's block and lose its scope.
1151 let body_key = SCRIPT_BODY;
1152 self.push_block(body_key, NO_PARENT);
1153 self.state().body_block = body_key;
1154 // A module body opens with a re-entry guard. The host evaluates a module exactly
1155 // once, so the guard never fires in practice — but the reference emits it, and a
1156 // module function called a second time (through `eval` of its own source, say)
1157 // must not run its body again.
1158 let module_guard = self.module.then(|| self.new_label());
1159 if let Some(body) = module_guard {
1160 // The guard wraps the *hoisting* too: a second evaluation of the same module
1161 // body must not even re-create its function declarations.
1162 self.emit(Opcode::PushThis, &[]);
1163 self.emit_jump(Opcode::IfFalse, body, &[]);
1164 }
1165 self.hoist(&program.body, body_key)?;
1166 // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1167 // come before the guard's `return_undef`: the reference's jump target sits past
1168 // both, and a second evaluation therefore re-creates nothing.
1169 self.emit_scope_enter(body_key);
1170 if let Some(body) = module_guard {
1171 self.emit(Opcode::ReturnUndef, &[]);
1172 self.place_label(body);
1173 }
1174 // Through `stmts` rather than the loop, so a `using` region at the top level of an
1175 // eval'd body or a module gets its disposal epilogue like any other block.
1176 self.stmts(&program.body)?;
1177 if self.module {
1178 // A module has no completion value; its body simply ends.
1179 self.emit(Opcode::Undefined, &[]);
1180 self.emit(Opcode::ReturnAsync, &[]);
1181 // Top-level `await` makes the body an async function, so the host runs it as
1182 // a coroutine and waits. Without this the `await` opcode would suspend in a
1183 // body that nothing knows how to resume — which is what "a generator body ran
1184 // as an ordinary call" was reporting.
1185 if self.cur().has_await {
1186 self.state().kind = FunctionKind::Async;
1187 }
1188 } else if self.async_body {
1189 // An async body reports its completion value the same way, but through an
1190 // object: the function answers a promise, and resolving that promise *with*
1191 // the completion value would adopt a promise completion instead of reporting
1192 // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1193 // resolve to `{value: <promise>}` rather than to `7`.
1194 //
1195 // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1196 // value in an object so that promises can be safely returned").
1197 self.emit(Opcode::Object, &[]);
1198 self.emit(Opcode::Dup, &[]);
1199 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1200 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1201 self.emit(Opcode::Return, &[]);
1202 self.state().kind = FunctionKind::Async;
1203 } else {
1204 // The program's value is whatever the last expression statement stored in
1205 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1206 // case into a single `set_loc0`.
1207 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1208 self.emit(Opcode::Return, &[]);
1209 }
1210 Ok(self.finish_current())
1211 }
1212
1213 // -- emitting ----------------------------------------------------------
1214
1215 fn state(&mut self) -> &mut FnState {
1216 self.stack.last_mut().expect("a function is being compiled")
1217 }
1218
1219 fn cur(&self) -> &FnState {
1220 self.stack.last().expect("a function is being compiled")
1221 }
1222
1223 fn emit(&mut self, op: Opcode, operands: &[Op]) {
1224 self.state().label_since_insn = false;
1225 let pos = self.cur().cur_pos;
1226 self.state().insns.push(Insn::Fixed {
1227 op,
1228 operands: operands.to_vec(),
1229 });
1230 self.state().insn_pos.push(pos);
1231 }
1232
1233 /// Reset the script's hidden return value to `undefined`.
1234 ///
1235 /// Called at the start of every statement that does not itself produce the
1236 /// program's value, which is how the reference keeps `if`/loop results from
1237 /// leaking into an eval result.
1238 fn reset_value(&mut self) {
1239 if !self.cur().is_script {
1240 return;
1241 }
1242 self.emit(Opcode::Undefined, &[]);
1243 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1244 self.state().leaves_value = false;
1245 }
1246
1247 /// Whether `name` is a local or argument slot rather than a global.
1248 fn is_slot(&self, name: &str) -> bool {
1249 self.cur().vars.iter().any(|v| v.name == name)
1250 || self.cur().args.iter().any(|a| a.name == name)
1251 }
1252
1253 /// `with (object) body`
1254 ///
1255 /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1256 /// what makes the object reachable from a closure created inside the block, and it
1257 /// is also what lets an `eval` find it: the runtime collects the active `With`
1258 /// locals of every frame and resolves names against them before the realm.
1259 ///
1260 /// Inside the block every name reference is spelled as "look in the with objects
1261 /// first", innermost outwards, and falls through to the ordinary access. The test is
1262 /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1263 /// Record asks.
1264 fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1265 // `with (e) s` completes with `UpdateEmpty(s, undefined)` — an *empty* body still
1266 // produces `undefined`, it does not inherit the previous statement's value. So
1267 // `eval("1; with({}){}")` is `undefined` while `eval("1; with({}){2;}")` is `2`.
1268 // Without this the sticky `<ret>` local leaked the `1` through, the same way it
1269 // would for an `if` or a loop.
1270 self.reset_value();
1271 let name = self.next_with_name();
1272 // The object expression is evaluated *outside* the scope it introduces, so no
1273 // wrapper may be emitted for the names it mentions.
1274 let saved = std::mem::take(&mut self.state().with_names);
1275 self.expr(object)?;
1276 self.state().with_names = saved;
1277 self.emit(Opcode::ToObject, &[]);
1278 self.declare_hidden_local(&name, VarKind::With);
1279 // Pushed before the store so the store itself is not guarded by an *outer*
1280 // `with` — the object being stored is the new one, not something to look up.
1281 self.state().with_names.push(name.clone());
1282 self.emit_var(VarAction::Put, &name);
1283 let result = self.stmt(body);
1284 self.state().with_names.pop();
1285 result
1286 }
1287
1288 /// A hidden-local name for one `with` block, distinct from every enclosing one.
1289 fn next_with_name(&self) -> String {
1290 let depth = self.cur().with_names.len();
1291 if depth == 0 {
1292 "<with>".to_string()
1293 } else {
1294 format!("<with{depth}>")
1295 }
1296 }
1297
1298 /// Declare a hidden local that must stay a *local* even in a script.
1299 ///
1300 /// A script's `var` is a property of the global object, but the `with` object is not
1301 /// part of the source program's name space at all — it only exists for the compiler
1302 /// and the runtime — so it goes straight into the frame's slot list.
1303 fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1304 let state = self.state();
1305 if state.vars.iter().any(|v| v.name == name) {
1306 return;
1307 }
1308 state.var_block.push(FUNCTION_SCOPE);
1309 state.vars.push(VarDef {
1310 kind,
1311 ..VarDef::var(name)
1312 });
1313 }
1314
1315 /// Emit a name access, guarded by every active `with` object.
1316 ///
1317 /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1318 /// the read itself; the outer guards and the plain access are what the `if_false`
1319 /// jumps to, so the innermost object wins.
1320 fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1321 let names = self.visible_with_names(name);
1322 let done = self.new_label();
1323 let mut starts = Vec::new();
1324 // Innermost object first: the last `with` opened is the one that shadows the
1325 // others, so its guard has to be the first chance to satisfy the name.
1326 for with_name in names.iter().rev() {
1327 let next = self.new_label();
1328 // `with_has_var` takes the object and carries the name as an atom. It is not
1329 // `in`: an Object Environment Record also consults `Symbol.unscopables`, so
1330 // `globalThis[Symbol.unscopables] = {v: true}` leaves `v` to the outer scope.
1331 self.emit_var(VarAction::Get, with_name);
1332 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1333 self.emit_jump(Opcode::IfFalse, next, &[]);
1334 starts.push(next);
1335 // The operation is `with_get_var`/`with_put_var`, not a plain property access:
1336 // `GetBindingValue`/`SetMutableBinding` ask `HasProperty` **again** before
1337 // getting or setting. That second question is observable — a proxy's `has`
1338 // trap runs one more time (`get-binding-value-call-with-proxy-env` logs
1339 // `has, get unscopables, has, get`) and an `unscopables` getter that deletes
1340 // the property leaves a binding that has gone, which strict code must report
1341 // as a `ReferenceError` rather than write to.
1342 match action {
1343 // A store already has its value on the stack, and `with_put_var` takes the
1344 // pair in `put_field`'s order: object first, then the value.
1345 VarAction::Put | VarAction::PutInit => {
1346 self.emit_var(VarAction::Get, with_name);
1347 self.emit(Opcode::Swap, &[]);
1348 self.emit(Opcode::WithPutVar, &[Op::Atom(Atom::from_text(name))]);
1349 }
1350 _ => {
1351 self.emit_var(VarAction::Get, with_name);
1352 self.emit(Opcode::WithGetVar, &[Op::Atom(Atom::from_text(name))]);
1353 }
1354 }
1355 self.emit_jump(Opcode::Goto, done, &[]);
1356 self.place_label(next);
1357 }
1358 self.emit_var(action, name);
1359 self.place_label(done);
1360 }
1361
1362 /// The `with` blocks that can shadow `name`, innermost last.
1363 ///
1364 /// A parameter or a local of this function is *inside* every `with` this function
1365 /// opened, so those shadow it; a `with` that was already open when this function was
1366 /// created is outside the function's own environment, so the local wins and that
1367 /// block is skipped. See [`FnState::inherited_with_names`].
1368 fn visible_with_names(&self, name: &str) -> Vec<String> {
1369 let state = self.cur();
1370 // The hidden `<with…>` locals are how the guard reaches its own objects, so they
1371 // must never be guarded themselves — not by their own block (which would recurse)
1372 // and not by an enclosing one (which would ask a `with` object whether it has a
1373 // property called `<with>`, always answer no, and waste the chain). Source can
1374 // never spell these names, so exempting all of them changes nothing else.
1375 if state.with_names.iter().any(|hidden| hidden == name) {
1376 return Vec::new();
1377 }
1378 let start = if self.is_slot(name) {
1379 state.inherited_with_names
1380 } else {
1381 0
1382 };
1383 state.with_names[start..]
1384 .iter()
1385 .filter(|hidden| hidden.as_str() != name)
1386 .cloned()
1387 .collect()
1388 }
1389
1390 /// Compile `x` as a **reference** to the with object's property, resolving the object
1391 /// once for the whole read-modify-write.
1392 ///
1393 /// `x += 1`, `x++` and `x ||= v` read and then write the same name. Two independent
1394 /// guards get that wrong the moment the read changes the answer: with
1395 /// `{ get x(){ delete this.x; return 2 } }`, `with (o) { x++ }` reads through the
1396 /// getter — which removes the property — and then the write's own guard no longer
1397 /// finds it, so the store landed on the *global* `x` and `o.x` stayed `undefined`. The
1398 /// reference resolves the base once (`with_make_ref`) and reuses it for both halves.
1399 ///
1400 /// The same shape comes out of compiling the name as a **member** of the with object:
1401 /// `get_field2`/`put_field` already evaluate their receiver once, and the hidden
1402 /// `<with>` local holds exactly the object the guard just tested. So each candidate
1403 /// object gets `if the name is bound here, compile as `this.name`; otherwise fall
1404 /// through to the next object`, and the last fallback is the ordinary name.
1405 fn with_reference(
1406 &mut self,
1407 name: &str,
1408 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1409 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1410 ) -> Result<(), SyntaxError> {
1411 let targets = self.visible_with_names(name);
1412 if targets.is_empty() {
1413 return plain(self);
1414 }
1415 let done = self.new_label();
1416 let result = self.with_reference_inner(name, &targets, guarded, plain, done);
1417 self.place_label(done);
1418 result
1419 }
1420
1421 fn with_reference_inner(
1422 &mut self,
1423 name: &str,
1424 targets: &[String],
1425 guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1426 plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1427 done: Label,
1428 ) -> Result<(), SyntaxError> {
1429 let Some((innermost, outer)) = targets.split_last() else {
1430 return plain(self);
1431 };
1432 let next = self.new_label();
1433 self.emit_var(VarAction::Get, innermost);
1434 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1435 self.emit_jump(Opcode::IfFalse, next, &[]);
1436 guarded(self, innermost)?;
1437 self.emit_jump(Opcode::Goto, done, &[]);
1438 self.place_label(next);
1439 self.with_reference_inner(name, outer, guarded, plain, done)
1440 }
1441
1442 /// `delete name`, honouring any enclosing `with`.
1443 ///
1444 /// Inside a `with` the name may be a property of the with object, and then `delete`
1445 /// removes *that* property instead of touching the outer binding —
1446 /// `with (o) { delete p }` answers `true` and leaves `o` without `p` even when a
1447 /// global `p` exists. Left to the resolver it deleted the global instead, so the
1448 /// `statements/with/S12.10_A1.*` family then saw a `ReferenceError` on every later
1449 /// `p`.
1450 ///
1451 /// Emitted as a sequence here rather than during resolution because a resolution slot
1452 /// holds one instruction, and this is a loop over the with objects plus a fallback.
1453 fn delete_ident(&mut self, name: &str) {
1454 let names = self.cur().with_names.clone();
1455 let done = self.new_label();
1456 let mut starts = Vec::new();
1457 if !names.is_empty() {
1458 self.state().emitting_with_guard = true;
1459 // Innermost object first, like the read/write guard: the last `with` opened is
1460 // the one that shadows the others.
1461 for with_name in names.iter().rev() {
1462 let next = self.new_label();
1463 self.emit_var(VarAction::Get, with_name);
1464 self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1465 self.emit_jump(Opcode::IfFalse, next, &[]);
1466 // `delete` takes the receiver then the key.
1467 self.emit_var(VarAction::Get, with_name);
1468 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1469 self.emit(Opcode::Delete, &[]);
1470 self.emit_jump(Opcode::Goto, done, &[]);
1471 self.place_label(next);
1472 starts.push(next);
1473 }
1474 self.state().emitting_with_guard = false;
1475 }
1476 // The fallback: not a property of any with object, so the ordinary rule applies.
1477 let pos = self.cur().cur_pos;
1478 self.state().insns.push(Insn::DeleteVar {
1479 name: name.to_string(),
1480 });
1481 self.state().insn_pos.push(pos);
1482 if !names.is_empty() {
1483 self.place_label(done);
1484 }
1485 }
1486
1487 fn emit_var(&mut self, action: VarAction, name: &str) {
1488 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1489 // stores and keeps the value in one instruction. The reference does this
1490 // in a post-pass; folding it at emit time keeps instruction indices
1491 // stable, which matters because labels are recorded as indices.
1492 //
1493 // Only slots have a `set_` form: a global is stored with `put_var` and
1494 // read with `get_var`, and the reference does not fold those.
1495 //
1496 // A label between the two cancels the fold. `set_x v` leaves the value on
1497 // the stack, which is only equivalent when the read immediately follows the
1498 // store; when a jump target sits in between, the store must *consume* the
1499 // value and the read must fetch it afresh. A loop head is exactly that
1500 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1501 // condition re-reads it — and folding across the label would make the
1502 // condition compare whatever the previous iteration left on the stack.
1503 if action == VarAction::Get {
1504 let is_slot = self.is_slot(name);
1505 let at_label = std::mem::take(&mut self.state().label_since_insn);
1506 //
1507 // `arguments` is excluded because the reference treats it as a special
1508 // binding: it is initialised once and read many times, and folding its
1509 // initialisation into a `set_` would leave the object on the stack where
1510 // the reference leaves nothing.
1511 if is_slot
1512 && name != "arguments"
1513 && !at_label
1514 && let Some(Insn::Var {
1515 action: previous,
1516 name: previous_name,
1517 ..
1518 }) = self.state().insns.last_mut()
1519 && *previous == VarAction::Put
1520 && previous_name == name
1521 {
1522 *previous = VarAction::Set;
1523 return;
1524 }
1525 }
1526 // Inside a `with`, every name lookup consults the with objects first. Two names
1527 // are exempt:
1528 //
1529 // * the hidden `<with…>` locals themselves, or the guard would recurse;
1530 // * a name this function **declares** — a parameter, a `var`, or a `let` of the
1531 // current body. `with` sits *outside* the function's own environment, so a
1532 // function declared inside a `with` still resolves its own bindings first:
1533 // `with (o) { function f(){ var value = "x" } }` writes `f`'s local `value`, not
1534 // `o.value`. Guarding it anyway wrote through to the with object whenever it
1535 // happened to have the name, which is why
1536 // `statements/with/S12.10_A1.7` saw `myObj.value` change. The runtime's
1537 // `eval_binding_value` already models the same order.
1538 let guarded = !self.visible_with_names(name).is_empty()
1539 && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1540 && !self.state().emitting_with_guard;
1541 if guarded {
1542 self.state().emitting_with_guard = true;
1543 self.emit_with_guarded(action, name);
1544 self.state().emitting_with_guard = false;
1545 return;
1546 }
1547 let block = self.cur().current_block;
1548 self.state().label_since_insn = false;
1549 let pos = self.cur().cur_pos;
1550 let in_params = self.cur().in_params;
1551 self.state().insns.push(Insn::Var {
1552 action,
1553 name: name.to_string(),
1554 block,
1555 in_params,
1556 });
1557 self.state().insn_pos.push(pos);
1558 }
1559
1560 fn new_label(&mut self) -> Label {
1561 let state = self.state();
1562 state.labels.push(None);
1563 Label(state.labels.len() as u32 - 1)
1564 }
1565
1566 fn place_label(&mut self, label: Label) {
1567 let index = self.cur().insns.len();
1568 self.state().label_since_insn = true;
1569 self.state().labels[label.0 as usize] = Some(index);
1570 }
1571
1572 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1573 let mut operands = vec![Op::Label(label)];
1574 operands.extend_from_slice(extra);
1575 self.emit(op, &operands);
1576 }
1577
1578 // -- scopes ------------------------------------------------------------
1579
1580 /// Start a new lexical scope inside `parent`.
1581 fn push_block(&mut self, key: u64, parent: u64) {
1582 let state = self.state();
1583 if !state.blocks.iter().any(|b| b.key == key) {
1584 state.blocks.push(Block { key, parent });
1585 }
1586 state.current_block = key;
1587 }
1588
1589 /// Emit the code that runs when a lexical scope is entered.
1590 ///
1591 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1592 /// so entering its block marks it uninitialised. Hoisted function
1593 /// declarations are created here instead, which is why a call before the
1594 /// declaration still works.
1595 ///
1596 /// The order is not obvious: bindings are emitted in *reverse* declaration
1597 /// order, because the reference walks its scope chain, which is built by
1598 /// prepending.
1599 fn emit_scope_enter(&mut self, block: u64) {
1600 // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1601 // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1602 // so entering an outer scope threw away every nested block's function
1603 // declarations: `function h(){ { function k(){} } return k; }` answered
1604 // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1605 // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1606 // in a block is also a `var` of the enclosing function), and it is what makes the
1607 // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1608 let mut hoisted = std::mem::take(&mut self.state().hoisted);
1609 let mut rest = Vec::with_capacity(hoisted.len());
1610 let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1611 for (owner, target, pool_index) in hoisted.drain(..) {
1612 if owner == block {
1613 mine.push((target, pool_index));
1614 } else {
1615 rest.push((owner, target, pool_index));
1616 }
1617 }
1618 self.state().hoisted = rest;
1619 mine.sort_by_key(|(target, _)| match target {
1620 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1621 HoistTarget::Global(_) => u32::MAX,
1622 });
1623 for (target, pool_index) in mine {
1624 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1625 match target {
1626 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1627 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1628 HoistTarget::Global(name) => {
1629 // A global binding lives in a reference cell, so the store
1630 // goes through `put_var_ref` while reads use `get_var`.
1631 let block = self.cur().current_block;
1632 let pos = self.cur().cur_pos;
1633 let in_params = self.cur().in_params;
1634 self.state().insns.push(Insn::Var {
1635 action: VarAction::PutRef,
1636 name,
1637 block,
1638 in_params,
1639 });
1640 self.state().insn_pos.push(pos);
1641 }
1642 }
1643 }
1644 for index in self.block_vars_reversed(block) {
1645 self.emit(
1646 Opcode::SetLocUninitialized,
1647 &[Op::Slot(Slot::Loc(index as u32))],
1648 );
1649 }
1650 }
1651
1652 /// Emit the code that runs when a lexical scope is exited.
1653 ///
1654 /// A captured binding has to be closed: detaching its reference cell freezes
1655 /// the value the binding had when the block ended, which is what a closure
1656 /// created inside the block must keep seeing.
1657 fn emit_scope_leave(&mut self, block: u64) {
1658 for index in self.block_vars_reversed(block) {
1659 if self.cur().vars[index].is_captured {
1660 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1661 }
1662 }
1663 }
1664
1665 /// Locals declared in `block`, in reverse declaration order.
1666 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1667 let state = self.cur();
1668 let mut out: Vec<usize> = (0..state.vars.len())
1669 .filter(|index| {
1670 state.var_block.get(*index).copied() == Some(block)
1671 && state.vars[*index].is_lexical
1672 // A derived constructor's `this` is lexical but is not initialised by
1673 // entering the scope: `check_ctor` proves it, so its dead-zone marker
1674 // was emitted with the constructor's own prologue.
1675 && state.vars[*index].name != "this"
1676 })
1677 .collect();
1678 out.reverse();
1679 out
1680 }
1681
1682 /// Declare a local, even at the top level of a script.
1683 ///
1684 /// A `catch` parameter is always a local: the reference puts it in the
1685 /// function's own variable list (`1: catch e`), never in the global object,
1686 /// because it only exists while the handler runs.
1687 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1688 let state = self.state();
1689 let index = state.vars.len() as u32;
1690 // A `catch` parameter belongs to a scope even though it is not lexical: the
1691 // runtime instantiates it per handler entry, but it never sits in the
1692 // temporal dead zone.
1693 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1694 state.current_block
1695 } else {
1696 0
1697 };
1698 state.var_block.push(block);
1699 state.vars.push(def);
1700 index
1701 }
1702
1703 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1704 if self.cur().is_module
1705 && self.cur().current_block == self.cur().body_block
1706 && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1707 {
1708 // Only the body's own block: a `let` inside a module-level `{}` is still an
1709 // ordinary local of that block, not a module variable.
1710 //
1711 // A `using` binding is excluded on purpose, and the reference excludes it in
1712 // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1713 // "'using' variables are currently not exported in modules"): a module-level
1714 // `using` is an ordinary *local* of the module body function, not a module
1715 // cell. Two things follow, and both are what the reference does — `export {a}`
1716 // of a `using` binding is "exported variable 'a' does not exist", and
1717 // disposal works, because the disposal epilogue addresses locals by slot.
1718 //
1719 // The hidden dispose-method variable is excluded for a stronger reason: it is
1720 // *always* a local (`add_scope_var` in the reference), and it must sit
1721 // immediately after its value so `using_dispose` can find it at `slot + 1`.
1722 return self.declare_module(name, &def);
1723 }
1724 if self.cur().declares_globally(&def) {
1725 self.declare_global(name, &def);
1726 return 0;
1727 }
1728 let state = self.state();
1729 let index = state.vars.len() as u32;
1730 let block = if def.is_lexical {
1731 state.current_block
1732 } else {
1733 0
1734 };
1735 state.var_block.push(block);
1736 state.vars.push(def);
1737 index
1738 }
1739
1740 /// Declare a `using` binding and its cached dispose method, returning both slots.
1741 ///
1742 /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1743 /// `(value, value + 1)` — the reference does the same and documents the constraint.
1744 fn declare_using(&mut self, name: &str) -> (u32, u32) {
1745 let mut def = VarDef::lexical(name);
1746 def.kind = VarKind::Using;
1747 // A `using` binding is immutable, exactly like a `const`: assigning to one is a
1748 // `TypeError` at run time, which is what `using-invalid-assignment-*-for` assert.
1749 // `VarDef::lexical` leaves `is_const` false, so the store would have landed.
1750 def.is_const = true;
1751 let value = self.declare(name, def);
1752 let mut method = VarDef::lexical(using_method_name(name));
1753 method.kind = VarKind::UsingMethod;
1754 let method_slot = self.declare(&using_method_name(name), method);
1755 (value, method_slot)
1756 }
1757
1758 /// The slot a `using` binding's dispose method lives in.
1759 fn using_method_slot(&self, name: &str) -> Option<u32> {
1760 let hidden = using_method_name(name);
1761 self.cur()
1762 .vars
1763 .iter()
1764 .position(|var| var.name == hidden)
1765 .map(|index| index as u32)
1766 }
1767
1768 // -- statements --------------------------------------------------------
1769
1770 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1771 self.stmt_labelled(stmt, &[])
1772 }
1773
1774 /// Compile a statement that a chain of labels names.
1775 ///
1776 /// Only a loop consumes `labels`; every other statement ignores them (the
1777 /// parser has already rejected a label on a statement that cannot use it).
1778 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1779 // Only a *top-level* expression statement supplies the program's value.
1780 let saved = self.cur().leaves_value;
1781 self.state().leaves_value =
1782 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1783 self.state().stmt_depth += 1;
1784 let result = self.stmt_inner(stmt, labels);
1785 self.state().stmt_depth -= 1;
1786 // A nested statement never contributes the program's value, so the flag
1787 // the wrapper set above is what survives.
1788 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1789 self.state().leaves_value = produced;
1790 let _ = saved;
1791 result
1792 }
1793
1794 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1795 match &stmt.kind {
1796 StmtKind::Empty | StmtKind::Debugger => {}
1797 StmtKind::Expr(expr) => {
1798 // The statement's first token is a position the reference records: an
1799 // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1800 // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1801 // is why an error from a construct with no position of its own (`[...it]`
1802 // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1803 let saved = self.cur().cur_pos;
1804 self.state().cur_pos = Some(expr.span.start);
1805 // An expression statement's value is thrown away — except in a
1806 // script, where it becomes the program's result. `assign` reads this
1807 // and clears it, so a nested assignment still produces a value.
1808 self.state().discard_value = !self.cur().is_script;
1809 let result = self.expr(expr);
1810 self.state().discard_value = false;
1811 result?;
1812 if std::mem::take(&mut self.state().no_value) {
1813 // A store whose value was discarded left nothing to drop.
1814 } else if self.cur().is_script {
1815 // The program's value lands in the hidden `<ret>` local.
1816 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1817 } else {
1818 self.emit(Opcode::Drop, &[]);
1819 }
1820 // Restored last: the trailing `drop` is part of the statement, and in the
1821 // reference it simply inherits whatever the expression last recorded.
1822 self.state().cur_pos = saved;
1823 }
1824 StmtKind::Block(body) => {
1825 // The block's declarations were hoisted with its enclosing
1826 // statement list, so there is nothing left to declare here.
1827 let key = stmt.span.start.offset as u64;
1828 let parent = self.cur().current_block;
1829 self.push_block(key, parent);
1830 self.emit_scope_enter(key);
1831 // A block is where a `using` region lives, so its statements have to go
1832 // through `stmts`: that is what emits the disposal epilogue.
1833 self.stmts(body)?;
1834 self.emit_scope_leave(key);
1835 self.state().current_block = parent;
1836 }
1837 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1838 // A function declaration was already instantiated when its scope was
1839 // entered, so the statement itself emits nothing.
1840 StmtKind::FuncDecl(_) => {}
1841 StmtKind::If { test, cons, alt } => {
1842 self.reset_value();
1843 let else_label = self.new_label();
1844 let end_label = self.new_label();
1845 self.expr(test)?;
1846 self.emit_jump(Opcode::IfFalse, else_label, &[]);
1847 self.stmt(cons)?;
1848 if alt.is_some() {
1849 self.emit_jump(Opcode::Goto, end_label, &[]);
1850 }
1851 self.place_label(else_label);
1852 if let Some(alt) = alt {
1853 self.stmt(alt)?;
1854 self.place_label(end_label);
1855 }
1856 }
1857 StmtKind::While { test, body } => {
1858 self.reset_value();
1859 let top = self.new_label();
1860 let end = self.new_label();
1861 self.place_label(top);
1862 self.expr(test)?;
1863 // The condition's false branch and `break` share one target,
1864 // which is why a `while` loop needs only one end label.
1865 self.emit_jump(Opcode::IfFalse, end, &[]);
1866 self.loop_body(body, labels, top, end)?;
1867 self.emit_jump(Opcode::Goto, top, &[]);
1868 self.place_label(end);
1869 }
1870 StmtKind::DoWhile { body, test } => {
1871 self.reset_value();
1872 let top = self.new_label();
1873 let cont = self.new_label();
1874 let end = self.new_label();
1875 self.place_label(top);
1876 // `continue` in a `do…while` runs the test, so it lands on `cont`
1877 // rather than on the loop head.
1878 self.loop_body(body, labels, cont, end)?;
1879 self.place_label(cont);
1880 self.expr(test)?;
1881 self.emit_jump(Opcode::IfTrue, top, &[]);
1882 self.place_label(end);
1883 }
1884 StmtKind::For {
1885 init,
1886 test,
1887 update,
1888 body,
1889 } => {
1890 self.reset_value();
1891 let for_key = stmt.span.start.offset as u64;
1892 let for_parent = self.cur().current_block;
1893 self.push_block(for_key, for_parent);
1894 self.emit_scope_enter(for_key);
1895 let mut using_head = None;
1896 if let Some(init) = init {
1897 match init {
1898 ForInit::VarDecl(decl) if decl.kind.is_using() => {
1899 // A `using` resource declared in the head lives until the whole
1900 // statement ends, not one iteration, so the disposal region has
1901 // to wrap the loop — and there may be several of them, each
1902 // needing its own region so that a later initialiser that
1903 // throws still disposes the earlier resources
1904 // (`initializer-disposed-if-subsequent-initializer-throws-in-forstatement-head`).
1905 using_head = Some(decl);
1906 }
1907 ForInit::VarDecl(decl) => {
1908 self.var_decl(decl)?;
1909 }
1910 ForInit::Expr(expr) => {
1911 // The head's value is discarded. Saying so lets an
1912 // assignment store with `put` instead of `dup`+`put`, which
1913 // is what the reference emits — and the difference matters:
1914 // a `dup`/`drop` pair around the store gives the peephole a
1915 // chance to fold the store into the *condition's* read.
1916 self.state().discard_value = true;
1917 let result = self.expr(expr);
1918 self.state().discard_value = false;
1919 result?;
1920 if !std::mem::take(&mut self.state().no_value) {
1921 self.emit(Opcode::Drop, &[]);
1922 }
1923 }
1924 }
1925 }
1926 // A `using` head's resource is disposed when the statement ends, on every
1927 // way out: `break`, `return`, an exception, and reaching the end.
1928 let flow = match using_head {
1929 Some(decl) => self.for_using_head(
1930 decl, 0, init, test, update, body, labels, for_key, for_parent,
1931 ),
1932 None => {
1933 self.for_loop_tail(init, test, update, body, labels, for_key, for_parent)
1934 }
1935 };
1936 flow?;
1937 }
1938 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1939 StmtKind::Throw(expr) => {
1940 self.expr(expr)?;
1941 self.emit(Opcode::Throw, &[]);
1942 }
1943 StmtKind::Break(_) | StmtKind::Continue(_) => {
1944 // Labels and loops are wired up in a later milestone; a bare
1945 // break/continue jumps to the innermost enclosing target, which
1946 // the loop helpers register.
1947 self.control_transfer(stmt)?;
1948 }
1949 StmtKind::Labeled { label, body } => {
1950 self.labeled(label, body, stmt)?;
1951 }
1952 StmtKind::Switch {
1953 discriminant,
1954 cases,
1955 } => {
1956 self.switch(discriminant, cases, stmt)?;
1957 }
1958 StmtKind::Try {
1959 block,
1960 handler,
1961 finalizer,
1962 } => {
1963 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1964 }
1965 StmtKind::ForIn { left, right, body } => {
1966 self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1967 }
1968 StmtKind::ForOf {
1969 left,
1970 right,
1971 body,
1972 is_await,
1973 } => {
1974 let kind = if *is_await {
1975 ForLoopKind::AwaitOf
1976 } else {
1977 ForLoopKind::Of
1978 };
1979 self.for_in_of(stmt, left, right, body, kind, labels)?;
1980 }
1981 StmtKind::With { object, body } => self.with_stmt(object, body)?,
1982 StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1983 // `import` emits nothing: hoisting already bound its names, and the host
1984 // fills their cells before the body runs.
1985 StmtKind::Import(_) => {}
1986 StmtKind::Export(decl) => self.export_stmt(decl)?,
1987 }
1988 Ok(())
1989 }
1990
1991 /// Compile `return`, running every enclosing finalizer on the way out.
1992 ///
1993 /// `nip_catch` is what makes this possible: it discards everything on the stack
1994 /// down to and including the `catch` offset while keeping the return value on
1995 /// top, so the frame the finalizer sees has the same shape as on the normal
1996 /// path.
1997 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1998 let mut has_value = value.is_some();
1999 if let Some(expr) = value {
2000 // `return f(x)` is a tail call *only* when nothing has to happen to the
2001 // value afterwards. A `finally` or an open iterator in scope forces the
2002 // normal path, because the cleanup has to run after the call returns —
2003 // which is exactly what a tail call refuses to do.
2004 //
2005 // A **generator or async function** never tail-calls either: its `return` is
2006 // not a return to the caller but `return_async`, which reads the value off the
2007 // stack and finishes the coroutine. A tail call replaces the frame and hands
2008 // the callee's result straight to whoever resumed us, so the value vanished and
2009 // `it.next(42)` answered `{done: true, value: undefined}` for
2010 // `function* g(){ return f(yield) }`. The reference emits `call1` plus
2011 // `return_async` there and has no tail form for a suspending body at all.
2012 let plain = !self.cur().is_suspending()
2013 // A derived constructor's return is not just the value: a non-object answer
2014 // becomes `this`, so the frame has to survive to run that.
2015 && self.cur().ctor_kind != CtorKind::Derived
2016 && self
2017 .cur()
2018 .jump_targets
2019 .iter()
2020 .all(|target| target.finally_label.is_none() && !target.has_iterator);
2021 if plain && self.expr_if_tail_call(expr)? {
2022 // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
2023 // happen here as well.
2024 self.note_direct_eval(expr);
2025 return Ok(());
2026 }
2027 self.expr(expr)?;
2028 }
2029 // `return v` in an *async generator* awaits `v` before anything else happens —
2030 // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
2031 // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
2032 // exactly that reason ("the await must be done before handling the finally in case
2033 // it raises an exception").
2034 if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
2035 self.emit(Opcode::Await, &[]);
2036 self.state().has_await = true;
2037 }
2038 has_value = self.emit_unwind_for_return(has_value);
2039 // A generator or async function does not return to its caller: it either
2040 // finishes, and the value becomes `{value, done: true}`, or it suspends.
2041 // `return_async` is the "finished" half, and it reads the value off the stack
2042 // rather than carrying it, which is what the resume machinery expects.
2043 if self.cur().is_suspending() {
2044 if !has_value {
2045 self.emit(Opcode::Undefined, &[]);
2046 }
2047 self.emit(Opcode::ReturnAsync, &[]);
2048 return Ok(());
2049 }
2050 // A derived constructor's result is `this` whenever the body does not answer an
2051 // object, and `this` is a local in the dead zone until `super()` returns — which is
2052 // why reading it here is also what turns `constructor(){ return; }` into the
2053 // ReferenceError the reference reports. The interpreter could not do this on its
2054 // own: by the time it sees `undefined` come back, the frame that held `this` is
2055 // gone, and `construct`'s own idea of `this` is the placeholder it made before the
2056 // body ran (`derived-class-return-override-with-{undefined,empty}`).
2057 if self.cur().ctor_kind == CtorKind::Derived {
2058 if !has_value {
2059 self.emit_var(VarAction::Get, "this");
2060 self.emit(Opcode::Return, &[]);
2061 return Ok(());
2062 }
2063 // `return <expr>` is only *sometimes* `this`: `undefined` is, any other
2064 // primitive is a `TypeError` (raised by `construct`), and an object replaces
2065 // `this` outright. Which one it is can only be known at run time.
2066 let keep = self.new_label();
2067 self.emit(Opcode::Dup, &[]);
2068 self.emit(Opcode::IsUndefined, &[]);
2069 self.emit_jump(Opcode::IfFalse, keep, &[]);
2070 self.emit(Opcode::Drop, &[]);
2071 self.emit_var(VarAction::Get, "this");
2072 self.place_label(keep);
2073 self.emit(Opcode::Return, &[]);
2074 return Ok(());
2075 }
2076 if has_value {
2077 self.emit(Opcode::Return, &[]);
2078 } else {
2079 self.emit(Opcode::ReturnUndef, &[]);
2080 }
2081 Ok(())
2082 }
2083
2084 /// Close an iterator: the reference's `emit_iterator_close`.
2085 ///
2086 /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
2087 /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
2088 /// sequence, and three details in it are load-bearing:
2089 ///
2090 /// * the iterator object is compared against `undefined` first, because a loop that
2091 /// ran to completion clears that slot rather than closing an exhausted iterator;
2092 /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
2093 /// * `preserve_completion` keeps whatever was underneath (the return value of the
2094 /// function being left), which is why one branch ends on `nip` and the other on `drop`.
2095 fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
2096 if !is_async {
2097 if preserve_completion {
2098 self.emit(Opcode::Rot3r, &[]);
2099 self.emit(Opcode::Undefined, &[]);
2100 }
2101 self.emit(Opcode::IteratorClose, &[]);
2102 return;
2103 }
2104 if preserve_completion {
2105 // `iter next completion -> completion iter`
2106 self.emit(Opcode::Nip, &[]);
2107 self.emit(Opcode::Swap, &[]);
2108 } else {
2109 // `iter next catch_offset -> iter`
2110 self.emit(Opcode::Drop, &[]);
2111 self.emit(Opcode::Drop, &[]);
2112 }
2113 let done = self.new_label();
2114 let no_return = self.new_label();
2115 self.emit(Opcode::Dup, &[]);
2116 self.emit(Opcode::IsUndefined, &[]);
2117 self.emit_jump(Opcode::IfTrue, done, &[]);
2118 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
2119 self.emit(Opcode::Dup, &[]);
2120 self.emit(Opcode::IsUndefinedOrNull, &[]);
2121 self.emit_jump(Opcode::IfTrue, no_return, &[]);
2122 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
2123 self.emit(Opcode::Await, &[]);
2124 self.state().has_await = true;
2125 self.emit_jump(Opcode::Goto, done, &[]);
2126 self.place_label(no_return);
2127 self.emit(Opcode::Drop, &[]);
2128 self.place_label(done);
2129 self.emit(Opcode::Drop, &[]);
2130 }
2131
2132 /// Emit the finalizer/iterator cleanup for leaving the current position with a
2133 /// return, and report whether a value is now on the stack for it to carry.
2134 ///
2135 /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
2136 /// enclosing `finally` at once, and the two used to be separate — the `yield` path
2137 /// simply emitted `return_async`, so `it.return()` ended the generator without ever
2138 /// running `finally` blocks the body was sitting inside.
2139 fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
2140 let targets = self.cur().jump_targets.clone();
2141 for target in targets.iter().rev() {
2142 if target.finally_label.is_none() && !target.has_iterator {
2143 continue;
2144 }
2145 if !has_value {
2146 // The cleanup expects a value to pass through; with nothing to
2147 // return, `undefined` stands in.
2148 self.emit(Opcode::Undefined, &[]);
2149 has_value = true;
2150 }
2151 self.emit(Opcode::NipCatch, &[]);
2152 if target.has_iterator {
2153 // Rewind to the loop's own slots and hand the close a dummy catch offset:
2154 // the loop is being abandoned, so there is nothing left to catch.
2155 self.emit_iterator_close(target.is_async_iterator, true);
2156 } else if let Some(finally) = target.finally_label {
2157 self.emit_jump(Opcode::Gosub, finally, &[]);
2158 }
2159 }
2160 has_value
2161 }
2162
2163 /// Compile a statement list, stopping at the first statement that cannot
2164 /// fall through.
2165 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2166 for (index, stmt) in body.iter().enumerate() {
2167 // A `using` declaration is not just a binding: everything after it, to the end
2168 // of the list, runs inside its disposal region. Compiling the rest of the list
2169 // recursively is what gives nested regions their innermost-first order.
2170 if Self::using_declaration(stmt).is_some() {
2171 return self.using_region(stmt, &body[index + 1..]);
2172 }
2173 self.stmt(stmt)?;
2174 if Self::terminates(stmt) {
2175 break;
2176 }
2177 }
2178 Ok(())
2179 }
2180
2181 /// The declaration a `using` statement carries, if it is one.
2182 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2183 match &stmt.kind {
2184 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2185 _ => None,
2186 }
2187 }
2188
2189 /// Compile `decl` and then the rest of its block, disposing when the block ends.
2190 ///
2191 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2192 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2193 /// exception — and this engine already funnels all of those through `catch` plus
2194 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2195 /// `return` and `break` dispose without knowing anything about `using`.
2196 ///
2197 /// ```text
2198 /// <declaration> value -> x, method -> x+1
2199 /// catch CATCH <- an exception in the rest lands here
2200 /// REST:
2201 /// <the rest of the block>
2202 /// drop <- the catch offset, on the fall-through path
2203 /// undefined; gosub DISPOSE; drop
2204 /// goto END
2205 /// CATCH:
2206 /// using_dispose x <- merges the failure into the pending exception
2207 /// throw
2208 /// DISPOSE:
2209 /// using_dispose_init
2210 /// using_dispose x
2211 /// using_dispose_end <- rethrows if a dispose failed
2212 /// ret
2213 /// END:
2214 /// ```
2215 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2216 let Some(decl) = Self::using_declaration(stmt) else {
2217 unreachable!("using_region is only called for a using declaration");
2218 };
2219 self.using_declarator(stmt, decl, 0, rest)
2220 }
2221
2222 /// One declarator of a `using` declaration, plus the region around everything after it.
2223 ///
2224 /// A `using` may list several resources — `using a = x, b = y;` — and each one is
2225 /// disposed when the block ends, in **reverse** order: §14.3.1.4 pushes them onto
2226 /// `DisposableResourceStack` in source order and §9.5.5 disposes from the top. Nesting
2227 /// one region per declarator gives exactly that, because the inner region ends first
2228 /// (`multiple-resources-disposed-in-reverse-order`). Compiling only the first left the
2229 /// rest undisposed.
2230 fn using_declarator(
2231 &mut self,
2232 stmt: &Stmt,
2233 decl: &VarDecl,
2234 index: usize,
2235 rest: &[Stmt],
2236 ) -> Result<(), SyntaxError> {
2237 let Some(declarator) = decl.declarators.get(index) else {
2238 return self.stmts(rest);
2239 };
2240 // `using` binds a plain identifier and has no pattern form, which the parser
2241 // enforces; the region still has to know *which* slot to dispose.
2242 let name = match &declarator.target.kind {
2243 PatternKind::Ident(ident) => Some(ident.name.clone()),
2244 _ => None,
2245 };
2246 let single = Stmt {
2247 kind: StmtKind::VarDecl(VarDecl {
2248 kind: decl.kind,
2249 declarators: vec![declarator.clone()],
2250 span: declarator.span,
2251 }),
2252 span: declarator.span,
2253 };
2254 self.stmt(&single)?;
2255 let Some(name) = name else {
2256 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2257 // must not make the compiler panic.
2258 return self.using_declarator(stmt, decl, index + 1, rest);
2259 };
2260 let Some(value_slot) = self.using_value_slot(&name) else {
2261 // Declared globally, which the parser rules out for a script; a module's
2262 // top level is a scope, and there the disposal stays a known gap.
2263 return self.using_declarator(stmt, decl, index + 1, rest);
2264 };
2265 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2266 // exit path already disposed.
2267 let live = !rest.last().is_some_and(Self::terminates);
2268 let _ = stmt;
2269 self.using_region_around(
2270 value_slot,
2271 live,
2272 decl.kind == VarDeclKind::AwaitUsing,
2273 |compiler| compiler.using_declarator(stmt, decl, index + 1, rest),
2274 )
2275 }
2276
2277 /// One `using` declarator of a `for` head, wrapped in its disposal region, and then the
2278 /// next — so the resources nest inside-out and dispose in reverse order.
2279 #[allow(clippy::too_many_arguments)]
2280 fn for_using_head(
2281 &mut self,
2282 decl: &VarDecl,
2283 index: usize,
2284 init: &Option<ForInit>,
2285 test: &Option<Box<Expr>>,
2286 update: &Option<Box<Expr>>,
2287 body: &Stmt,
2288 labels: &[String],
2289 for_key: u64,
2290 for_parent: u64,
2291 ) -> Result<(), SyntaxError> {
2292 let Some(declarator) = decl.declarators.get(index) else {
2293 return self.for_loop_tail(init, test, update, body, labels, for_key, for_parent);
2294 };
2295 let name = match &declarator.target.kind {
2296 PatternKind::Ident(ident) => Some(ident.name.clone()),
2297 _ => None,
2298 };
2299 self.var_decl(&VarDecl {
2300 kind: decl.kind,
2301 declarators: vec![declarator.clone()],
2302 span: declarator.span,
2303 })?;
2304 let Some(slot) = name.and_then(|name| self.using_value_slot(&name)) else {
2305 return self.for_using_head(
2306 decl,
2307 index + 1,
2308 init,
2309 test,
2310 update,
2311 body,
2312 labels,
2313 for_key,
2314 for_parent,
2315 );
2316 };
2317 self.using_region_around(
2318 slot,
2319 true,
2320 decl.kind == VarDeclKind::AwaitUsing,
2321 |compiler| {
2322 compiler.for_using_head(
2323 decl,
2324 index + 1,
2325 init,
2326 test,
2327 update,
2328 body,
2329 labels,
2330 for_key,
2331 for_parent,
2332 )
2333 },
2334 )
2335 }
2336
2337 /// The half of a `for` statement that runs inside its head's disposal region: the
2338 /// per-iteration bindings, the test, the body and the update.
2339 ///
2340 /// Split out so that a `using` head can wrap exactly this much — see the
2341 /// `StmtKind::For` arm — because the resource lives as long as the statement.
2342 #[allow(clippy::too_many_arguments)]
2343 fn for_loop_tail(
2344 &mut self,
2345 init: &Option<ForInit>,
2346 test: &Option<Box<Expr>>,
2347 update: &Option<Box<Expr>>,
2348 body: &Stmt,
2349 labels: &[String],
2350 for_key: u64,
2351 for_parent: u64,
2352 ) -> Result<(), SyntaxError> {
2353 // A `let`/`const` in the head gets a *fresh binding per iteration*,
2354 // so a closure made in the body captures that iteration's value
2355 // instead of sharing one. The reference expresses this with
2356 // `close_loc`, which swaps in a new reference cell holding the
2357 // current value; the three points below are the ones it uses — after
2358 // the initialiser, before the update, and after the loop.
2359 let loop_bindings = match init {
2360 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
2361 let mut names: Vec<String> = Vec::new();
2362 for declarator in &decl.declarators {
2363 let mut idents = Vec::new();
2364 declarator.target.bound_names(&mut idents);
2365 names.extend(idents.into_iter().map(|ident| ident.name));
2366 }
2367 names
2368 }
2369 _ => Vec::new(),
2370 };
2371 // The reference also closes right after the initialiser, so the first
2372 // iteration's closures get their own cell rather than sharing the one
2373 // the initialiser wrote into.
2374 for name in &loop_bindings {
2375 let pos = self.cur().cur_pos;
2376 self.state().insns.push(Insn::CloseCaptured {
2377 name: name.clone(),
2378 block: for_key,
2379 });
2380 self.state().insn_pos.push(pos);
2381 }
2382 let top = self.new_label();
2383 let cont = self.new_label();
2384 let end = self.new_label();
2385 self.place_label(top);
2386 if let Some(test) = test {
2387 self.expr(test)?;
2388 self.emit_jump(Opcode::IfFalse, end, &[]);
2389 }
2390 // `continue` runs the update expression first, so it lands on
2391 // `cont`, which sits just before the update.
2392 self.loop_body(body, labels, cont, end)?;
2393 self.place_label(cont);
2394 // Each iteration ends with a fresh cell, so the closures the body just
2395 // created keep the cell they captured and the update writes to a new
2396 // one. Without this every closure in the loop shares one binding.
2397 let binding_block = for_key;
2398 for name in &loop_bindings {
2399 let pos = self.cur().cur_pos;
2400 self.state().insns.push(Insn::CloseCaptured {
2401 name: name.clone(),
2402 block: binding_block,
2403 });
2404 self.state().insn_pos.push(pos);
2405 }
2406 if let Some(update) = update {
2407 self.state().discard_value = true;
2408 let result = self.expr(update);
2409 self.state().discard_value = false;
2410 result?;
2411 if !std::mem::take(&mut self.state().no_value) {
2412 self.emit(Opcode::Drop, &[]);
2413 }
2414 }
2415 self.emit_jump(Opcode::Goto, top, &[]);
2416 self.place_label(end);
2417 self.emit_scope_leave(for_key);
2418 self.state().current_block = for_parent;
2419 Ok(())
2420 }
2421
2422 /// The slot a `using` binding's value lives in.
2423 fn using_value_slot(&self, name: &str) -> Option<u32> {
2424 self.cur()
2425 .vars
2426 .iter()
2427 .position(|var| var.name == name && var.kind == VarKind::Using)
2428 .map(|index| index as u32)
2429 }
2430
2431 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2432 ///
2433 /// Shared between a `using` statement — which owns the rest of its block — and a
2434 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2435 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2436 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2437 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2438 /// target with a `finally_label` is what makes `return` and `break` dispose without
2439 /// knowing anything about `using`.
2440 ///
2441 /// ```text
2442 /// catch CATCH <- an exception inside lands here
2443 /// <inside>
2444 /// drop <- the catch offset, on the fall-through path
2445 /// undefined; gosub DISPOSE; drop
2446 /// goto END
2447 /// CATCH:
2448 /// using_dispose slot <- merges the failure into the pending exception
2449 /// throw
2450 /// DISPOSE:
2451 /// using_dispose_init
2452 /// using_dispose slot
2453 /// using_dispose_end <- rethrows if a dispose failed
2454 /// ret
2455 /// END:
2456 /// ```
2457 fn using_region_around(
2458 &mut self,
2459 value_slot: u32,
2460 live: bool,
2461 is_await_using: bool,
2462 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2463 ) -> Result<(), SyntaxError> {
2464 let catch_label = self.new_label();
2465 let end_label = self.new_label();
2466 let dispose_label = self.new_label();
2467
2468 self.emit_jump(Opcode::Catch, catch_label, &[]);
2469 self.push_jump_target(JumpTarget {
2470 names: Vec::new(),
2471 break_label: None,
2472 continue_label: None,
2473 // The catch offset is the one thing on the stack that leaving has to remove.
2474 drop_count: 1,
2475 finally_label: Some(dispose_label),
2476 is_regular_stmt: false,
2477 has_iterator: false,
2478 is_async_iterator: false,
2479 });
2480 inside(self)?;
2481 self.pop_jump_target();
2482
2483 if live {
2484 self.emit(Opcode::Drop, &[]);
2485 self.emit(Opcode::Undefined, &[]);
2486 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2487 self.emit(Opcode::Drop, &[]);
2488 self.emit_jump(Opcode::Goto, end_label, &[]);
2489 }
2490
2491 // An exception unwinds to here with the thrown value on the stack, which is exactly
2492 // the shape `using_dispose` expects as its error state.
2493 self.place_label(catch_label);
2494 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2495 self.emit(Opcode::Throw, &[]);
2496
2497 self.place_label(dispose_label);
2498 // Inside the subroutine the return value and the `gosub` return address are both
2499 // live, and neither an outer finalizer nor another region may run before this one
2500 // has finished.
2501 self.push_jump_target(JumpTarget {
2502 names: Vec::new(),
2503 break_label: None,
2504 continue_label: None,
2505 drop_count: 2,
2506 finally_label: None,
2507 is_regular_stmt: false,
2508 has_iterator: false,
2509 is_async_iterator: false,
2510 });
2511 self.emit(Opcode::UsingDisposeInit, &[]);
2512 if is_await_using {
2513 // `AsyncDisposableStack`'s order: call the method, **await** its result, and
2514 // fold a rejection into the error state. The catch is what turns that
2515 // rejection — which arrives as an exception from `await` — into the merged
2516 // error, so one failure is rethrown as itself and two become a
2517 // `SuppressedError` (§27.1.3.3's `DisposeResources` steps 5–6).
2518 //
2519 // The shape is the reference's `js_emit_dispose_scope`, adapted to this
2520 // engine's error-state protocol: `using_dispose_init` pushed the state and
2521 // `using_dispose_end` will consume it, so both arms have to leave it in place.
2522 let catch_label = self.new_label();
2523 let merged_label = self.new_label();
2524 self.emit_jump(Opcode::Catch, catch_label, &[]);
2525 self.emit(
2526 Opcode::UsingDisposeAsync,
2527 &[Op::Slot(Slot::Loc(value_slot))],
2528 );
2529 self.emit(Opcode::Await, &[]);
2530 // The awaited value, and the catch offset the successful path still holds.
2531 self.emit(Opcode::Drop, &[]);
2532 self.emit(Opcode::Drop, &[]);
2533 self.emit_jump(Opcode::Goto, merged_label, &[]);
2534 self.place_label(catch_label);
2535 self.emit(Opcode::UsingDisposeMerge, &[]);
2536 self.place_label(merged_label);
2537 self.state().has_await = true;
2538 } else {
2539 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2540 }
2541 self.emit(Opcode::UsingDisposeEnd, &[]);
2542 self.pop_jump_target();
2543 self.emit(Opcode::Ret, &[]);
2544 self.place_label(end_label);
2545 Ok(())
2546 }
2547
2548 /// Declare every name a statement list introduces, before compiling any of
2549 /// it, so a reference that appears textually before a declaration still
2550 /// resolves.
2551 ///
2552 /// Declarations are walked in source order because that is the order the
2553 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2554 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2555 /// declarations hoist out to the function scope; lexical names belong to the
2556 /// block they were written in, which `block` records.
2557 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2558 let saved = self.cur().current_block;
2559 self.state().current_block = block;
2560 let result = self.hoist_list(body);
2561 // Only now is every binding of this scope known, so the deferred function
2562 // bodies can be compiled against the finished list. Compiled at its own
2563 // declaration instead, a body that names a `var` written further down would
2564 // have resolved that name as a global.
2565 if result.is_ok() {
2566 let deferred = std::mem::take(&mut self.state().deferred_funcs);
2567 let mut outcome = Ok(());
2568 for (owner, func) in deferred {
2569 let previous = self.cur().current_block;
2570 self.state().current_block = owner;
2571 outcome = self.func_decl(&func);
2572 self.state().current_block = previous;
2573 if outcome.is_err() {
2574 break;
2575 }
2576 }
2577 self.state().current_block = saved;
2578 return outcome;
2579 }
2580 // `current_block` is restored by the caller for a block statement, since
2581 // it needs it set while compiling; only clean up on the hoist path.
2582 self.state().current_block = saved;
2583 result
2584 }
2585
2586 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2587 for stmt in body {
2588 self.hoist_stmt(stmt)?;
2589 }
2590 Ok(())
2591 }
2592
2593 /// Whether a statement always transfers control away, making everything after
2594 /// it in the same list unreachable.
2595 ///
2596 /// The reference drops such statements in `skip_dead_code`, so `return 1;
2597 /// let x = 2;` compiles to the same bytecode as `return 1;`.
2598 fn terminates(stmt: &Stmt) -> bool {
2599 matches!(
2600 stmt.kind,
2601 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2602 )
2603 }
2604
2605 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2606 match &stmt.kind {
2607 StmtKind::VarDecl(decl) => {
2608 for declarator in &decl.declarators {
2609 let mut names = Vec::new();
2610 declarator.target.bound_names(&mut names);
2611 for name in names {
2612 let text = name.name.clone();
2613 if decl.kind == VarDeclKind::Var {
2614 let def = VarDef::var(text.clone());
2615 self.declare_var(&text, def);
2616 } else if decl.kind.is_using() {
2617 // Two adjacent slots: the resource, then the dispose method
2618 // snapshotted at declaration. `using_dispose` reads them as a
2619 // pair `(slot, slot + 1)`, so nothing may be declared between
2620 // them — which is why both are declared here, in one step,
2621 // rather than the method being added at emission time.
2622 self.declare_using(&text);
2623 } else {
2624 let def = if decl.kind == VarDeclKind::Const {
2625 VarDef::constant(text.clone())
2626 } else {
2627 VarDef::lexical(text.clone())
2628 };
2629 self.declare(&text, def);
2630 }
2631 }
2632 }
2633 }
2634 StmtKind::FuncDecl(func) => {
2635 if let Some(name) = &func.name {
2636 // A function declaration is a `var` binding that happens to
2637 // hold a function, not a lexical one.
2638 let def = VarDef::var(name.name.clone());
2639 self.declare_var(&name.name.clone(), def);
2640 }
2641 // The function object is created when the scope is entered, so it
2642 // exists before the declaration is reached. Its body is compiled
2643 // *after* this scope's hoisting finishes, so a name it uses resolves
2644 // even when the `var` that declares it comes later in the source.
2645 let owner = self.cur().current_block;
2646 self.state().deferred_funcs.push((owner, func.clone()));
2647 }
2648 StmtKind::ClassDecl(class) => {
2649 if let Some(name) = &class.name {
2650 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2651 }
2652 }
2653 // A module's imports are bound before any of its code runs, and its exports
2654 // declare the very bindings they export — so both hoist the declarations
2655 // their `StmtKind` arm will later emit code for.
2656 StmtKind::Import(decl) => self.hoist_import(decl)?,
2657 StmtKind::Export(decl) => self.hoist_export(decl)?,
2658 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2659 StmtKind::If { cons, alt, .. } => {
2660 self.hoist_stmt(cons)?;
2661 if let Some(alt) = alt {
2662 self.hoist_stmt(alt)?;
2663 }
2664 }
2665 StmtKind::While { body, .. }
2666 | StmtKind::DoWhile { body, .. }
2667 | StmtKind::Labeled { body, .. }
2668 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2669 StmtKind::For { init, body, .. } => {
2670 // A `for` head gets its own scope even when it declares nothing,
2671 // because `let` in the head is scoped to the loop.
2672 let key = stmt.span.start.offset as u64;
2673 let parent = self.cur().current_block;
2674 self.push_block(key, parent);
2675 if let Some(init) = init
2676 && let ForInit::VarDecl(decl) = init
2677 {
2678 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2679 }
2680 self.hoist_stmt(body)?;
2681 self.state().current_block = parent;
2682 }
2683 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2684 let key = stmt.span.start.offset as u64;
2685 let parent = self.cur().current_block;
2686 self.push_block(key, parent);
2687 if let ForHead::VarDecl(decl) = left {
2688 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2689 }
2690 self.hoist_stmt(body)?;
2691 self.state().current_block = parent;
2692 }
2693 StmtKind::Try {
2694 block,
2695 handler,
2696 finalizer,
2697 } => {
2698 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2699 let try_parent = self.cur().current_block;
2700 if let Some(handler) = handler {
2701 // The catch parameter belongs to the function scope, not to a
2702 // block: it is a `catch` binding rather than a `let`, so it is
2703 // never in the temporal dead zone and `emit_scope_enter` must
2704 // not mark it uninitialised. It still has to be declared before
2705 // the handler body is hoisted, so it takes the slot the
2706 // reference gives it (bindings are numbered in source order).
2707 if let Some(pattern) = &handler.param {
2708 // The parameter gets its own scope, so entering the handler
2709 // does not have to re-declare it. It is not lexical, so it
2710 // is never marked uninitialised.
2711 let key = Self::try_block_key(stmt, TryPart::Param);
2712 let parent = self.cur().current_block;
2713 self.push_block(key, parent);
2714 // A destructuring parameter binds several names, one slot each,
2715 // in the order they are written. The reference declares those as
2716 // `let`s rather than as one `catch` binding — its dump prints
2717 // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2718 // so the kind follows the shape of the parameter.
2719 //
2720 // Neither form is in the dead zone: the stores run as the handler
2721 // is entered, so both use the unchecked `put_loc`.
2722 let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2723 let mut names = Vec::new();
2724 pattern.bound_names(&mut names);
2725 for name in names {
2726 let def = VarDef {
2727 name: name.name.clone(),
2728 is_const: false,
2729 is_lexical: destructures,
2730 kind: if destructures {
2731 crate::bytecode::VarKind::LexicalCatch
2732 } else {
2733 crate::bytecode::VarKind::Catch
2734 },
2735 is_captured: false,
2736 scope_level: 0,
2737 scope_next: None,
2738 };
2739 self.declare_local(&name.name.clone(), def);
2740 }
2741 // The handler body nests inside the parameter's scope, so the
2742 // body's bindings chain on to the parameter (the reference
2743 // prints `let y [next:1]`, pointing at `e`).
2744 self.state().current_block = key;
2745 }
2746 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2747 // Back to the block the `try` itself lives in, so the finalizer
2748 // is a sibling of the handler rather than nested in it.
2749 self.state().current_block = try_parent;
2750 }
2751 if let Some(finalizer) = finalizer {
2752 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2753 }
2754 }
2755 StmtKind::Switch { cases, .. } => {
2756 let key = stmt.span.start.offset as u64;
2757 let parent = self.cur().current_block;
2758 self.push_block(key, parent);
2759 for case in cases {
2760 self.hoist_list(&case.body)?;
2761 }
2762 self.state().current_block = parent;
2763 }
2764 _ => {}
2765 }
2766 Ok(())
2767 }
2768
2769 /// Hoist a nested statement list, which is its own lexical scope.
2770 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2771 let parent = self.cur().current_block;
2772 self.push_block(key, parent);
2773 self.hoist_list(body)?;
2774 self.state().current_block = parent;
2775 Ok(())
2776 }
2777
2778 /// A block key for one part of a `try` statement.
2779 ///
2780 /// The three parts are three separate scopes, so they cannot share the key a
2781 /// statement's own offset would give them: the try block, the handler body and
2782 /// the finalizer would then look like one scope, and their `let` bindings would
2783 /// be marked uninitialised only on entering the first of them.
2784 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2785 (stmt.span.start.offset as u64) * 4 + part as u64
2786 }
2787
2788 /// Declare a `var`: it lives in the function's own scope, not the block's.
2789 fn declare_var(&mut self, name: &str, def: VarDef) {
2790 if self.cur().is_module {
2791 self.declare_module(name, &def);
2792 return;
2793 }
2794 if self.cur().declares_globally(&def) {
2795 self.declare_global(name, &def);
2796 return;
2797 }
2798 let state = self.state();
2799 // A binding of the *parameter* scope does not count: the body's `var` of the
2800 // same name is a different binding and needs a slot of its own.
2801 if state.vars.iter().enumerate().any(|(index, v)| {
2802 v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2803 }) {
2804 return;
2805 }
2806 // A `var` belongs to the function scope, never to the enclosing block.
2807 state.var_block.push(FUNCTION_SCOPE);
2808 state.vars.push(def);
2809 }
2810
2811 /// Declare `name` as a binding of the parameter scope, returning its slot.
2812 fn declare_param_var(&mut self, name: &str) -> u32 {
2813 declare_param_var_at(self.state(), name)
2814 }
2815
2816 /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2817 ///
2818 /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2819 /// so each points at the one declared before it and the oldest ends the chain with
2820 /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2821 /// runtime walks when it instantiates them.
2822 fn declare_param_binding(&mut self, name: &str) -> u32 {
2823 let state = self.state();
2824 let previous = state
2825 .vars
2826 .iter()
2827 .enumerate()
2828 .rev()
2829 .find(|(index, var)| {
2830 state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2831 })
2832 .map(|(index, _)| index as i32);
2833 let index = state.vars.len() as u32;
2834 state.var_block.push(PARAM_SCOPE);
2835 let mut def = VarDef::lexical(name);
2836 // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2837 // the function's, and its bindings are initialised one by one rather than all at
2838 // once — which is exactly what the dead zone needs.
2839 def.scope_level = 1;
2840 def.scope_next = Some(previous.unwrap_or(-2));
2841 state.vars.push(def);
2842 index
2843 }
2844
2845 /// The slot of a parameter-list binding, if the list has one by that name.
2846 fn param_binding_slot(&self, name: &str) -> Option<u32> {
2847 let state = self.cur();
2848 state
2849 .vars
2850 .iter()
2851 .enumerate()
2852 .position(|(index, var)| {
2853 var.name == name
2854 && var.is_lexical
2855 && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2856 })
2857 .map(|index| index as u32)
2858 }
2859
2860 /// Every parameter-list binding, in declaration order.
2861 fn param_binding_names(&self) -> Vec<String> {
2862 let state = self.cur();
2863 state
2864 .vars
2865 .iter()
2866 .enumerate()
2867 .filter(|(index, var)| {
2868 var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2869 })
2870 .map(|(_, var)| var.name.clone())
2871 .collect()
2872 }
2873
2874 /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2875 fn body_var_slot(&self, name: &str) -> Option<u32> {
2876 let state = self.cur();
2877 state
2878 .vars
2879 .iter()
2880 .enumerate()
2881 .find(|(index, var)| {
2882 var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2883 })
2884 .map(|(index, _)| index as u32)
2885 }
2886
2887 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2888 /// one.
2889 ///
2890 /// With parameter expressions the reference creates two: an unmapped one in the
2891 /// argument scope, for the defaults and anything they close over, and the body's own.
2892 /// They are separate bindings, which is what makes
2893 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2894 /// report 1 from `p` and 2 from the body.
2895 fn provide_param_arguments(&mut self) {
2896 if !self.cur().has_parameter_expressions {
2897 return;
2898 }
2899 let mentioned = self.cur().needs_param_arguments
2900 || self
2901 .cur()
2902 .insns
2903 .iter()
2904 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2905 if !mentioned {
2906 return;
2907 }
2908 let slot = self.declare_param_var("arguments");
2909 let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2910 0
2911 } else {
2912 1
2913 };
2914 self.prepend_initialiser_to(
2915 slot,
2916 Insn::Fixed {
2917 op: Opcode::SpecialObject,
2918 operands: vec![Op::Int(magic)],
2919 },
2920 );
2921 }
2922
2923 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2924 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2925 let current = self.stack.len() - 1;
2926 let init = [
2927 producer,
2928 Insn::Fixed {
2929 op: Opcode::PutLoc,
2930 operands: vec![Op::Slot(Slot::Loc(slot))],
2931 },
2932 ];
2933 let inserted = init.len();
2934 for (index, instruction) in init.into_iter().enumerate() {
2935 self.stack[current].insns.insert(index, instruction);
2936 }
2937 for placed in self.stack[current].labels.iter_mut().flatten() {
2938 *placed += inserted;
2939 }
2940 self.state().label_since_insn = false;
2941 }
2942
2943 /// Give the function an `arguments` binding if its body mentions one.
2944 ///
2945 /// The check runs on the *instruction* stream rather than the AST: by this point
2946 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2947 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2948 /// would renumber every later local slot and stop the bytecode matching the
2949 /// reference, which only adds the binding when the body uses it.
2950 ///
2951 /// `arguments` is a local, initialised at the top of the body by
2952 /// `special_object`; that is the reference's shape, so the disassembly agrees.
2953 fn provide_arguments(&mut self) {
2954 let current = self.stack.len() - 1;
2955 if self.stack[current].is_script || self.stack[current].is_module {
2956 // A module has no `arguments` binding; referring to it is a ReferenceError,
2957 // which is exactly what an unbound name produces.
2958 return;
2959 }
2960 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2961 // function, which is why `() => arguments` sees the caller's arguments.
2962 if self.stack[current].is_arrow {
2963 if self.mentions("arguments") {
2964 self.ensure_enclosing_arguments();
2965 }
2966 return;
2967 }
2968 // Only a *body* mention needs the body's binding: the parameter list has one of
2969 // its own (see [`Compiler::provide_param_arguments`]).
2970 //
2971 // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2972 // `Var`, so without this the body got no binding at all — the name resolved to
2973 // the global object and `delete` answered `true` for a binding that cannot be
2974 // deleted. The reference answers `false`.
2975 let mentioned = self.cur().insns.iter().any(|insn| match insn {
2976 Insn::Var {
2977 name, in_params, ..
2978 } => name == "arguments" && !*in_params,
2979 Insn::DeleteVar { name } => name == "arguments",
2980 _ => false,
2981 });
2982 // A mention that resolves to the body's *own* lexical `arguments` is not a request
2983 // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
2984 // implicit binding is not created at all. Providing it anyway was worse than useless:
2985 // its prologue store resolved past the shadowing `let` and landed on the **global**,
2986 // so `function f(p = eval("var arguments")) { let arguments; }` defined
2987 // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
2988 // test262's `fn-body-cntns-arguments-lex-bind` family).
2989 //
2990 // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
2991 // var *is* the binding, and the implicit arguments object is initialised into it at
2992 // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
2993 // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
2994 // `typeof arguments` `"undefined"`.
2995 if self
2996 .cur()
2997 .vars
2998 .iter()
2999 .any(|var| var.name == "arguments" && var.needs_check())
3000 {
3001 return;
3002 }
3003 if !mentioned && !self.cur().needs_arguments_local {
3004 return;
3005 }
3006 // The request may have come only from a parameter-list arrow, in which case the
3007 // parameter scope's binding already answers for it and the body needs none.
3008 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
3009 return;
3010 }
3011 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
3012 //
3013 // With parameter expressions the list and the body are separate environments, so
3014 // an assignment to a parameter cannot be reflected into `arguments` at all — the
3015 // arguments object is unmapped whatever the mode, which is why the reference emits
3016 // `special_object 0` here even in sloppy code.
3017 // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
3018 // object unmapped whatever the mode — §10.4.4 keys the decision on
3019 // `IsSimpleParameterList`, not on strictness alone.
3020 let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
3021 0
3022 } else {
3023 1
3024 };
3025 // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
3026 // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
3027 // The only storage both sides can see is a reference cell, so every parameter the
3028 // object maps gets one — even a parameter no closure captured. Without this the
3029 // slot holds a plain copy and the mapping has nothing to write through.
3030 if magic == 1 {
3031 for arg in &mut self.stack[current].args {
3032 arg.is_captured = true;
3033 }
3034 }
3035 self.prepend_binding("arguments", magic);
3036 }
3037
3038 /// Whether a *body* instruction refers to `arguments`.
3039 fn body_mentions_arguments(&self) -> bool {
3040 self.cur()
3041 .insns
3042 .iter()
3043 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
3044 }
3045
3046 /// Whether the function body's instruction stream refers to `name`.
3047 fn mentions(&self, name: &str) -> bool {
3048 let current = self.stack.len() - 1;
3049 // A binding of the parameter scope does not answer for the body: the body's own
3050 // `arguments` (or self-name) still has to be provided for it.
3051 if self.stack[current]
3052 .vars
3053 .iter()
3054 .enumerate()
3055 .any(|(index, v)| {
3056 v.name == name
3057 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
3058 })
3059 {
3060 return false;
3061 }
3062 self.stack[current]
3063 .insns
3064 .iter()
3065 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
3066 }
3067
3068 /// Bind the name a named function expression uses to refer to itself.
3069 ///
3070 /// The value is `special_object 2`, the function currently running, so the binding
3071 /// is the closure itself and not a copy. It is a local of this function, which is
3072 /// what keeps `g` out of the enclosing scope.
3073 /// Give the function a local `this`, for an arrow inside it to capture.
3074 fn provide_this_local(&mut self) {
3075 let current = self.stack.len() - 1;
3076 if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
3077 return;
3078 }
3079 if !self.stack[current]
3080 .vars
3081 .iter()
3082 .any(|var| var.name == "this")
3083 {
3084 self.declare_hidden_local("this", VarKind::Normal);
3085 }
3086 self.prepend_initialiser(
3087 "this",
3088 Insn::Fixed {
3089 op: Opcode::PushThis,
3090 operands: vec![],
3091 },
3092 );
3093 }
3094
3095 /// Give the function a local `<home_object>`, for an arrow or a static block inside it
3096 /// to read through `super`.
3097 fn provide_home_object_local(&mut self) {
3098 let current = self.stack.len() - 1;
3099 if !self.stack[current].needs_home_object_local {
3100 return;
3101 }
3102 if !self.stack[current]
3103 .vars
3104 .iter()
3105 .any(|var| var.name == HOME_OBJECT)
3106 {
3107 self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
3108 }
3109 self.prepend_initialiser(
3110 HOME_OBJECT,
3111 Insn::Fixed {
3112 op: Opcode::SpecialObject,
3113 operands: vec![Op::Int(4)],
3114 },
3115 );
3116 }
3117
3118 fn provide_self_name(&mut self) {
3119 let current = self.stack.len() - 1;
3120 let Some(name) = self.stack[current].self_name.clone() else {
3121 return;
3122 };
3123 if self.stack[current].self_name_initialized {
3124 return;
3125 }
3126 // Either the body refers to the name, or a nested function already forced the
3127 // binding into existence while being resolved. A direct `eval` can name it
3128 // without mentioning it, so its presence is a third reason: in strict mode
3129 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
3130 // that only happens if the binding exists.
3131 let declared = self.stack[current].vars.iter().any(|v| v.name == name);
3132 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
3133 return;
3134 }
3135 self.stack[current].self_name_initialized = true;
3136 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
3137 }
3138
3139 /// Insert `special_object magic` plus the store to `name` at the top of the body.
3140 ///
3141 /// Prepending shifts every label that has been placed, so they are all moved by
3142 /// the number of instructions inserted.
3143 fn prepend_binding(&mut self, name: &str, magic: i32) {
3144 self.prepend_binding_with(name, magic, VarKind::Normal);
3145 }
3146
3147 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
3148 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
3149 let current = self.stack.len() - 1;
3150 // A function-expression's own name is immutable in strict mode, which is what
3151 // makes `f = 1` inside a strict body throw instead of being dropped.
3152 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
3153 self.declare_var(
3154 name,
3155 VarDef {
3156 kind,
3157 is_const,
3158 ..VarDef::var(name)
3159 },
3160 );
3161 let init = [
3162 Insn::Fixed {
3163 op: Opcode::SpecialObject,
3164 operands: vec![Op::Int(magic)],
3165 },
3166 Insn::Var {
3167 // An initialisation, not an assignment: sloppy mode drops stores to a
3168 // function-expression's own name, and the prologue is what puts the
3169 // value there in the first place.
3170 action: if kind == VarKind::FunctionName {
3171 VarAction::PutInit
3172 } else {
3173 VarAction::Put
3174 },
3175 name: name.to_string(),
3176 block: 0,
3177 in_params: false,
3178 },
3179 ];
3180 let inserted = init.len();
3181 for (index, instruction) in init.into_iter().enumerate() {
3182 self.stack[current].insns.insert(index, instruction);
3183 }
3184 for placed in self.stack[current].labels.iter_mut().flatten() {
3185 *placed += inserted;
3186 }
3187 // A store sits at the insertion point now, so the `put`/`get` fold must not
3188 // reach across it.
3189 self.stack[current].label_since_insn = true;
3190 }
3191
3192 /// Record a top-level script declaration as a global.
3193 ///
3194 /// A script's top-level `var`/`let`/`function` create properties of the
3195 /// global object, not slots in the script's frame, so they show up as closure
3196 /// variables instead.
3197 fn declare_global(&mut self, name: &str, def: &VarDef) {
3198 let state = self.state();
3199 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3200 // The name was already referenced, from a function compiled before this
3201 // declaration was reached — `function a(){ b() } function b(){}` resolves
3202 // `b` while `b` is still unknown, and that guess has to be corrected here.
3203 // Leaving it as a plain global meant the declaration was never registered,
3204 // so the binding did not exist at run time and `a()` threw
3205 // `b is not defined`.
3206 if matches!(existing.closure_type, ClosureType::Global) {
3207 existing.closure_type = ClosureType::GlobalDecl;
3208 existing.is_const = def.is_const;
3209 existing.is_lexical = def.is_lexical;
3210 }
3211 return;
3212 }
3213 state.closure_vars.push(ClosureVar {
3214 name: name.to_string(),
3215 is_const: def.is_const,
3216 is_lexical: def.is_lexical,
3217 closure_type: ClosureType::GlobalDecl,
3218 var_idx: 0,
3219 });
3220 }
3221
3222 /// Record a module-level declaration as a module variable.
3223 ///
3224 /// The binding is a closure variable of the module body, so reads and writes are
3225 /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
3226 /// *who fills the cell*: the module record does, before the body runs, and an import
3227 /// points its cell at the exporting module's, which is what makes bindings live and
3228 /// cycles work.
3229 fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
3230 let state = self.state();
3231 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3232 // The name may have been referenced before this declaration was hoisted,
3233 // which resolved it as a plain global. Correct that here, the way
3234 // `declare_global` does.
3235 if matches!(existing.closure_type, ClosureType::Global) {
3236 existing.closure_type = ClosureType::ModuleDecl;
3237 existing.is_const = def.is_const;
3238 existing.is_lexical = def.is_lexical;
3239 }
3240 return 0;
3241 }
3242 state.closure_vars.push(ClosureVar {
3243 name: name.to_string(),
3244 is_const: def.is_const,
3245 is_lexical: def.is_lexical,
3246 closure_type: ClosureType::ModuleDecl,
3247 var_idx: 0,
3248 });
3249 0
3250 }
3251
3252 /// Declare a module variable and answer its closure-variable index.
3253 ///
3254 /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
3255 /// module variable is not one. The import table needs the real index instead, because
3256 /// that is the position the host writes the cell into.
3257 fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
3258 self.declare_module(name, def);
3259 self.cur()
3260 .closure_vars
3261 .iter()
3262 .position(|c| c.name == name)
3263 .map(|index| index as u32)
3264 .unwrap_or(0)
3265 }
3266
3267 /// Declare one imported binding as a module variable.
3268 ///
3269 /// Returns the closure-variable index, which is what the import table records: the
3270 /// host writes the exporter's cell into that slot before the body runs.
3271 fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
3272 let state = self.state();
3273 if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
3274 // Keep the slot, fix the kind: the name may already have been referenced.
3275 state.closure_vars[index].closure_type = ClosureType::ModuleImport;
3276 state.closure_vars[index].is_const = is_const;
3277 return index as u32;
3278 }
3279 state.closure_vars.push(ClosureVar {
3280 name: name.to_string(),
3281 // An imported binding cannot be assigned: `x = 1` on an import is a
3282 // `TypeError` at run time, which the const flag is what produces.
3283 is_const: true,
3284 // Lexical, so reads go through `get_var_ref_check`: before linking has filled
3285 // the cell an import is in its dead zone, and reading it there must say so
3286 // rather than answer `undefined`.
3287 is_lexical: true,
3288 closure_type: ClosureType::ModuleImport,
3289 var_idx: 0,
3290 });
3291 state.closure_vars.len() as u32 - 1
3292 }
3293
3294 /// Emit the code an `export` needs.
3295 ///
3296 /// Only `export default <expr>` has any: everything else is a table entry whose
3297 /// binding is declared elsewhere. The expression is stored into the hidden
3298 /// `*default*` variable rather than returned, because the module body has no value
3299 /// to speak of.
3300 fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3301 match &decl.kind {
3302 ExportKind::Declaration(stmt) => self.stmt(stmt),
3303 ExportKind::Default(expr) => {
3304 // `export default class Foo {}`: evaluate the declaration (which binds
3305 // `Foo`), then copy its value into the hidden `*default*` binding, because a
3306 // class declaration is a *statement* and `expr` cannot be compiled as one.
3307 if let ExprKind::Class(class) = &expr.kind
3308 && class.name.is_some()
3309 {
3310 self.stmt(&Stmt {
3311 kind: StmtKind::ClassDecl(class.clone()),
3312 span: expr.span,
3313 })?;
3314 let Some(name) = &class.name else {
3315 return Ok(());
3316 };
3317 self.emit_var(VarAction::Get, &name.name);
3318 let index = self.declare_export_default();
3319 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3320 return Ok(());
3321 }
3322 // A named default function/class is already a module binding; the export
3323 // points at it and there is nothing to evaluate.
3324 if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
3325 return Ok(());
3326 }
3327 self.expr(expr)?;
3328 // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
3329 // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
3330 // name is observable — `imported.default.name` — and without this an
3331 // anonymous `export default class {}` arrived with the empty name.
3332 self.set_name_if_anonymous(expr, &Wtf8::new("default"));
3333 let index = self.declare_export_default();
3334 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3335 Ok(())
3336 }
3337 ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
3338 }
3339 }
3340
3341 /// A module name as the string it denotes.
3342 fn module_name_text(name: &ModuleName) -> &str {
3343 match name {
3344 ModuleName::Ident(ident) => &ident.name,
3345 ModuleName::Str(text) => text,
3346 }
3347 }
3348
3349 /// Bind `import`'s local names and record where each one comes from.
3350 ///
3351 /// Nothing is emitted: an import is not an instruction, it is a promise that the
3352 /// binding's cell will be filled before the body runs. The cell lands in the module's
3353 /// environment at a fixed index, and the host fills it from the exporter's cell —
3354 /// which is why a cyclic import can bind before the other module has evaluated.
3355 fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
3356 let request = self.module_request(&decl.source, &decl.attributes);
3357 for specifier in &decl.specifiers {
3358 let (local, name, is_star) = match specifier {
3359 ImportSpecifier::Default(ident) => {
3360 (ident.name.clone(), "default".to_string(), false)
3361 }
3362 ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3363 ImportSpecifier::Named { imported, local } => (
3364 local.name.clone(),
3365 Self::module_name_text(imported).to_string(),
3366 false,
3367 ),
3368 };
3369 // `import * as ns` is *not* a live binding of another module's variable —
3370 // it is a value of its own, which is why the reference declares it like a
3371 // module variable and the host stores the namespace object in that cell.
3372 let var_idx = if is_star {
3373 // `const`: a namespace object is a value, and the binding is immutable.
3374 self.declare_module_var(&local, &VarDef::constant(local.clone()))
3375 } else {
3376 self.declare_import(&local, true)
3377 };
3378 self.module_meta().imports.push(ImportEntry {
3379 module: request,
3380 name,
3381 var_idx,
3382 is_star,
3383 });
3384 }
3385 Ok(())
3386 }
3387
3388 /// Record what an `export` offers, declaring the binding it exports.
3389 ///
3390 /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3391 fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3392 match &decl.kind {
3393 ExportKind::Declaration(stmt) => {
3394 // The inner declaration keeps its own hoisting, then every name it binds
3395 // becomes an export of the same name.
3396 self.hoist_stmt(stmt)?;
3397 let mut names = Vec::new();
3398 Self::declared_names(stmt, &mut names);
3399 for name in names {
3400 let var_idx = self.module_binding_index(&name);
3401 self.exports_local(&name, var_idx);
3402 }
3403 }
3404 ExportKind::Default(expr) => {
3405 // The reference puts a default export in a hidden `*default*` variable,
3406 // so `export default function f(){}` can export a *value* while `f` stays
3407 // a binding of the module.
3408 if let ExprKind::Function(func) = &expr.kind
3409 && let Some(name) = &func.name
3410 {
3411 let text = name.name.clone();
3412 self.hoist_stmt(&Stmt {
3413 kind: StmtKind::FuncDecl(func.clone()),
3414 span: expr.span,
3415 })?;
3416 let var_idx = self.module_binding_index(&text);
3417 self.module_meta().exports.push(ExportEntry::Local {
3418 export_name: "default".to_string(),
3419 var_idx,
3420 });
3421 return Ok(());
3422 }
3423 if let ExprKind::Class(class) = &expr.kind
3424 && class.name.is_some()
3425 {
3426 // `export default class Foo {}` binds `Foo` in the module scope **and**
3427 // stores the class into the hidden `*default*` binding — it is a
3428 // declaration *and* a value, unlike `export default class {}` which is
3429 // only a value.
3430 //
3431 // Pointing the `default` export straight at `Foo` looked simpler and was
3432 // wrong twice over: `module_binding_index` did not find the lexical
3433 // binding the hoist had just made, so it declared a second one that
3434 // nothing ever wrote, and `export_stmt` then had no code to emit for the
3435 // declaration either. `imported.default` came out `undefined` and `Foo`
3436 // was not in scope inside its own module.
3437 self.hoist_stmt(&Stmt {
3438 kind: StmtKind::ClassDecl(class.clone()),
3439 span: expr.span,
3440 })?;
3441 let var_idx = self.declare_export_default();
3442 self.exports_local("default", var_idx);
3443 return Ok(());
3444 }
3445 let var_idx = self.declare_export_default();
3446 self.module_meta().exports.push(ExportEntry::Local {
3447 export_name: "default".to_string(),
3448 var_idx,
3449 });
3450 }
3451 ExportKind::Named {
3452 specifiers,
3453 source,
3454 attributes,
3455 } => match source {
3456 Some(source) => {
3457 let request = self.module_request(source, attributes);
3458 for specifier in specifiers {
3459 self.module_meta().exports.push(ExportEntry::Indirect {
3460 export_name: Self::module_name_text(&specifier.exported).to_string(),
3461 module: request,
3462 import_name: Self::module_name_text(&specifier.local).to_string(),
3463 });
3464 }
3465 }
3466 None => {
3467 for specifier in specifiers {
3468 let local = Self::module_name_text(&specifier.local).to_string();
3469 let export_name = Self::module_name_text(&specifier.exported).to_string();
3470 // `export { x }` where `x` is itself an **import** re-exports the
3471 // binding the import names, not a binding of this module
3472 // (§16.2.1.6.3: a local export whose local name is imported resolves
3473 // through the imported module). Recording it as a local made two
3474 // modules that both forward one import look like two different
3475 // bindings, and the name was reported ambiguous
3476 // (`import-and-export-propagates-binding`;
3477 // `namespace-unambiguous-if-import-star-as-and-export`).
3478 let closure_names: Vec<String> = self
3479 .cur()
3480 .closure_vars
3481 .iter()
3482 .map(|var| var.name.clone())
3483 .collect();
3484 let forwarded = self
3485 .module_meta()
3486 .imports
3487 .iter()
3488 .filter(|entry| {
3489 closure_names
3490 .get(entry.var_idx as usize)
3491 .is_some_and(|name| *name == local)
3492 })
3493 .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3494 .find(|(_, name, is_star)| !is_star || name.is_empty());
3495 if let Some((request, name, is_star)) = forwarded {
3496 // A namespace import has no export *name* of its own; the
3497 // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3498 // which is what the marker below records.
3499 let import_name = if is_star {
3500 "*namespace*".to_string()
3501 } else {
3502 name
3503 };
3504 self.module_meta().exports.push(ExportEntry::Indirect {
3505 export_name,
3506 module: request,
3507 import_name,
3508 });
3509 continue;
3510 }
3511 let var_idx = self.module_binding_index(&local);
3512 self.module_meta().exports.push(ExportEntry::Local {
3513 export_name,
3514 var_idx,
3515 });
3516 }
3517 }
3518 },
3519 ExportKind::All {
3520 source,
3521 exported,
3522 attributes,
3523 } => {
3524 let request = self.module_request(source, attributes);
3525 match exported {
3526 Some(name) => {
3527 self.module_meta().exports.push(ExportEntry::StarAs {
3528 export_name: Self::module_name_text(name).to_string(),
3529 module: request,
3530 });
3531 }
3532 None => {
3533 self.module_meta()
3534 .exports
3535 .push(ExportEntry::Star { module: request });
3536 }
3537 }
3538 }
3539 }
3540 Ok(())
3541 }
3542
3543 /// The names a declaration binds, which is what `export <decl>` exports.
3544 fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3545 match &stmt.kind {
3546 StmtKind::VarDecl(decl) => {
3547 for declarator in &decl.declarators {
3548 let mut names = Vec::new();
3549 declarator.target.bound_names(&mut names);
3550 out.extend(names.into_iter().map(|name| name.name));
3551 }
3552 }
3553 StmtKind::FuncDecl(func) => {
3554 if let Some(name) = &func.name {
3555 out.push(name.name.clone());
3556 }
3557 }
3558 StmtKind::ClassDecl(class) => {
3559 if let Some(name) = &class.name {
3560 out.push(name.name.clone());
3561 }
3562 }
3563 _ => {}
3564 }
3565 }
3566
3567 /// The closure-variable index of a module binding, declaring it if the name was
3568 /// exported without being declared here.
3569 ///
3570 /// `export { x }` where `x` is not declared in the module is a link-time
3571 /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3572 fn module_binding_index(&mut self, name: &str) -> u32 {
3573 if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3574 return index as u32;
3575 }
3576 self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3577 }
3578
3579 fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3580 self.module_meta().exports.push(ExportEntry::Local {
3581 export_name: export_name.to_string(),
3582 var_idx,
3583 });
3584 }
3585
3586 /// The hidden `*default*` binding `export default <expr>` stores into.
3587 fn declare_export_default(&mut self) -> u32 {
3588 const DEFAULT: &str = "*default*";
3589 if let Some(index) = self
3590 .cur()
3591 .closure_vars
3592 .iter()
3593 .position(|c| c.name == DEFAULT)
3594 {
3595 return index as u32;
3596 }
3597 self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3598 }
3599
3600 /// The module tables, which only the top-level state has.
3601 fn module_meta(&mut self) -> &mut ModuleMeta {
3602 self.state()
3603 .module
3604 .as_mut()
3605 .expect("module tables are only touched while compiling a module")
3606 }
3607
3608 /// The index of `specifier`'s request, adding it if it is new.
3609 ///
3610 /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3611 /// JSON and once as text is two modules with two different contents, which is exactly
3612 /// what `hello_module.js` does.
3613 fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3614 let attributes: Vec<(String, String)> = attributes
3615 .iter()
3616 .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3617 .collect();
3618 let meta = self.module_meta();
3619 if let Some(index) = meta
3620 .requests
3621 .iter()
3622 .position(|request| request.specifier == specifier && request.attributes == attributes)
3623 {
3624 return index as u32;
3625 }
3626 meta.requests.push(ModuleRequest {
3627 specifier: specifier.to_string(),
3628 attributes,
3629 });
3630 meta.requests.len() as u32 - 1
3631 }
3632
3633 /// Compile a loop body with a `break`/`continue` target pushed for it.
3634 fn loop_body(
3635 &mut self,
3636 body: &Stmt,
3637 labels: &[String],
3638 continue_label: Label,
3639 break_label: Label,
3640 ) -> Result<(), SyntaxError> {
3641 self.push_jump_target(JumpTarget {
3642 names: labels.to_vec(),
3643 break_label: Some(break_label),
3644 continue_label: Some(continue_label),
3645 // A loop leaves nothing of its own on the value stack.
3646 drop_count: 0,
3647 finally_label: None,
3648 is_regular_stmt: false,
3649 has_iterator: false,
3650 is_async_iterator: false,
3651 });
3652 let result = self.stmt(body);
3653 self.pop_jump_target();
3654 result
3655 }
3656
3657 fn push_jump_target(&mut self, target: JumpTarget) {
3658 self.state().jump_targets.push(target);
3659 }
3660
3661 fn pop_jump_target(&mut self) {
3662 self.state().jump_targets.pop();
3663 }
3664
3665 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3666 let (label, is_break) = match &stmt.kind {
3667 StmtKind::Break(label) => (label.as_ref(), true),
3668 StmtKind::Continue(label) => (label.as_ref(), false),
3669 _ => unreachable!("control_transfer is only called for break and continue"),
3670 };
3671
3672 // Walk outward from the innermost construct. Everything considered before
3673 // the match is a construct control is leaving, and leaving it has a cost:
3674 // its stack slots go, and its finalizer runs.
3675 let targets = self.cur().jump_targets.clone();
3676 for target in targets.iter().rev() {
3677 let destination = match (label, is_break) {
3678 // An unlabelled `break` skips a labelled non-loop statement: `break`
3679 // may name one, but the bare form only means "leave the loop".
3680 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3681 (None, false) => target.continue_label,
3682 (Some(name), true) => target
3683 .break_label
3684 .filter(|_| target.names.contains(&name.name)),
3685 (Some(name), false) => target
3686 .continue_label
3687 .filter(|_| target.names.contains(&name.name)),
3688 };
3689
3690 if let Some(destination) = destination {
3691 self.emit_jump(Opcode::Goto, destination, &[]);
3692 return Ok(());
3693 }
3694
3695 // Closing the iterator consumes the three slots the loop keeps on the
3696 // stack (iterator, next method, catch offset), so those are not dropped
3697 // again below.
3698 let mut remaining = target.drop_count;
3699 if target.has_iterator {
3700 self.emit_iterator_close(target.is_async_iterator, false);
3701 remaining = remaining.saturating_sub(3);
3702 }
3703 for _ in 0..remaining {
3704 self.emit(Opcode::Drop, &[]);
3705 }
3706 if let Some(finally) = target.finally_label {
3707 // The finalizer runs as a subroutine and is handed a dummy return
3708 // value, which is dropped afterwards to keep the stack the depth it
3709 // had before.
3710 self.emit(Opcode::Undefined, &[]);
3711 self.emit_jump(Opcode::Gosub, finally, &[]);
3712 self.emit(Opcode::Drop, &[]);
3713 }
3714 }
3715
3716 // The parser rejects a break/continue with no target, so reaching here
3717 // means the compiler's own bookkeeping is wrong.
3718 Err(SyntaxError::new(
3719 if is_break {
3720 "break has no enclosing loop or switch"
3721 } else {
3722 "continue has no enclosing loop"
3723 },
3724 stmt.span,
3725 ))
3726 }
3727
3728 /// Compile a labelled statement.
3729 ///
3730 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3731 /// that loop's targets, so the chain is collected and handed to the loop. A
3732 /// label on a non-loop statement only provides a `break` target, because
3733 /// `continue` may not target it.
3734 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3735 let mut names = vec![label.name.clone()];
3736 let mut inner = body;
3737 while let StmtKind::Labeled {
3738 label: next,
3739 body: deeper,
3740 } = &inner.kind
3741 {
3742 names.push(next.name.clone());
3743 inner = deeper;
3744 }
3745 if Self::is_loop(inner) {
3746 return self.stmt_labelled(inner, &names);
3747 }
3748 let end = self.new_label();
3749 self.push_jump_target(JumpTarget {
3750 names,
3751 break_label: Some(end),
3752 continue_label: None,
3753 drop_count: 0,
3754 finally_label: None,
3755 is_regular_stmt: true,
3756 has_iterator: false,
3757 is_async_iterator: false,
3758 });
3759 let result = self.stmt(inner);
3760 self.pop_jump_target();
3761 result?;
3762 self.place_label(end);
3763 let _ = stmt;
3764 Ok(())
3765 }
3766
3767 /// Whether a statement is a loop, i.e. a valid target for `continue`.
3768 fn is_loop(stmt: &Stmt) -> bool {
3769 matches!(
3770 stmt.kind,
3771 StmtKind::While { .. }
3772 | StmtKind::DoWhile { .. }
3773 | StmtKind::For { .. }
3774 | StmtKind::ForIn { .. }
3775 | StmtKind::ForOf { .. }
3776 )
3777 }
3778
3779 /// Compile `switch`.
3780 ///
3781 /// The discriminant is evaluated once and stays on the value stack while the
3782 /// clauses compare against copies of it, so it is dropped at the end — which is
3783 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3784 /// clause's body jumps over the *next* clause's tests straight into its body.
3785 ///
3786 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3787 /// the next run's tests. Only the last run's miss reaches the `default` body, or
3788 /// the end of the switch when there is no `default`. That failure path can point
3789 /// backwards (`default` written first), so the runs and their labels are worked
3790 /// out before any code is emitted.
3791 fn switch(
3792 &mut self,
3793 discriminant: &Expr,
3794 cases: &[SwitchCase],
3795 stmt: &Stmt,
3796 ) -> Result<(), SyntaxError> {
3797 self.reset_value();
3798 // The discriminant is evaluated outside the switch's block scope, before
3799 // any `case` clause exists.
3800 self.expr(discriminant)?;
3801
3802 let switch_key = stmt.span.start.offset as u64;
3803 let switch_parent = self.cur().current_block;
3804 self.push_block(switch_key, switch_parent);
3805 self.emit_scope_enter(switch_key);
3806
3807 let break_label = self.new_label();
3808 self.push_jump_target(JumpTarget {
3809 names: Vec::new(),
3810 break_label: Some(break_label),
3811 // `switch` is a valid `break` target but not a `continue` target.
3812 continue_label: None,
3813 // The discriminant stays on the value stack for the whole statement, so
3814 // a `break` aimed further out has to discard it.
3815 drop_count: 1,
3816 finally_label: None,
3817 is_regular_stmt: false,
3818 has_iterator: false,
3819 is_async_iterator: false,
3820 });
3821
3822 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3823 // its label to the clause after it, so both tests reach the same body.
3824 let mut runs: Vec<(usize, usize)> = Vec::new();
3825 let mut scan = 0;
3826 while scan < cases.len() {
3827 if cases[scan].test.is_some() {
3828 let mut last = scan;
3829 while last + 1 < cases.len()
3830 && cases[last].test.is_some()
3831 && cases[last].body.is_empty()
3832 && cases[last + 1].test.is_some()
3833 {
3834 last += 1;
3835 }
3836 runs.push((scan, last));
3837 scan = last + 1;
3838 } else {
3839 scan += 1;
3840 }
3841 }
3842
3843 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3844 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3845 let default_at = cases.iter().position(|case| case.test.is_none());
3846 // Where the last run sends control when nothing matched.
3847 let miss_target = match default_at {
3848 Some(index) => body_labels[index],
3849 None => break_label,
3850 };
3851
3852 // When `default` comes first, control has to jump over it to reach the
3853 // tests. It only needs to when some clause actually has a test; otherwise
3854 // the default body is the entry point.
3855 let mut entry = None;
3856 if default_at == Some(0) && !runs.is_empty() {
3857 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3858 entry = Some(run_labels[0]);
3859 }
3860
3861 let mut index = 0;
3862 let mut run = 0;
3863 let result = (|| -> Result<(), SyntaxError> {
3864 while index < cases.len() {
3865 if cases[index].test.is_some() {
3866 let (first, last) = runs[run];
3867 // Reaching these tests from the preceding body is a
3868 // fallthrough, which continues inside the body and skips them.
3869 if index > 0 {
3870 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3871 }
3872 if let Some(label) = entry.take() {
3873 self.place_label(label);
3874 }
3875 self.place_label(run_labels[run]);
3876
3877 for (offset, case) in cases[first..=last].iter().enumerate() {
3878 let test = case.test.as_ref().unwrap();
3879 self.emit(Opcode::Dup, &[]);
3880 self.expr(test)?;
3881 self.emit(Opcode::StrictEq, &[]);
3882 if first + offset < last {
3883 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3884 } else {
3885 // Hand over to the next run's tests, or give up.
3886 let next = match runs.get(run + 1) {
3887 Some(_) => run_labels[run + 1],
3888 None => miss_target,
3889 };
3890 self.emit_jump(Opcode::IfFalse, next, &[]);
3891 }
3892 }
3893
3894 self.place_label(body_labels[index]);
3895 for case in &cases[first..=last] {
3896 self.stmts(&case.body)?;
3897 }
3898 index = last + 1;
3899 run += 1;
3900 } else {
3901 // `default`: control arrives here either by falling through or
3902 // because every test missed.
3903 self.place_label(body_labels[index]);
3904 self.stmts(&cases[index].body)?;
3905 index += 1;
3906 }
3907 }
3908 Ok(())
3909 })();
3910
3911 if result.is_ok() {
3912 self.place_label(break_label);
3913 // Discard the discriminant now that no test needs it.
3914 self.emit(Opcode::Drop, &[]);
3915 }
3916
3917 self.pop_jump_target();
3918 self.emit_scope_leave(switch_key);
3919 self.state().current_block = switch_parent;
3920 result
3921 }
3922
3923 /// Compile `try`/`catch`/`finally`.
3924 ///
3925 /// The shape is an exception table built out of `catch` instructions, each of
3926 /// which records where control goes if the instructions that follow raise:
3927 ///
3928 /// ```text
3929 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
3930 /// <guarded block>
3931 /// drop <- discard the catch offset
3932 /// undefined; gosub FINALLY; drop
3933 /// goto END
3934 /// HANDLER:
3935 /// <bind the catch parameter>
3936 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
3937 /// <handler body>
3938 /// drop; undefined; gosub FINALLY; drop; goto END
3939 /// CATCH2:
3940 /// gosub FINALLY; throw <- run the finalizer, then let the error out
3941 /// FINALLY:
3942 /// <finalizer>
3943 /// ret <- return to the `gosub`
3944 /// END:
3945 /// ```
3946 ///
3947 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3948 /// of the finalizer serves the normal path, the handler path and the
3949 /// propagating-exception path.
3950 ///
3951 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3952 /// runs with `ret_value` on the stack, and the normal path has no value to
3953 /// keep, so it pushes one to keep the stack depth identical on every path.
3954 fn try_stmt(
3955 &mut self,
3956 stmt: &Stmt,
3957 block: &[Stmt],
3958 handler: &Option<CatchClause>,
3959 finalizer: Option<&[Stmt]>,
3960 ) -> Result<(), SyntaxError> {
3961 self.reset_value();
3962
3963 let catch_label = self.new_label();
3964 let catch2_label = self.new_label();
3965 let finally_label = self.new_label();
3966 let end_label = self.new_label();
3967
3968 self.emit_jump(Opcode::Catch, catch_label, &[]);
3969
3970 // The guarded block. `break` may not target it, so its entry exists purely
3971 // to unwind: a jump out has to discard the catch offset and run the
3972 // finalizer.
3973 self.push_jump_target(JumpTarget {
3974 names: Vec::new(),
3975 break_label: None,
3976 continue_label: None,
3977 drop_count: 1,
3978 finally_label: Some(finally_label),
3979 is_regular_stmt: false,
3980 has_iterator: false,
3981 is_async_iterator: false,
3982 });
3983
3984 let block_key = Self::try_block_key(stmt, TryPart::Block);
3985 let block_parent = self.cur().current_block;
3986 self.push_block(block_key, block_parent);
3987 self.emit_scope_enter(block_key);
3988 self.stmts(block)?;
3989 self.emit_scope_leave(block_key);
3990 self.state().current_block = block_parent;
3991 // A guarded block that ends in a `return`/`throw` never reaches the
3992 // epilogue, so the reference does not emit one.
3993 self.pop_jump_target();
3994 let block_live = !block.last().is_some_and(Self::terminates);
3995
3996 if block_live {
3997 self.emit(Opcode::Drop, &[]);
3998 self.emit(Opcode::Undefined, &[]);
3999 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4000 self.emit(Opcode::Drop, &[]);
4001 self.emit_jump(Opcode::Goto, end_label, &[]);
4002 }
4003
4004 if let Some(handler) = handler {
4005 self.place_label(catch_label);
4006 // The thrown value is on top of the stack: bind it, or discard it for
4007 // `catch { }`.
4008 match &handler.param {
4009 Some(pattern) => {
4010 // The stores resolve the names, so they have to run inside the
4011 // parameter's own scope; otherwise a same-named `catch` further out
4012 // could win. A `catch` binding is never in the dead zone, so the store
4013 // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
4014 let param_key = Self::try_block_key(stmt, TryPart::Param);
4015 let param_parent = self.cur().current_block;
4016 self.push_block(param_key, param_parent);
4017 self.destructure(pattern, Some(VarDeclKind::Var))?;
4018 self.state().current_block = param_parent;
4019 }
4020 None => self.emit(Opcode::Drop, &[]),
4021 }
4022 self.emit_jump(Opcode::Catch, catch2_label, &[]);
4023
4024 self.push_jump_target(JumpTarget {
4025 names: Vec::new(),
4026 break_label: None,
4027 continue_label: None,
4028 drop_count: 1,
4029 finally_label: Some(finally_label),
4030 is_regular_stmt: false,
4031 has_iterator: false,
4032 is_async_iterator: false,
4033 });
4034 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
4035 let catch_parent = self.cur().current_block;
4036 self.push_block(catch_key, catch_parent);
4037 self.emit_scope_enter(catch_key);
4038 self.stmts(&handler.body)?;
4039 self.emit_scope_leave(catch_key);
4040 self.state().current_block = catch_parent;
4041 self.pop_jump_target();
4042 let handler_live = !handler.body.last().is_some_and(Self::terminates);
4043
4044 if handler_live {
4045 self.emit(Opcode::Drop, &[]);
4046 self.emit(Opcode::Undefined, &[]);
4047 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4048 self.emit(Opcode::Drop, &[]);
4049 self.emit_jump(Opcode::Goto, end_label, &[]);
4050 }
4051
4052 // An error raised inside the handler still has to run the finalizer.
4053 self.place_label(catch2_label);
4054 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4055 self.emit(Opcode::Throw, &[]);
4056 } else {
4057 // `try`/`finally` with no handler: the finalizer runs, then the error
4058 // keeps propagating.
4059 self.place_label(catch_label);
4060 self.emit_jump(Opcode::Gosub, finally_label, &[]);
4061 self.emit(Opcode::Throw, &[]);
4062 }
4063
4064 self.place_label(finally_label);
4065 // Inside the finalizer, leaving has a different cost: the return value and
4066 // the `gosub` return address are both on the stack, and neither finalizer nor
4067 // any outer one may run before the block has finished.
4068 self.push_jump_target(JumpTarget {
4069 names: Vec::new(),
4070 break_label: None,
4071 continue_label: None,
4072 drop_count: 2,
4073 finally_label: None,
4074 is_regular_stmt: false,
4075 has_iterator: false,
4076 is_async_iterator: false,
4077 });
4078 // §14.15.3 step 7: a finalizer that completes **normally** is discarded — the
4079 // `try` block's completion is what the statement answers. Only an abrupt exit from
4080 // the finalizer (`break`, `return`, a throw) replaces it, and that path jumps out
4081 // before the restore below.
4082 //
4083 // Without this the finalizer's last expression statement won: `eval('4; try { }
4084 // catch { } finally { 5; }')` answered `5` where the spec says `undefined`
4085 // (`cptn-finally-skip-catch`, `completion-values`).
4086 let saved_completion = if finalizer.is_some() && self.completion_slot().is_some() {
4087 self.declare_hidden_local("<finally.ret>", VarKind::Normal);
4088 self.emit_var(VarAction::Get, "<ret>");
4089 self.emit_var(VarAction::Put, "<finally.ret>");
4090 // And the body starts from *empty*, because an abrupt exit from the finalizer
4091 // keeps whatever the finalizer itself produced: `finally { break; }` answers
4092 // `undefined`, not the `try` block's value, while `finally { 42; break; }`
4093 // answers `42`. §14.15.3's `UpdateEmpty(F, undefined)` is what fills the empty
4094 // one in.
4095 self.emit(Opcode::Undefined, &[]);
4096 self.emit_var(VarAction::Put, "<ret>");
4097 true
4098 } else {
4099 false
4100 };
4101 if let Some(finalizer) = finalizer {
4102 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
4103 let finally_parent = self.cur().current_block;
4104 self.push_block(finally_key, finally_parent);
4105 self.emit_scope_enter(finally_key);
4106 self.stmts(finalizer)?;
4107 self.emit_scope_leave(finally_key);
4108 self.state().current_block = finally_parent;
4109 }
4110 if saved_completion {
4111 // The finalizer's own statements have already run, so restoring now is what
4112 // discards a normal completion.
4113 self.emit_var(VarAction::Get, "<finally.ret>");
4114 self.emit_var(VarAction::Put, "<ret>");
4115 }
4116 self.pop_jump_target();
4117 self.emit(Opcode::Ret, &[]);
4118 self.place_label(end_label);
4119 Ok(())
4120 }
4121
4122 /// The slot of the completion-value local, when this body has one.
4123 ///
4124 /// Only a script or `eval` body has `<ret>`: a function's completion value is not
4125 /// observable, so there is nothing to keep.
4126 fn completion_slot(&self) -> Option<u32> {
4127 self.cur()
4128 .vars
4129 .iter()
4130 .position(|var| var.name == "<ret>")
4131 .map(|index| index as u32)
4132 }
4133
4134 /// Compile `for`/`in` and `for`/`of`.
4135 ///
4136 /// Both keep an enumeration record on the value stack for the whole loop, which
4137 /// is what makes leaving early expensive: the record has to be dropped, or the
4138 /// iterator closed. The layout is
4139 ///
4140 /// ```text
4141 /// <iterated expression>
4142 /// for_in_start | for_of_start <- pushes the record
4143 /// goto TEST
4144 /// NEXT:
4145 /// <bind the loop variable>
4146 /// <body>
4147 /// TEST:
4148 /// for_in_next | for_of_next 0
4149 /// if_false NEXT <- not finished: next iteration
4150 /// drop <- finished: discard the leftover value
4151 /// BREAK:
4152 /// drop | iterator_close <- the one cleanup `break` also uses
4153 /// ```
4154 ///
4155 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
4156 /// normal exit share one copy — which is why `break` inside the loop emits nothing
4157 /// of its own, and only a jump that passes *through* the loop pays for its record.
4158 fn for_in_of(
4159 &mut self,
4160 stmt: &Stmt,
4161 left: &ForHead,
4162 right: &Expr,
4163 body: &Stmt,
4164 kind: ForLoopKind,
4165 labels: &[String],
4166 ) -> Result<(), SyntaxError> {
4167 self.reset_value();
4168
4169 let loop_key = stmt.span.start.offset as u64;
4170 let loop_parent = self.cur().current_block;
4171 self.push_block(loop_key, loop_parent);
4172 self.emit_scope_enter(loop_key);
4173
4174 // The iterated expression is evaluated inside the loop's scope, after the
4175 // bindings exist in the temporal dead zone.
4176 self.expr(right)?;
4177
4178 let next = self.new_label();
4179 let test = self.new_label();
4180 let break_target = self.new_label();
4181
4182 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
4183 match kind {
4184 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
4185 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
4186 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
4187 }
4188 self.emit_jump(Opcode::Goto, test, &[]);
4189
4190 self.push_jump_target(JumpTarget {
4191 // `outer: for (x of xs) … break outer` needs the name here. Without it the
4192 // loop had no label to break to, and the compiler reported "break has no
4193 // enclosing loop" for a loop that was plainly enclosing it.
4194 names: labels.to_vec(),
4195 break_label: Some(break_target),
4196 continue_label: Some(test),
4197 // Passing through the loop has to dispose of its record. A `for`/`of`
4198 // record is three slots, and closing the iterator consumes all of them.
4199 drop_count: if has_iterator { 3 } else { 1 },
4200 finally_label: None,
4201 is_regular_stmt: false,
4202 has_iterator,
4203 is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
4204 });
4205
4206 self.place_label(next);
4207 self.bind_loop_variable(left)?;
4208
4209 // The reference marks the body with its own label here. Nothing jumps to it
4210 // once the loop is laid out, but it is not decoration: a label between the
4211 // store and the body is why `put_loc v; get_loc v` does *not* fold into
4212 // `set_loc v` when the body starts by reading the loop variable.
4213 let body_label = self.new_label();
4214 self.place_label(body_label);
4215 // `for (using x of …)` disposes once per iteration, so the body is a disposal
4216 // region rather than the whole loop: the resource is the element that this
4217 // iteration produced.
4218 let using_head = match left {
4219 ForHead::VarDecl(decl) if decl.kind.is_using() => {
4220 let slot =
4221 decl.declarators
4222 .first()
4223 .and_then(|declarator| match &declarator.target.kind {
4224 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
4225 _ => None,
4226 });
4227 slot.map(|slot| (slot, decl.kind == VarDeclKind::AwaitUsing))
4228 }
4229 _ => None,
4230 };
4231 match using_head {
4232 Some((slot, awaited)) => {
4233 let live = !Self::terminates(body);
4234 self.using_region_around(slot, live, awaited, |compiler| compiler.stmt(body))?;
4235 }
4236 None => self.stmt(body)?,
4237 }
4238
4239 // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
4240 // binding each iteration**, so a closure the body creates keeps that iteration's
4241 // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
4242 // a new reference cell holding the current value.
4243 //
4244 // The position is the *end* of the body, not the start: closing before the body
4245 // would leave the closures pointing at the cell the next `put_loc` overwrites, and
4246 // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
4247 for name in Self::loop_binding_names(left) {
4248 let pos = self.cur().cur_pos;
4249 self.state().insns.push(Insn::CloseCaptured {
4250 name,
4251 block: loop_key,
4252 });
4253 self.state().insn_pos.push(pos);
4254 }
4255 self.place_label(test);
4256 match kind {
4257 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
4258 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
4259 ForLoopKind::AwaitOf => {
4260 // The reference's shape: step, `await` the result, then unpack it.
4261 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
4262 self.emit(Opcode::Await, &[]);
4263 self.state().has_await = true;
4264 self.emit(Opcode::IteratorGetValueDone, &[]);
4265 }
4266 }
4267 self.emit_jump(Opcode::IfFalse, next, &[]);
4268 // The loop is finished; `for_xx_next` left an `undefined` behind.
4269 self.emit(Opcode::Drop, &[]);
4270
4271 self.pop_jump_target();
4272 self.place_label(break_target);
4273 if has_iterator {
4274 // A loop that ran to completion finds its iterator slot already cleared (see
4275 // `iterator_get_value_done`), so this closes only an iterator abandoned by a
4276 // `break` that jumped here.
4277 self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
4278 } else {
4279 self.emit(Opcode::Drop, &[]);
4280 }
4281
4282 self.emit_scope_leave(loop_key);
4283 self.state().current_block = loop_parent;
4284 Ok(())
4285 }
4286
4287 /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
4288 /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
4289 fn loop_binding_names(left: &ForHead) -> Vec<String> {
4290 let ForHead::VarDecl(decl) = left else {
4291 return Vec::new();
4292 };
4293 if decl.kind == VarDeclKind::Var {
4294 return Vec::new();
4295 }
4296 let mut names = Vec::new();
4297 for declarator in &decl.declarators {
4298 let mut idents = Vec::new();
4299 declarator.target.bound_names(&mut idents);
4300 names.extend(idents.into_iter().map(|ident| ident.name));
4301 }
4302 names
4303 }
4304
4305 /// Store the value `for_xx_next` left on the stack into the loop variable.
4306 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
4307 // A declaration *initialises* the binding, which is what takes a `let` out of
4308 // the temporal dead zone, so the store is the unchecked form. Assigning to a
4309 // binding declared elsewhere is an ordinary write and keeps its check.
4310 let (pattern, action) = match left {
4311 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
4312 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
4313 };
4314 match &pattern.kind {
4315 PatternKind::Ident(name) => {
4316 // `for (using x of …)` validates and snapshots each iteration's value
4317 // before the body runs, which is what makes a non-disposable element fail
4318 // on the iteration that produced it rather than at the end of the loop.
4319 if let ForHead::VarDecl(decl) = left
4320 && decl.kind.is_using()
4321 {
4322 let method_slot = self
4323 .using_method_slot(&name.name)
4324 .expect("a using binding was declared during hoisting");
4325 self.emit(
4326 Opcode::UsingCheck,
4327 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4328 );
4329 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4330 }
4331 self.emit_var(action, &name.name);
4332 Ok(())
4333 }
4334 // Every other target stores through the same path an assignment pattern
4335 // uses, which is what makes `for (a[0] in obj)` write each key into the
4336 // property instead of refusing the loop outright.
4337 _ => self.destructure(
4338 pattern,
4339 match left {
4340 ForHead::VarDecl(decl) => Some(decl.kind),
4341 ForHead::Assign(_) => None,
4342 },
4343 ),
4344 }
4345 }
4346
4347 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
4348 for declarator in &decl.declarators {
4349 let Some(init) = &declarator.init else {
4350 // `var x;` stays `undefined`. A lexical binding is different: it
4351 // has to be *initialised* to leave the temporal dead zone, so the
4352 // compiler supplies an explicit `undefined`.
4353 if decl.kind.is_lexical() {
4354 // A lexical binding has to be *initialised* to leave the temporal
4355 // dead zone, and a destructuring one is no different — `let {a}`
4356 // with no initialiser is a syntax error, but `let [a] = []` still
4357 // needs `a` to be initialised from an empty source, which the
4358 // pattern does on its own.
4359 self.emit(Opcode::Undefined, &[]);
4360 self.destructure(&declarator.target, Some(decl.kind))?;
4361 }
4362 continue;
4363 };
4364 match &declarator.target.kind {
4365 PatternKind::Ident(name) => {
4366 self.expr(init)?;
4367 self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
4368 if decl.kind.is_using() {
4369 // `using_check` validates the value and snapshots its dispose
4370 // method: `value -> value, method`. The snapshot is what makes a
4371 // later change to `Symbol.dispose` irrelevant, and validating here
4372 // is what keeps the body from running at all when the value is not
4373 // disposable.
4374 let method_slot = self
4375 .using_method_slot(&name.name)
4376 .expect("a using binding was declared during hoisting");
4377 self.emit(
4378 Opcode::UsingCheck,
4379 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4380 );
4381 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4382 self.emit_var(VarAction::PutInit, &name.name);
4383 continue;
4384 }
4385 // A declaration statement produces no value, so nothing is
4386 // duplicated onto the stack.
4387 match decl.kind {
4388 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
4389 _ => self.emit_var(VarAction::PutInit, &name.name),
4390 }
4391 }
4392 _ => {
4393 // A destructuring declaration keeps nothing on the stack: the
4394 // pattern consumes the initialiser.
4395 self.expr(init)?;
4396 self.destructure(&declarator.target, Some(decl.kind))?;
4397 }
4398 }
4399 }
4400 Ok(())
4401 }
4402
4403 /// Bind a destructuring pattern from the value on top of the stack.
4404 ///
4405 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4406 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4407 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4408 /// *assignment*, where a member expression is a legal target and the store is an
4409 /// ordinary property write.
4410 ///
4411 /// The value is consumed. An assignment expression's own result is the right-hand
4412 /// side, which the caller keeps separately — the spec does not make the pattern's
4413 /// last store produce it.
4414 fn destructure(
4415 &mut self,
4416 pattern: &Pattern,
4417 decl: Option<VarDeclKind>,
4418 ) -> Result<(), SyntaxError> {
4419 match &pattern.kind {
4420 PatternKind::Ident(name) => {
4421 match decl {
4422 Some(VarDeclKind::Var) | None => {
4423 self.emit_var(VarAction::Put, &name.name);
4424 }
4425 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4426 }
4427 Ok(())
4428 }
4429 PatternKind::Assign { target, default } => {
4430 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4431 // keeps `null`.
4432 //
4433 // The shape is the reference's: test for `undefined`, and when the value is
4434 // present fall **through** to a single store both paths share. The
4435 // alternatives — branching to the store on each side — need a second store
4436 // and a jump between them, which is what the dump used to show.
4437 let has_value = self.new_label();
4438 self.emit(Opcode::Dup, &[]);
4439 self.emit(Opcode::IsUndefined, &[]);
4440 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4441 self.emit(Opcode::Drop, &[]);
4442 self.expr(default)?;
4443 // `var {f = function(){}} = {}` names the function `f`, like a plain
4444 // `var f = function(){}` does. Both pattern forms do it:
4445 // `BindingInitialization` names the value for a *binding* target, and since
4446 // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4447 // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4448 // no name to give, which is why only an identifier qualifies.
4449 if let PatternKind::Ident(name) = &target.kind {
4450 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4451 }
4452 self.place_label(has_value);
4453 self.destructure(target, decl)
4454 }
4455 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4456 PatternKind::Object { properties, rest } => {
4457 self.destructure_object(properties, rest, decl, pattern)
4458 }
4459 PatternKind::Member(member) if decl.is_none() => {
4460 // An assignment pattern may store into a property. The value is on the
4461 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4462 // put the three in the order `put_array_el`/`put_field` expect.
4463 self.expr(&member.object)?;
4464 match &member.property {
4465 MemberProp::Ident(name) => {
4466 // `value obj` -> `obj value`, the order `put_field` takes.
4467 // Nothing needs to be left behind: a pattern element's value is
4468 // consumed by its own store.
4469 self.emit(Opcode::Swap, &[]);
4470 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4471 }
4472 MemberProp::Computed(index) => {
4473 self.expr(index)?;
4474 // `value obj key` -> `obj key value`.
4475 self.emit(Opcode::Rot3l, &[]);
4476 self.emit(Opcode::PutArrayEl, &[]);
4477 }
4478 MemberProp::Private(name) => {
4479 // `value obj` -> `obj value`, and the store half of the assignment is
4480 // the same one `obj.#x = value` uses — only without `insert2`,
4481 // because a pattern element's value is not wanted back.
4482 let binding = format!("#{}", name.name);
4483 let (kind, setter) = self.private_use(&binding, member.span)?;
4484 self.emit(Opcode::Swap, &[]);
4485 self.private_store(&binding, kind, setter.as_deref())?;
4486 }
4487 }
4488 Ok(())
4489 }
4490 PatternKind::Rest(inner) => self.destructure(inner, decl),
4491 PatternKind::Invalid(expr) => {
4492 Err(SyntaxError::new("invalid assignment target", expr.span))
4493 }
4494 _ => Err(SyntaxError::new(
4495 "this destructuring target is not supported by the compiler yet",
4496 pattern.span,
4497 )),
4498 }
4499 }
4500
4501 /// `[…]` on the left: drain an iterator, binding one target per element.
4502 ///
4503 /// A target that stores into a **property** — `[o.p] = it` — has its reference worked
4504 /// out *before* the value is pulled. That ordering is observable twice over
4505 /// (`array-elem-iter-thrw-close`):
4506 ///
4507 /// * `next` must not have been called yet when the reference throws, so
4508 /// `[ {}[thrower()] ] = iterable` reports `nextCount === 0`;
4509 /// * the iterator must still be closed, because the throw happens while the record is
4510 /// live — which is `catch_here`'s `catch_offset 0` doing its work.
4511 ///
4512 /// Doing it the other way round — pull the value, then evaluate the reference — got
4513 /// both wrong: an extra `next` call, and, when the reference threw, an iterator that had
4514 /// already been drained past.
4515 fn destructure_array(
4516 &mut self,
4517 elements: &[Option<PatternElement>],
4518 rest: &Option<Box<RestElement>>,
4519 decl: Option<VarDeclKind>,
4520 ) -> Result<(), SyntaxError> {
4521 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4522 // pattern accepts any iterable and closes the iterator when the pattern ends
4523 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4524 // first because it is on top.
4525 //
4526 // It also counts as an open iterator for `return` and `break`: a pattern is not a
4527 // loop, but the record is live across everything the pattern evaluates, so
4528 // `function* g(){ [ {} = yield ] = it }` resumed with `return()` has to close it
4529 // (`array-elem-iter-rtrn-close`). `emit_unwind_for_return` finds it by this entry
4530 // and `nip_catch` uncovers exactly the `iter next` pairs it left behind.
4531 //
4532 // A `break`/`continue` cannot occur inside a pattern, so `names` and both labels
4533 // are empty and `drop_count` — read only by that unreachable path — keeps the
4534 // reference's 2.
4535 self.push_jump_target(JumpTarget {
4536 names: Vec::new(),
4537 break_label: None,
4538 continue_label: None,
4539 drop_count: 2,
4540 finally_label: None,
4541 is_regular_stmt: false,
4542 has_iterator: true,
4543 is_async_iterator: false,
4544 });
4545 self.emit(Opcode::ForOfStart, &[]);
4546 for element in elements {
4547 match element {
4548 Some(PatternElement::Pattern(pattern)) => {
4549 match Self::member_element_target(pattern, decl) {
4550 // A prepared reference sits above the record, so `for_of_next` is
4551 // told how many values are in the way.
4552 Some(member) => {
4553 let extra = self.prepare_member_target(member)?;
4554 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4555 self.emit(Opcode::Drop, &[]);
4556 self.destructure_prepared(pattern, member)?;
4557 }
4558 None => {
4559 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4560 self.emit(Opcode::Drop, &[]);
4561 self.destructure(pattern, decl)?;
4562 }
4563 }
4564 }
4565 Some(PatternElement::Property { span, .. }) => {
4566 return Err(SyntaxError::new(
4567 "a property pattern is not a valid array element",
4568 *span,
4569 ));
4570 }
4571 // An elision skips the value, which is already on the stack.
4572 None => {
4573 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4574 self.emit(Opcode::Drop, &[]);
4575 self.emit(Opcode::Drop, &[]);
4576 }
4577 }
4578 }
4579 if let Some(rest) = rest {
4580 // The remaining values go into a fresh array. The target and its running
4581 // index stay on the stack above the iterator, which is what the operand of
4582 // `for_of_next` accounts for: two values sit above the iterator triple.
4583 let prepared = match decl {
4584 None => Self::member_rest_target(rest),
4585 // A binding pattern cannot store into a property.
4586 Some(_) => None,
4587 };
4588 let extra = match prepared {
4589 Some(member) => 2 + self.prepare_member_target(member)?,
4590 None => 2,
4591 };
4592 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4593 self.emit(Opcode::Push0, &[]);
4594 let top = self.new_label();
4595 self.place_label(top);
4596 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4597 let done = self.new_label();
4598 self.emit_jump(Opcode::IfTrue, done, &[]);
4599 self.emit(Opcode::DefineArrayEl, &[]);
4600 self.emit(Opcode::Inc, &[]);
4601 self.emit_jump(Opcode::Goto, top, &[]);
4602 self.place_label(done);
4603 self.emit(Opcode::Drop, &[]);
4604 self.emit(Opcode::Drop, &[]);
4605 match prepared {
4606 Some(member) => self.store_member_value(member)?,
4607 None => self.destructure_rest(rest, decl)?,
4608 }
4609 }
4610 self.emit(Opcode::IteratorClose, &[]);
4611 self.pop_jump_target();
4612 Ok(())
4613 }
4614
4615 /// The property an array element stores into, when it stores into one at all.
4616 ///
4617 /// `Assign` is peeled because `[o.p = d] = it` evaluates `o.p`'s reference at the same
4618 /// point `[o.p] = it` does; the default value is applied afterwards, on the pulled
4619 /// value. Nothing deeper is: a nested pattern's own targets are reached by recursing
4620 /// into `destructure`, and those never straddle a `for_of_next`.
4621 fn member_element_target(
4622 pattern: &Pattern,
4623 decl: Option<VarDeclKind>,
4624 ) -> Option<&ast::MemberPattern> {
4625 if decl.is_some() {
4626 return None;
4627 }
4628 match &pattern.kind {
4629 PatternKind::Member(member) => Some(member),
4630 PatternKind::Assign { target, .. } => Self::member_element_target(target, decl),
4631 _ => None,
4632 }
4633 }
4634
4635 /// The same, for a rest element.
4636 fn member_rest_target(rest: &RestElement) -> Option<&ast::MemberPattern> {
4637 match rest {
4638 RestElement::Member(member) => Some(member),
4639 RestElement::Pattern(pattern) => match &pattern.kind {
4640 PatternKind::Member(member) => Some(member),
4641 _ => None,
4642 },
4643 }
4644 }
4645
4646 /// Push a member target's reference — the object, and the key when the property is
4647 /// computed — and answer how many values that put above the iterator record.
4648 fn prepare_member_target(&mut self, member: &ast::MemberPattern) -> Result<i32, SyntaxError> {
4649 self.expr(&member.object)?;
4650 match &member.property {
4651 MemberProp::Ident(_) | MemberProp::Private(_) => Ok(1),
4652 MemberProp::Computed(index) => {
4653 self.expr(index)?;
4654 Ok(2)
4655 }
4656 }
4657 }
4658
4659 /// Store the value on top of the stack through a prepared member reference.
4660 ///
4661 /// `obj value` for a named property, `obj key value` for a computed one — the orders
4662 /// `put_field` and `put_array_el` take, so no reordering is needed here. The `swap` and
4663 /// `rot3l` in [`Compiler::destructure`]'s member case exist only because *it* starts
4664 /// with the value already on the stack.
4665 fn store_member_value(&mut self, member: &ast::MemberPattern) -> Result<(), SyntaxError> {
4666 match &member.property {
4667 MemberProp::Ident(name) => {
4668 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4669 }
4670 MemberProp::Computed(_) => self.emit(Opcode::PutArrayEl, &[]),
4671 MemberProp::Private(name) => {
4672 let binding = format!("#{}", name.name);
4673 let (kind, setter) = self.private_use(&binding, member.span)?;
4674 self.private_store(&binding, kind, setter.as_deref())?;
4675 }
4676 }
4677 Ok(())
4678 }
4679
4680 /// The value of an array element whose member reference is already prepared.
4681 ///
4682 /// Only the default-value test differs from [`Compiler::destructure`]: the reference
4683 /// and the value are both on the stack while the test runs, which is why the object is
4684 /// evaluated before the default rather than after it.
4685 fn destructure_prepared(
4686 &mut self,
4687 pattern: &Pattern,
4688 member: &ast::MemberPattern,
4689 ) -> Result<(), SyntaxError> {
4690 if let PatternKind::Assign { default, .. } = &pattern.kind {
4691 let has_value = self.new_label();
4692 self.emit(Opcode::Dup, &[]);
4693 self.emit(Opcode::IsUndefined, &[]);
4694 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4695 self.emit(Opcode::Drop, &[]);
4696 self.expr(default)?;
4697 self.place_label(has_value);
4698 }
4699 self.store_member_value(member)
4700 }
4701
4702 /// `{…}` on the left: read properties off one boxed source object.
4703 fn destructure_object(
4704 &mut self,
4705 properties: &[Option<PatternElement>],
4706 rest: &Option<Box<RestElement>>,
4707 decl: Option<VarDeclKind>,
4708 pattern: &Pattern,
4709 ) -> Result<(), SyntaxError> {
4710 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4711 // aside for the rest element below.
4712 self.emit(Opcode::ToObject, &[]);
4713 let mut taken: Vec<Wtf8> = Vec::new();
4714 // A computed key's *value* is only known at run time, so with a rest element the
4715 // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4716 // local array that every key is written into as the pattern is walked — literal
4717 // keys by name, computed ones by the value the expression produced. Without this,
4718 // `let { [k]: a, ...rest } = o` was refused outright.
4719 let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4720 let key_log = if needs_key_log {
4721 let name = "<rest_exclude>";
4722 self.declare_hidden_local(name, VarKind::Normal);
4723 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4724 self.emit_var(VarAction::Put, name);
4725 Some(name)
4726 } else {
4727 None
4728 };
4729 for property in properties {
4730 let Some(PatternElement::Property {
4731 key, value, span, ..
4732 }) = property
4733 else {
4734 return Err(SyntaxError::new(
4735 "a bare pattern is not a valid object property",
4736 properties
4737 .iter()
4738 .flatten()
4739 .map(|element| match element {
4740 PatternElement::Pattern(pattern) => pattern.span,
4741 PatternElement::Property { span, .. } => *span,
4742 })
4743 .next()
4744 .unwrap_or(pattern.span),
4745 ));
4746 };
4747 // Every read needs the source twice: to read from, and to keep for the next
4748 // property. `get_field2` is that duplicate-and-read in one instruction, but it
4749 // leaves the copy *under* the value, so it is only usable when whatever
4750 // consumes the value tolerates that. See [`reads_with_get_field2`].
4751 let nested = reads_with_get_field2(decl, value);
4752 if !nested {
4753 self.emit(Opcode::Dup, &[]);
4754 }
4755 let slot = taken.len();
4756 match key {
4757 PropName::Literal(literal) => {
4758 let name = self.property_key_text(literal, *span)?;
4759 taken.push(name.clone());
4760 if let Some(log) = &key_log {
4761 // `arr index key -> arr`: the key is written into the log before
4762 // the read, so the order of observable operations is unchanged.
4763 self.emit_var(VarAction::Get, log);
4764 self.push_number(slot as f64);
4765 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4766 self.emit(Opcode::PutArrayEl, &[]);
4767 }
4768 self.emit(
4769 if nested {
4770 Opcode::GetField2
4771 } else {
4772 Opcode::GetField
4773 },
4774 &[Op::Atom(Atom::from_wtf8(&name))],
4775 );
4776 }
4777 PropName::Computed(index) => {
4778 self.expr(index)?;
4779 // `key key`: one stays on the stack for the read, the other goes into
4780 // the exclusion log. The index is a compile-time constant, so no counter
4781 // local is needed.
4782 if let Some(log) = &key_log {
4783 taken.push(Wtf8::default());
4784 self.emit(Opcode::Dup, &[]);
4785 self.emit_var(VarAction::Get, log);
4786 self.emit(Opcode::Swap, &[]);
4787 self.push_number(slot as f64);
4788 self.emit(Opcode::Swap, &[]);
4789 self.emit(Opcode::PutArrayEl, &[]);
4790 }
4791 self.emit(Opcode::GetArrayEl, &[]);
4792 }
4793 PropName::Private(_) => {
4794 return Err(SyntaxError::new(
4795 "private fields are not supported by the compiler yet",
4796 value.span,
4797 ));
4798 }
4799 }
4800 self.destructure(value, decl)?;
4801 }
4802 match rest {
4803 Some(rest) => {
4804 // `target src exclude`: the exclusion list is an array of the keys the
4805 // literal part already took, so the rest object gets only the others.
4806 self.emit(Opcode::Object, &[]);
4807 self.emit(Opcode::Swap, &[]);
4808 match &key_log {
4809 // Built while walking the pattern; see `needs_key_log`.
4810 Some(log) => {
4811 self.emit_var(VarAction::Get, log);
4812 }
4813 None => {
4814 for name in &taken {
4815 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4816 }
4817 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4818 }
4819 }
4820 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4821 self.emit(Opcode::Drop, &[]);
4822 self.emit(Opcode::Drop, &[]);
4823 self.destructure_rest(rest, decl)?;
4824 }
4825 // The source was only kept for a rest element.
4826 None => self.emit(Opcode::Drop, &[]),
4827 }
4828 Ok(())
4829 }
4830
4831 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4832 fn destructure_rest(
4833 &mut self,
4834 rest: &RestElement,
4835 decl: Option<VarDeclKind>,
4836 ) -> Result<(), SyntaxError> {
4837 match rest {
4838 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4839 // `[...a.b] = c` stores into a property.
4840 RestElement::Member(member) => {
4841 let pattern = Pattern {
4842 kind: PatternKind::Member(member.clone()),
4843 span: member.span,
4844 };
4845 self.destructure(&pattern, decl)
4846 }
4847 }
4848 }
4849
4850 /// Compile a function declaration and queue it for instantiation at scope
4851 /// entry.
4852 ///
4853 /// A declaration is visible before the statement that declares it, so the
4854 /// code that creates the function object belongs at the top of the enclosing
4855 /// scope, not at the declaration.
4856 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4857 let name = func.name.as_ref().expect("a declaration has a name");
4858 let function = self.compile_function(func)?;
4859 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4860 let target = self.hoist_target(&name.name);
4861 let block = self.cur().current_block;
4862 self.state().hoisted.push((block, target, pool_index));
4863 Ok(())
4864 }
4865
4866 /// Where a name lives, for a hoisted declaration.
4867 fn hoist_target(&self, name: &str) -> HoistTarget {
4868 let state = self.cur();
4869 if let Some(index) = state.args.iter().position(|a| a.name == name) {
4870 return HoistTarget::Arg(index as u32);
4871 }
4872 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4873 return HoistTarget::Loc(index as u32);
4874 }
4875 // A global function declaration is not a slot at all.
4876 HoistTarget::Global(name.to_string())
4877 }
4878
4879 // -- expressions -------------------------------------------------------
4880
4881 /// Compile one expression, recording where its instructions sit.
4882 ///
4883 /// The position is the node's operator when it has one and its first token
4884 /// otherwise, and it is restored on the way out so a parent's own instructions —
4885 /// which are emitted *after* its children — are blamed on the parent. Without the
4886 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4887 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4888 // `discard_value` belongs to the *statement* that is about to be compiled, so it
4889 // may only be honoured by that statement's own top-level expression. Taking it here
4890 // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4891 // the argument list is a different expression — it must still leave its value on the
4892 // stack. Without this the argument vanished, and `call` then consumed the callee as
4893 // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4894 // function).
4895 self.discard_root = std::mem::take(&mut self.state().discard_value);
4896 let saved = self.cur().cur_pos;
4897 // Only the node kinds the reference calls `emit_source_pos` for record a position:
4898 // the operator a node exists for, and a variable *read*, which the reference
4899 // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4900 // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4901 // start, a parenthesised group, an anonymous function expression — leaves the
4902 // previous position in place, because a table entry the reference never writes is
4903 // one we must not write either: the instruction that inherits a position (the
4904 // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4905 // report a more recent token than the reference does.
4906 let pos = expr.op_pos.or(match &expr.kind {
4907 ExprKind::Ident(ident) => Some(ident.span.start),
4908 _ => None,
4909 });
4910 match pos {
4911 Some(pos) => self.state().cur_pos = Some(pos),
4912 // A node the reference records nothing for: its own instructions stay
4913 // unpositioned, so they inherit whatever was written last — which is what an
4914 // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4915 // enclosing position instead would blame them on a token the reference has not
4916 // reached yet: a spread's `iterator_open` reports the expression it follows, and
4917 // a template's `to_propkey` the interpolation.
4918 None => self.state().cur_pos = None,
4919 }
4920 // Note a direct `eval` call before compiling it, because the *whole* function
4921 // is affected: an eval can name any binding the function declares, so every one
4922 // of them has to live in a cell for a closure it creates to capture it.
4923 self.note_direct_eval(expr);
4924 let result = self.expr_inner(expr);
4925 self.discard_root = false;
4926 self.state().cur_pos = saved;
4927 result
4928 }
4929
4930 /// Record which bindings are in scope at a direct `eval` call.
4931 ///
4932 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4933 /// resolves names from a string at run time, so the only chance to pin down *which*
4934 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4935 /// its block is the current block, an enclosing one, or the function scope.
4936 fn materialize_eval_sites(&mut self) {
4937 let pending = std::mem::take(&mut self.state().pending_eval_sites);
4938 for (span, site_block, in_params, private, arguments_allowed) in pending {
4939 self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
4940 }
4941 }
4942
4943 /// Resolve the bindings visible at one `eval` call.
4944 fn resolve_eval_site(
4945 &mut self,
4946 span: Span,
4947 site_block: u64,
4948 site_in_params: bool,
4949 private_names: Vec<EvalPrivate>,
4950 arguments_allowed: bool,
4951 ) {
4952 /// How near a binding is: function distance first, then block depth, then the
4953 /// later declaration (which shadows the earlier one in the same block).
4954 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4955
4956 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4957 // walked, innermost function first: a direct `eval` sees every enclosing
4958 // function's bindings, and none of them can be resolved at run time because the
4959 // runtime only has names to go on.
4960 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4961 let deepest = self.stack.len() - 1;
4962 for (level, state) in self.stack.iter().enumerate().rev() {
4963 let owner = (deepest - level) as u32;
4964 // The innermost function's block is the one the call sat in, which is not
4965 // the block the compiler is in now; the enclosing functions are still at
4966 // the point where this one was created.
4967 let here = if level == deepest {
4968 site_block
4969 } else {
4970 state.current_block
4971 };
4972 // The chain of live blocks, innermost first, with a depth for each. The walk
4973 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4974 // block can start at source offset zero.
4975 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4976 let mut block = here;
4977 while let Some(parent) = state
4978 .blocks
4979 .iter()
4980 .find(|candidate| candidate.key == block)
4981 .map(|candidate| candidate.parent)
4982 .filter(|parent| *parent != NO_PARENT)
4983 .filter(|parent| parent != &block)
4984 {
4985 live.push((parent, live.len()));
4986 block = parent;
4987 }
4988 let depth_of = |key: u64| {
4989 live.iter()
4990 .find(|(candidate, _)| *candidate == key)
4991 .map(|(_, depth)| *depth)
4992 // The function scope is the outermost depth there is. A binding of a
4993 // block this site is not inside lands here too, which pushes it
4994 // behind every live one — the right answer: it is out of scope.
4995 .unwrap_or(live.len())
4996 };
4997 for (index, arg) in state.args.iter().enumerate() {
4998 bindings.push((
4999 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
5000 EvalVisible {
5001 name: arg.name.clone(),
5002 is_arg: true,
5003 index: index as u32,
5004 owner,
5005 },
5006 ));
5007 }
5008 // A parameter list cannot see the body, so a body `var` is not a binding the
5009 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
5010 // not let that eval write the body's `c`.
5011 let hides_body = if level == deepest {
5012 site_in_params
5013 } else {
5014 state.created_in_params
5015 };
5016 for (index, var) in state.vars.iter().enumerate() {
5017 let block = state
5018 .var_block
5019 .get(index)
5020 .copied()
5021 .unwrap_or(FUNCTION_SCOPE);
5022 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
5023 continue;
5024 }
5025 bindings.push((
5026 (
5027 owner as usize,
5028 depth_of(block),
5029 std::cmp::Reverse(index as u32),
5030 ),
5031 EvalVisible {
5032 name: var.name.clone(),
5033 is_arg: false,
5034 index: index as u32,
5035 owner,
5036 },
5037 ));
5038 }
5039 }
5040 // Innermost function first, then innermost block, then the later declaration
5041 // (which shadows the earlier one within a block).
5042 bindings.sort_by_key(|(priority, _)| *priority);
5043 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
5044 self.state().eval_sites.push(EvalSite {
5045 line: span.start.line,
5046 column: span.start.column,
5047 bindings,
5048 private_names,
5049 arguments_allowed,
5050 });
5051 }
5052
5053 /// The private names visible from the compiler's current position, innermost last.
5054 ///
5055 /// A direct `eval` inherits these because private names are lexically scoped
5056 /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
5057 /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
5058 /// shadowing `ClassPlan::find` gives a use site inside the body.
5059 fn visible_private_names(&self) -> Vec<EvalPrivate> {
5060 let mut out: Vec<EvalPrivate> = Vec::new();
5061 for scope in &self.private_scopes {
5062 for (name, use_) in scope {
5063 if out.iter().any(|entry| &entry.name == name) {
5064 continue;
5065 }
5066 out.push(EvalPrivate {
5067 name: name.clone(),
5068 kind: match use_.kind {
5069 PrivateKind::Field => EvalPrivateKind::Field,
5070 PrivateKind::Method => EvalPrivateKind::Method,
5071 PrivateKind::Getter => EvalPrivateKind::Getter,
5072 PrivateKind::Setter => EvalPrivateKind::Setter,
5073 },
5074 setter: use_.setter.clone(),
5075 });
5076 }
5077 }
5078 out
5079 }
5080
5081 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
5082 ///
5083 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
5084 /// a bare identifier callee counts.
5085 /// Record everything a direct `eval` call site has to tell the runtime.
5086 ///
5087 /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
5088 /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
5089 /// entirely. Missing the tail-call path is not hypothetical — it is why
5090 /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
5091 /// names were otherwise wired through.
5092 fn note_direct_eval(&mut self, expr: &Expr) {
5093 if !Self::is_direct_eval(expr) {
5094 return;
5095 }
5096 // Every enclosing function is affected too: the eval sees the whole scope chain,
5097 // and a closure it creates can capture a binding of any of them.
5098 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
5099 // because the closure the eval builds outlives the loop iteration.
5100 for state in &mut self.stack {
5101 state.has_direct_eval = true;
5102 }
5103 let block = self.cur().current_block;
5104 let in_params = self.cur().in_params;
5105 // The private names are snapshotted **here**, at the call site, not when the sites
5106 // are materialised: materialisation happens once the whole function is compiled, by
5107 // which point every class scope has been popped and the answer would always be
5108 // empty.
5109 let private = self.visible_private_names();
5110 // An arrow has no `arguments` of its own and inherits the restriction from the
5111 // nearest real function: `x = () => { () => eval('arguments') }` is still a
5112 // class field initializer's arrow, and still has no `arguments` to see.
5113 let arguments_allowed = !self
5114 .stack
5115 .iter()
5116 .rev()
5117 .find(|state| !state.is_arrow)
5118 .is_some_and(|state| state.no_arguments_binding);
5119 self.state().pending_eval_sites.push((
5120 expr.span,
5121 block,
5122 in_params,
5123 private,
5124 arguments_allowed,
5125 ));
5126 }
5127
5128 fn is_direct_eval(expr: &Expr) -> bool {
5129 matches!(
5130 &expr.kind,
5131 ExprKind::Call { callee, .. }
5132 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
5133 )
5134 }
5135
5136 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5137 match &expr.kind {
5138 ExprKind::Number(value) => self.push_number(*value),
5139 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
5140 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
5141 ExprKind::Null => self.emit(Opcode::Null, &[]),
5142 ExprKind::String(text) => self.push_string(text),
5143 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
5144 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
5145 ExprKind::This => self.this_expression(),
5146 ExprKind::NewTarget => self.new_target_expression(),
5147 ExprKind::Paren(inner) => self.expr(inner)?,
5148 ExprKind::Binary { op, left, right } => {
5149 self.expr(left)?;
5150 self.expr(right)?;
5151 self.emit(binary_opcode(*op), &[]);
5152 }
5153 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
5154 ExprKind::Unary {
5155 op: UnaryOp::Minus,
5156 argument,
5157 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
5158 let ExprKind::Number(value) = argument.unparen().kind else {
5159 unreachable!("matched above")
5160 };
5161 // The reference folds a negative literal only when the negation is
5162 // exact in the integer range: `-1` becomes `push_minus1` and
5163 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
5164 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
5165 // `-Infinity`, not `Infinity` — and folding a fraction would change
5166 // which instruction the reference emits.
5167 let negated = -value;
5168 // `-2147483648` is deliberately excluded: its magnitude is one past
5169 // `i32::MAX`, so the reference sends it through the constant pool and
5170 // negates at run time instead.
5171 if value > 0.0
5172 && negated == negated.trunc()
5173 && negated >= -(i32::MAX as f64)
5174 && negated < 0.0
5175 {
5176 self.push_number(negated);
5177 } else {
5178 self.push_number(value);
5179 self.emit(Opcode::Neg, &[]);
5180 }
5181 }
5182 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
5183 ExprKind::Conditional { test, cons, alt } => {
5184 let else_label = self.new_label();
5185 let end_label = self.new_label();
5186 self.expr(test)?;
5187 self.emit_jump(Opcode::IfFalse, else_label, &[]);
5188 self.expr(cons)?;
5189 self.emit_jump(Opcode::Goto, end_label, &[]);
5190 self.place_label(else_label);
5191 self.expr(alt)?;
5192 self.place_label(end_label);
5193 }
5194 ExprKind::Assign { op, target, value } => {
5195 let discard = std::mem::take(&mut self.discard_root);
5196 self.assign(*op, target, value, discard)?
5197 }
5198 ExprKind::Update {
5199 op,
5200 argument,
5201 prefix,
5202 } => self.update(*op, argument, *prefix)?,
5203 ExprKind::Sequence(items) => {
5204 for (index, item) in items.iter().enumerate() {
5205 self.expr(item)?;
5206 if index + 1 != items.len() {
5207 self.emit(Opcode::Drop, &[]);
5208 }
5209 }
5210 }
5211 ExprKind::Call { .. } => self.chain_link_top(expr)?,
5212 ExprKind::Member { .. } => self.chain_link_top(expr)?,
5213 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
5214 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
5215 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
5216 ExprKind::Template(template) => self.template_literal(template)?,
5217 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
5218 ExprKind::New { callee, arguments } => {
5219 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
5220 // The `dup` is not redundant: `call_constructor` takes the
5221 // constructor twice, once as the target and once as `new.target`,
5222 // which is what makes `new.target === C` inside the body.
5223 self.expr(callee)?;
5224 self.emit(Opcode::Dup, &[]);
5225 let args = arguments.as_deref().unwrap_or(&[]);
5226 if Self::has_spread(args) {
5227 // `C C array`: the duplicated callee is already both the target
5228 // and `new.target`, so no reordering is needed before `apply 1`.
5229 self.argument_array(args)?;
5230 self.emit(Opcode::Apply, &[Op::Int(1)]);
5231 return Ok(());
5232 }
5233 for argument in args {
5234 self.expr(argument)?;
5235 }
5236 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
5237 }
5238 ExprKind::Class(class) => self.class_definition(class, true)?,
5239 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
5240 ExprKind::Yield { argument, delegate } => {
5241 self.yield_expression(argument.as_deref(), *delegate)?
5242 }
5243 ExprKind::Await(argument) => self.await_expression(argument)?,
5244 ExprKind::RegExp { pattern, flags } => {
5245 // A literal is compiled *here*, at parse time, not when the line runs. The
5246 // spec is explicit that an invalid pattern is an early error (§12.9.4:
5247 // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
5248 // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
5249 // also validates `\p{…}` names: 163 conformance cases are patterns that have
5250 // to be rejected before any code runs.
5251 //
5252 // This is the whole reason the engine lives in its own crate rather than
5253 // inside `quickjs-pure`: the compiler could not depend on the interpreter
5254 // (`pure` depends on `compile`), but both need this.
5255 // The lexer already rejected an unknown or repeated flag, so an unparsable
5256 // flag string here would be a bug in the lexer rather than in the script;
5257 // fall back to the default flags instead of inventing a second message.
5258 let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
5259 let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
5260 SyntaxError::new(
5261 format!("invalid regular expression: {}", error.message),
5262 expr.span,
5263 )
5264 })?;
5265 // The tree is thrown away and rebuilt when the literal first runs: keeping it
5266 // would mean serialising the syntax tree into the function's constant pool,
5267 // and a literal is created once per evaluation of its expression anyway.
5268 let _ = parsed;
5269 // The pattern and its flags travel as two string constants; `regexp` builds
5270 // the object. A dedicated opcode (rather than a call to the constructor) is
5271 // what the reference does too, so that a literal never goes through the
5272 // public `RegExp` function and its string-coercion rules.
5273 self.push_string(&Wtf8::new(pattern));
5274 self.push_string(&Wtf8::new(flags));
5275 self.emit(Opcode::Regexp, &[]);
5276 }
5277 ExprKind::Arrow(func) => {
5278 let function = self.compile_function(func)?;
5279 let index = self.push_constant(Constant::Function(Box::new(function)));
5280 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5281 }
5282 ExprKind::Function(func) => {
5283 let function = self.compile_function_with_name(func, true)?;
5284 let index = self.push_constant(Constant::Function(Box::new(function)));
5285 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5286 }
5287 // `import.meta`: the host fills a per-module object at link time.
5288 ExprKind::ImportMeta => {
5289 self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
5290 }
5291 // `import("x")` compiles to a two-slot push followed by one opcode: the
5292 // specifier, then the options object. Both are evaluated, in that order, because
5293 // §13.3.10.1 numbers them that way and their side effects are observable — the
5294 // absent second argument is a literal `undefined`, which evaluates to nothing.
5295 ExprKind::ImportCall(specifier, options) => {
5296 self.expr(specifier)?;
5297 match options {
5298 Some(options) => self.expr(options)?,
5299 None => {
5300 self.emit(Opcode::Undefined, &[]);
5301 }
5302 }
5303 self.emit(Opcode::Import, &[]);
5304 }
5305 ExprKind::PrivateIn { name, object } => {
5306 // `#x in o`: the object, then the binding, then one opcode which decides what
5307 // to do with the second operand. A field's binding holds a symbol and the
5308 // answer is an own-property test; a method's holds a function and the answer
5309 // is a brand check — both live in `private_in`, so the compiler emits the
5310 // same instruction for either.
5311 self.expr(object)?;
5312 self.emit_var(VarAction::Get, &format!("#{}", name.name));
5313 self.emit(Opcode::PrivateIn, &[]);
5314 }
5315 _ => {
5316 return Err(SyntaxError::new(
5317 "this expression form is not supported by the compiler yet",
5318 expr.span,
5319 ));
5320 }
5321 }
5322 Ok(())
5323 }
5324
5325 /// Build one array holding the evaluated call arguments, which is how a call
5326 /// containing a spread is compiled: the reference does the same, building the
5327 /// list on the stack and handing it to `apply`.
5328 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5329 let elements: Vec<Option<ArrayElement>> = arguments
5330 .iter()
5331 .map(|argument| match &argument.unparen().kind {
5332 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
5333 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
5334 })
5335 .collect();
5336 self.array_literal(&elements, Span::default())
5337 }
5338
5339 /// Whether any argument is a spread, which is what selects the `apply` form.
5340 fn has_spread(arguments: &[Expr]) -> bool {
5341 arguments
5342 .iter()
5343 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
5344 }
5345
5346 /// Compile `a${x}b`.
5347 ///
5348 /// A template is a `+` chain built left to right: the leading chunk (or an empty
5349 /// string when the template starts with a substitution), then for each
5350 /// substitution its value, `to_propkey` and `add`, then the following chunk when
5351 /// it is not empty. `to_propkey` is what makes a number or object substitute the
5352 /// way `ToString` would while leaving the result a string for `add` to
5353 /// concatenate.
5354 ///
5355 /// The chunk is an atom rather than a constant-pool string, because a non-empty
5356 /// chunk always lands where a value is pushed and `push_atom_value` is the
5357 /// instruction the reference uses for it; the empty first chunk has its own
5358 /// zero-byte form.
5359 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
5360 let first = template.quasis.first();
5361 match first.and_then(|quasi| quasi.cooked.clone()) {
5362 Some(text) if !text.is_empty() => {
5363 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5364 }
5365 // Either the template begins with a substitution, or the chunk is
5366 // empty — in both cases the chain needs a string to start from.
5367 _ => self.emit(Opcode::PushEmptyString, &[]),
5368 }
5369 for (index, expression) in template.expressions.iter().enumerate() {
5370 self.expr(expression)?;
5371 self.emit(Opcode::ToPropkey, &[]);
5372 self.emit(Opcode::Add, &[]);
5373 if let Some(text) = template
5374 .quasis
5375 .get(index + 1)
5376 .and_then(|quasi| quasi.cooked.clone())
5377 && !text.is_empty()
5378 {
5379 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5380 self.emit(Opcode::Add, &[]);
5381 }
5382 }
5383 Ok(())
5384 }
5385
5386 /// Compile an object literal.
5387 ///
5388 /// The object is built in place: `object` pushes it, and each property leaves it
5389 /// on the stack with one field more, so no temporary is needed and later
5390 /// properties can overwrite earlier ones.
5391 ///
5392 /// The instruction depends on *how* the property was written, not on what kind
5393 /// of value it holds:
5394 ///
5395 /// | source | instruction |
5396 /// |---|---|
5397 /// | `{ a: v }` | `define_field a` |
5398 /// | `{ __proto__: v }` | `set_proto` |
5399 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
5400 /// | `{ m() {} }` | `define_method m,4` |
5401 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
5402 /// | `{ [k]() {} }` | `define_method_computed 4` |
5403 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
5404 ///
5405 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
5406 /// key itself, which is why the trailing `drop` is absent there too.
5407 /// `tag`…``: a call whose first argument is the call site's template object.
5408 ///
5409 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
5410 /// array beside it, so `String.raw` can read the source text back. It is a constant
5411 /// because its contents never change; the reference builds one per call site and
5412 /// reuses it, while this builds one per evaluation, which only `tag` code that
5413 /// compares template objects across calls could tell apart.
5414 /// A fresh template site id. See [`Constant::Template`].
5415 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
5416 let cooked = quasi
5417 .quasis
5418 .iter()
5419 .map(|chunk| chunk.cooked.clone())
5420 .collect();
5421 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
5422 let index = self.push_constant(Constant::Template {
5423 site: next_template_site(),
5424 cooked,
5425 raw,
5426 });
5427 let count = quasi.expressions.len() + 1;
5428 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
5429 if let ExprKind::Member {
5430 object, property, ..
5431 } = &tag.unparen().kind
5432 {
5433 self.expr(object)?;
5434 match property {
5435 MemberProp::Ident(name) => {
5436 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5437 }
5438 MemberProp::Computed(key) => {
5439 self.expr(key)?;
5440 self.emit(Opcode::GetArrayEl2, &[]);
5441 }
5442 MemberProp::Private(name) => {
5443 let binding = format!("#{}", name.name);
5444 let (kind, _) = self.private_use(&binding, tag.span)?;
5445 self.private_callee(&binding, kind)?;
5446 }
5447 }
5448 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5449 for expression in &quasi.expressions {
5450 self.expr(expression)?;
5451 }
5452 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
5453 return Ok(());
5454 }
5455 self.expr(tag)?;
5456 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5457 for expression in &quasi.expressions {
5458 self.expr(expression)?;
5459 }
5460 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
5461 Ok(())
5462 }
5463
5464 fn object_literal(
5465 &mut self,
5466 properties: &[ObjectProperty],
5467 span: Span,
5468 ) -> Result<(), SyntaxError> {
5469 self.emit(Opcode::Object, &[]);
5470 for property in properties {
5471 match property {
5472 ObjectProperty::Spread(value) => {
5473 // `copy_data_properties` takes the target, the source and an
5474 // exclusion list; a literal `null` means "exclude nothing".
5475 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
5476 // exclusion list by stack offset.
5477 self.expr(spread_argument(value))?;
5478 self.emit(Opcode::Null, &[]);
5479 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
5480 self.emit(Opcode::Drop, &[]);
5481 self.emit(Opcode::Drop, &[]);
5482 }
5483 ObjectProperty::Property {
5484 key,
5485 value,
5486 kind,
5487 shorthand,
5488 span: property_span,
5489 } => match key {
5490 PropName::Computed(key_expr) => {
5491 self.expr(key_expr)?;
5492 match kind {
5493 PropertyKind::Value => {
5494 self.emit(Opcode::ToPropkey, &[]);
5495 self.expr(value)?;
5496 self.set_name_if_anonymous_computed(value);
5497 self.emit(Opcode::DefineArrayEl, &[]);
5498 // `define_array_el` leaves the object and the key;
5499 // the key is no longer needed.
5500 self.emit(Opcode::Drop, &[]);
5501 }
5502 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5503 self.emit_method_function(value)?;
5504 self.emit(
5505 Opcode::DefineMethodComputed,
5506 &[Op::Int(define_method_flags(*kind))],
5507 );
5508 }
5509 }
5510 }
5511 PropName::Literal(key) => {
5512 let name = self.property_key_text(key, *property_span)?;
5513 match kind {
5514 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5515 self.emit_method_function(value)?;
5516 self.emit(
5517 Opcode::DefineMethod,
5518 &[
5519 Op::Atom(Atom::from_wtf8(&name)),
5520 Op::Int(define_method_flags(*kind)),
5521 ],
5522 );
5523 }
5524 PropertyKind::Value => {
5525 self.expr(value)?;
5526 // `{__proto__: x}` sets the prototype instead of
5527 // creating a property; the shorthand `{__proto__}`
5528 // is an ordinary property and does not.
5529 if name == "__proto__" && !shorthand {
5530 self.emit(Opcode::SetProto, &[]);
5531 } else {
5532 self.set_name_if_anonymous(value, &name);
5533 self.emit(
5534 Opcode::DefineField,
5535 &[Op::Atom(Atom::from_wtf8(&name))],
5536 );
5537 }
5538 }
5539 }
5540 }
5541 PropName::Private(_) => {
5542 return Err(SyntaxError::new(
5543 "private names are not valid in object literals",
5544 *property_span,
5545 ));
5546 }
5547 },
5548 }
5549 }
5550 let _ = span;
5551 Ok(())
5552 }
5553
5554 /// Emit the function a method/accessor property defines.
5555 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
5556 self.expr(value)
5557 }
5558
5559 /// The name a literal property key contributes.
5560 ///
5561 /// String keys are used as written. A numeric key is converted the way
5562 /// `ToString` would convert it, because the atom is made from that spelling:
5563 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5564 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5565 match key {
5566 PropKey::Str(text) => Ok(text.clone()),
5567 PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5568 }
5569 }
5570
5571 /// Compile an optional chain.
5572 ///
5573 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5574 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5575 /// `undefined`. So the chain is compiled with one end label and every guard
5576 /// jumps to it. The parser hands us the extent of that spine as an
5577 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5578 /// exactly the scope the label has to cover.
5579 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5580 let end = self.new_label();
5581 self.chain_link(inner, end)?;
5582 self.place_label(end);
5583 Ok(())
5584 }
5585
5586 /// A member access or call reached from outside any optional chain.
5587 ///
5588 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5589 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5590 /// still created because [`Self::chain_link`] takes it, and placing it at the
5591 /// end is a no-op that keeps a single code path.
5592 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5593 let end = self.new_label();
5594 self.chain_link(expr, end)?;
5595 self.place_label(end);
5596 Ok(())
5597 }
5598
5599 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5600 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5601 match &expr.kind {
5602 ExprKind::Member {
5603 object,
5604 property,
5605 optional,
5606 } => {
5607 // `super.x` is not a lookup on a value: it starts at the home object's
5608 // prototype and keeps `this` as the receiver, so it cannot go through
5609 // `chain_link` and the ordinary field read.
5610 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5611 self.super_base();
5612 match property {
5613 MemberProp::Ident(name) => self.emit(
5614 Opcode::PushAtomValue,
5615 &[Op::Atom(Atom::from_text(&name.name))],
5616 ),
5617 MemberProp::Computed(index) => self.expr(index)?,
5618 MemberProp::Private(_) => {
5619 return Err(SyntaxError::new(
5620 "private fields are not supported by the compiler yet",
5621 expr.span,
5622 ));
5623 }
5624 }
5625 self.emit(Opcode::GetSuperValue, &[]);
5626 return Ok(());
5627 }
5628 self.chain_link(object, end)?;
5629 if *optional {
5630 self.optional_guard(end);
5631 }
5632 match property {
5633 // `.length` has its own opcode. The reference emits it for every
5634 // object, not just arrays, so a name-based rule is right and
5635 // cheaper than the generic field read.
5636 MemberProp::Ident(name) if name.name == "length" => {
5637 self.emit(Opcode::GetLength, &[]);
5638 }
5639 MemberProp::Ident(name) => {
5640 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5641 }
5642 MemberProp::Computed(index) => {
5643 self.expr(index)?;
5644 self.emit(Opcode::GetArrayEl, &[]);
5645 }
5646 MemberProp::Private(name) => {
5647 // The binding comes from the class scope, so a read from outside the
5648 // class cannot name it at all. `?.` checks the object, not the field:
5649 // `o?.#x` guards on `o` being nullish.
5650 let binding = format!("#{}", name.name);
5651 let (kind, _) = self.private_use(&binding, expr.span)?;
5652 self.private_load(&binding, kind, expr.span)?;
5653 }
5654 }
5655 Ok(())
5656 }
5657 ExprKind::Call {
5658 callee,
5659 arguments,
5660 optional,
5661 } => {
5662 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5663 // cannot: it reads the function and then calls it with no
5664 // receiver at all. The reference's answer is to keep the object
5665 // under the function value — `get_field2` reads a field and leaves
5666 // its base in place — and to use `call_method`, which takes the
5667 // receiver from the stack. Missing this does not just cost an
5668 // instruction, it loses the `this` binding.
5669 if let ExprKind::Member {
5670 object,
5671 property,
5672 optional: member_optional,
5673 } = &callee.unparen().kind
5674 {
5675 // `super.m()` reads the method off the home object's prototype but
5676 // calls it with `this`, so the receiver goes under the read instead of
5677 // being replaced by it.
5678 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5679 self.super_base();
5680 match property {
5681 MemberProp::Ident(name) => self.emit(
5682 Opcode::PushAtomValue,
5683 &[Op::Atom(Atom::from_text(&name.name))],
5684 ),
5685 MemberProp::Computed(index) => self.expr(index)?,
5686 MemberProp::Private(_) => {
5687 return Err(SyntaxError::new(
5688 "private fields are not supported by the compiler yet",
5689 expr.span,
5690 ));
5691 }
5692 }
5693 // The two-output form would drop the receiver; this one replaces
5694 // the prototype and the key, leaving `this` underneath.
5695 self.emit(Opcode::GetArrayEl, &[]);
5696 if Self::has_spread(arguments) {
5697 self.argument_array(arguments)?;
5698 self.emit(Opcode::Perm3, &[]);
5699 self.emit(Opcode::Apply, &[Op::Int(0)]);
5700 return Ok(());
5701 }
5702 for argument in arguments {
5703 self.expr(argument)?;
5704 }
5705 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5706 return Ok(());
5707 }
5708 self.chain_link(object, end)?;
5709 if *member_optional {
5710 self.optional_guard(end);
5711 }
5712 match property {
5713 MemberProp::Ident(name) => {
5714 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5715 }
5716 MemberProp::Computed(index) => {
5717 self.expr(index)?;
5718 // The key is not needed after the read, so this is the
5719 // two-output form: object, value.
5720 self.emit(Opcode::GetArrayEl2, &[]);
5721 }
5722 MemberProp::Private(name) => {
5723 // The receiver is already under the callee, which is exactly the
5724 // shape `call_method` and `apply` want — so nothing is dropped.
5725 let binding = format!("#{}", name.name);
5726 let (kind, _) = self.private_use(&binding, expr.span)?;
5727 self.private_callee(&binding, kind)?;
5728 }
5729 }
5730 if Self::has_spread(arguments) {
5731 // Stack is `obj func`; the array goes on top, then `perm3`
5732 // reorders to the `func this array` that `apply` wants.
5733 self.argument_array(arguments)?;
5734 self.emit(Opcode::Perm3, &[]);
5735 self.emit(Opcode::Apply, &[Op::Int(0)]);
5736 return Ok(());
5737 }
5738 for argument in arguments {
5739 self.expr(argument)?;
5740 }
5741 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5742 return Ok(());
5743 }
5744 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5745 // with `get_field2` so the base stays under it, and on the short-circuit
5746 // path pushes an extra `undefined` as a placeholder receiver — the call
5747 // then throws, which is what calling a missing optional chain should do.
5748 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5749 && let ExprKind::Member {
5750 object,
5751 property,
5752 optional: member_optional,
5753 } = &inner.unparen().kind
5754 {
5755 let call = self.new_label();
5756 // A guard target of its own: the outer `end` skips the whole
5757 // expression, and a short-circuited receiver still has to reach the
5758 // call so that calling it throws.
5759 let short = self.new_label();
5760 self.chain_link(object, end)?;
5761 if *member_optional {
5762 self.optional_guard(short);
5763 }
5764 match property {
5765 MemberProp::Ident(name) => {
5766 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5767 }
5768 MemberProp::Computed(index) => {
5769 self.expr(index)?;
5770 self.emit(Opcode::GetArrayEl2, &[]);
5771 }
5772 MemberProp::Private(name) => {
5773 let binding = format!("#{}", name.name);
5774 let (kind, _) = self.private_use(&binding, expr.span)?;
5775 self.private_callee(&binding, kind)?;
5776 }
5777 }
5778 self.emit_jump(Opcode::Goto, call, &[]);
5779 self.place_label(short);
5780 self.emit(Opcode::Undefined, &[]);
5781 self.place_label(call);
5782 if Self::has_spread(arguments) {
5783 self.argument_array(arguments)?;
5784 self.emit(Opcode::Perm3, &[]);
5785 self.emit(Opcode::Apply, &[Op::Int(0)]);
5786 return Ok(());
5787 }
5788 for argument in arguments {
5789 self.expr(argument)?;
5790 }
5791 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5792 return Ok(());
5793 }
5794 self.chain_link(callee, end)?;
5795 if *optional {
5796 self.optional_guard(end);
5797 }
5798 if Self::has_spread(arguments) {
5799 // `func array -> func undefined array`, which is the plain-call
5800 // form of `apply`: the receiver is `undefined`.
5801 self.argument_array(arguments)?;
5802 self.emit(Opcode::Undefined, &[]);
5803 self.emit(Opcode::Swap, &[]);
5804 self.emit(Opcode::Apply, &[Op::Int(0)]);
5805 return Ok(());
5806 }
5807 for argument in arguments {
5808 self.expr(argument)?;
5809 }
5810 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5811 Ok(())
5812 }
5813 _ => self.expr(expr),
5814 }
5815 }
5816
5817 /// Compile `expr` as a tail call when it is one, reporting whether it was.
5818 ///
5819 /// `tail_call` reuses the current frame instead of pushing a new one, so a
5820 /// tail-recursive function runs in constant stack space. It also has to be the
5821 /// *last* thing the function does, which is why only a `return` reaches here.
5822 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5823 let ExprKind::Call {
5824 callee,
5825 arguments,
5826 optional: false,
5827 } = &expr.unparen().kind
5828 else {
5829 return Ok(false);
5830 };
5831 // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5832 // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5833 // as an ordinary call costs the one frame the optimisation was saving and keeps the
5834 // semantics — the alternative was reaching the spread expression below and failing
5835 // with "this expression form is not supported", which is how `return super.m(...a)`
5836 // stopped compiling. Checked before anything is emitted, because the decision cannot
5837 // be taken back once `super_base` or a `get_field2` is on the stack.
5838 if Self::has_spread(arguments) {
5839 return Ok(false);
5840 }
5841 let end = self.new_label();
5842 if let ExprKind::Member {
5843 object,
5844 property,
5845 optional: false,
5846 } = &callee.unparen().kind
5847 {
5848 // `super.m()` in tail position is still an ordinary method call with `this`
5849 // as the receiver; only the read of the method differs.
5850 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5851 self.super_base();
5852 match property {
5853 MemberProp::Ident(name) => self.emit(
5854 Opcode::PushAtomValue,
5855 &[Op::Atom(Atom::from_text(&name.name))],
5856 ),
5857 MemberProp::Computed(index) => self.expr(index)?,
5858 MemberProp::Private(_) => return Ok(false),
5859 }
5860 self.emit(Opcode::GetArrayEl, &[]);
5861 for argument in arguments {
5862 self.expr(argument)?;
5863 }
5864 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5865 self.place_label(end);
5866 return Ok(true);
5867 }
5868 self.chain_link(object, end)?;
5869 match property {
5870 MemberProp::Ident(name) => {
5871 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5872 }
5873 MemberProp::Computed(index) => {
5874 self.expr(index)?;
5875 self.emit(Opcode::GetArrayEl2, &[]);
5876 }
5877 MemberProp::Private(_) => return Ok(false),
5878 }
5879 for argument in arguments {
5880 self.expr(argument)?;
5881 }
5882 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5883 self.place_label(end);
5884 return Ok(true);
5885 }
5886 self.chain_link(callee, end)?;
5887 for argument in arguments {
5888 self.expr(argument)?;
5889 }
5890 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5891 self.place_label(end);
5892 Ok(true)
5893 }
5894
5895 /// The `?.` guard: keep the value if it is neither null nor undefined,
5896 /// otherwise replace it with `undefined` and leave the whole chain.
5897 fn optional_guard(&mut self, end: Label) {
5898 let cont = self.new_label();
5899 self.emit(Opcode::Dup, &[]);
5900 self.emit(Opcode::IsUndefinedOrNull, &[]);
5901 self.emit_jump(Opcode::IfFalse, cont, &[]);
5902 self.emit(Opcode::Drop, &[]);
5903 self.emit(Opcode::Undefined, &[]);
5904 self.emit_jump(Opcode::Goto, end, &[]);
5905 self.place_label(cont);
5906 }
5907
5908 fn push_number(&mut self, value: f64) {
5909 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5910 // goes into the constant pool.
5911 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5912 let int = value as i32;
5913 if (-1..=7).contains(&int) {
5914 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5915 return;
5916 }
5917 if (-128..=127).contains(&int) {
5918 self.emit(Opcode::PushI8, &[Op::Int(int)]);
5919 return;
5920 }
5921 if (-32768..=32767).contains(&int) {
5922 self.emit(Opcode::PushI16, &[Op::Int(int)]);
5923 return;
5924 }
5925 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5926 return;
5927 }
5928 let index = self.push_constant(Constant::Number(value));
5929 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5930 }
5931
5932 /// Push a `BigInt` literal.
5933 ///
5934 /// A value that fits an `i32` uses the immediate form, which is what the reference
5935 /// emits too; anything larger goes into the constant pool, because the operand of
5936 /// `push_bigint` is only four bytes wide.
5937 fn push_bigint(&mut self, digits: &str, radix: u32) {
5938 if radix == 10
5939 && let Ok(value) = digits.parse::<i64>()
5940 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5941 {
5942 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5943 return;
5944 }
5945 let index = self.push_constant(Constant::BigInt {
5946 digits: digits.to_string(),
5947 radix,
5948 });
5949 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5950 }
5951
5952 fn push_string(&mut self, text: &Wtf8) {
5953 if text.is_empty() {
5954 self.emit(Opcode::PushEmptyString, &[]);
5955 return;
5956 }
5957 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5958 }
5959
5960 /// Name an anonymous function from the binding it is assigned to.
5961 ///
5962 /// `var f = function(){}` produces a function whose `name` is `f`, which the
5963 /// runtime cannot know without being told: the function object is created
5964 /// before the store. `set_name` carries the name across.
5965 fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5966 if !value.is_anonymous_function_definition() {
5967 return;
5968 }
5969 // A class cannot use `set_name`, because its static field initialisers have already
5970 // run by the time the store happens and they can see `this.name`:
5971 // `var E = class { static f = this.name }` has to answer `"E"`. The reference patches
5972 // the `define_class` instruction's name operand instead, which is why
5973 // `set_class_name` is a compile-time marker with no runtime effect
5974 // (`class-name-static-initializer-anonymous`).
5975 if matches!(value.unparen().kind, ExprKind::Class(_)) {
5976 if let Some(index) = self.last_define_class() {
5977 let atom = Atom::from_wtf8(name);
5978 if let Some(Insn::Fixed { operands, .. }) = self.state().insns.get_mut(index) {
5979 // `define_class <atom> <flags>`: the name is operand 0.
5980 operands[0] = Op::Atom(atom);
5981 }
5982 }
5983 return;
5984 }
5985 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5986 }
5987
5988 /// The index of the most recent `define_class` in this function's instruction stream.
5989 ///
5990 /// A backwards scan, because everything the class body emitted for the *enclosing*
5991 /// function is still there after it — the static initialiser's call, the class
5992 /// binding's store, `leave_scope` — and only the `define_class` carries the name.
5993 fn last_define_class(&self) -> Option<usize> {
5994 self.cur().insns.iter().rposition(|insn| {
5995 matches!(
5996 insn,
5997 Insn::Fixed {
5998 op: Opcode::DefineClass,
5999 ..
6000 }
6001 )
6002 })
6003 }
6004
6005 /// The same, for a computed key: the name comes from the value on the stack
6006 /// rather than from an atom, so a different instruction carries it.
6007 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
6008 if value.is_anonymous_function_definition() {
6009 self.emit(Opcode::SetNameComputed, &[]);
6010 }
6011 }
6012
6013 /// Compile a function body that exists only in the compiler's head — a class's
6014 /// implicit constructor or its field initialiser.
6015 ///
6016 /// Everything structural is the same as a written function: a fresh `FnState`, its
6017 /// own body block, and resolution while the frame is still on the stack. Only the
6018 /// statements differ.
6019 fn compile_synthetic_function(
6020 &mut self,
6021 name: &str,
6022 strict: bool,
6023 span: Span,
6024 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
6025 ) -> Result<CompiledFunction, SyntaxError> {
6026 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
6027 state.span = Some((span.start.offset as usize, span.end.offset as usize));
6028 state.strict = strict;
6029 state.created_in_block = self.cur().current_block;
6030 state.with_names = self.cur().with_names.clone();
6031 state.line = span.start.line;
6032 state.column = span.start.column;
6033 let depth = self.stack.len();
6034 self.stack.push(state);
6035 let body_key = span.start.offset as u64;
6036 self.push_block(body_key, NO_PARENT);
6037 self.state().body_block = body_key;
6038 let result = (|| {
6039 self.emit_scope_enter(body_key);
6040 body(self)?;
6041 if self.end_is_reachable() {
6042 self.emit(Opcode::ReturnUndef, &[]);
6043 }
6044 Ok(())
6045 })();
6046 if result.is_err() {
6047 self.stack.truncate(depth);
6048 return result.map(|()| unreachable!());
6049 }
6050 Ok(self.finish_current())
6051 }
6052
6053 /// The implicit return of a class constructor.
6054 ///
6055 /// A constructor that falls off the end initialises its instance fields first, and a
6056 /// derived one returns `this` — which is what makes `new D()` the object `super()`
6057 /// built rather than `undefined`.
6058 fn emit_class_constructor_tail(&mut self) {
6059 match self.cur().ctor_kind {
6060 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
6061 // Nothing to install: a base constructor did it in its prologue and a derived
6062 // one at each `super()` site, which is where `this` first exists.
6063 CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
6064 CtorKind::Derived => {
6065 // `get_loc_check` rather than `get_loc`: reaching the end without ever
6066 // running `super()` is a ReferenceError, not `undefined`.
6067 self.emit_var(VarAction::Get, "this");
6068 self.emit(Opcode::Return, &[]);
6069 }
6070 }
6071 }
6072
6073 /// `yield expr` / `yield* expr`.
6074 ///
6075 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
6076 /// it to the caller and parks the frame. On resume the stack holds the value the
6077 /// caller passed *and* a "magic" number saying which method resumed it — `next`
6078 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
6079 /// `if_false <continue>` asks whether this was an ordinary `next`:
6080 ///
6081 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
6082 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
6083 /// and uses the value sitting under the magic number.
6084 ///
6085 /// A `throw` never reaches here: the interpreter unwinds instead (see
6086 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
6087 fn yield_expression(
6088 &mut self,
6089 argument: Option<&Expr>,
6090 delegate: bool,
6091 ) -> Result<(), SyntaxError> {
6092 if delegate {
6093 return self.yield_star(argument);
6094 }
6095 // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
6096 // does the same for the `return(v)` that can resume it — which is why an async
6097 // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
6098 // generator's is just `yield`.
6099 let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
6100 match argument {
6101 Some(value) => self.expr(value)?,
6102 None => self.emit(Opcode::Undefined, &[]),
6103 }
6104 if is_async {
6105 self.emit(Opcode::Await, &[]);
6106 self.state().has_await = true;
6107 }
6108 self.emit(Opcode::Yield, &[]);
6109 let resume = self.new_label();
6110 self.emit_jump(Opcode::IfFalse, resume, &[]);
6111 // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
6112 // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
6113 // finished the generator and never ran the `finally`.
6114 if is_async {
6115 self.emit(Opcode::Await, &[]);
6116 }
6117 self.emit_unwind_for_return(true);
6118 self.emit(Opcode::ReturnAsync, &[]);
6119 self.place_label(resume);
6120 // Nothing is emitted here: the value the caller passed to `next` *is* the value
6121 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
6122 // it through the ordinary expression-statement discard.
6123 Ok(())
6124 }
6125
6126 /// `yield* iterable`.
6127 ///
6128 /// The shape is the reference's, and it is a fall-through chain rather than a
6129 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
6130 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
6131 /// the inner iterator and finishes, `throw` forwards the exception into it and
6132 /// continues only if it has a `throw` method.
6133 ///
6134 /// The stack is `iter next catch value` throughout, `catch` being the offset
6135 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
6136 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
6137 match argument {
6138 Some(value) => self.expr(value)?,
6139 // The parser rejects a bare `yield*`, so this is unreachable in practice.
6140 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
6141 }
6142 // `for await of` is the same protocol as `for of` with two differences that matter
6143 // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
6144 // every `next()` result is a promise the delegate has to await.
6145 let is_async = self.cur().kind.is_async();
6146 self.emit(
6147 if is_async {
6148 Opcode::ForAwaitOfStart
6149 } else {
6150 Opcode::ForOfStart
6151 },
6152 &[],
6153 );
6154 self.emit(Opcode::Drop, &[]);
6155 self.emit(Opcode::Undefined, &[]);
6156 self.emit(Opcode::Undefined, &[]);
6157 let next = self.new_label();
6158 let resume = self.new_label();
6159 let finished = self.new_label();
6160 let rethrow = self.new_label();
6161 let throw_no_method = self.new_label();
6162 let done = self.new_label();
6163 self.place_label(next);
6164 self.emit(Opcode::IteratorNext, &[]);
6165 if is_async {
6166 self.emit(Opcode::Await, &[]);
6167 self.state().has_await = true;
6168 }
6169 self.emit(Opcode::IteratorCheckObject, &[]);
6170 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6171 self.emit_jump(Opcode::IfTrue, done, &[]);
6172 // The suspension. `resume` is both the label the return path jumps back to in order
6173 // to yield one more value and where the caller's answer arrives, as the value
6174 // followed by the magic number.
6175 //
6176 // The two forms differ in what they hand the suspension: `yield_star` takes the
6177 // result object itself, `async_yield_star` takes `.value`, because an async
6178 // generator awaits and re-wraps whatever it yields.
6179 self.place_label(resume);
6180 if is_async {
6181 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6182 self.emit(Opcode::AsyncYieldStar, &[]);
6183 } else {
6184 self.emit(Opcode::YieldStar, &[]);
6185 }
6186 self.emit(Opcode::Dup, &[]);
6187 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
6188 self.emit(Opcode::Drop, &[]);
6189 self.emit_jump(Opcode::Goto, next, &[]);
6190
6191 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
6192 self.place_label(rethrow);
6193 self.emit(Opcode::PushI32, &[Op::Int(2)]);
6194 self.emit(Opcode::StrictEq, &[]);
6195 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
6196 // A `return` closes the inner iterator; if it had none, the delegate simply
6197 // finishes with the requested value. In an async generator both the call and its
6198 // result are awaited, because the inner `return` may itself be async.
6199 if is_async {
6200 self.emit(Opcode::Await, &[]);
6201 }
6202 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
6203 self.emit_jump(Opcode::IfTrue, finished, &[]);
6204 if is_async {
6205 self.emit(Opcode::Await, &[]);
6206 }
6207 self.emit(Opcode::IteratorCheckObject, &[]);
6208 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6209 self.emit_jump(Opcode::IfFalse, resume, &[]);
6210 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6211 self.place_label(finished);
6212 self.emit(Opcode::Nip, &[]);
6213 self.emit(Opcode::Nip, &[]);
6214 self.emit(Opcode::Nip, &[]);
6215 // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
6216 // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
6217 // awaits the value in an async generator and then runs the same `finally`/iterator
6218 // unwinding a written `return` would. Skipping the unwinding made
6219 // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
6220 if is_async {
6221 self.emit(Opcode::Await, &[]);
6222 }
6223 self.emit_unwind_for_return(true);
6224 self.emit(Opcode::ReturnAsync, &[]);
6225
6226 // `throw(e)`: forward it into the inner iterator.
6227 self.place_label(throw_no_method);
6228 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
6229 let no_throw = self.new_label();
6230 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
6231 if is_async {
6232 self.emit(Opcode::Await, &[]);
6233 }
6234 self.emit(Opcode::IteratorCheckObject, &[]);
6235 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6236 self.emit_jump(Opcode::IfFalse, resume, &[]);
6237 self.emit_jump(Opcode::Goto, done, &[]);
6238 // No `throw` method: close the iterator, then report the spec's TypeError. The
6239 // `if_true` before the `await` is the reference's shape — the flag it consumes is
6240 // what `iterator_call` leaves behind, and a close that *did* find no `return`
6241 // method has nothing to await.
6242 self.place_label(no_throw);
6243 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
6244 let no_close = self.new_label();
6245 self.emit_jump(Opcode::IfTrue, no_close, &[]);
6246 if is_async {
6247 self.emit(Opcode::Await, &[]);
6248 }
6249 self.place_label(no_close);
6250 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
6251
6252 // The inner iterator finished: the delegate's value is the `yield*` expression's
6253 // value, so it is left on the stack for whatever consumes it.
6254 self.place_label(done);
6255 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6256 self.emit(Opcode::Nip, &[]);
6257 self.emit(Opcode::Nip, &[]);
6258 self.emit(Opcode::Nip, &[]);
6259 Ok(())
6260 }
6261
6262 /// `await expr`: exactly one instruction.
6263 ///
6264 /// No resume-magic branch follows it. The reference's `await` leaves a single value
6265 /// on the stack and completion is signalled by the `return_async` at the end of the
6266 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
6267 /// reference never emits, and a `for await` loop — which reaches `await` through the
6268 /// same opcode — would then spill a value the loop's unpacking does not expect.
6269 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
6270 self.expr(argument)?;
6271 self.emit(Opcode::Await, &[]);
6272 self.state().has_await = true;
6273 Ok(())
6274 }
6275
6276 /// The `super` base: the receiver followed by the home object's prototype.
6277 ///
6278 /// Everything `super` does needs both. A *read* starts at the prototype but reports
6279 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
6280 /// prototype but calls it with the receiver.
6281 fn super_base(&mut self) {
6282 self.this_expression();
6283 self.home_object();
6284 self.emit(Opcode::GetSuper, &[]);
6285 }
6286
6287 /// `[[HomeObject]]` as `super` sees it.
6288 ///
6289 /// A method, a constructor and a field initialiser each carry one — `set_home_object`
6290 /// put it there — so for them the special object *is* the answer. An arrow and a
6291 /// static block have none: they read the enclosing function's, which has to be
6292 /// materialised into a local, exactly as `this` is for an arrow.
6293 ///
6294 /// The name matches what the reference stores, so the disassembly agrees; it is not a
6295 /// name any program can write.
6296 fn home_object(&mut self) {
6297 if !self.cur().is_arrow {
6298 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
6299 return;
6300 }
6301 if let Some(target) = self.enclosing_function() {
6302 self.state_at(target).needs_home_object_local = true;
6303 self.declare_at(target, HOME_OBJECT);
6304 }
6305 self.emit_var(VarAction::Get, HOME_OBJECT);
6306 }
6307
6308 /// `super(args)`: construct the parent class and adopt the result as `this`.
6309 ///
6310 /// The parent is the prototype of the constructor that is running, which is exactly
6311 /// what `extends` set up. `new.target` is passed through unchanged so that
6312 /// `new.target` inside the parent is the class actually being constructed.
6313 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
6314 self.active_func_expression();
6315 self.emit(Opcode::GetSuper, &[]);
6316 self.new_target_expression();
6317 if Self::has_spread(arguments) {
6318 self.argument_array(arguments)?;
6319 self.emit(Opcode::Apply, &[Op::Int(1)]);
6320 } else {
6321 for argument in arguments {
6322 self.expr(argument)?;
6323 }
6324 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
6325 }
6326 // The value stays on the stack: `super()` is an expression, and a derived
6327 // constructor's `this` may only be initialised once.
6328 self.emit(Opcode::Dup, &[]);
6329 self.emit_var(VarAction::PutInitChecked, "this");
6330 // Instance fields are installed here, not at the top of the body: a derived
6331 // constructor has no `this` to install them on until `super()` returns. The
6332 // reference emits the same call at every `super()` site.
6333 self.call_field_initialiser();
6334 Ok(())
6335 }
6336
6337 /// `this` as a local, which every class constructor and field initialiser needs.
6338 ///
6339 /// The reference materialises the receiver into a local rather than reading
6340 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
6341 /// and a field initialiser has to see the final value.
6342 fn begin_this_local(&mut self) {
6343 self.declare_hidden_local("this", VarKind::Normal);
6344 self.emit(Opcode::PushThis, &[]);
6345 self.emit_var(VarAction::Put, "this");
6346 // The store is already at the top of the body, so `provide_this_local` has
6347 // nothing left to prepend. Without this the initialiser ended up with
6348 // `push_this; put_loc0 this` twice whenever the class also held a field
6349 // initialiser whose body read `this` through an arrow.
6350 self.state().has_this_prologue = true;
6351 }
6352
6353 /// Compile a constructor the class wrote.
6354 ///
6355 /// The flags have to be in place before the body is compiled, but
6356 /// `compile_function_with_name` creates its own state — so the caller's state is
6357 /// marked instead and the new one inherits it. That is the same trick the parameter
6358 /// prologue uses, and it keeps one code path for both.
6359 fn compile_class_constructor(
6360 &mut self,
6361 func: &ast::Function,
6362 has_heritage: bool,
6363 ) -> Result<CompiledFunction, SyntaxError> {
6364 let saved = self.cur().ctor_kind;
6365 self.state().class_ctor_pending = Some(if has_heritage {
6366 CtorKind::Derived
6367 } else {
6368 CtorKind::Base
6369 });
6370 let result = self.compile_function_with_name(func, false);
6371 self.state().ctor_kind = saved;
6372 self.state().class_ctor_pending = None;
6373 result
6374 }
6375
6376 /// The constructor a class gets when it does not declare one.
6377 ///
6378 /// A base class's is empty; a derived class's forwards every argument to the parent
6379 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
6380 /// instance field initialiser afterwards when the class has fields, which is why the
6381 /// initialiser is captured rather than inlined.
6382 fn compile_implicit_constructor(
6383 &mut self,
6384 class: &Class,
6385 has_heritage: bool,
6386 ) -> Result<CompiledFunction, SyntaxError> {
6387 self.compile_synthetic_function(
6388 "",
6389 true,
6390 Span::new(class.body_end, class.body_end),
6391 |compiler| {
6392 if has_heritage {
6393 // A derived constructor's `this` does not exist until `super()` returns,
6394 // so it starts in the dead zone and `init_ctor` fills it.
6395 compiler.declare("this", VarDef::lexical("this"));
6396 compiler.emit(
6397 Opcode::SetLocUninitialized,
6398 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6399 );
6400 compiler.emit(Opcode::InitCtor, &[]);
6401 compiler.emit(
6402 Opcode::PutLocCheckInit,
6403 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6404 );
6405 } else {
6406 compiler.begin_this_local();
6407 compiler.emit(Opcode::CheckCtor, &[]);
6408 }
6409 compiler.call_field_initialiser();
6410 // A derived constructor returns `this`, the object `super()` built. Without
6411 // this the implicit constructor fell through to `return_undef`, and `new B()`
6412 // handed back the empty object `construct` had made instead of the one the
6413 // parent constructor initialised.
6414 if has_heritage {
6415 compiler.emit_var(VarAction::Get, "this");
6416 compiler.emit(Opcode::Return, &[]);
6417 }
6418 Ok(())
6419 },
6420 )
6421 }
6422
6423 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
6424 ///
6425 /// A class with no instance fields leaves the binding `undefined`, and calling it
6426 /// would throw; the reference emits the same guard rather than branching at compile
6427 /// time because a class can be extended by a subclass whose fields still have to run.
6428 fn call_field_initialiser(&mut self) {
6429 let skip = self.new_label();
6430 self.emit_var(VarAction::Get, "<class_fields_init>");
6431 self.emit(Opcode::Dup, &[]);
6432 self.emit_jump(Opcode::IfFalse, skip, &[]);
6433 self.emit_var(VarAction::Get, "this");
6434 self.emit(Opcode::Swap, &[]);
6435 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6436 self.place_label(skip);
6437 self.emit(Opcode::Drop, &[]);
6438 }
6439
6440 /// The function that defines one class's fields on `this`, and runs its static blocks.
6441 ///
6442 /// `define_field` rather than `put_field`: a field is an own property created
6443 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
6444 /// `x = 1` field must not call the setter.
6445 ///
6446 /// One function serves the whole class: it is called once per instance (or once, for
6447 /// the static half) and walks the members in source order. Static blocks are compiled
6448 /// into the same function because they *are* part of the same sequence — `static a =
6449 /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
6450 /// different values, so the two kinds cannot be split apart.
6451 fn compile_field_initialiser(
6452 &mut self,
6453 items: &[StaticInitItem<'_>],
6454 span: Span,
6455 instance: bool,
6456 add_brand: bool,
6457 ) -> Result<CompiledFunction, SyntaxError> {
6458 self.compile_synthetic_function("", true, span, |compiler| {
6459 // A field initialiser and a static block are not functions, so neither has an
6460 // `arguments` of its own; see `FnState::no_arguments_binding`.
6461 let current = compiler.stack.len() - 1;
6462 compiler.stack[current].no_arguments_binding = true;
6463 if instance {
6464 // An instance initialiser always carries a `<home_object>` local, because the
6465 // brand block below reads it — even when that block turns out to be dead. The
6466 // reference has the same artefact, and the store is visible in its dump.
6467 let current = compiler.stack.len() - 1;
6468 compiler.stack[current].needs_home_object_local = true;
6469 }
6470 compiler.begin_this_local();
6471 if instance {
6472 // `this` gets the brand the prototype created, before any field is defined —
6473 // which is what makes `#m()` usable from inside a field initialiser.
6474 //
6475 // The reference always emits `push_false; if_false L; this; home; add_brand;
6476 // L:` and patches the `push_false` to `push_true` from the class parse when
6477 // the class has private methods; either way the branch folds, but the *mark*
6478 // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
6479 // `this` local from being fused into a `set_loc`.
6480 let skip = compiler.new_label();
6481 if add_brand {
6482 compiler.emit(Opcode::PushTrue, &[]);
6483 } else {
6484 compiler.emit(Opcode::PushFalse, &[]);
6485 }
6486 compiler.emit_jump(Opcode::IfFalse, skip, &[]);
6487 compiler.emit_var(VarAction::Get, "this");
6488 compiler.emit_var(VarAction::Get, HOME_OBJECT);
6489 compiler.emit(Opcode::AddBrand, &[]);
6490 compiler.place_label(skip);
6491 }
6492 for item in items {
6493 match item {
6494 StaticInitItem::Field(key, value) => {
6495 // A private field is *defined*, not assigned: `define_private_field`
6496 // reads `obj symbol value`, and its point is that it fails on a
6497 // receiver that is not this class's — which `put_field` would not.
6498 //
6499 // The three shapes are the reference's: `define_field <atom>` for a
6500 // static name, `define_array_el` for a key that is only known at run
6501 // time (`obj key value`), `define_private_field` for `#x`, and a
6502 // computed key is read from its binding rather than recomputed.
6503 compiler.emit_var(VarAction::Get, "this");
6504 match key {
6505 FieldKey::Private(binding) | FieldKey::Computed(binding) => {
6506 compiler.emit_var(VarAction::Get, binding);
6507 }
6508 FieldKey::Literal(_) => {}
6509 }
6510 match value {
6511 Some(value) => {
6512 compiler.expr(value)?;
6513 // A field initialiser is a `NamedEvaluation` target:
6514 // `x = function(){}` names the function `"x"`, and a private
6515 // field keeps its `#` (`static #f = () => 1` is named
6516 // `"#f"` (elements/static-field-anonymous-function-name).
6517 match key {
6518 FieldKey::Literal(literal) => {
6519 let text = compiler.property_key_text(literal, span)?;
6520 compiler.set_name_if_anonymous(value, &text);
6521 }
6522 FieldKey::Private(binding) => {
6523 compiler.set_name_if_anonymous(value, &Wtf8::new(binding));
6524 }
6525 // The key is a value on the stack, and `set_name_computed`
6526 // is exactly the instruction for that.
6527 FieldKey::Computed(_) => {
6528 compiler.set_name_if_anonymous_computed(value);
6529 }
6530 }
6531 }
6532 None => compiler.emit(Opcode::Undefined, &[]),
6533 }
6534 match key {
6535 FieldKey::Literal(literal) => {
6536 let text = compiler.property_key_text(literal, span)?;
6537 compiler
6538 .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
6539 }
6540 FieldKey::Computed(_) => {
6541 compiler.emit(Opcode::DefineArrayEl, &[]);
6542 // `define_array_el` leaves `obj key`; the key is consumed by
6543 // the copy the pattern machinery wants, so both go.
6544 compiler.emit(Opcode::Drop, &[]);
6545 }
6546 FieldKey::Private(_) => {
6547 compiler.emit(Opcode::DefinePrivateField, &[]);
6548 }
6549 }
6550 compiler.emit(Opcode::Drop, &[]);
6551 }
6552 StaticInitItem::Block { body, body_start } => {
6553 let block = compiler.compile_static_block(body, *body_start)?;
6554 let index = compiler.push_constant(Constant::Function(Box::new(block)));
6555 // `this fclosure`, so `call_method` finds the receiver below the
6556 // callee: the block runs with `this` bound to the class.
6557 compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
6558 compiler.emit_var(VarAction::Get, "this");
6559 compiler.emit(Opcode::Swap, &[]);
6560 compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
6561 // Nothing the block evaluates is wanted; its effects are the point.
6562 compiler.emit(Opcode::Drop, &[]);
6563 }
6564 }
6565 }
6566 Ok(())
6567 })
6568 }
6569
6570 /// Compile a `static { … }` body into the function the class calls for it.
6571 ///
6572 /// Shaped like an arrow, because that is the one function form with no `this`,
6573 /// `new.target` or `arguments` of its own: all three reach the enclosing static
6574 /// initialiser, and through it the class. `arguments` never gets that far — the parser
6575 /// rejects the reference — but `this` and `super` both depend on it.
6576 ///
6577 /// The body is hoisted like a function body's, because the reference parses it as one:
6578 /// `var` inside a block is a local of the block's function, not of whatever encloses
6579 /// the class.
6580 fn compile_static_block(
6581 &mut self,
6582 body: &[Stmt],
6583 body_start: Position,
6584 ) -> Result<CompiledFunction, SyntaxError> {
6585 let mut state = FnState::new(String::new(), FunctionKind::Normal);
6586 // Class bodies are strict, so a static block is too.
6587 state.strict = true;
6588 // The one property that makes this an arrow: nothing of its own to bind `this` to,
6589 // so `this` and `super` come from the initialiser that calls it.
6590 state.is_arrow = true;
6591 state.created_in_block = self.cur().current_block;
6592 state.with_names = self.cur().with_names.clone();
6593 state.line = body_start.line;
6594 state.column = body_start.column;
6595 let depth = self.stack.len();
6596 self.stack.push(state);
6597 let body_key = body_start.offset as u64;
6598 self.push_block(body_key, NO_PARENT);
6599 self.state().body_block = body_key;
6600 let result = (|| {
6601 self.hoist(body, body_key)?;
6602 self.emit_scope_enter(body_key);
6603 for statement in body {
6604 self.stmt(statement)?;
6605 }
6606 if self.end_is_reachable() {
6607 self.emit(Opcode::ReturnUndef, &[]);
6608 }
6609 Ok(())
6610 })();
6611 if result.is_err() {
6612 self.stack.truncate(depth);
6613 return result.map(|()| unreachable!());
6614 }
6615 Ok(self.finish_current())
6616 }
6617
6618 /// Compile a class, leaving the constructor on the stack when `keep`.
6619 ///
6620 /// The shape follows the reference: the class body is its own scope holding the
6621 /// class's *inner* name as a `const` — which is what lets a method refer to the
6622 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6623 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6624 /// on the top of the stack: the prototype for instance members, the constructor
6625 /// itself for `static` ones, which is why a static member costs an extra `swap`.
6626 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6627 let parent_block = self.cur().current_block;
6628 let key = class.span.start.offset as u64;
6629 self.push_block(key, parent_block);
6630 let name = class.name.as_ref().map(|ident| ident.name.clone());
6631 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6632 // resolves `E` without a global lookup. An *unnamed* class expression has no such
6633 // binding, and `define_class` is handed the empty name.
6634 if let Some(name) = &name {
6635 self.declare(name, VarDef::constant(name.clone()));
6636 }
6637 self.emit_scope_enter(key);
6638
6639 // The heritage clause is evaluated outside the class's own scope: it cannot see
6640 // the class binding it is about to initialise.
6641 let saved_block = self.cur().current_block;
6642 self.state().current_block = parent_block;
6643 match &class.super_class {
6644 Some(parent) => self.expr(parent)?,
6645 None => self.emit(Opcode::Undefined, &[]),
6646 }
6647 self.state().current_block = saved_block;
6648 let has_heritage = class.super_class.is_some();
6649
6650 // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6651 // lands after the heritage's code — which is where the reference puts it, because it
6652 // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6653 // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6654 // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6655 // came out in the opposite order from the reference's.
6656 //
6657 // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6658 // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6659 // a const accepts — so the old comment's worry ("a const would refuse the second
6660 // store") did not apply: there is no second store.
6661 // Every `#name` the class declares gets a `const` binding in the class scope, and so
6662 // does every computed field key. That is how the reference does it
6663 // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6664 // what makes a private name resolve like any other class-scope variable — including
6665 // through a nested function's closure — while remaining invisible outside.
6666 //
6667 // All of them are declared *before* `<class_fields_init>`, in member order, because
6668 // that is when the reference's parser creates them.
6669 let plan = ClassPlan::build(class);
6670 // The body's private names are visible from here to the end of the class, and shadow
6671 // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6672 // — it is compiled first because `define_class` consumes it, but its body can name
6673 // `#x` like any other member's.
6674 self.private_scopes.push(plan.uses.clone());
6675 let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6676 for binding in &plan.bindings {
6677 class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6678 }
6679 let fci = self.declare(
6680 "<class_fields_init>",
6681 VarDef::constant("<class_fields_init>"),
6682 );
6683 // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6684 // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6685 // members' bindings follow in reverse.
6686 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6687 for slot in class_slots.iter().rev() {
6688 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6689 }
6690
6691 // The constructor is compiled before `define_class` because that instruction
6692 // consumes it; a class without one gets the implicit version.
6693 let constructor = class.elements.iter().find_map(|element| match element {
6694 ClassElement::Method {
6695 kind: MethodKind::Constructor,
6696 func,
6697 ..
6698 } => Some(&**func),
6699 _ => None,
6700 });
6701 // A constructor is compiled differently from a method: it owns `this`. The flags
6702 // go on the *enclosing* state because a constructor is a nested function and
6703 // `compile_function_with_name` starts a fresh one.
6704 let ctor = match constructor {
6705 Some(func) => self.compile_class_constructor(func, has_heritage)?,
6706 None => self.compile_implicit_constructor(class, has_heritage)?,
6707 };
6708 // A closure, not the bare constant: the constructor captures
6709 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6710 // has to hold the cell rather than a copy of its value.
6711 //
6712 // The pool slot is left unassigned for now, because the reference gives the
6713 // constructor the *last* index of the members' range: `js_parse_class` emits a
6714 // `push_const` whose operand is patched at the end of the class parse, after every
6715 // method has taken a slot. Emitting the members first and the constant second is how
6716 // the numbering comes out the same; the instruction itself stays where it is.
6717 let ctor_insn = self.cur().insns.len();
6718 self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6719 let flags = if has_heritage { 1 } else { 0 };
6720 self.emit(
6721 Opcode::DefineClass,
6722 &[
6723 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6724 Op::Int(flags),
6725 ],
6726 );
6727
6728 // Instance fields and static fields are two different functions: the first runs
6729 // per instance from the constructor, the second runs once, here.
6730 let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6731 let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6732 for (index, element) in class.elements.iter().enumerate() {
6733 match element {
6734 ClassElement::Method {
6735 key: member_key,
6736 is_static,
6737 kind,
6738 func,
6739 span,
6740 } => {
6741 if *kind == MethodKind::Constructor {
6742 continue;
6743 }
6744 // `static(x)` is a *method* named `static`, not a static method; the
6745 // parser already decided which by putting it in `kind`.
6746 if *is_static {
6747 self.emit(Opcode::Swap, &[]);
6748 }
6749 // A computed key is evaluated *here*, before the method's closure
6750 // exists, and stays under it: `define_method_computed` pops
6751 // `function, key, object`, so the stack has to read
6752 // `[class, prototype, key, function]`. Evaluating the key after the
6753 // `fclosure` and swapping the two put the prototype *below* the
6754 // closure, which defined the method on the function and lost the
6755 // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6756 // also the spec's — a class body evaluates every element's name before
6757 // that element's function.
6758 if let PropName::Computed(key) = member_key {
6759 self.expr(key)?;
6760 }
6761 let function = self.compile_function_with_name(func, true)?;
6762 let index = self.push_constant(Constant::Function(Box::new(function)));
6763 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6764 match member_key {
6765 // A private method is not a property of the prototype: it is a
6766 // closure in the class scope, which is why nothing outside can reach
6767 // it and why a use site has to brand-check. `set_name` gives the
6768 // function its `name` (`#m`), which an accessor does not get — the
6769 // reference leaves that commented out.
6770 PropName::Private(ident) => {
6771 let name = format!("#{}", ident.name);
6772 // `set_home_object` first: the brand check reads the function's
6773 // home object, and for a method that is the prototype.
6774 self.emit(Opcode::SetHomeObject, &[]);
6775 let binding = if *kind == MethodKind::Set {
6776 format!("{name}<set>")
6777 } else {
6778 name.clone()
6779 };
6780 if *kind == MethodKind::Method {
6781 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6782 }
6783 self.emit_var(VarAction::PutInit, &binding);
6784 }
6785 PropName::Computed(_) => {
6786 self.emit(
6787 Opcode::DefineMethodComputed,
6788 &[Op::Int(class_method_flags(*kind))],
6789 );
6790 }
6791 PropName::Literal(literal) => {
6792 let text = self.property_key_text(literal, *span)?;
6793 self.emit(
6794 Opcode::DefineMethod,
6795 &[
6796 Op::Atom(Atom::from_wtf8(&text)),
6797 Op::Int(class_method_flags(*kind)),
6798 ],
6799 );
6800 }
6801 }
6802 if *is_static {
6803 self.emit(Opcode::Swap, &[]);
6804 }
6805 }
6806 ClassElement::Field {
6807 key: field_key,
6808 is_static,
6809 value,
6810 ..
6811 } => {
6812 // A private field's *symbol* is created here, at the member, and stored
6813 // in its binding: the field's property is keyed by it, so it has to exist
6814 // before any initialiser runs, and a fresh one per class body is what
6815 // makes two classes that both write `#x` independent.
6816 //
6817 // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6818 // whose `toString` has a side effect must not run again per instance.
6819 let key = match field_key {
6820 PropName::Private(ident) => {
6821 let binding = format!("#{}", ident.name);
6822 if *is_static {
6823 self.emit(Opcode::Swap, &[]);
6824 }
6825 self.emit(
6826 Opcode::PrivateSymbol,
6827 &[Op::Atom(Atom::from_text(&binding))],
6828 );
6829 self.emit_var(VarAction::PutInit, &binding);
6830 if *is_static {
6831 self.emit(Opcode::Swap, &[]);
6832 }
6833 FieldKey::Private(binding)
6834 }
6835 PropName::Computed(expression) => {
6836 let binding = plan
6837 .computed
6838 .get(&index)
6839 .cloned()
6840 .expect("every computed key got a binding");
6841 if *is_static {
6842 self.emit(Opcode::Swap, &[]);
6843 }
6844 self.expr(expression)?;
6845 self.emit(Opcode::ToPropkey, &[]);
6846 self.emit_var(VarAction::PutInit, &binding);
6847 if *is_static {
6848 self.emit(Opcode::Swap, &[]);
6849 }
6850 FieldKey::Computed(binding)
6851 }
6852 PropName::Literal(literal) => FieldKey::Literal(literal),
6853 };
6854 if *is_static {
6855 static_items.push(StaticInitItem::Field(key, value.as_deref()));
6856 } else {
6857 instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6858 }
6859 }
6860 ClassElement::StaticBlock {
6861 body, body_start, ..
6862 } => static_items.push(StaticInitItem::Block {
6863 body,
6864 body_start: *body_start,
6865 }),
6866 }
6867 }
6868
6869 // Now that every member has its slot, the constructor can have the next one and the
6870 // `fclosure` above can name it.
6871 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6872 match self.state().insns.get_mut(ctor_insn) {
6873 Some(Insn::Fixed { operands, .. }) => {
6874 operands[0] = Op::Const(ctor_index);
6875 }
6876 // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6877 // loudly beats emitting a `fclosure` of slot 4294967295.
6878 _ => {
6879 return Err(SyntaxError::new(
6880 "the class constructor's fclosure went missing",
6881 class.span,
6882 ));
6883 }
6884 }
6885
6886 // The instance brand: a symbol created once on the prototype, which every instance
6887 // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6888 // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6889 // copy is created. The prototype is on top of the stack at this point.
6890 if plan.instance_brand {
6891 self.emit(Opcode::Dup, &[]);
6892 self.emit(Opcode::Null, &[]);
6893 self.emit(Opcode::Swap, &[]);
6894 self.emit(Opcode::AddBrand, &[]);
6895 }
6896
6897 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6898 // class has no instance fields. The constructor calls it only when it is defined.
6899 //
6900 // A class with private *methods* but no fields still needs one, because adding the
6901 // brand to each new instance is the initialiser's job.
6902 if instance_fields.is_empty() && !plan.instance_brand {
6903 self.emit(Opcode::Undefined, &[]);
6904 } else {
6905 let initialiser = self.compile_field_initialiser(
6906 &instance_fields,
6907 class.span,
6908 true,
6909 plan.instance_brand,
6910 )?;
6911 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6912 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6913 // `set_home_object` reads `obj func`, so the prototype stays where it is.
6914 self.emit(Opcode::SetHomeObject, &[]);
6915 }
6916 self.emit_var(VarAction::PutInit, "<class_fields_init>");
6917 // The prototype has done its job: every instance member is defined on it. What
6918 // is left under it is the constructor.
6919 self.emit(Opcode::Drop, &[]);
6920
6921 // The static brand, for `static #m() {}`: same opcode, but the home object is the
6922 // constructor itself, so the symbol lands on the class and the class carries it.
6923 if plan.static_brand {
6924 self.emit(Opcode::Dup, &[]);
6925 self.emit(Opcode::Dup, &[]);
6926 self.emit(Opcode::AddBrand, &[]);
6927 }
6928
6929 // The class binding is initialised *before* static fields run, so a static field
6930 // can refer to the class by name (`static y = S.x`).
6931 // `set_loc` leaves the constructor on the stack, which is what the static field
6932 // call and the outer store both consume.
6933 //
6934 // Only when there *is* such a binding: an anonymous class expression declares no
6935 // class-scope name, and asking for one by the empty string resolved to nothing —
6936 // which made `var x = class {}` assign `undefined` and put a bogus global store in
6937 // the instruction stream.
6938 if let Some(name) = &name {
6939 self.emit_var(VarAction::SetInit, name);
6940 }
6941 if !static_items.is_empty() {
6942 // The static half has no brand prologue of its own: the constructor got its
6943 // brand above, before this runs.
6944 let initialiser =
6945 self.compile_field_initialiser(&static_items, class.span, false, false)?;
6946 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6947 self.emit(Opcode::Dup, &[]);
6948 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6949 self.emit(Opcode::SetHomeObject, &[]);
6950 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6951 self.emit(Opcode::Drop, &[]);
6952 }
6953 // The body is over, and with it this class's private names.
6954 let _ = self.private_scopes.pop();
6955 self.emit_scope_leave(key);
6956 self.state().current_block = parent_block;
6957 if keep {
6958 // A class *expression* is its own value; the class-scope binding was only
6959 // ever an alias for it.
6960 return Ok(());
6961 }
6962 // A declaration stores into the binding the enclosing statement declared.
6963 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6964 Ok(())
6965 }
6966
6967 fn push_this(&mut self) {
6968 self.emit(Opcode::PushThis, &[]);
6969 }
6970
6971 /// `this`, which an arrow does not have of its own.
6972 ///
6973 /// The reference gives the enclosing function a local named `this`, initialised from
6974 /// `push_this` at the top of its body, and the arrow then reads it as a captured
6975 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6976 /// the arrow is called with none.
6977 fn this_expression(&mut self) {
6978 // In a class constructor `this` is a local: a derived constructor only gets one
6979 // when `super()` returns, and reading the raw receiver would give the *outer*
6980 // one instead.
6981 if self.cur().ctor_kind != CtorKind::None {
6982 self.emit_var(VarAction::Get, "this");
6983 return;
6984 }
6985 if !self.cur().is_arrow {
6986 self.push_this();
6987 return;
6988 }
6989 // An arrow at the **top level** of a script or module has no enclosing function,
6990 // but it still inherits `this` — the script's or module's own. Falling through to
6991 // `emit_var(Get, "this")` without a target made that a *global* lookup, so
6992 // `var f = () => typeof this` at top level reported
6993 // `ReferenceError: 'this' is not defined` instead of `"object"`
6994 // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
6995 // is the test262 case that reaches it, through a native `forEach`).
6996 //
6997 // The script state is the bottom of the stack, so it is the fallback target. Its
6998 // own `provide_this_local` then prepends the `push_this` the arrow reads.
6999 let target = self.enclosing_function().unwrap_or(0);
7000 self.state_at(target).needs_this_local = true;
7001 self.declare_at(target, "this");
7002 self.emit_var(VarAction::Get, "this");
7003 }
7004
7005 /// `new.target`, which an arrow likewise does not own.
7006 fn new_target_expression(&mut self) {
7007 if !self.cur().is_arrow {
7008 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
7009 return;
7010 }
7011 if let Some(target) = self.enclosing_function() {
7012 self.state_at(target).needs_new_target_local = true;
7013 self.declare_at(target, NEW_TARGET);
7014 }
7015 self.emit_var(VarAction::Get, NEW_TARGET);
7016 }
7017
7018 /// `this.active_func`: the function `super()` resolves against.
7019 ///
7020 /// In a constructor or a method that is the function being run, so the special object
7021 /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
7022 /// a closure variable — see [`FnState::needs_active_func_local`].
7023 fn active_func_expression(&mut self) {
7024 if !self.cur().is_arrow {
7025 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
7026 return;
7027 }
7028 if let Some(target) = self.enclosing_function() {
7029 self.state_at(target).needs_active_func_local = true;
7030 self.declare_at(target, ACTIVE_FUNC);
7031 }
7032 self.emit_var(VarAction::Get, ACTIVE_FUNC);
7033 }
7034
7035 /// Give the function a local `<active_func>`, for an arrow inside it to capture.
7036 fn provide_active_func_local(&mut self) {
7037 let current = self.stack.len() - 1;
7038 if !self.stack[current].needs_active_func_local {
7039 return;
7040 }
7041 if !self.stack[current]
7042 .vars
7043 .iter()
7044 .any(|var| var.name == ACTIVE_FUNC)
7045 {
7046 self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
7047 }
7048 self.prepend_initialiser(
7049 ACTIVE_FUNC,
7050 Insn::Fixed {
7051 op: Opcode::SpecialObject,
7052 operands: vec![Op::Int(2)],
7053 },
7054 );
7055 }
7056
7057 /// Give the function a local `new.target`, for an arrow inside it to capture.
7058 fn provide_new_target_local(&mut self) {
7059 let current = self.stack.len() - 1;
7060 if !self.stack[current].needs_new_target_local {
7061 return;
7062 }
7063 if !self.stack[current]
7064 .vars
7065 .iter()
7066 .any(|var| var.name == NEW_TARGET)
7067 {
7068 self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
7069 }
7070 self.prepend_initialiser(
7071 NEW_TARGET,
7072 Insn::Fixed {
7073 op: Opcode::SpecialObject,
7074 operands: vec![Op::Int(3)],
7075 },
7076 );
7077 }
7078
7079 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
7080 /// function.
7081 fn ensure_enclosing_arguments(&mut self) {
7082 // An arrow created in a parameter list needs the *parameter* scope's
7083 // `arguments`, not the body's: the two are separate bindings and the arrow was
7084 // born before the body existed.
7085 let from_params = self.cur().created_in_params;
7086 if let Some(target) = self.enclosing_function() {
7087 self.state_at(target).needs_arguments_local = true;
7088 if from_params {
7089 self.state_at(target).needs_param_arguments = true;
7090 // Declare it now, not at the enclosing function's `finish_current`: the
7091 // arrow resolves its own `arguments` before that runs, and a binding that
7092 // does not exist yet resolves as a global.
7093 declare_param_var_at(&mut self.stack[target], "arguments");
7094 }
7095 self.declare_at(target, "arguments");
7096 }
7097 }
7098
7099 /// The innermost enclosing frame that is a real function — an arrow inherits from it
7100 /// rather than starting a scope of its own.
7101 /// The innermost enclosing frame that can own a lexical binding an arrow reads —
7102 /// a real function, or a **script** top level.
7103 ///
7104 /// A script is in the list because an `eval` body is compiled as one and an arrow
7105 /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
7106 /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
7107 /// a *global* lookup of `new.target`, which no frame provides — so it raised
7108 /// `ReferenceError` instead of answering the caller's value
7109 /// (`arrow-body-direct-eval-err-contains-newtarget`).
7110 fn enclosing_function(&self) -> Option<usize> {
7111 (0..self.stack.len())
7112 .rev()
7113 .find(|index| !self.stack[*index].is_arrow)
7114 }
7115
7116 fn state_at(&mut self, index: usize) -> &mut FnState {
7117 &mut self.stack[index]
7118 }
7119
7120 /// Declare a `var` binding directly in a specific frame.
7121 fn declare_at(&mut self, index: usize, name: &str) {
7122 let state = &mut self.stack[index];
7123 if state.vars.iter().any(|var| var.name == name) {
7124 return;
7125 }
7126 state.var_block.push(FUNCTION_SCOPE);
7127 state.vars.push(VarDef::var(name));
7128 }
7129
7130 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
7131 /// the reference calls a `special_object` gets initialised on entry.
7132 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
7133 let current = self.stack.len() - 1;
7134 let init = [
7135 producer,
7136 Insn::Var {
7137 action: VarAction::Put,
7138 name: name.to_string(),
7139 block: 0,
7140 // A prologue initialiser runs before the body proper, but it is body
7141 // code: `this` and `arguments` are provided for it, not by it.
7142 in_params: false,
7143 },
7144 ];
7145 let inserted = init.len();
7146 for (index, instruction) in init.into_iter().enumerate() {
7147 self.stack[current].insns.insert(index, instruction);
7148 }
7149 for placed in self.stack[current].labels.iter_mut().flatten() {
7150 *placed += inserted;
7151 }
7152 self.stack[current].label_since_insn = true;
7153 }
7154
7155 fn push_constant(&mut self, constant: Constant) -> u32 {
7156 let state = self.state();
7157 let index = state.cpool.len() as u32;
7158 state.cpool.push(constant);
7159 index
7160 }
7161
7162 /// Compile `a && b`, `a || b`, `a ?? b`.
7163 ///
7164 /// A run of the *same* operator shares one end label, so `a || b || c` tests
7165 /// `a` once and jumps past everything when it is truthy, instead of falling
7166 /// into `b`'s test. The parser builds such a run left-associated —
7167 /// `((a || b) || c)` — so the operands are collected off the left spine.
7168 ///
7169 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
7170 /// `||`'s label, because the inner chain really does end before `&&` begins.
7171 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
7172 let mut operands = Vec::new();
7173 collect_same_operator(op, left, &mut operands);
7174 operands.push(right);
7175
7176 let end = self.new_label();
7177 // Every operand but the last decides whether the chain stops here.
7178 let last = operands.pop().expect("the right operand is always present");
7179 for operand in operands {
7180 self.expr(operand)?;
7181 self.emit(Opcode::Dup, &[]);
7182 match op {
7183 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
7184 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
7185 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
7186 // `0 || b` is `b`. The dedicated test keeps the value unless it is
7187 // null-ish, so the jump is taken on `false`.
7188 LogicalOp::Coalesce => {
7189 self.emit(Opcode::IsUndefinedOrNull, &[]);
7190 self.emit_jump(Opcode::IfFalse, end, &[]);
7191 }
7192 }
7193 self.emit(Opcode::Drop, &[]);
7194 }
7195 self.expr(last)?;
7196 self.place_label(end);
7197 Ok(())
7198 }
7199
7200 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
7201 match op {
7202 UnaryOp::Typeof => {
7203 // `typeof x` must not throw on an undeclared name.
7204 if let ExprKind::Ident(name) = &argument.kind {
7205 self.emit_var(VarAction::GetUndef, &name.name);
7206 } else {
7207 self.expr(argument)?;
7208 }
7209 self.emit(Opcode::Typeof, &[]);
7210 }
7211 UnaryOp::Delete => {
7212 // `delete obj.prop` really deletes, and answers whether it could.
7213 // Deleting a *binding* is always `false`: a local, an argument and a
7214 // declared global are all non-configurable, which the reference encodes
7215 // as a constant `push_false` rather than a runtime check. Only a
7216 // property access has anything to do at run time.
7217 // `delete super.x` is not a delete at all: the spec refuses it, and the
7218 // reference encodes the refusal as a `throw_error`. The receiver and the
7219 // key are still evaluated first, which is what keeps the evaluation order
7220 // of the operand intact.
7221 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
7222 // nothing to delete, and a failed delete is not the same as a skipped
7223 // one. The reference emits the guards so they land on a `drop; push_true`
7224 // tail, which is what this reproduces.
7225 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
7226 && let ExprKind::Member {
7227 object, property, ..
7228 } = &inner.unparen().kind
7229 {
7230 let end = self.new_label();
7231 let done = self.new_label();
7232 self.chain_link(object, end)?;
7233 match property {
7234 MemberProp::Ident(name) => self.emit(
7235 Opcode::PushAtomValue,
7236 &[Op::Atom(Atom::from_text(&name.name))],
7237 ),
7238 MemberProp::Computed(index) => self.expr(index)?,
7239 MemberProp::Private(_) => {
7240 return Err(SyntaxError::new(
7241 "deleting a private field is not allowed",
7242 argument.span,
7243 ));
7244 }
7245 }
7246 self.emit(Opcode::Delete, &[]);
7247 self.emit_jump(Opcode::Goto, done, &[]);
7248 self.place_label(end);
7249 self.emit(Opcode::Drop, &[]);
7250 self.emit(Opcode::PushTrue, &[]);
7251 self.place_label(done);
7252 return Ok(());
7253 }
7254 if let ExprKind::Member { object, .. } = &argument.unparen().kind
7255 && matches!(object.unparen().kind, ExprKind::SuperProp)
7256 {
7257 self.super_base();
7258 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
7259 return Ok(());
7260 }
7261 // Parentheses are transparent to `delete`: `(x)` is still a Reference to
7262 // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
7263 // does, and `delete (a().b)` still evaluates `a()`. Matching on the
7264 // unparenthesised operand is what keeps both — matching on `argument.kind`
7265 // sent every parenthesised form to the "not a Reference" arm, which cost
7266 // `delete(__variable) === false` in test262's `S12.2_A2`.
7267 match &argument.unparen().kind {
7268 ExprKind::Member {
7269 object, property, ..
7270 } => {
7271 self.expr(object)?;
7272 match property {
7273 MemberProp::Ident(name) => {
7274 self.emit(
7275 Opcode::PushAtomValue,
7276 &[Op::Atom(Atom::from_text(&name.name))],
7277 );
7278 }
7279 MemberProp::Computed(index) => self.expr(index)?,
7280 MemberProp::Private(_) => {
7281 return Err(SyntaxError::new(
7282 "deleting a private field is not allowed",
7283 argument.span,
7284 ));
7285 }
7286 }
7287 self.emit(Opcode::Delete, &[]);
7288 }
7289 ExprKind::Ident(name) => {
7290 self.delete_ident(&name.name);
7291 }
7292 // §13.5.1.2 step 2: an operand that is **not** a Reference Record
7293 // answers `true` — there is nothing to delete, and "nothing needed
7294 // deleting" is success. `delete !0`, `delete (1 + 2)` and
7295 // `delete typeof 0` are all `true`, and the operand is still evaluated
7296 // (which is why it is `Drop`ed rather than skipped:
7297 // `delete f()` must call `f`).
7298 //
7299 // Answering `false` here is the C reference's old behaviour and was
7300 // wrong in an observable way: test262's
7301 // `dynamic-import/assignment-expression/logical-and-expr` builds a
7302 // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
7303 // half turned the whole `&&` into `false`, so the import asked for a
7304 // module named "false".
7305 _ => {
7306 self.expr(argument)?;
7307 self.emit(Opcode::Drop, &[]);
7308 self.emit(Opcode::PushTrue, &[]);
7309 }
7310 }
7311 }
7312 UnaryOp::Void => {
7313 self.expr(argument)?;
7314 self.emit(Opcode::Drop, &[]);
7315 self.emit(Opcode::Undefined, &[]);
7316 }
7317 UnaryOp::Minus => {
7318 self.expr(argument)?;
7319 self.emit(Opcode::Neg, &[]);
7320 }
7321 UnaryOp::Plus => {
7322 self.expr(argument)?;
7323 self.emit(Opcode::Plus, &[]);
7324 }
7325 UnaryOp::Not => {
7326 self.expr(argument)?;
7327 self.emit(Opcode::Lnot, &[]);
7328 }
7329 UnaryOp::BitNot => {
7330 self.expr(argument)?;
7331 self.emit(Opcode::Not, &[]);
7332 }
7333 }
7334 Ok(())
7335 }
7336
7337 /// A store to `name` while a `with` may capture it.
7338 ///
7339 /// The reference is resolved **first**, before the right-hand side runs. That order is
7340 /// the whole point: in `x = (delete env.x, 0)` the resolution has already decided that
7341 /// `x` is `env`'s property, so `PutValue` then finds it gone and strict code throws
7342 /// `ReferenceError` (`set-mutable-binding-binding-deleted-with-typed-array-in-
7343 /// proto-chain-strict-mode`). The ordinary path evaluates the right-hand side before
7344 /// the guard runs, which put the guard *after* the mutation.
7345 ///
7346 /// Shapes mirror [`Compiler::assign_ident_plain`] and the member arms of
7347 /// [`Compiler::assign`], with `dup; with_get_var` in place of `get_field2` and
7348 /// `with_put_var` in place of `put_field` — the same stack effects, but each half also
7349 /// asks the `HasProperty` that `GetBindingValue`/`SetMutableBinding` require.
7350 fn with_assign(
7351 &mut self,
7352 with_local: &str,
7353 name: &Ident,
7354 op: AssignOp,
7355 value: &Expr,
7356 keep: bool,
7357 ) -> Result<(), SyntaxError> {
7358 let atom = Atom::from_text(&name.name);
7359 self.state().cur_pos = Some(name.span.start);
7360 match op {
7361 AssignOp::Assign => {
7362 self.expr(value)?;
7363 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7364 if keep {
7365 self.emit(Opcode::Dup, &[]);
7366 }
7367 self.state().no_value = !keep;
7368 self.emit_var(VarAction::Get, with_local);
7369 self.emit(Opcode::Swap, &[]);
7370 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7371 }
7372 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7373 let (keep_label, end) = (self.new_label(), self.new_label());
7374 self.emit_var(VarAction::Get, with_local);
7375 self.emit(Opcode::Dup, &[]);
7376 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7377 // `obj value` — the object stays underneath for the store.
7378 self.emit(Opcode::Dup, &[]);
7379 self.emit_logical_test(op);
7380 self.emit_jump(logical_jump(op), keep_label, &[]);
7381 self.emit(Opcode::Drop, &[]);
7382 self.expr(value)?;
7383 self.emit(Opcode::Insert2, &[]);
7384 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7385 self.emit_jump(Opcode::Goto, end, &[]);
7386 self.place_label(keep_label);
7387 self.emit(Opcode::Nip, &[]);
7388 self.place_label(end);
7389 }
7390 _ => {
7391 self.emit_var(VarAction::Get, with_local);
7392 self.emit(Opcode::Dup, &[]);
7393 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7394 self.expr(value)?;
7395 self.state().cur_pos = Some(name.span.start);
7396 self.emit(compound_opcode(op), &[]);
7397 self.state().no_value = !keep;
7398 if keep {
7399 self.emit(Opcode::Insert2, &[]);
7400 }
7401 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7402 }
7403 }
7404 Ok(())
7405 }
7406
7407 /// `x++` / `++x` while a `with` may capture `x`, with one resolution for both halves.
7408 fn with_update(
7409 &mut self,
7410 with_local: &str,
7411 name: &Ident,
7412 op: UpdateOp,
7413 prefix: bool,
7414 ) -> Result<(), SyntaxError> {
7415 let instruction = match (op, prefix) {
7416 (UpdateOp::Increment, true) => Opcode::Inc,
7417 (UpdateOp::Increment, false) => Opcode::PostInc,
7418 (UpdateOp::Decrement, true) => Opcode::Dec,
7419 (UpdateOp::Decrement, false) => Opcode::PostDec,
7420 };
7421 let atom = Atom::from_text(&name.name);
7422 self.state().cur_pos = Some(name.span.start);
7423 self.emit_var(VarAction::Get, with_local);
7424 self.emit(Opcode::Dup, &[]);
7425 self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7426 self.emit(instruction, &[]);
7427 self.emit(
7428 if prefix {
7429 Opcode::Insert2
7430 } else {
7431 Opcode::Perm3
7432 },
7433 &[],
7434 );
7435 self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7436 Ok(())
7437 }
7438
7439 /// A store to a plain identifier, with no `with` in the way.
7440 fn assign_ident_plain(
7441 &mut self,
7442 op: AssignOp,
7443 name: &Ident,
7444 value: &Expr,
7445 discard: bool,
7446 ) -> Result<(), SyntaxError> {
7447 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7448 // about, so it is set only when this assignment *is* that expression.
7449 let keep = !discard;
7450 // A *simple* store is blamed on the identifier, not on the `=`: a
7451 // strict-mode `not_def = 1` raises when the name is written, which the
7452 // reference reports at the name's column. A compound store is blamed on
7453 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
7454 // which the reference reports at the `+=`), so only the simple case
7455 // moves the position.
7456 let saved = self.cur().cur_pos;
7457 let name_pos = Some(name.span.start);
7458 if matches!(op, AssignOp::Assign) {
7459 self.state().cur_pos = name_pos;
7460 }
7461 // A *compound* store reads the binding before it combines, and that read
7462 // is blamed on the identifier: `not_def += 2` fails while reading
7463 // `not_def`, so the position is the name's, not the `+=`'s. The
7464 // combination that follows is blamed on the operator, which is why
7465 // `cur_pos` is put back to the operator position before it is emitted.
7466 self.state().cur_pos = name_pos;
7467 match op {
7468 AssignOp::Assign => {
7469 self.expr(value)?;
7470 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7471 // A discarded store to a *slot* consumes its value, so no copy
7472 // is needed. A global store goes through `put_var`, which the
7473 // reference always pairs with a `dup` — matching it keeps the
7474 // bytecode identical. Getting this wrong is not only an extra
7475 // instruction: a stray copy gives the peephole a chance to fold
7476 // the store into an unrelated later read.
7477 let slot = self.is_slot(&name.name);
7478 if keep || !slot {
7479 self.emit(Opcode::Dup, &[]);
7480 }
7481 self.state().no_value = !keep && slot;
7482 self.emit_var(VarAction::Put, &name.name);
7483 }
7484 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7485 let end = self.new_label();
7486 self.emit_var(VarAction::Get, &name.name);
7487 self.state().cur_pos = saved;
7488 self.emit(Opcode::Dup, &[]);
7489 self.emit_logical_test(op);
7490 self.emit_jump(logical_jump(op), end, &[]);
7491 self.emit(Opcode::Drop, &[]);
7492 self.expr(value)?;
7493 // `x ||= function(){}` is a `NamedEvaluation` of the right-hand side, so the
7494 // function is named `x` — the same rule plain assignment follows
7495 // (`lgcl-*-namedevaluation-function`).
7496 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7497 self.emit(Opcode::Dup, &[]);
7498 self.emit_var(VarAction::Put, &name.name);
7499 self.place_label(end);
7500 }
7501 _ => {
7502 self.emit_var(VarAction::Get, &name.name);
7503 self.expr(value)?;
7504 self.state().cur_pos = saved;
7505 self.emit(compound_opcode(op), &[]);
7506 self.emit(Opcode::Dup, &[]);
7507 self.emit_var(VarAction::Put, &name.name);
7508 }
7509 }
7510 self.state().cur_pos = saved;
7511 Ok(())
7512 }
7513
7514 /// Compile an assignment.
7515 ///
7516 /// Three operator families, three shapes:
7517 ///
7518 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
7519 /// the value is kept, because `put_field`/`put_array_el` consume both the
7520 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
7521 /// the pair it wants and leaves a copy on top.
7522 /// * **compound** `+=` … — read the place, apply the operator, store. A member
7523 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
7524 /// index) underneath the value precisely so the store can follow.
7525 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
7526 /// right-hand side. The test *keeps* the current value and skips the store
7527 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
7528 /// `a` is already truthy.
7529 fn assign(
7530 &mut self,
7531 op: AssignOp,
7532 target: &Pattern,
7533 value: &Expr,
7534 discard: bool,
7535 ) -> Result<(), SyntaxError> {
7536 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7537 // about, so it is set only when this assignment *is* that expression.
7538 let keep = !discard;
7539 match &target.kind {
7540 PatternKind::Ident(name) => {
7541 // Any store to a name a `with` may capture resolves the reference first and
7542 // keeps that resolution for both halves — see [`Compiler::with_assign`].
7543 // Plain `=` needs it just as much as `+=`: `x = (delete env.x, 0)` must
7544 // resolve `x` before the right-hand side deletes it.
7545 let plain_name = name.name.clone();
7546 if !self.visible_with_names(&plain_name).is_empty() {
7547 return self.with_reference(
7548 &plain_name,
7549 &mut |compiler, with_local| {
7550 compiler.with_assign(with_local, name, op, value, !discard)
7551 },
7552 &mut |compiler| compiler.assign_ident_plain(op, name, value, discard),
7553 );
7554 }
7555 self.assign_ident_plain(op, name, value, discard)
7556 }
7557 PatternKind::Member(member) => {
7558 // `super.x = v` is not a store through a value: it starts at the home
7559 // object's prototype but writes to `this`, so it goes through
7560 // `put_super_value` rather than `put_field`. The receiver, prototype, key
7561 // and value are handed over together.
7562 if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
7563 return self.assign_super(member, op, value);
7564 }
7565 // A store is blamed on the selector punctuator (`.` or `[`), the same
7566 // token a load is blamed on — the reference records `put_field obj.a`
7567 // at the `.`, so a setter that throws reports that column and not the
7568 // `=` of the assignment it sits in. The inner expressions restore their
7569 // own positions, so the selector's sticks for the store instructions.
7570 let saved = self.cur().cur_pos;
7571 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7572 self.expr(&member.object)?;
7573 match &member.property {
7574 MemberProp::Ident(property) => {
7575 let atom = Atom::from_text(&property.name);
7576 match op {
7577 AssignOp::Assign => {
7578 self.expr(value)?;
7579 // `put_field` consumes the object and the value, so
7580 // without `insert2` nothing is left over for the
7581 // statement to drop.
7582 self.state().no_value = !keep;
7583 if keep {
7584 self.emit(Opcode::Insert2, &[]);
7585 }
7586 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7587 }
7588 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7589 // `get_field2` leaves the object under the value, so
7590 // the keep path has an object to dispose of. The store
7591 // path must jump *over* that cleanup: falling into it
7592 // would `nip` a stack that only holds the value.
7593 let (keep_label, end) = (self.new_label(), self.new_label());
7594 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7595 self.emit(Opcode::Dup, &[]);
7596 self.emit_logical_test(op);
7597 self.emit_jump(logical_jump(op), keep_label, &[]);
7598 self.emit(Opcode::Drop, &[]);
7599 self.expr(value)?;
7600 self.emit(Opcode::Insert2, &[]);
7601 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7602 self.emit_jump(Opcode::Goto, end, &[]);
7603 self.place_label(keep_label);
7604 self.emit(Opcode::Nip, &[]);
7605 self.place_label(end);
7606 }
7607 _ => {
7608 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7609 self.expr(value)?;
7610 self.emit(compound_opcode(op), &[]);
7611 self.state().no_value = !keep;
7612 if keep {
7613 self.emit(Opcode::Insert2, &[]);
7614 }
7615 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7616 }
7617 }
7618 }
7619 MemberProp::Computed(index) => {
7620 self.expr(index)?;
7621 match op {
7622 AssignOp::Assign => {
7623 self.expr(value)?;
7624 self.state().no_value = !keep;
7625 if keep {
7626 self.emit(Opcode::Insert3, &[]);
7627 }
7628 self.emit(Opcode::PutArrayEl, &[]);
7629 }
7630 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7631 let (keep_label, end) = (self.new_label(), self.new_label());
7632 self.emit(Opcode::GetArrayEl3, &[]);
7633 self.emit(Opcode::Dup, &[]);
7634 self.emit_logical_test(op);
7635 self.emit_jump(logical_jump(op), keep_label, &[]);
7636 self.emit(Opcode::Drop, &[]);
7637 self.expr(value)?;
7638 self.emit(Opcode::Insert3, &[]);
7639 self.emit(Opcode::PutArrayEl, &[]);
7640 self.emit_jump(Opcode::Goto, end, &[]);
7641 self.place_label(keep_label);
7642 // Both the object and the index are left over.
7643 self.emit(Opcode::Nip, &[]);
7644 self.emit(Opcode::Nip, &[]);
7645 self.place_label(end);
7646 }
7647 _ => {
7648 self.emit(Opcode::GetArrayEl3, &[]);
7649 self.expr(value)?;
7650 self.emit(compound_opcode(op), &[]);
7651 self.state().no_value = !keep;
7652 if keep {
7653 self.emit(Opcode::Insert3, &[]);
7654 }
7655 self.emit(Opcode::PutArrayEl, &[]);
7656 }
7657 }
7658 }
7659 MemberProp::Private(name) => {
7660 // `obj value` is on the stack, and every private store wants exactly
7661 // that. A top-level private name cannot be assigned (the parser rejects
7662 // `#x = 1`), so the only way here is `this.#x = …` inside the class.
7663 //
7664 // The reference emits `insert2` whether or not the value is wanted,
7665 // so this does too: the copy left behind is the assignment expression's
7666 // value, and a discarded one is simply never read.
7667 let binding = format!("#{}", name.name);
7668 let (kind, setter) = self.private_use(&binding, member.span)?;
7669 match op {
7670 AssignOp::Assign => {
7671 self.expr(value)?;
7672 if keep {
7673 self.emit(Opcode::Insert2, &[]);
7674 }
7675 self.private_store(&binding, kind, setter.as_deref())?;
7676 self.state().no_value = !keep;
7677 }
7678 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7679 let (keep_label, end) = (self.new_label(), self.new_label());
7680 self.emit(Opcode::Dup, &[]);
7681 self.private_load(&binding, kind, member.span)?;
7682 self.emit(Opcode::Dup, &[]);
7683 self.emit_logical_test(op);
7684 self.emit_jump(logical_jump(op), keep_label, &[]);
7685 self.emit(Opcode::Drop, &[]);
7686 self.expr(value)?;
7687 self.emit(Opcode::Insert2, &[]);
7688 self.private_store(&binding, kind, setter.as_deref())?;
7689 self.emit_jump(Opcode::Goto, end, &[]);
7690 self.place_label(keep_label);
7691 self.emit(Opcode::Nip, &[]);
7692 self.place_label(end);
7693 }
7694 _ => {
7695 self.emit(Opcode::Dup, &[]);
7696 self.private_load(&binding, kind, member.span)?;
7697 self.expr(value)?;
7698 self.emit(compound_opcode(op), &[]);
7699 self.emit(Opcode::Insert2, &[]);
7700 self.private_store(&binding, kind, setter.as_deref())?;
7701 }
7702 }
7703 }
7704 }
7705 self.state().cur_pos = saved;
7706 Ok(())
7707 }
7708 // A destructuring assignment: the right-hand side is the expression's own
7709 // value, so it is evaluated once and kept under the pattern's stores.
7710 PatternKind::Array { .. } | PatternKind::Object { .. } => {
7711 self.expr(value)?;
7712 if keep {
7713 self.emit(Opcode::Dup, &[]);
7714 }
7715 self.destructure(target, None)?;
7716 self.state().no_value = !keep;
7717 Ok(())
7718 }
7719 _ => Err(SyntaxError::new(
7720 "this assignment target is not supported by the compiler yet",
7721 target.span,
7722 )),
7723 }
7724 }
7725
7726 /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
7727 ///
7728 /// The stack has to carry four values — receiver, prototype, key, value — because
7729 /// `put_super_value` takes them together; the receiver is what makes a setter found on
7730 /// the prototype run with `this`, and the key has to survive until the store, which is
7731 /// why a compound form converts it to a property key once and `dup3`s rather than
7732 /// evaluating it twice.
7733 fn assign_super(
7734 &mut self,
7735 member: &MemberPattern,
7736 op: AssignOp,
7737 value: &Expr,
7738 ) -> Result<(), SyntaxError> {
7739 let saved = self.cur().cur_pos;
7740 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7741 self.super_base();
7742 match &member.property {
7743 MemberProp::Ident(property) => self.emit(
7744 Opcode::PushAtomValue,
7745 &[Op::Atom(Atom::from_text(&property.name))],
7746 ),
7747 MemberProp::Computed(index) => self.expr(index)?,
7748 MemberProp::Private(_) => {
7749 return Err(SyntaxError::new(
7750 "private fields are not supported by the compiler yet",
7751 member.span,
7752 ));
7753 }
7754 }
7755 match op {
7756 AssignOp::Assign => {
7757 // The key is only converted once, by `put_super_value` itself, so a
7758 // computed key's `toString` runs exactly once.
7759 self.expr(value)?;
7760 self.emit(Opcode::Insert4, &[]);
7761 self.emit(Opcode::PutSuperValue, &[]);
7762 }
7763 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7764 let (keep_label, end) = (self.new_label(), self.new_label());
7765 self.emit(Opcode::ToPropkey, &[]);
7766 self.emit(Opcode::Dup3, &[]);
7767 self.emit(Opcode::GetSuperValue, &[]);
7768 self.emit(Opcode::Dup, &[]);
7769 self.emit_logical_test(op);
7770 self.emit_jump(logical_jump(op), keep_label, &[]);
7771 self.emit(Opcode::Drop, &[]);
7772 self.expr(value)?;
7773 self.emit(Opcode::Insert4, &[]);
7774 self.emit(Opcode::PutSuperValue, &[]);
7775 self.emit_jump(Opcode::Goto, end, &[]);
7776 self.place_label(keep_label);
7777 // The prototype and the key are still under the value that was read.
7778 self.emit(Opcode::Nip, &[]);
7779 self.emit(Opcode::Nip, &[]);
7780 self.emit(Opcode::Nip, &[]);
7781 self.place_label(end);
7782 }
7783 _ => {
7784 self.emit(Opcode::ToPropkey, &[]);
7785 self.emit(Opcode::Dup3, &[]);
7786 self.emit(Opcode::GetSuperValue, &[]);
7787 self.expr(value)?;
7788 self.emit(compound_opcode(op), &[]);
7789 self.emit(Opcode::Insert4, &[]);
7790 self.emit(Opcode::PutSuperValue, &[]);
7791 }
7792 }
7793 // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7794 // is still on the stack when the store finishes, and the expression statement is
7795 // what disposes of it — the same arrangement as `put_field`, reached from the other
7796 // side: there the store consumes the value (`no_value`), here it leaves it
7797 // (`keep` already false, so nothing tells the statement otherwise).
7798 self.state().cur_pos = saved;
7799 Ok(())
7800 }
7801
7802 /// The test a logical assignment applies to the current value.
7803 ///
7804 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7805 /// assign, while `0 ||= b` must not.
7806 fn emit_logical_test(&mut self, op: AssignOp) {
7807 if op == AssignOp::Coalesce {
7808 self.emit(Opcode::IsUndefinedOrNull, &[]);
7809 }
7810 }
7811
7812 /// The private name `#name` this use site resolves against.
7813 ///
7814 /// The parser has already rejected a name no enclosing class declares, so a miss here
7815 /// means the compiler lost track of a class scope — which is worth a real error rather
7816 /// than an `unwrap`.
7817 fn private_use(
7818 &self,
7819 binding: &str,
7820 span: Span,
7821 ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7822 ClassPlan::find(self, binding)
7823 .map(|use_| (use_.kind, use_.setter.clone()))
7824 .ok_or_else(|| {
7825 SyntaxError::new(
7826 format!("the private name '{binding}' is out of scope here"),
7827 span,
7828 )
7829 })
7830 }
7831
7832 /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7833 ///
7834 /// The three readable kinds take three different instructions, because a private name
7835 /// holds three different things — a symbol, a method function, a getter function — and
7836 /// only the first one is a property read at all.
7837 fn private_load(
7838 &mut self,
7839 binding: &str,
7840 kind: PrivateKind,
7841 span: Span,
7842 ) -> Result<(), SyntaxError> {
7843 match kind {
7844 PrivateKind::Field => {
7845 self.emit_var(VarAction::Get, binding);
7846 self.emit(Opcode::GetPrivateField, &[]);
7847 }
7848 PrivateKind::Method => {
7849 self.emit_var(VarAction::Get, binding);
7850 self.emit(Opcode::CheckBrand, &[]);
7851 // `check_brand` reads `obj func` and leaves both; the method itself is what
7852 // `this.#m` evaluates to.
7853 self.emit(Opcode::Nip, &[]);
7854 }
7855 PrivateKind::Getter => {
7856 self.emit_var(VarAction::Get, binding);
7857 self.emit(Opcode::CheckBrand, &[]);
7858 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7859 }
7860 // `#a` is declared but never filled when only a setter exists, so reading it is
7861 // the same refusal as assigning to a `const`. The reference reports it with the
7862 // generic read-only wording and leaves the better message as a `XXX`.
7863 PrivateKind::Setter => self.emit(
7864 Opcode::ThrowError,
7865 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7866 ),
7867 }
7868 let _ = span;
7869 Ok(())
7870 }
7871
7872 /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
7873 fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
7874 match kind {
7875 // A method *is* the callee, so only the check goes in between.
7876 PrivateKind::Method => {
7877 self.emit_var(VarAction::Get, binding);
7878 self.emit(Opcode::CheckBrand, &[]);
7879 }
7880 _ => self.private_load(binding, kind, Span::default())?,
7881 }
7882 Ok(())
7883 }
7884
7885 /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
7886 /// wanted back.
7887 ///
7888 /// A getter/setter pair is a *method call*, not a property store: the reference reads
7889 /// the setter out of its own binding and calls it with the receiver, which is why the
7890 /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
7891 /// keeps the assignment's value for an expression context.
7892 fn private_store(
7893 &mut self,
7894 binding: &str,
7895 kind: PrivateKind,
7896 setter: Option<&str>,
7897 ) -> Result<(), SyntaxError> {
7898 match kind {
7899 PrivateKind::Field => {
7900 self.emit_var(VarAction::Get, binding);
7901 self.emit(Opcode::PutPrivateField, &[]);
7902 }
7903 PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
7904 Some(setter) => {
7905 self.emit_var(VarAction::Get, setter);
7906 // `obj func value` -> `value obj func` for the check, and back again for
7907 // the call, which wants `obj func arg`.
7908 self.emit(Opcode::Swap, &[]);
7909 self.emit(Opcode::Rot3r, &[]);
7910 self.emit(Opcode::CheckBrand, &[]);
7911 self.emit(Opcode::Rot3l, &[]);
7912 self.emit(Opcode::CallMethod, &[Op::Int(1)]);
7913 // The setter's return value is discarded; the assignment's own value is
7914 // whatever the caller left underneath.
7915 self.emit(Opcode::Drop, &[]);
7916 }
7917 None => self.emit(
7918 Opcode::ThrowError,
7919 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7920 ),
7921 },
7922 }
7923 Ok(())
7924 }
7925
7926 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
7927 // `x++` inside a `with` is a read-modify-write of a *property*, so the object is
7928 // resolved once for both halves. See [`Compiler::with_reference`].
7929 let unparened = argument.unparen();
7930 if let ExprKind::Ident(ident) = &unparened.kind {
7931 let name = ident.name.clone();
7932 if !self.visible_with_names(&name).is_empty() {
7933 return self.with_reference(
7934 &name,
7935 &mut |compiler, with_local| compiler.with_update(with_local, ident, op, prefix),
7936 &mut |compiler| compiler.update_plain(op, unparened, prefix),
7937 );
7938 }
7939 }
7940 self.update_plain(op, argument, prefix)
7941 }
7942
7943 fn update_plain(
7944 &mut self,
7945 op: UpdateOp,
7946 argument: &Expr,
7947 prefix: bool,
7948 ) -> Result<(), SyntaxError> {
7949 let instruction = match (op, prefix) {
7950 (UpdateOp::Increment, true) => Opcode::Inc,
7951 (UpdateOp::Increment, false) => Opcode::PostInc,
7952 (UpdateOp::Decrement, true) => Opcode::Dec,
7953 (UpdateOp::Decrement, false) => Opcode::PostDec,
7954 };
7955 // `(y)++` and `((o.x))++` are the same updates as the unparenthesised forms: §13.4
7956 // evaluates the operand as a `LeftHandSideExpression` and the parentheses around a
7957 // reference change nothing — they do not copy the value. Reading `argument.kind`
7958 // directly therefore rejected every parenthesised target with "increment of a
7959 // non-variable", which is not a thing the language has (`target-cover-id`).
7960 let argument = argument.unparen();
7961 if let ExprKind::Member {
7962 object,
7963 property,
7964 optional: _,
7965 } = &argument.kind
7966 {
7967 // `o.x++` needs the receiver twice, so the last link is read with the
7968 // `get_*2`/`get_*3` form that keeps it, and the update is written back
7969 // with `put_field`/`put_array_el`. The reordering in between is what puts
7970 // the old value below the receiver for a postfix update and the new one
7971 // above it for a prefix one:
7972 //
7973 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
7974 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
7975 //
7976 // This mirrors the reference instruction for instruction.
7977 self.expr(object)?;
7978 match property {
7979 MemberProp::Ident(name) => {
7980 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
7981 self.emit(instruction, &[]);
7982 self.emit(
7983 if prefix {
7984 Opcode::Insert2
7985 } else {
7986 Opcode::Perm3
7987 },
7988 &[],
7989 );
7990 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
7991 }
7992 MemberProp::Computed(index) => {
7993 self.expr(index)?;
7994 self.emit(Opcode::GetArrayEl3, &[]);
7995 self.emit(instruction, &[]);
7996 self.emit(
7997 if prefix {
7998 Opcode::Insert3
7999 } else {
8000 Opcode::Perm4
8001 },
8002 &[],
8003 );
8004 self.emit(Opcode::PutArrayEl, &[]);
8005 }
8006 MemberProp::Private(name) => {
8007 // The receiver is duplicated and the read keeps it, exactly as `get_field2`
8008 // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
8009 // `perm3` -> `old obj new` -> store.
8010 let binding = format!("#{}", name.name);
8011 let (kind, setter) = self.private_use(&binding, argument.span)?;
8012 self.emit(Opcode::Dup, &[]);
8013 self.private_load(&binding, kind, argument.span)?;
8014 self.emit(instruction, &[]);
8015 self.emit(
8016 if prefix {
8017 Opcode::Insert2
8018 } else {
8019 Opcode::Perm3
8020 },
8021 &[],
8022 );
8023 self.private_store(&binding, kind, setter.as_deref())?;
8024 }
8025 }
8026 return Ok(());
8027 }
8028 let ExprKind::Ident(name) = &argument.kind else {
8029 return Err(SyntaxError::new(
8030 "increment of a non-variable is not supported by the compiler yet",
8031 argument.span,
8032 ));
8033 };
8034 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
8035 // reference's `inc_loc` folds those three into one, but it does so only in some
8036 // positions (a `for` update and not a bare statement, and never for a lexical
8037 // binding), so emitting it unconditionally would move *away* from its output.
8038 // The instruction is equivalent either way; matching the reference matters more
8039 // than saving two instructions.
8040 let _ = !std::mem::take(&mut self.state().discard_value);
8041 self.emit_var(VarAction::Get, &name.name);
8042 self.emit(instruction, &[]);
8043 if prefix {
8044 self.emit(Opcode::Dup, &[]);
8045 }
8046 self.emit_var(VarAction::Put, &name.name);
8047 Ok(())
8048 }
8049
8050 /// Compile an array literal.
8051 ///
8052 /// The reference splits this into three phases, and the split is load-bearing
8053 /// rather than an optimisation detail:
8054 ///
8055 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
8056 /// the array in one instruction.
8057 /// 2. **Everything up to the first spread** is appended with explicit indices
8058 /// (`define_field <index>`), because a hole has no element to pass to
8059 /// `array_from`. A hole here is what makes `length` need fixing up: an
8060 /// explicit index does not extend the array the way a pushed element does.
8061 /// 3. **From the first spread on** the index lives on the stack, so `append` and
8062 /// `define_array_el` can consume it and `inc` advances it.
8063 ///
8064 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
8065 /// forces phase 2, and `[...a]` forces phase 3.
8066 fn array_literal(
8067 &mut self,
8068 elements: &[Option<ArrayElement>],
8069 span: Span,
8070 ) -> Result<(), SyntaxError> {
8071 let _ = span;
8072 let mut index: u32 = 0;
8073 let mut cursor = 0usize;
8074
8075 // Phase 1: a leading run of plain elements, at most 32 of them.
8076 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
8077 if index >= 32 {
8078 break;
8079 }
8080 self.expr(element)?;
8081 index += 1;
8082 cursor += 1;
8083 }
8084 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
8085
8086 // Phase 2: explicit indices, up to the first spread.
8087 let mut need_length = false;
8088 while let Some(element) = elements.get(cursor) {
8089 if matches!(element, Some(ArrayElement::Spread(_))) {
8090 break;
8091 }
8092 need_length = true;
8093 if let Some(ArrayElement::Expr(expression)) = element {
8094 self.expr(expression)?;
8095 self.emit_define_index(index);
8096 need_length = false;
8097 }
8098 index += 1;
8099 cursor += 1;
8100 }
8101
8102 if cursor >= elements.len() {
8103 if need_length {
8104 // `define_field` cannot set `length`, which is not configurable.
8105 self.emit(Opcode::Dup, &[]);
8106 self.push_number(index as f64);
8107 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8108 }
8109 return Ok(());
8110 }
8111
8112 // Phase 3: the index moves onto the stack for the spreading tail.
8113 //
8114 // `need_length` deliberately carries over from phase 2: a hole before the
8115 // first spread still has to be reflected in `length`, and only the final
8116 // check can do it because the array is not finished until the tail is
8117 // appended.
8118 self.push_number(index as f64);
8119 while let Some(element) = elements.get(cursor) {
8120 match element {
8121 Some(ArrayElement::Spread(expression)) => {
8122 // `append` copies an iterable and leaves the next index behind,
8123 // so no `inc` is needed here.
8124 self.expr(spread_argument(expression))?;
8125 self.emit(Opcode::Append, &[]);
8126 }
8127 None | Some(ArrayElement::Expr(_)) => {
8128 need_length = true;
8129 if let Some(ArrayElement::Expr(expression)) = element {
8130 self.expr(expression)?;
8131 self.emit(Opcode::DefineArrayEl, &[]);
8132 need_length = false;
8133 }
8134 self.emit(Opcode::Inc, &[]);
8135 }
8136 }
8137 cursor += 1;
8138 }
8139 if need_length {
8140 self.emit(Opcode::Dup1, &[]);
8141 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8142 } else {
8143 self.emit(Opcode::Drop, &[]);
8144 }
8145 Ok(())
8146 }
8147
8148 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
8149 fn emit_define_index(&mut self, index: u32) {
8150 self.emit(
8151 Opcode::DefineField,
8152 &[Op::Atom(Atom::from_text(&index.to_string()))],
8153 );
8154 }
8155
8156 // -- functions ---------------------------------------------------------
8157
8158 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
8159 self.compile_function_with_name(func, false)
8160 }
8161
8162 /// Compile a function, recording whether it is a *named function expression*.
8163 ///
8164 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
8165 /// must not leak outside. The reference does that by declaring `g` as a local of
8166 /// the function itself and initialising it with `special_object 2` (the current
8167 /// function), which is why this has to be known at compile time.
8168 fn compile_function_with_name(
8169 &mut self,
8170 func: &ast::Function,
8171 is_expression: bool,
8172 ) -> Result<CompiledFunction, SyntaxError> {
8173 let kind = match (func.is_generator, func.is_async) {
8174 (false, false) => FunctionKind::Normal,
8175 (true, false) => FunctionKind::Generator,
8176 (false, true) => FunctionKind::Async,
8177 (true, true) => FunctionKind::AsyncGenerator,
8178 };
8179 let mut state = FnState::new(
8180 func.name
8181 .as_ref()
8182 .map(|n| n.name.clone())
8183 .unwrap_or_default(),
8184 kind,
8185 );
8186 // The function's own mode, recorded by the parser. Inheriting the enclosing
8187 // function's instead let a nested `"use strict"` directive be ignored, so the
8188 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
8189 state.strict = func.strict;
8190 // A function defined inside a `with` block keeps seeing that object: the guard
8191 // chain names the enclosing `<with>` locals, which resolve outward into closure
8192 // variables exactly like any other captured binding.
8193 state.inherited_with_names = self.cur().with_names.len();
8194 state.with_names = self.cur().with_names.clone();
8195 state.is_arrow = func.is_arrow;
8196 state.created_in_block = self.cur().current_block;
8197 // A default anywhere in the parameter list is what gives the function two
8198 // variable environments. The reference decides this the same way: it scans the
8199 // parenthesis for a top-level `=`, so a destructured name without a default
8200 // stays a plain function-scope binding.
8201 state.in_params = false;
8202 // The reference scans the parenthesis for *any* `=`, including one nested inside
8203 // a pattern, so `function f({a = 1})` has parameter expressions even though the
8204 // parameter itself carries no initialiser.
8205 state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
8206 // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
8207 // flag above this looks at the *shape* of each parameter, not just for `=`.
8208 state.simple_parameter_list = func
8209 .params
8210 .iter()
8211 .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
8212 // A function born inside a parameter list inherits the prohibition: it must not
8213 // see the body bindings of the function it was created in.
8214 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
8215 // A class constructor knows what it is only because the class told it.
8216 if let Some(kind) = self.cur().class_ctor_pending {
8217 state.ctor_kind = kind;
8218 }
8219 // A named *expression* binds its own name; a declaration's name is already
8220 // bound in the enclosing scope.
8221 state.self_name = if is_expression && !func.is_arrow {
8222 func.name.as_ref().map(|n| n.name.clone())
8223 } else {
8224 None
8225 };
8226 // Keep the written range so `Function.prototype.toString` can answer with the
8227 // original text rather than `[native code]`.
8228 //
8229 // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
8230 // accessor and generator prefixes, and for a method it must not include the name
8231 // or a leading `static`. `params_span` is exactly that boundary.
8232 // A *method* keeps the old `[native code]` answer: its reported text is defined
8233 // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
8234 // the comments in between kept verbatim), and reconstructing that from a byte
8235 // span got it wrong in more cases than it got right. A plain function and an
8236 // arrow are the shapes libraries actually introspect, and those are exact.
8237 // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
8238 // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
8239 // so the same slice works for every form. (`Params_span` is the boundary that
8240 // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
8241 // `source_span` is set only where the reported text is not the function's own
8242 // range — a class's constructor reports the whole class definition.
8243 let reported = func.source_span.unwrap_or(func.span);
8244 state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
8245 state.line = func.span.start.line;
8246 state.column = func.span.start.column;
8247 // A function body has no hidden `<ret>` local; the value comes back on
8248 // the stack. Only a script keeps one.
8249 // Parameters are positional, so even a pattern occupies one argument slot. A
8250 // simple name is that slot itself; anything else (a pattern, a default, a rest
8251 // parameter) takes an anonymous slot and is unpicked into locals at the top of
8252 // the body, which is the only way one argument can bind several names.
8253 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
8254 // `.length` stops at the first parameter that can be substituted: a default
8255 // fills a missing argument in, and a rest parameter absorbs the rest.
8256 let mut defined_args = func.params.len() as u32;
8257 for (index, param) in func.params.iter().enumerate() {
8258 match simple_parameter(param) {
8259 Some(name) => state.args.push(VarDef::var(name.name.clone())),
8260 None => {
8261 state.args.push(VarDef::var(ANONYMOUS_BINDING));
8262 prologue.push((index, param.clone()));
8263 }
8264 }
8265 }
8266 // A default anywhere before the end also ends the count, which the loop above
8267 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
8268 for (position, param) in func.params.iter().enumerate() {
8269 if matches!(
8270 param.kind,
8271 PatternKind::Assign { .. } | PatternKind::Rest(_)
8272 ) {
8273 defined_args = position as u32;
8274 break;
8275 }
8276 }
8277 state.defined_args = defined_args;
8278 state.param_prologue = prologue;
8279 let depth = self.stack.len();
8280 self.stack.push(state);
8281 let result = self.compile_function_body(func);
8282 if result.is_err() {
8283 // A failed compile must not leave its `FnState` behind. Every caller
8284 // reads `self.state()` as "the function being compiled", so a leftover
8285 // frame silently retargets all later bookkeeping at a dead function.
8286 self.stack.truncate(depth);
8287 }
8288 result
8289 }
8290
8291 /// The body of a function, with its frame already pushed.
8292 fn compile_function_body(
8293 &mut self,
8294 func: &ast::Function,
8295 ) -> Result<CompiledFunction, SyntaxError> {
8296 let body_key = func.params_span.end.offset as u64;
8297 // Where the body begins, in source order. The runtime needs this to tell a
8298 // closure created by a default expression from one the body creates — the two see
8299 // different variable environments — and a bytecode offset would not survive the
8300 // instruction shuffling that building the frame does. Positions are in source
8301 // order, so a comparison answers it.
8302 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
8303 self.push_block(body_key, NO_PARENT);
8304 self.state().body_block = body_key;
8305 // An arrow with an expression body has no statements; the expression is
8306 // its `return`. Building the statement here keeps one code path below, and
8307 // matters for correctness beyond convenience: returning early with the new
8308 // `FnState` still on the stack would leave the compiler looking at the
8309 // wrong function, which surfaces as an unrelated underflow later.
8310 let concise = match &func.body {
8311 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
8312 StmtKind::Return(Some(Box::new((**value).clone()))),
8313 value.span,
8314 )),
8315 js_parse::ast::FunctionBody::Block(_) => None,
8316 };
8317 let body: &[Stmt] = match &concise {
8318 Some(stmt) => std::slice::from_ref(stmt),
8319 None => func
8320 .body
8321 .statements()
8322 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
8323 };
8324 let prologue = std::mem::take(&mut self.state().param_prologue);
8325 let has_param_scope = self.cur().has_parameter_expressions;
8326 // The parameter scope's own bindings, declared in source order.
8327 //
8328 // With parameter expressions the list gets a variable environment of its own, and
8329 // every name it binds is a `let` there. That is what puts the *list* in the
8330 // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
8331 // and `function f(x = y, y){}` does the same, where a single shared environment
8332 // would answer `undefined` to both.
8333 if has_param_scope {
8334 let mut declared: Vec<String> = Vec::new();
8335 for param in &func.params {
8336 let mut names = Vec::new();
8337 param.bound_names(&mut names);
8338 for name in names {
8339 if declared.contains(&name.name) {
8340 continue;
8341 }
8342 declared.push(name.name.clone());
8343 self.declare_param_binding(&name.name);
8344 }
8345 }
8346 }
8347 // A pattern parameter binds its names as function-scope locals, so they have to
8348 // exist — and be unpicked from the argument — before the body runs. With a
8349 // parameter scope these are the *second* environment: the pattern fills the
8350 // parameter's copy, and the body's binding is filled from it afterwards.
8351 for (_, pattern) in &prologue {
8352 let mut names = Vec::new();
8353 pattern.bound_names(&mut names);
8354 for name in names {
8355 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
8356 }
8357 }
8358 self.hoist(body, body_key)?;
8359 // A constructor's prologue is not a parameter unpacking but the `this` binding:
8360 // a base constructor takes the receiver, a derived one starts in the dead zone
8361 // because only `super()` may produce it.
8362 match self.cur().ctor_kind {
8363 CtorKind::None => {}
8364 CtorKind::Base => {
8365 self.begin_this_local();
8366 self.emit(Opcode::CheckCtor, &[]);
8367 // Instance fields are installed at the top of a base constructor's body,
8368 // before any statement — `class C { x = 1; constructor() { this.x } }` sees
8369 // `1`. This used to be emitted at the *tail*, which made every field read
8370 // `undefined` inside the constructor that declared it.
8371 self.call_field_initialiser();
8372 }
8373 CtorKind::Derived => {
8374 self.declare("this", VarDef::lexical("this"));
8375 let slot = self.cur().vars.len() as u32 - 1;
8376 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8377 self.emit(Opcode::CheckCtor, &[]);
8378 }
8379 }
8380 // Entering the parameter list: everything it binds starts in the dead zone.
8381 // The order is the reference's — it walks the scope chain, which is prepended, so
8382 // the bindings come out newest first.
8383 for name in self.param_binding_names().into_iter().rev() {
8384 if let Some(slot) = self.param_binding_slot(&name) {
8385 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8386 }
8387 }
8388 // The whole parameter list is one scope, and nothing in the body exists yet, so
8389 // every name it mentions resolves against the parameter bindings and outward.
8390 self.state().in_params = has_param_scope;
8391 for (index, param) in func.params.iter().enumerate() {
8392 if let Some(pattern) = prologue_pattern(&prologue, index) {
8393 // A destructuring parameter *initialises* its bindings: with a parameter
8394 // scope they are the list's own `let`s, which is why the stores skip the
8395 // dead-zone check, and why the reference reads their properties with
8396 // `get_field2` — a `let` needs no reference.
8397 let kind = if has_param_scope {
8398 VarDeclKind::Let
8399 } else {
8400 VarDeclKind::Var
8401 };
8402 match &pattern.kind {
8403 // `...rest` collects what is left rather than reading one slot.
8404 PatternKind::Rest(inner) => {
8405 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8406 self.destructure(inner, Some(kind))?;
8407 }
8408 _ => {
8409 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8410 self.destructure(pattern, Some(kind))?;
8411 }
8412 }
8413 continue;
8414 }
8415 // A plain name binds straight from its argument slot. With a parameter scope
8416 // the slot is also copied into the parameter binding, which is what a later
8417 // default (or a closure made among the defaults) reads.
8418 let Some(name) = simple_parameter(param) else {
8419 continue;
8420 };
8421 let target = self.param_binding_slot(&name.name);
8422 if matches!(param.kind, PatternKind::Rest(_)) {
8423 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8424 if let Some(slot) = target {
8425 self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
8426 }
8427 // `put_arg` rather than `set_arg`: the array is the last thing on the
8428 // stack and nothing keeps it. Named by hand because a name in the
8429 // parameter list resolves to the parameter binding, and this store has to
8430 // reach the *argument* — that is what the body reads.
8431 self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
8432 continue;
8433 }
8434 if let PatternKind::Assign { default, .. } = ¶m.kind {
8435 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8436 let has_value = self.new_label();
8437 self.emit(Opcode::Dup, &[]);
8438 self.emit(Opcode::IsUndefined, &[]);
8439 self.emit_jump(Opcode::IfFalse, has_value, &[]);
8440 self.emit(Opcode::Drop, &[]);
8441 self.expr(default)?;
8442 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
8443 // The argument slot keeps the substituted value, because the *body* reads
8444 // the slot rather than the parameter binding — so this store is named
8445 // explicitly, like the rest parameter's.
8446 self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8447 self.place_label(has_value);
8448 if let Some(slot) = target {
8449 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8450 }
8451 continue;
8452 }
8453 if let Some(slot) = target {
8454 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8455 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8456 }
8457 }
8458 // Copy the parameter scope into the body. A plain parameter needs nothing: the
8459 // body reads its argument slot, and the list kept the two in step. A name a
8460 // pattern bound has no argument slot of its own, so the body gets a `var` filled
8461 // from the parameter's copy — and *that* is why an assignment inside a default
8462 // does not reach the body.
8463 if has_param_scope {
8464 for (_, pattern) in &prologue {
8465 let mut names = Vec::new();
8466 pattern.bound_names(&mut names);
8467 for name in names {
8468 let Some(slot) = self.param_binding_slot(&name.name) else {
8469 continue;
8470 };
8471 let Some(body) = self.body_var_slot(&name.name) else {
8472 continue;
8473 };
8474 self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
8475 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
8476 }
8477 }
8478 }
8479 // The parameter list is over; from here on a direct `eval` belongs to the body.
8480 self.state().in_params = false;
8481 // Entering the body's own scope comes *after* the parameter list: the body's
8482 // `let`s are not in existence while the defaults run, and the reference emits
8483 // their `set_loc_uninitialized` only once the parameters are bound.
8484 self.emit_scope_enter(body_key);
8485 // A generator starts suspended: `initial_yield` parks the body so that creating one
8486 // runs no body code until the first `next()`.
8487 //
8488 // It comes *after* the parameter unpacking, not before, because a parameter
8489 // initialiser is not body code — `function* g(a = sideEffect())` must run
8490 // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
8491 // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
8492 // until the first `next()` and 29 test262 cases that check for a synchronous throw
8493 // saw none at all.
8494 //
8495 // An async function does **not** get one. Its body runs synchronously up to the
8496 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
8497 // before its caller's next statement — so an `initial_yield` here would park the
8498 // body before it started, which is not fixable at run time: the suspension looks
8499 // exactly like a real `await`.
8500 if self.cur().kind.is_generator() {
8501 self.emit(Opcode::InitialYield, &[]);
8502 }
8503 // Through `stmts`: the body is a block, and a `using` declaration in it is a
8504 // disposal region.
8505 self.stmts(body)?;
8506 // The implicit return only exists if control can actually get here: an
8507 // infinite loop never falls off the end.
8508 if self.end_is_reachable() {
8509 if self.cur().is_suspending() {
8510 // Falling off the end finishes the generator with `undefined`, and the
8511 // value is what tells the resume machinery "completed" rather than
8512 // "suspended".
8513 self.emit(Opcode::Undefined, &[]);
8514 self.emit(Opcode::ReturnAsync, &[]);
8515 } else {
8516 self.emit_class_constructor_tail();
8517 }
8518 }
8519 // Resolution runs while this function is still on the stack: capturing a
8520 // variable from an enclosing function means reaching into that
8521 // function's state, which requires the whole chain to be present.
8522 Ok(self.finish_current())
8523 }
8524
8525 /// Put every binding of a function that contains a direct `eval` into a cell.
8526 ///
8527 /// A direct eval can name any binding in scope, and any closure it creates has to
8528 /// keep sharing that binding after the function returns — `for (let i …)
8529 /// eval("push(() => i)")` collects one closure per iteration and each must read its
8530 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
8531 /// a cell. Doing this unconditionally for such functions is the cheap, honest
8532 /// answer: the alternative is knowing at compile time which names a string will
8533 /// mention.
8534 fn capture_everything_for_eval(&mut self) {
8535 let current = self.stack.len() - 1;
8536 if !self.stack[current].has_direct_eval {
8537 return;
8538 }
8539 for arg in &mut self.stack[current].args {
8540 arg.is_captured = true;
8541 }
8542 for var in &mut self.stack[current].vars {
8543 var.is_captured = true;
8544 }
8545 }
8546
8547 /// Whether the current position in the instruction stream can be reached.
8548 ///
8549 /// A walk over the control-flow graph, using labels as instruction indices.
8550 /// The reference does the same thing to decide whether an implicit
8551 /// `return_undef` is needed.
8552 fn end_is_reachable(&self) -> bool {
8553 let state = self.cur();
8554 reachable_instructions(state, state.insns.len())[state.insns.len()]
8555 }
8556
8557 /// Resolve and assemble the function on top of the compiler stack, then pop
8558 /// it.
8559 fn finish_current(&mut self) -> CompiledFunction {
8560 self.provide_param_arguments();
8561 self.provide_arguments();
8562 self.provide_this_local();
8563 self.provide_new_target_local();
8564 self.provide_home_object_local();
8565 self.provide_active_func_local();
8566 self.provide_self_name();
8567 self.materialize_eval_sites();
8568 self.capture_everything_for_eval();
8569 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
8570 // Captured bindings need a reference cell; the count goes in the header so
8571 // the runtime knows how many cells to allocate on entry.
8572 let current = self.stack.len() - 1;
8573 let captured = self.stack[current]
8574 .args
8575 .iter()
8576 .filter(|a| a.is_captured)
8577 .count()
8578 + self.stack[current]
8579 .vars
8580 .iter()
8581 .filter(|v| v.is_captured)
8582 .count();
8583 self.stack[current].var_ref_count = captured as u32;
8584 // The scope chain is only final now that every binding is known.
8585 rebuild_scope_chain(&mut self.stack[current]);
8586 let (code, stack_size, positions) =
8587 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
8588 let _ = &mut resolved;
8589 let mut state = self.stack.pop().expect("a function is being compiled");
8590 CompiledFunction {
8591 name: state.name,
8592 kind: state.kind,
8593 strict: state.strict,
8594 is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
8595 is_arrow: state.is_arrow,
8596 has_parameter_expressions: state.has_parameter_expressions,
8597 simple_parameter_list: state.simple_parameter_list,
8598 body_start: state.body_start,
8599 args: state.args,
8600 defined_args: state.defined_args,
8601 vars: state.vars,
8602 closure_vars: state.closure_vars,
8603 cpool: state.cpool,
8604 atoms: state.atoms,
8605 code,
8606 stack_size,
8607 var_ref_count: state.var_ref_count,
8608 positions,
8609 source: self.function_source(state.span, state.line, state.column),
8610 line: state.line,
8611 column: state.column,
8612 filename: None,
8613 eval_sites: state.eval_sites,
8614 module: state.module.take().map(Box::new),
8615 }
8616 }
8617}
8618
8619/// Assign each binding a scope level and rebuild the scope chains.
8620///
8621/// Levels are numbered in the order the blocks appear, with 0 reserved for the
8622/// function scope where `var` and hoisted functions live. Every binding outside
8623/// level 0 gets a `scope_next` link to the next binding visible from the same
8624/// point, so walking a block's chain enumerates exactly the bindings live there.
8625///
8626/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
8627/// point at `b`, which is declared later in the source but earlier in the chain.
8628fn rebuild_scope_chain(state: &mut FnState) {
8629 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
8630 // real block that happens to start at offset zero keeps its own level instead of
8631 // being merged into the function scope.
8632 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
8633 for block in &state.blocks {
8634 if !levels.contains(&block.key) {
8635 levels.push(block.key);
8636 }
8637 }
8638 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
8639 let parent_level = |level: usize| -> usize {
8640 if level == 0 {
8641 return 0;
8642 }
8643 let key = levels[level];
8644 let parent = state
8645 .blocks
8646 .iter()
8647 .find(|b| b.key == key)
8648 .map(|b| b.parent)
8649 .unwrap_or(FUNCTION_SCOPE);
8650 level_of(parent)
8651 };
8652
8653 // Own bindings per level, in declaration order.
8654 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
8655 let keys: Vec<u64> = (0..state.vars.len())
8656 .map(|index| {
8657 state
8658 .var_block
8659 .get(index)
8660 .copied()
8661 .unwrap_or(FUNCTION_SCOPE)
8662 })
8663 .collect();
8664 for (index, key) in keys.into_iter().enumerate() {
8665 // The parameter scope is not a block: it is a level of its own with no parent,
8666 // assigned below. Letting it land in level 0 would chain the body's bindings onto
8667 // it, which the reference does not do — the two environments are siblings.
8668 if key == PARAM_SCOPE {
8669 continue;
8670 }
8671 let level = level_of(key);
8672 state.vars[index].scope_level = level as u32;
8673 // A `catch` parameter is part of the runtime scope chain even though it is
8674 // not lexical: the handler's own bindings chain on to it, which is why the
8675 // reference prints `let y [next:1]` with `e` at 1.
8676 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
8677 {
8678 own[level].push(index);
8679 }
8680 }
8681
8682 // A scope's chain is its own bindings in reverse declaration order followed
8683 // by the enclosing scope's chain.
8684 let mut head = vec![-1i32; levels.len()];
8685 for level in 0..levels.len() {
8686 let inherited = if level == 0 {
8687 -1
8688 } else {
8689 head[parent_level(level)]
8690 };
8691 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
8692 head[level] = chain.first().map_or(inherited, |first| *first as i32);
8693 for (position, &index) in chain.iter().enumerate() {
8694 let next = chain
8695 .get(position + 1)
8696 .map_or(inherited, |next| *next as i32);
8697 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
8698 }
8699 }
8700 state.block_heads = head;
8701
8702 // The parameter list is a scope of its own, and it has no parent: the reference pops
8703 // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
8704 // the `-1` a block uses. A level past every real block keeps it out of the walk above
8705 // — nothing but the dump reads it — and the links run newest-to-oldest through the
8706 // bindings themselves, which is the order `set_loc_uninitialized` walks.
8707 let param_level = levels.len() as u32;
8708 let mut previous: Option<usize> = None;
8709 for index in 0..state.vars.len() {
8710 if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
8711 {
8712 continue;
8713 }
8714 state.vars[index].scope_level = param_level;
8715 state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
8716 previous = Some(index);
8717 }
8718}
8719
8720/// This is where names become slots and where the temporal dead zone shows up in
8721/// the instruction stream: a read of a `let`/`const` binding compiles to
8722/// `get_loc_check`, which throws if the binding is still uninitialised.
8723///
8724/// The peephole pass from the reference implementation is applied at the end,
8725/// for the same reason it is applied to resolved bytecode there: the patterns are
8726/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
8727/// resolution. Deleted instructions stay in the list as `None` so that label
8728/// indices remain valid; [`Assembler`] maps them to byte offsets.
8729/// A resolved instruction and the source position it came from.
8730type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
8731
8732/// A resolved instruction paired with its position, which is what `assemble` consumes.
8733type PositionedInsn = (Opcode, Vec<Op>);
8734
8735fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
8736 let current = stack.len() - 1;
8737 // Dead-code elimination, on the symbolic form where labels are still
8738 // instruction indices. A `break` inside a loop leaves the trailing `goto`
8739 // unreachable, and a `return` leaves everything after it unreachable; the
8740 // reference drops both. Doing it here means the emitter never has to think
8741 // about reachability.
8742 strip_empty_gosubs(stack, current);
8743 eliminate_dead_code(stack, current);
8744 let insns = std::mem::take(&mut stack[current].insns);
8745 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
8746 // `insns`, and every arm below pushes exactly one instruction, so the positions
8747 // stay aligned with `out`.
8748 let positions = std::mem::take(&mut stack[current].insn_pos);
8749 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
8750 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8751 for (index, insn) in insns.iter().enumerate() {
8752 let pos = positions.get(index).copied().flatten();
8753 out_pos.push(pos);
8754 match insn {
8755 Insn::Fixed { op, operands } => {
8756 let operands = operands
8757 .iter()
8758 .map(|operand| match operand {
8759 Op::Atom(atom) => {
8760 Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
8761 }
8762 other => other.clone(),
8763 })
8764 .collect();
8765 out.push(Some((*op, operands)));
8766 }
8767 Insn::Var {
8768 action,
8769 name,
8770 block,
8771 in_params,
8772 } => {
8773 // Both reads and writes in the parameter list address the parameter
8774 // scope. That is what puts the list in the temporal dead zone — a read of
8775 // a later parameter is `get_loc_check` on an uninitialised slot — and it
8776 // is also what keeps an assignment made inside a default away from the
8777 // body, which sees a separate environment.
8778 let slot = resolve_slot(stack, current, name, *block, *in_params);
8779 // A store to the name of a named function expression is special: the
8780 // reference drops it in sloppy mode and throws in strict mode, because
8781 // the binding is immutable but only *checked* when the body is strict.
8782 // The same rule applies when the name is reached through a closure:
8783 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8784 // the store in the arrow too, not just in the function that owns the
8785 // binding. Reaching the owner means walking the chain of closure
8786 // entries, which is what `self_name_binding` does.
8787 let self_name = matches!(action, VarAction::Put | VarAction::Set)
8788 .then(|| {
8789 // A local of this function is the common case and needs no
8790 // chain walk; only an access that resolves elsewhere can be
8791 // pointing at an enclosing function's name binding.
8792 if let Slot::Loc(index) = slot {
8793 stack[current]
8794 .vars
8795 .get(index as usize)
8796 .filter(|var| var.kind == VarKind::FunctionName)
8797 .map(|var| var.is_const)
8798 } else {
8799 self_name_binding(stack, current, name, *block)
8800 }
8801 })
8802 .flatten();
8803 if let Some(is_const) = self_name {
8804 out.push(Some(if is_const {
8805 (
8806 Opcode::ThrowError,
8807 vec![
8808 Op::AtomId(intern_atom(&mut stack[current], name)),
8809 Op::Int(0),
8810 ],
8811 )
8812 } else {
8813 (Opcode::Drop, Vec::new())
8814 }));
8815 continue;
8816 }
8817 out.push(Some(variable_instruction(stack, current, *action, slot)));
8818 }
8819 Insn::CloseCaptured { name, block } => {
8820 // The block matters: a loop variable is scoped to the `for` head's own
8821 // block, so resolving it against block 0 would miss it entirely and
8822 // silently emit nothing.
8823 let slot = resolve_slot(stack, current, name, *block, false);
8824 // Only a local with a reference cell has anything to close. A global
8825 // or a never-captured local resolves to no instruction at all, which
8826 // keeps the bytecode identical to the reference's.
8827 if let Slot::Loc(index) = slot
8828 && stack[current]
8829 .vars
8830 .get(index as usize)
8831 .is_some_and(|v| v.is_captured)
8832 {
8833 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
8834 } else {
8835 out.push(None);
8836 }
8837 }
8838 Insn::DeleteVar { name } => {
8839 // A binding — a local, an argument, or a declared global — cannot be
8840 // deleted, and the reference encodes that as a constant `push_false`.
8841 // Only an implicit global needs the runtime lookup.
8842 if matches!(
8843 resolve_slot(stack, current, name, 0, false),
8844 Slot::Global(_)
8845 ) {
8846 let atom = intern_atom(&mut stack[current], name);
8847 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
8848 } else {
8849 out.push(Some((Opcode::PushFalse, Vec::new())));
8850 }
8851 }
8852 Insn::Dead => out.push(None),
8853 }
8854 }
8855 // Which label (if any) sits on each instruction, so the jump patterns can
8856 // tell whether they would cross a jump target.
8857 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
8858 for (id, placed) in stack[current].labels.iter().enumerate() {
8859 if let Some(index) = *placed
8860 && index < label_at.len()
8861 && label_at[index].is_none()
8862 {
8863 label_at[index] = Some(id as u32);
8864 }
8865 }
8866 if std::env::var_os("QJS_DEBUG").is_some() {
8867 eprintln!("--- peephole entry ---");
8868 for (i, e) in out.iter().enumerate() {
8869 eprintln!("{i}: {e:?}");
8870 }
8871 eprintln!("label_at: {label_at:?}");
8872 }
8873 peephole(&mut out, &label_at, &stack[current].labels);
8874 (out, out_pos)
8875}
8876
8877/// Find where `name` lives, capturing it in an enclosing function when needed.
8878///
8879/// The search runs outward through the enclosing functions' states, which are
8880/// still on the compiler stack while a nested function is resolved. Finding the
8881/// name in an enclosing function is what creates a closure reference, and every
8882/// function in between has to forward it — a function can only reach its own
8883/// parent's frame.
8884///
8885/// A name declared nowhere is a global. The reference does *not* look it up by
8886/// name from the inner function: the top-level function gets one `[global]`
8887/// entry and every nested function gets a `[global_ref<n>]` pointing at its
8888/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
8889/// rather than `[global]`.
8890/// The lexical blocks enclosing `block`, innermost first.
8891fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
8892 let mut chain = Vec::new();
8893 let mut current = Some(block);
8894 while let Some(key) = current {
8895 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
8896 // explicitly (rather than on "no block with this key") is what keeps a block
8897 // that happens to sit at offset zero from being mistaken for the terminator.
8898 if key == NO_PARENT || chain.contains(&key) {
8899 break;
8900 }
8901 chain.push(key);
8902 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
8903 }
8904 chain
8905}
8906
8907/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
8908///
8909/// The binding may be several functions away: an arrow nested in `function myfunc`
8910/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
8911/// means following `Ref` entries down and then reading the owning function's var table.
8912fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
8913 let state = stack.get(current)?;
8914 // A parameter shadows everything and is never a function-expression name.
8915 if state.args.iter().any(|arg| arg.name == name) {
8916 return None;
8917 }
8918 // A local of this very function: the answer is in its var table.
8919 if let Some(index) = local_slot_index(state, name, block) {
8920 let var = state.vars.get(index)?;
8921 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8922 }
8923 // Otherwise the name lives further out, and the closure entry says how to get
8924 // there. `Local` names the owner's slot directly; `Ref` names the next level's
8925 // closure entry, so the walk continues downwards.
8926 let mut level = current;
8927 let mut index = state
8928 .closure_vars
8929 .iter()
8930 .position(|closure| closure.name == name)?;
8931 loop {
8932 let state = stack.get(level)?;
8933 let closure = state.closure_vars.get(index)?;
8934 match closure.closure_type {
8935 ClosureType::Local => {
8936 let owner = stack.get(level.checked_sub(1)?)?;
8937 let var = owner.vars.get(closure.var_idx as usize)?;
8938 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8939 }
8940 ClosureType::Arg => return None,
8941 ClosureType::Ref => {
8942 level -= 1;
8943 index = closure.var_idx as usize;
8944 }
8945 // A global is never a function-expression name.
8946 ClosureType::Global
8947 | ClosureType::GlobalDecl
8948 | ClosureType::GlobalRef
8949 | ClosureType::ModuleDecl
8950 | ClosureType::ModuleImport => return None,
8951 }
8952 }
8953}
8954
8955/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
8956fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
8957 block_chain(state, block).into_iter().find_map(|scope| {
8958 state.vars.iter().enumerate().find_map(|(index, var)| {
8959 (var.name == name && state.var_block.get(index).copied() == Some(scope))
8960 .then_some(index)
8961 })
8962 })
8963}
8964
8965/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
8966fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
8967 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
8968 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
8969 }) {
8970 return index as u32;
8971 }
8972 state.var_block.push(PARAM_SCOPE);
8973 state.vars.push(VarDef::var(name));
8974 state.vars.len() as u32 - 1
8975}
8976
8977/// The name a parameter binds straight from its argument slot, if it has one.
8978///
8979/// A plain name does — with or without a default, and with or without `...`. Everything
8980/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
8981/// reference names the argument in the first case and leaves it `<null>` in the second,
8982/// so both the dump and the closures that capture the argument depend on this.
8983fn simple_parameter(param: &Pattern) -> Option<&Ident> {
8984 match ¶m.kind {
8985 PatternKind::Ident(name) => Some(name),
8986 PatternKind::Assign { target, .. } => match &target.kind {
8987 PatternKind::Ident(name) => Some(name),
8988 _ => None,
8989 },
8990 PatternKind::Rest(inner) => match &inner.kind {
8991 PatternKind::Ident(name) => Some(name),
8992 _ => None,
8993 },
8994 _ => None,
8995 }
8996}
8997
8998/// The pattern a parameter list has to unpick, if `index` is one of them.
8999fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
9000 prologue
9001 .iter()
9002 .find(|(at, _)| *at == index)
9003 .map(|(_, pattern)| pattern)
9004}
9005
9006fn pattern_has_default(pattern: &Pattern) -> bool {
9007 match &pattern.kind {
9008 PatternKind::Assign { .. } => true,
9009 PatternKind::Rest(inner) => pattern_has_default(inner),
9010 PatternKind::Array { elements, rest } => {
9011 elements.iter().flatten().any(element_has_default)
9012 || rest.as_deref().is_some_and(rest_has_default)
9013 }
9014 PatternKind::Object { properties, rest } => {
9015 properties.iter().flatten().any(element_has_default)
9016 || rest.as_deref().is_some_and(rest_has_default)
9017 }
9018 _ => false,
9019 }
9020}
9021
9022fn element_has_default(element: &PatternElement) -> bool {
9023 match element {
9024 PatternElement::Pattern(pattern) => pattern_has_default(pattern),
9025 PatternElement::Property { value, .. } => pattern_has_default(value),
9026 }
9027}
9028
9029fn rest_has_default(rest: &RestElement) -> bool {
9030 match rest {
9031 RestElement::Pattern(pattern) => pattern_has_default(pattern),
9032 RestElement::Member(_) => false,
9033 }
9034}
9035
9036/// Whether a function-scope binding is visible to the parameter list.
9037///
9038/// The parameter list runs before the body, so the body's `var`s and function
9039/// declarations do not exist yet — a name that only the body declares has to resolve
9040/// outward instead. What *does* exist by then is the compiler's own prologue: the
9041/// self-name of a named function expression (bound by `special_object 2` before anything
9042/// else), `this` and `new.target`. Those stay visible, which is what makes
9043/// `function f(a = this)` and `var f = function f(a = f)` work.
9044///
9045/// `arguments` is handled separately, as a binding of the parameter scope itself: with
9046/// parameter expressions the reference creates two of them, and the one the parameter
9047/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
9048fn visible_in_params(var: &VarDef) -> bool {
9049 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
9050}
9051
9052fn resolve_slot(
9053 stack: &mut [FnState],
9054 current: usize,
9055 name: &str,
9056 block: u64,
9057 in_params: bool,
9058) -> Slot {
9059 // The parameter list's own bindings. They are consulted first because they shadow
9060 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
9061 // `a` in the parameter scope, so a closure made there reads the parameter even after
9062 // the body assigns to its own `a`.
9063 if in_params
9064 && let Some(index) = stack[current]
9065 .vars
9066 .iter()
9067 .enumerate()
9068 .position(|(index, var)| {
9069 var.name == name
9070 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
9071 })
9072 {
9073 return Slot::Loc(index as u32);
9074 }
9075 // A name can be bound more than once: two `catch` parameters in nested
9076 // handlers are two slots. The binding that wins is the one whose scope encloses
9077 // the access, and among those the innermost — so the blocks are walked outward
9078 // and the first binding found on the way is the one that counts. A binding in
9079 // no block (`var`) is reachable from anywhere, which is why the function scope
9080 // is the end of the walk.
9081 //
9082 // The block walk comes *before* the argument slots, because a block may shadow a
9083 // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
9084 // slot is only the answer once nothing nearer claims the name.
9085 let chain = block_chain(&stack[current], block);
9086 for scope in &chain {
9087 let found = stack[current]
9088 .vars
9089 .iter()
9090 .enumerate()
9091 .find(|(index, var)| {
9092 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
9093 })
9094 .map(|(index, _)| index);
9095 if let Some(index) = found {
9096 return Slot::Loc(index as u32);
9097 }
9098 }
9099 // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
9100 // its own slot, and `var` of the same name in the body is the same binding.
9101 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
9102 return Slot::Arg(index as u32);
9103 }
9104 // Function-scope bindings — `var` and function declarations — are recorded with
9105 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
9106 // them. They are reachable from anywhere in the function, which is exactly what
9107 // the sentinel means.
9108 //
9109 // This pass is *only* for those. A lexical binding has to be found through the
9110 // chain or not at all, and looking a name up without its block is precisely how
9111 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
9112 // block leaked out of it.
9113 let function_scoped = stack[current]
9114 .vars
9115 .iter()
9116 .enumerate()
9117 .find(|(index, var)| {
9118 var.name == name
9119 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
9120 && (!in_params || visible_in_params(var))
9121 })
9122 .map(|(index, _)| index);
9123 if let Some(index) = function_scoped {
9124 return Slot::Loc(index as u32);
9125 }
9126 if let Some(index) = stack[current]
9127 .closure_vars
9128 .iter()
9129 .position(|c| c.name == name)
9130 {
9131 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
9132 }
9133
9134 for owner in (0..current).rev() {
9135 // The nested function was created inside one of this frame's blocks, and the
9136 // outermost visible binding is the innermost block on that chain — not whatever
9137 // comes first in the variable table. `function f(){ class S{} }` has two `S`
9138 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
9139 // the class body is the one a method may see.
9140 let entry = stack
9141 .get(owner + 1)
9142 .map(|s| s.created_in_block)
9143 .unwrap_or(0);
9144 let lexical = block_chain(&stack[owner], entry)
9145 .into_iter()
9146 .find_map(|scope| {
9147 stack[owner]
9148 .vars
9149 .iter()
9150 .enumerate()
9151 .find(|(index, var)| {
9152 var.name == name
9153 && stack[owner].var_block.get(*index).copied() == Some(scope)
9154 })
9155 .map(|(index, _)| index)
9156 });
9157 // A function born in a parameter list sees that list's bindings, not the body's:
9158 // the parameter scope is the environment it was created in.
9159 let in_param_scope = stack
9160 .get(owner + 1)
9161 .is_some_and(|child| child.created_in_params)
9162 .then(|| {
9163 stack[owner]
9164 .vars
9165 .iter()
9166 .enumerate()
9167 .position(|(index, var)| {
9168 var.name == name
9169 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
9170 })
9171 })
9172 .flatten();
9173 let found = if let Some(index) = in_param_scope {
9174 let var = &stack[owner].vars[index];
9175 Some(Found::Local(
9176 ClosureType::Local,
9177 index as u32,
9178 var.is_const,
9179 var.needs_check(),
9180 ))
9181 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
9182 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
9183 } else if let Some(index) = lexical {
9184 let var = &stack[owner].vars[index];
9185 Some(Found::Local(
9186 ClosureType::Local,
9187 index as u32,
9188 var.is_const,
9189 var.needs_check(),
9190 ))
9191 } else if let Some(index) = stack[owner]
9192 .vars
9193 .iter()
9194 .enumerate()
9195 .find_map(|(index, var)| {
9196 // A function created inside a parameter list must not see the body of the
9197 // function it was born in; see [`FnState::created_in_params`].
9198 let hidden = stack
9199 .get(owner + 1)
9200 .is_some_and(|child| child.created_in_params);
9201 (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
9202 })
9203 {
9204 let var = &stack[owner].vars[index];
9205 Some(Found::Local(
9206 ClosureType::Local,
9207 index as u32,
9208 var.is_const,
9209 var.needs_check(),
9210 ))
9211 } else if stack[owner].self_name.as_deref() == Some(name) {
9212 // A named function expression's own name. The reference declares it here,
9213 // on the first lookup that fails, rather than up front — and that is what
9214 // makes it reachable from a *nested* function: the nested lookup is what
9215 // walks out and creates the binding. A direct reference in the body is
9216 // caught the same way, which is why `provide_self_name` only has to add
9217 // the prologue.
9218 let strict = stack[owner].strict;
9219 stack[owner].var_block.push(FUNCTION_SCOPE);
9220 stack[owner].vars.push(VarDef {
9221 kind: VarKind::FunctionName,
9222 // In strict mode the name is immutable, so a store raises; sloppy
9223 // mode drops the store instead (see `variable_instruction`).
9224 is_const: strict,
9225 ..VarDef::var(name)
9226 });
9227 let index = stack[owner].vars.len() as u32 - 1;
9228 Some(Found::Local(ClosureType::Local, index, strict, false))
9229 } else if let Some(index) = stack[owner]
9230 .closure_vars
9231 .iter()
9232 .position(|c| c.name == name)
9233 {
9234 let closure = &stack[owner].closure_vars[index];
9235 Some(match closure.closure_type {
9236 // `GlobalRef` belongs here too: it is a *global* reached through this
9237 // frame's reference table, so treating it as a `Ref` to a local cell makes
9238 // the reader look for a cell no frame ever fills. That is how a second
9239 // function using `eval` in its parameter list read `undefined` after a
9240 // sibling had already made `eval` a closure entry.
9241 ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
9242 Found::Global(index as u32)
9243 }
9244 // A module variable is a cell in the *module's* environment, which is
9245 // the module body's parent as far as a nested function is concerned — so
9246 // it is captured as a plain reference, not looked up as a global.
9247 ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
9248 ClosureType::Ref,
9249 index as u32,
9250 closure.is_const,
9251 closure.is_lexical,
9252 ),
9253 _ => Found::Local(
9254 ClosureType::Ref,
9255 index as u32,
9256 closure.is_const,
9257 closure.is_lexical,
9258 ),
9259 })
9260 } else {
9261 None
9262 };
9263 let Some(found) = found else { continue };
9264
9265 let (is_const, is_lexical) = match found {
9266 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
9267 Found::Global(_) => (false, false),
9268 };
9269 // Mark the owner's binding as captured so it moves into a reference cell.
9270 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
9271 let slot = match found {
9272 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
9273 _ => &mut stack[owner].vars[index as usize],
9274 };
9275 slot.is_captured = true;
9276 }
9277 // Forward the reference through every function in between.
9278 let mut previous = match found {
9279 Found::Local(kind, index, _, _) => (kind, index),
9280 Found::Global(index) => (ClosureType::Global, index),
9281 };
9282 for level in owner + 1..=current {
9283 let kind = match (previous.0, level) {
9284 // A global stays a global at *every* level. Without `GlobalRef` in
9285 // this arm the second nested function over the same global got a
9286 // `Ref` to a cell no frame ever held, so the innermost closure read
9287 // `undefined` — which is how a two-deep getter lost its outer
9288 // variable.
9289 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
9290 ClosureType::GlobalRef
9291 }
9292 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
9293 _ => ClosureType::Ref,
9294 };
9295 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
9296 previous = (kind, index);
9297 }
9298 let index = previous.1;
9299 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
9300 }
9301
9302 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
9303 // creating a property. The top-level function holds the entry.
9304 let mut previous = (
9305 ClosureType::Global,
9306 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
9307 );
9308 for level in 1..=current {
9309 let index = ensure_closure(
9310 stack,
9311 level,
9312 name,
9313 false,
9314 false,
9315 ClosureType::GlobalRef,
9316 previous.1,
9317 );
9318 previous = (ClosureType::GlobalRef, index);
9319 }
9320 Slot::Global(previous.1)
9321}
9322
9323/// What an outward search turned up.
9324#[derive(Debug, Clone, Copy)]
9325enum Found {
9326 /// A binding in an enclosing function, reachable through a closure of this
9327 /// type, with its const/lexical flags.
9328 Local(ClosureType, u32, bool, bool),
9329 /// A global, reached through the enclosing function's closure entry.
9330 Global(u32),
9331}
9332
9333/// Add a closure entry to `level` if it is not there yet.
9334fn ensure_closure(
9335 stack: &mut [FnState],
9336 level: usize,
9337 name: &str,
9338 is_const: bool,
9339 is_lexical: bool,
9340 closure_type: ClosureType,
9341 var_idx: u32,
9342) -> u32 {
9343 if let Some(index) = stack[level]
9344 .closure_vars
9345 .iter()
9346 .position(|c| c.name == name)
9347 {
9348 return index as u32;
9349 }
9350 stack[level].closure_vars.push(ClosureVar {
9351 name: name.to_string(),
9352 is_const,
9353 is_lexical,
9354 closure_type,
9355 var_idx: var_idx as u16,
9356 });
9357 stack[level].closure_vars.len() as u32 - 1
9358}
9359
9360fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
9361 match closure.closure_type {
9362 // A `global_ref` only says *how* the binding is found (through the
9363 // parent's closure table); the access itself is an ordinary global one.
9364 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
9365 ClosureType::GlobalDecl => Slot::GlobalDecl(index),
9366 // A module variable is a real cell in the module's environment, so it is reached
9367 // exactly like a captured local — the host, not the global object, is what fills
9368 // the slot.
9369 ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
9370 _ => Slot::VarRef(index),
9371 }
9372}
9373
9374/// Pick the opcode for one variable access.
9375///
9376/// The `_check` variants are what enforce the temporal dead zone. They are used
9377/// for every access to a `let`/`const` binding except its own initialisation —
9378/// which is exactly the operation that takes the binding out of the dead zone.
9379fn variable_instruction(
9380 stack: &[FnState],
9381 current: usize,
9382 action: VarAction,
9383 slot: Slot,
9384) -> (Opcode, Vec<Op>) {
9385 let lexical = match slot {
9386 Slot::Loc(index) => stack[current]
9387 .vars
9388 .get(index as usize)
9389 .is_some_and(|v| v.needs_check()),
9390 Slot::VarRef(index) => stack[current]
9391 .closure_vars
9392 .get(index as usize)
9393 .is_some_and(|c| c.is_lexical),
9394 _ => false,
9395 };
9396 let operand = vec![Op::Slot(slot)];
9397 match (action, slot) {
9398 (VarAction::Get, Slot::Loc(index)) => (
9399 if lexical {
9400 Opcode::GetLocCheck
9401 } else {
9402 Opcode::GetLoc
9403 },
9404 vec![Op::Slot(Slot::Loc(index))],
9405 ),
9406 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
9407 (VarAction::Get, Slot::VarRef(index)) => (
9408 if lexical {
9409 Opcode::GetVarRefCheck
9410 } else {
9411 Opcode::GetVarRef
9412 },
9413 vec![Op::Slot(Slot::VarRef(index))],
9414 ),
9415 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
9416 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
9417 // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
9418 // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
9419 // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
9420 // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
9421 // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
9422 // `ReferenceError`.
9423 (VarAction::GetUndef, Slot::Loc(index)) => (
9424 if lexical {
9425 Opcode::GetLocCheck
9426 } else {
9427 Opcode::GetLoc
9428 },
9429 vec![Op::Slot(Slot::Loc(index))],
9430 ),
9431 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
9432 (VarAction::GetUndef, Slot::VarRef(index)) => (
9433 if lexical {
9434 Opcode::GetVarRefCheck
9435 } else {
9436 Opcode::GetVarRef
9437 },
9438 vec![Op::Slot(Slot::VarRef(index))],
9439 ),
9440 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9441 (Opcode::GetVarUndef, operand)
9442 }
9443
9444 (VarAction::Put, Slot::Loc(_)) => (
9445 if lexical {
9446 Opcode::PutLocCheck
9447 } else {
9448 Opcode::PutLoc
9449 },
9450 operand,
9451 ),
9452 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
9453 (VarAction::Put, Slot::VarRef(_)) => (
9454 if lexical {
9455 Opcode::PutVarRefCheck
9456 } else {
9457 Opcode::PutVarRef
9458 },
9459 operand,
9460 ),
9461 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
9462 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9463 // Initialisation is what ends the dead zone, so it never checks.
9464 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9465 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
9466 // `this` in a derived constructor is always a local, so these cannot happen;
9467 // routing them to the ordinary forms keeps the match total without inventing
9468 // opcodes the reference does not have.
9469 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
9470 // The captured form of `PutLocCheckInit`: `super()` inside an arrow that closes over
9471 // the constructor's `this` still has to refuse a second initialisation, and the
9472 // plain store accepted it (`fields-run-once-on-double-super`).
9473 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRefCheckInit, operand),
9474 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9475 (Opcode::PutVarInit, operand)
9476 }
9477 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
9478 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9479 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9480 (Opcode::PutVarInit, operand)
9481 }
9482 (VarAction::Set, Slot::Loc(_)) => (
9483 if lexical {
9484 Opcode::SetLocCheck
9485 } else {
9486 Opcode::SetLoc
9487 },
9488 operand,
9489 ),
9490 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
9491 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
9492 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9493 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9494 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
9495 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9496 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
9497 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
9498 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9499 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
9500 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9501 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
9502 }
9503}
9504
9505/// The instruction-rewriting pass.
9506///
9507/// These are the reference implementation's patterns, restricted to the ones the
9508/// constructs this compiler supports can produce. Each entry is a comment on the
9509/// bytecode it removes, because the whole point is that the result is one
9510/// instruction shorter than the literal translation of the AST.
9511fn peephole(
9512 insns: &mut [Option<(Opcode, Vec<Op>)>],
9513 label_at: &[Option<u32>],
9514 placed: &[Option<usize>],
9515) {
9516 fold_dup_patterns(insns, label_at);
9517
9518 // `drop` before `return_undef` is dead: the return discards the whole frame
9519 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
9520 // consumes its own `drop`; removing the drop first would leave the `dup` and
9521 // produce a `set_` where the reference has a `put_`.
9522 for index in 0..insns.len() {
9523 if opcode_at(insns, index) != Some(Opcode::Drop) {
9524 continue;
9525 }
9526 // Skip over a run of drops, but stop at a jump target: removing code on
9527 // one side of a label would silently retarget the jump.
9528 let mut next = index + 1;
9529 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
9530 next += 1;
9531 }
9532 if is_label_at(label_at, next) {
9533 continue;
9534 }
9535 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
9536 for entry in &mut insns[index..next] {
9537 *entry = None;
9538 }
9539 }
9540 }
9541
9542 // The rewrites below all decide against one fixed snapshot, which is what the
9543 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
9544 // the pass, so a rule never observes what an earlier rule removed. Gathering
9545 // every deletion first and applying them together reproduces that.
9546 let snapshot: Vec<Option<Opcode>> = insns
9547 .iter()
9548 .map(|entry| entry.as_ref().map(|(op, _)| *op))
9549 .collect();
9550 // The next instruction that is still there. Holes left by dead-code
9551 // elimination are not instructions, so a rule looks past them.
9552 let next_op = |index: usize| -> Option<usize> {
9553 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
9554 };
9555
9556 let mut doomed = vec![false; insns.len()];
9557 for index in 0..insns.len() {
9558 // A constant pushed only to be dropped does nothing at all. This is what a
9559 // comma expression with a literal left operand compiles to — `(0, f)()` — and
9560 // the reference removes the pair rather than making the reader step over it.
9561 let constant = matches!(
9562 snapshot[index],
9563 Some(
9564 Opcode::Undefined
9565 | Opcode::Null
9566 | Opcode::PushMinus1
9567 | Opcode::Push0
9568 | Opcode::Push1
9569 | Opcode::Push2
9570 | Opcode::Push3
9571 | Opcode::Push4
9572 | Opcode::Push5
9573 | Opcode::Push6
9574 | Opcode::Push7
9575 | Opcode::PushTrue
9576 | Opcode::PushFalse
9577 | Opcode::PushI32
9578 )
9579 );
9580 if constant
9581 && let Some(next) = next_op(index)
9582 && snapshot[next] == Some(Opcode::Drop)
9583 {
9584 doomed[index] = true;
9585 doomed[next] = true;
9586 }
9587 }
9588 for (index, entry) in insns.iter_mut().enumerate() {
9589 if doomed[index] {
9590 *entry = None;
9591 }
9592 }
9593
9594 // A conditional whose destination is the very next instruction just pops its
9595 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
9596 // compiles to.
9597 //
9598 // Order matters, and it is the reference's order: this runs *before* the
9599 // folding below, on the instruction the conditional originally had. Folding
9600 // moves a conditional's destination, and the reference never re-examines it
9601 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
9602 // a conditional even though folding leaves it pointing at the next
9603 // instruction.
9604 for (index, entry) in insns.iter_mut().enumerate() {
9605 let Some((op, operands)) = entry.clone() else {
9606 continue;
9607 };
9608 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
9609 continue;
9610 }
9611 let Some(id) = label_id(&operands) else {
9612 continue;
9613 };
9614 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
9615 *entry = Some((Opcode::Drop, Vec::new()));
9616 }
9617 }
9618
9619 // A constant condition is decided here rather than at run time.
9620 fold_constant_conditions(insns, label_at);
9621 // The conditional folding below is about pairs of *real* branches, so it runs
9622 // before a jump to the next instruction is dropped: `do { … if (c) continue }
9623 // while (t)` puts `continue` exactly on the condition, and the reference inverts
9624 // the branch first and only then notices the jump goes nowhere.
9625 fold_conditional_jumps(insns, label_at, placed);
9626
9627 // A jump whose destination is the very next instruction does nothing, which is
9628 // what constant folding leaves behind for `while (1) { … }`.
9629 remove_jump_to_next(insns, placed);
9630
9631 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
9632 // a use of the same variable boils down to.
9633 for index in 0..insns.len() {
9634 let Some((put_op, _)) = insns[index].clone() else {
9635 continue;
9636 };
9637 if !is_foldable_put(put_op) {
9638 continue;
9639 }
9640 if is_label_at(label_at, index + 1) {
9641 continue;
9642 }
9643 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
9644 continue;
9645 };
9646 if get_op != get_form_of(put_op) {
9647 continue;
9648 }
9649 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
9650 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
9651 continue;
9652 }
9653 insns[index] = Some((set_form_of(put_op), get_operands));
9654 insns[index + 1] = None;
9655 }
9656}
9657
9658/// Drop `gosub`s that call an empty subroutine.
9659///
9660/// A `gosub` whose target starts with `ret` returns immediately, so the reference
9661/// drops the call. This is how `try`/`catch` without a `finally` loses its
9662/// finalizer plumbing: the finalizer block is empty, its first instruction is
9663/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
9664/// [`eliminate_dead_code`] then removes.
9665fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
9666 let state = &stack[current];
9667 let mut targets = Vec::new();
9668 for insn in &state.insns {
9669 if let Insn::Fixed { op, operands } = insn
9670 && *op == Opcode::Gosub
9671 && let Some(id) = label_id(operands)
9672 && let Some(target) = state.labels.get(id as usize).copied().flatten()
9673 {
9674 targets.push(target);
9675 }
9676 }
9677 let empty: Vec<usize> = targets
9678 .into_iter()
9679 .filter(|target| {
9680 stack[current]
9681 .insns
9682 .get(*target)
9683 .map(|insn| {
9684 matches!(
9685 insn,
9686 Insn::Fixed {
9687 op: Opcode::Ret,
9688 ..
9689 }
9690 )
9691 })
9692 .unwrap_or(false)
9693 })
9694 .collect();
9695 if empty.is_empty() {
9696 return;
9697 }
9698 for insn in stack[current].insns.iter_mut() {
9699 if let Insn::Fixed { op, operands } = insn
9700 && *op == Opcode::Gosub
9701 && let Some(id) = label_id(operands)
9702 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
9703 && empty.contains(&target)
9704 {
9705 *insn = Insn::Dead;
9706 }
9707 }
9708}
9709
9710/// Replace unreachable instructions with [`Insn::Dead`].
9711fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
9712 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
9713 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
9714 if !reachable[index] {
9715 *insn = Insn::Dead;
9716 }
9717 }
9718}
9719
9720/// Mark every instruction index reachable from the entry, plus the index one past
9721/// the last instruction.
9722///
9723/// `seen[len]` answers "can control reach the end of this function", and the
9724/// entries before it identify dead code. Both DCE and the implicit-return decision
9725/// read the same result, which keeps them from disagreeing.
9726fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
9727 let mut seen = vec![false; count + 1];
9728 let mut worklist = vec![0usize];
9729 while let Some(index) = worklist.pop() {
9730 if index > count || seen[index] {
9731 continue;
9732 }
9733 seen[index] = true;
9734 if index == count {
9735 continue;
9736 }
9737 let (op, operands) = match &state.insns[index] {
9738 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
9739 // A variable access never transfers control, and a removed
9740 // instruction is only reachable if it is already marked.
9741 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
9742 worklist.push(index + 1);
9743 continue;
9744 }
9745 };
9746 match op {
9747 // A return, a throw and a `ret` all leave this instruction stream: the
9748 // first two give control to the caller or the handler, and `ret`
9749 // returns to a `gosub` elsewhere.
9750 // A tail call leaves the function too: the callee's result becomes this
9751 // function's result, so nothing after it runs.
9752 Opcode::Return
9753 | Opcode::ReturnUndef
9754 | Opcode::ReturnAsync
9755 | Opcode::TailCall
9756 | Opcode::TailCallMethod
9757 | Opcode::Throw
9758 | Opcode::ThrowError
9759 | Opcode::Ret => {}
9760 // A `catch` records where exceptions from the code that follows go.
9761 // That code is not reachable through normal control flow, but it is
9762 // reachable — through the exception edge — so the walk has to follow
9763 // it, or dead-code elimination would delete every handler.
9764 Opcode::Catch => {
9765 if let Some(target) = placed_label(state, operands) {
9766 worklist.push(target);
9767 }
9768 worklist.push(index + 1);
9769 }
9770 // A `gosub` calls a subroutine and then continues, so both edges count.
9771 Opcode::Gosub => {
9772 if let Some(target) = placed_label(state, operands) {
9773 worklist.push(target);
9774 }
9775 worklist.push(index + 1);
9776 }
9777 Opcode::Goto => {
9778 if let Some(target) = placed_label(state, operands) {
9779 worklist.push(target);
9780 }
9781 }
9782 Opcode::IfTrue | Opcode::IfFalse => {
9783 if let Some(target) = placed_label(state, operands) {
9784 worklist.push(target);
9785 }
9786 worklist.push(index + 1);
9787 }
9788 _ => worklist.push(index + 1),
9789 }
9790 }
9791 seen
9792}
9793
9794/// The instruction index a jump operand points at, resolved through the label
9795/// placement table.
9796fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
9797 let id = label_id(operands)?;
9798 state.labels.get(id as usize).copied().flatten()
9799}
9800
9801/// The label an instruction refers to.
9802fn label_id(operands: &[Op]) -> Option<u32> {
9803 operands.iter().find_map(|operand| match operand {
9804 Op::Label(label) => Some(label.0),
9805 _ => None,
9806 })
9807}
9808
9809/// Turn `if_false L; goto M; L:` into `if_true M`.
9810///
9811/// A conditional whose alternate branch is an unconditional jump needs one jump,
9812/// not two. This is the shape `if (c) break;` produces, so folding it removes an
9813/// instruction and a label from every conditional `break`.
9814/// The boolean a constant-push instruction produces, or `None` if it is not one.
9815///
9816/// Only the operators whose truthiness is decided by the opcode are covered; a
9817/// constant that needs the constant pool (a string) is left alone, because reading it
9818/// would mean threading the pool through the peephole for a case the reference also
9819/// skips.
9820fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
9821 match op {
9822 // `push_0` returns -1 for zero, `push_1` 1, and so on.
9823 Opcode::PushMinus1 => Some(true),
9824 Opcode::Push0 => Some(false),
9825 Opcode::Push1
9826 | Opcode::Push2
9827 | Opcode::Push3
9828 | Opcode::Push4
9829 | Opcode::Push5
9830 | Opcode::Push6
9831 | Opcode::Push7 => Some(true),
9832 Opcode::PushTrue => Some(true),
9833 Opcode::PushFalse => Some(false),
9834 Opcode::Undefined | Opcode::Null => Some(false),
9835 Opcode::PushI32 => match operands.first() {
9836 Some(Op::Int(value)) => Some(*value != 0),
9837 _ => None,
9838 },
9839 _ => None,
9840 }
9841}
9842
9843/// Fold a branch on a constant condition.
9844///
9845/// `if (0) a() else b()` must not test anything at run time, and the reference
9846/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
9847/// which is why the bytecode for a `while (1)` loop has no condition at all.
9848///
9849/// Two instructions become one, so the slot the test occupied is left empty rather
9850/// than shifting everything after it: labels have already been resolved to indices.
9851fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9852 for index in 0..insns.len() {
9853 let Some((push_op, push_operands)) = insns[index].clone() else {
9854 continue;
9855 };
9856 let Some(truth) = constant_truth(push_op, &push_operands) else {
9857 continue;
9858 };
9859 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
9860 continue;
9861 };
9862 // A label on the branch means something else jumps *here* — the value is on the
9863 // stack and the conditional is what pops it. Deleting the branch would leave that
9864 // jump with no instruction, and a label whose slot is empty resolves to the next
9865 // one that is not, i.e. to the far side of the branch. That is how
9866 // `if (a && false) then else` jumped to `then`: `&&` ends its chain on a label, and
9867 // the constant `false` sits directly in front of the statement's own conditional.
9868 if is_label_at(label_at, index + 1) {
9869 continue;
9870 }
9871 let (destination, taken) = match branch_op {
9872 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
9873 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
9874 _ => continue,
9875 };
9876 let Some(destination) = destination else {
9877 continue;
9878 };
9879 insns[index] = if taken {
9880 // The branch is always taken, so it becomes an unconditional jump.
9881 Some((Opcode::Goto, vec![destination]))
9882 } else {
9883 // The branch never runs: both instructions disappear and control falls
9884 // through to what came after.
9885 None
9886 };
9887 insns[index + 1] = None;
9888 }
9889}
9890
9891/// Remove a jump whose destination is the instruction right after it.
9892///
9893/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
9894/// its test into nothing, and the loop-end jump then points at the following
9895/// instruction. The reference drops them, so `stack_size` and the listing agree.
9896fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
9897 for index in 0..insns.len() {
9898 let Some((op, operands)) = insns[index].clone() else {
9899 continue;
9900 };
9901 if !is_goto(op) {
9902 continue;
9903 }
9904 let Some(id) = label_id(&operands) else {
9905 continue;
9906 };
9907 // The next instruction that still exists, which is what "the instruction
9908 // after this jump" means once earlier folds have punched holes.
9909 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
9910 if placed.get(id as usize).copied().flatten() == next {
9911 insns[index] = None;
9912 }
9913 }
9914}
9915
9916fn fold_conditional_jumps(
9917 insns: &mut [Option<(Opcode, Vec<Op>)>],
9918 label_at: &[Option<u32>],
9919 placed: &[Option<usize>],
9920) {
9921 for index in 0..insns.len() {
9922 let Some((op, operands)) = insns[index].clone() else {
9923 continue;
9924 };
9925 let inverted = match op {
9926 Opcode::IfFalse => Opcode::IfTrue,
9927 Opcode::IfTrue => Opcode::IfFalse,
9928 _ => continue,
9929 };
9930 // Next must be an unconditional jump that is not itself a target, and the
9931 // instruction after it must be exactly where the conditional goes.
9932 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
9933 continue;
9934 };
9935 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
9936 continue;
9937 }
9938 // The conditional must land on the instruction *after* the jump. Several
9939 // labels can share a position, so this asks where *this* label was put
9940 // rather than what label happens to sit there.
9941 let Some(taken) = label_id(&operands) else {
9942 continue;
9943 };
9944 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
9945 continue;
9946 }
9947 let Some(destination) = next_operands.first().cloned() else {
9948 continue;
9949 };
9950 insns[index] = Some((inverted, vec![destination]));
9951 insns[index + 1] = None;
9952 }
9953}
9954
9955/// Whether a jump target is placed at this instruction index.
9956fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
9957 label_at.get(index).copied().flatten().is_some()
9958}
9959
9960fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9961 // `dup put_x(n)` -> `set_x(n)`
9962 // `dup put_x(n) drop` -> `put_x(n)`
9963 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
9964 for index in 0..insns.len() {
9965 if opcode_at(insns, index) != Some(Opcode::Dup) {
9966 continue;
9967 }
9968 if is_label_at(label_at, index + 1) {
9969 continue;
9970 }
9971 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
9972 continue;
9973 };
9974 if !is_foldable_put(put_op) {
9975 continue;
9976 }
9977 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
9978 continue;
9979 };
9980 let mut new_op = set_form_of(put_op);
9981 let mut end = index + 2;
9982 if is_label_at(label_at, end) {
9983 // The `put` has to stay as it is; only the `dup` can be folded.
9984 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
9985 insns[index + 1] = None;
9986 continue;
9987 }
9988 // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
9989 // Deleting it moves the label's target onto whatever follows, and the code that
9990 // jumps there arrives with a different stack than the fall-through path: that is
9991 // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
9992 // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
9993 // an empty stack. The store had already consumed the value it was supposed to
9994 // leave behind.
9995 if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
9996 new_op = put_op;
9997 end += 1;
9998 if opcode_at(insns, end) == Some(get_form_of(put_op))
9999 && !is_label_at(label_at, end)
10000 && insns[end]
10001 .as_ref()
10002 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
10003 {
10004 new_op = set_form_of(put_op);
10005 end += 1;
10006 }
10007 }
10008 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
10009 for entry in &mut insns[index + 1..end] {
10010 *entry = None;
10011 }
10012 }
10013}
10014
10015fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
10016 insns
10017 .get(index)
10018 .and_then(|entry| entry.as_ref())
10019 .map(|(op, _)| *op)
10020}
10021
10022/// The four `put_` families that have a `set_` twin. Deliberately not including
10023/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
10024/// these, and folding the others would produce instructions that do not exist.
10025fn is_foldable_put(op: Opcode) -> bool {
10026 matches!(
10027 op,
10028 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
10029 )
10030}
10031
10032fn set_form_of(op: Opcode) -> Opcode {
10033 match op {
10034 Opcode::PutLoc => Opcode::SetLoc,
10035 Opcode::PutLocCheck => Opcode::SetLocCheck,
10036 Opcode::PutArg => Opcode::SetArg,
10037 Opcode::PutVarRef => Opcode::SetVarRef,
10038 other => other,
10039 }
10040}
10041
10042fn get_form_of(op: Opcode) -> Opcode {
10043 match op {
10044 Opcode::PutLoc => Opcode::GetLoc,
10045 Opcode::PutLocCheck => Opcode::GetLocCheck,
10046 Opcode::PutArg => Opcode::GetArg,
10047 Opcode::PutVarRef => Opcode::GetVarRef,
10048 other => other,
10049 }
10050}
10051
10052/// Atom interning, per function.
10053///
10054/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
10055/// identifiers, so the array-index rule applies here rather than at the handful of
10056/// call sites that build property keys.
10057fn intern_atom(state: &mut FnState, name: &str) -> u32 {
10058 intern_atom_value(state, Atom::from_text(name))
10059}
10060
10061/// [`intern_atom`] for an operand that is already an [`Atom`].
10062///
10063/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
10064/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
10065/// would have looked up.
10066fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
10067 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
10068 return index as u32;
10069 }
10070 state.atoms.push(atom);
10071 state.atoms.len() as u32 - 1
10072}
10073
10074fn binary_opcode(op: BinaryOp) -> Opcode {
10075 match op {
10076 BinaryOp::Add => Opcode::Add,
10077 BinaryOp::Sub => Opcode::Sub,
10078 BinaryOp::Mul => Opcode::Mul,
10079 BinaryOp::Div => Opcode::Div,
10080 BinaryOp::Mod => Opcode::Mod,
10081 BinaryOp::Pow => Opcode::Pow,
10082 BinaryOp::BitOr => Opcode::Or,
10083 BinaryOp::BitXor => Opcode::Xor,
10084 BinaryOp::BitAnd => Opcode::And,
10085 BinaryOp::Shl => Opcode::Shl,
10086 BinaryOp::Shr => Opcode::Sar,
10087 BinaryOp::UShr => Opcode::Shr,
10088 BinaryOp::Lt => Opcode::Lt,
10089 BinaryOp::LtEq => Opcode::Lte,
10090 BinaryOp::Gt => Opcode::Gt,
10091 BinaryOp::GtEq => Opcode::Gte,
10092 BinaryOp::Eq => Opcode::Eq,
10093 BinaryOp::NotEq => Opcode::Neq,
10094 BinaryOp::StrictEq => Opcode::StrictEq,
10095 BinaryOp::StrictNotEq => Opcode::StrictNeq,
10096 BinaryOp::In => Opcode::In,
10097 BinaryOp::Instanceof => Opcode::Instanceof,
10098 }
10099}
10100
10101fn compound_opcode(op: AssignOp) -> Opcode {
10102 match op {
10103 AssignOp::Add => Opcode::Add,
10104 AssignOp::Sub => Opcode::Sub,
10105 AssignOp::Mul => Opcode::Mul,
10106 AssignOp::Div => Opcode::Div,
10107 AssignOp::Mod => Opcode::Mod,
10108 AssignOp::Pow => Opcode::Pow,
10109 AssignOp::Shl => Opcode::Shl,
10110 AssignOp::Shr => Opcode::Sar,
10111 AssignOp::UShr => Opcode::Shr,
10112 AssignOp::BitOr => Opcode::Or,
10113 AssignOp::BitXor => Opcode::Xor,
10114 AssignOp::BitAnd => Opcode::And,
10115 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
10116 }
10117}
10118
10119/// Encode the resolved instruction stream, choosing short forms where possible.
10120///
10121/// The peephole pass leaves holes in the instruction list so that label indices
10122/// stay valid. A label names an *instruction index*, and an index that was
10123/// deleted has to resolve to the next surviving instruction, which is what
10124/// [`resolve_label`] does before the byte offsets are known.
10125fn assemble(
10126 insns: &mut [Option<(Opcode, Vec<Op>)>],
10127 insn_pos: &[Option<Position>],
10128 state: &mut FnState,
10129) -> (Vec<u8>, u32, Vec<LineCol>) {
10130 // Compaction: surviving instructions in order, plus the index mapping.
10131 //
10132 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
10133 // point below where instructions are removed — otherwise a stack trace would point
10134 // at the wrong source line as soon as dead-code elimination kicked in.
10135 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
10136 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
10137 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
10138 for (original, entry) in insns.iter_mut().enumerate() {
10139 if let Some((op, operands)) = entry.take() {
10140 original_to_kept[original] = Some(kept.len());
10141 kept.push((op, operands));
10142 spans.push(insn_pos.get(original).copied().flatten());
10143 }
10144 }
10145
10146 if std::env::var_os("QJS_DEBUG").is_some() {
10147 eprintln!("--- assemble entry --- {kept:?}");
10148 }
10149 // How many labels are real, as opposed to the per-instruction ones allocated
10150 // just below. Only a real label marks a spot in the source program.
10151 let real_labels = state.labels.len();
10152
10153 // Give every surviving instruction a label of its own. Jump cleanup below
10154 // redirects jumps to arbitrary instructions, and a jump target has to be a
10155 // label; pre-allocating one per index means a redirect never has to invent
10156 // anything.
10157 let existing = state.labels.len();
10158 let base = kept.len();
10159 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
10160 for offset in 0..=kept.len() {
10161 state.labels.push(Some(0));
10162 index_label.push(Label((existing + offset) as u32));
10163 }
10164 // Point each pre-allocated label at its instruction, reusing the count from
10165 // `original_to_kept` so the mapping survives compaction.
10166 let place_index_labels = |state: &mut FnState,
10167 original_to_kept: &[Option<usize>],
10168 kept_len: usize,
10169 index_label: &[Label]| {
10170 for (original, mapped) in original_to_kept.iter().enumerate() {
10171 if let Some(kept_index) = mapped {
10172 let label = index_label[*kept_index].0 as usize;
10173 state.labels[label] = Some(original);
10174 }
10175 }
10176 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
10177 };
10178 place_index_labels(state, &original_to_kept, base, &index_label);
10179
10180 // Resolve every label to a kept index once; the placement table maps labels
10181 // to original indices, so a second hop lands in kept space.
10182 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
10183 for (id, placed) in state.labels.iter().enumerate() {
10184 let Some(original) = placed else { continue };
10185 label_kept[id] = if *original == usize::MAX {
10186 Some(base)
10187 } else {
10188 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
10189 };
10190 }
10191
10192 // Code after an unconditional transfer is unreachable, and the reference drops it
10193 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
10194 // scans forward until it finds a label something still jumps to, so a run of
10195 // dead instructions between a `throw` and the next live target disappears.
10196 //
10197 // The scan repeats because dropping a jump lowers the reference count of the
10198 // label it pointed at, which can strand what follows. Only a real label keeps an
10199 // instruction alive here; the per-instruction labels allocated above belong to
10200 // this pass, not to the program.
10201 loop {
10202 let mut references = vec![false; kept.len() + 1];
10203 for (_, operands) in &kept {
10204 if let Some(target) = target_kept_index(operands, &label_kept)
10205 && target < references.len()
10206 {
10207 references[target] = true;
10208 }
10209 }
10210 let mut doomed = vec![false; kept.len()];
10211 let mut any = false;
10212 for (index, (op, _)) in kept.iter().enumerate() {
10213 if !is_transfer(*op) {
10214 continue;
10215 }
10216 for next in index + 1..kept.len() {
10217 if references[next] {
10218 break;
10219 }
10220 doomed[next] = true;
10221 any = true;
10222 }
10223 }
10224 if !any {
10225 break;
10226 }
10227 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
10228 }
10229
10230 // A label that lands on an unconditional jump stands for wherever that jump
10231 // goes, so retarget it once and every jump to the label follows for free.
10232 // This is what makes `continue` in a `for` head reach the loop top instead of
10233 // stopping at the update's trailing jump.
10234 let folded: Vec<Option<usize>> = label_kept
10235 .iter()
10236 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
10237 .collect();
10238 label_kept = folded;
10239
10240 // Jump cleanup, in compacted index space. Two rewrites the reference also
10241 // applies while it resolves labels:
10242 // * a jump whose destination is the very next instruction does nothing;
10243 // * a jump to a jump is redirected to its final destination.
10244 // The second can expose the first, so this repeats until it settles.
10245 loop {
10246 let mut delete = vec![false; kept.len()];
10247 let mut changed = false;
10248 for index in 0..kept.len() {
10249 let (op, operands) = &kept[index];
10250 if !is_goto(*op) {
10251 continue;
10252 }
10253 let Some(immediate) = target_kept_index(operands, &label_kept) else {
10254 continue;
10255 };
10256 let target = follow_jump_chain(&kept, &label_kept, immediate);
10257 if target == index + 1 {
10258 delete[index] = true;
10259 changed = true;
10260 } else if matches!(
10261 kept.get(target).map(|(op, _)| *op),
10262 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
10263 ) {
10264 // Jumping straight to a return or throw is the same as doing it
10265 // here, so the jump becomes that instruction.
10266 kept[index] = (kept[target].0, Vec::new());
10267 changed = true;
10268 } else if target != immediate {
10269 // Redirect to the end of the chain.
10270 let label = index_label[target];
10271 kept[index].1 = vec![Op::Label(label)];
10272 changed = true;
10273 }
10274 }
10275 if !changed {
10276 break;
10277 }
10278 if !delete.iter().any(|deleted| *deleted) {
10279 break;
10280 }
10281 // Drop the deleted instructions and renumber everything.
10282 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10283 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10284 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10285 for (old, entry) in kept.into_iter().enumerate() {
10286 if delete[old] {
10287 continue;
10288 }
10289 moved[old] = Some(next.len());
10290 next.push(entry);
10291 next_spans.push(spans[old]);
10292 }
10293 for (id, slot) in label_kept.iter_mut().enumerate() {
10294 let Some(old) = *slot else { continue };
10295 *slot = match moved.get(old).copied().flatten() {
10296 Some(new) => Some(new),
10297 // The target was deleted: the jump now lands on whatever follows.
10298 None => (old..moved.len())
10299 .find_map(|i| moved[i])
10300 .or(Some(next.len())),
10301 };
10302 let _ = id;
10303 }
10304 kept = next;
10305 spans = next_spans;
10306 }
10307
10308 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
10309 // jump to the next instruction and is deleted, leaving the label at the end with
10310 // nothing pointing at it. If that also strands the last instruction, it goes
10311 // too — which is how a `try` whose body always returns ends on its `ret` rather
10312 // than an implicit `return_undef`.
10313 // Which instructions something still jumps to. Reading the surviving jumps is
10314 // what the reference's reference counts amount to: once a jump has been folded
10315 // away the label it named is unreferenced, even though the program still has a
10316 // label there.
10317 let mut references = vec![false; kept.len() + 1];
10318 let _ = real_labels;
10319 for (_, operands) in &kept {
10320 if let Some(target) = target_kept_index(operands, &label_kept)
10321 && target < references.len()
10322 {
10323 references[target] = true;
10324 }
10325 }
10326 let mut end = kept.len();
10327 while end > 0 {
10328 let last = end - 1;
10329 let reachable = references[last] || end < kept.len();
10330 if reachable {
10331 break;
10332 }
10333 let after_transfer = last
10334 .checked_sub(1)
10335 .map(|previous| {
10336 matches!(
10337 kept[previous].0,
10338 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
10339 )
10340 })
10341 .unwrap_or(false);
10342 if !after_transfer {
10343 break;
10344 }
10345 end = last;
10346 }
10347 kept.truncate(end);
10348 spans.truncate(end);
10349
10350 // Choose an opcode for each instruction and its size, so label offsets can be
10351 // computed.
10352 let chosen = choose_opcodes(&kept, &label_kept);
10353 let offsets = instruction_offsets(&chosen);
10354 let offset = *offsets.last().unwrap_or(&0);
10355
10356 let mut code = Vec::with_capacity(offset);
10357 for (position, (_, operands)) in kept.iter().enumerate() {
10358 let op = chosen[position];
10359 code.push(op as u8);
10360 let operands = retarget_labels(operands, &label_kept, kept.len());
10361 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
10362 }
10363 let stack_size = compute_stack_size(&code);
10364 // Keep only the offsets where the position actually changes: a run of
10365 // instructions on one line is one table entry, and the runtime binary searches
10366 // the table for the frame's pc.
10367 //
10368 // The table always starts at pc 0 with the *function's own* position, because the
10369 // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
10370 // last_line_num)` from `fd->source_pos`, the token the function definition starts at
10371 // (`function`, `async`, a method's property name). An instruction before the first
10372 // recorded operator therefore reports the function's own start, which is what makes a
10373 // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
10374 let mut positions: Vec<LineCol> = vec![LineCol {
10375 pc: 0,
10376 line: state.line,
10377 column: state.column,
10378 }];
10379 let mut last: Option<Position> = None;
10380 for (index, span) in spans.iter().enumerate() {
10381 let Some(pos) = *span else { continue };
10382 if last == Some(pos) {
10383 continue;
10384 }
10385 last = Some(pos);
10386 if pos.line == state.line && pos.column == state.column {
10387 // Already the seed entry above.
10388 continue;
10389 }
10390 positions.push(LineCol {
10391 pc: offsets[index] as u32,
10392 line: pos.line,
10393 column: pos.column,
10394 });
10395 }
10396 (code, stack_size, positions)
10397}
10398
10399/// Whether an instruction always transfers control away, so anything after it in the
10400/// same stream is unreachable.
10401fn is_transfer(op: Opcode) -> bool {
10402 matches!(
10403 op,
10404 Opcode::Goto
10405 | Opcode::Goto8
10406 | Opcode::Goto16
10407 | Opcode::Return
10408 | Opcode::ReturnUndef
10409 | Opcode::Throw
10410 | Opcode::ThrowError
10411 | Opcode::Ret
10412 )
10413}
10414
10415/// Remove the marked instructions and renumber the label table so it keeps pointing
10416/// at the same instructions. A label whose instruction went away moves to whatever
10417/// follows it, since a jump is never left with nowhere to land.
10418fn drop_instructions(
10419 kept: Vec<(Opcode, Vec<Op>)>,
10420 spans: Vec<Option<Position>>,
10421 label_kept: &mut [Option<usize>],
10422 doomed: &[bool],
10423) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
10424 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10425 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10426 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10427 for (old, entry) in kept.into_iter().enumerate() {
10428 if doomed.get(old).copied().unwrap_or(false) {
10429 continue;
10430 }
10431 moved[old] = Some(result.len());
10432 result.push(entry);
10433 result_spans.push(spans[old]);
10434 }
10435 for slot in label_kept.iter_mut() {
10436 let Some(old) = *slot else { continue };
10437 *slot = match moved.get(old).copied().flatten() {
10438 Some(new) => Some(new),
10439 None => (old..moved.len())
10440 .find_map(|i| moved[i])
10441 .or(Some(result.len())),
10442 };
10443 }
10444 (result, result_spans)
10445}
10446
10447fn is_goto(op: Opcode) -> bool {
10448 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
10449}
10450
10451/// The kept index a jump operand points at.
10452fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
10453 let id = label_id(operands)?;
10454 label_kept.get(id as usize).copied().flatten()
10455}
10456
10457/// Follow a chain of unconditional jumps to its first real destination.
10458fn follow_jump_chain(
10459 kept: &[(Opcode, Vec<Op>)],
10460 label_kept: &[Option<usize>],
10461 start: usize,
10462) -> usize {
10463 let mut current = start;
10464 // `for(;;)` jumps to itself, so the walk has to be bounded.
10465 for _ in 0..kept.len() {
10466 let Some((op, operands)) = kept.get(current) else {
10467 return current;
10468 };
10469 if !is_goto(*op) {
10470 return current;
10471 }
10472 let Some(next) = target_kept_index(operands, label_kept) else {
10473 return current;
10474 };
10475 if next == current {
10476 return current;
10477 }
10478 current = next;
10479 }
10480 current
10481}
10482
10483/// Rewrite label operands from label ids to kept instruction indices.
10484fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
10485 operands
10486 .iter()
10487 .map(|operand| match operand {
10488 Op::Label(label) => {
10489 let target = label_kept
10490 .get(label.0 as usize)
10491 .copied()
10492 .flatten()
10493 .unwrap_or(kept_len);
10494 Op::Label(Label(target as u32))
10495 }
10496 other => other.clone(),
10497 })
10498 .collect()
10499}
10500
10501/// Encode the resolved instruction stream, choosing short forms where possible.
10502///
10503/// Compute the maximum value-stack depth by exploring the control-flow graph.
10504///
10505/// This is a breadth-first walk from the first instruction, tracking the stack
10506/// depth on entry to each instruction. Every instruction has at most two
10507/// successors (fall through, and a jump target), so a worklist over byte offsets
10508/// is enough. The reference does the same thing in `compute_stack_size`, which is
10509/// why the resulting numbers match exactly.
10510///
10511/// Instructions that pop a variable number of values (`call`, `array_from`, …)
10512/// encode that count in their operand, which is added to the static `n_pop`.
10513fn compute_stack_size(code: &[u8]) -> u32 {
10514 let mut depth_at = vec![u16::MAX; code.len()];
10515 // Each entry carries the enclosing `catch` levels, innermost last, because
10516 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
10517 // offset and forgets that level.
10518 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
10519 let mut max_depth = 0u32;
10520
10521 while let Some((pc, depth, catch_levels)) = worklist.pop() {
10522 if pc >= code.len() {
10523 continue;
10524 }
10525 if depth_at[pc] != u16::MAX {
10526 continue;
10527 }
10528 force_depth(&mut depth_at, pc, depth);
10529
10530 let Some(op) = Opcode::from_u8(code[pc]) else {
10531 break;
10532 };
10533 let info = op.info();
10534 let next = pc + info.size as usize;
10535 if next > code.len() {
10536 break;
10537 }
10538 let mut n_pop = info.n_pop as u32;
10539 let mut n_push = info.n_push as u32;
10540 // Variable-length forms carry their count in the operand.
10541 match info.format {
10542 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
10543 n_pop += read_u16(code, pc + 1) as u32;
10544 }
10545 crate::opcode::OpFormat::Npopx => {
10546 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
10547 }
10548 _ => {}
10549 }
10550 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
10551 // are the `set_` variant; the table already records that, so nothing to
10552 // adjust here.
10553 let _ = &mut n_push;
10554
10555 // The depth before this instruction's own push, which is what a `catch`
10556 // records as its level.
10557 let depth_before = depth;
10558 let mut depth = depth.saturating_sub(n_pop) + n_push;
10559 let mut catch_levels = catch_levels;
10560 if op == Opcode::NipCatch {
10561 // Discard everything above the innermost catch offset, keeping the value
10562 // on top: the frame the code after this sees is the same shape it would
10563 // have had if the `try` were not there.
10564 if let Some(base) = catch_levels.pop() {
10565 depth = base + 1;
10566 }
10567 }
10568 max_depth = max_depth.max(depth);
10569
10570 // Successors.
10571 let target = jump_target_of(code, pc, op);
10572 match op {
10573 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10574 if let Some(target) = target {
10575 worklist.push((target, depth, catch_levels));
10576 }
10577 }
10578 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
10579 if let Some(target) = target {
10580 worklist.push((target, depth, catch_levels.clone()));
10581 }
10582 worklist.push((next, depth, catch_levels));
10583 }
10584 // A `catch` records an exception edge to the handler. The handler is
10585 // entered with the thrown value on top of the stack, in the slot the
10586 // catch offset occupies on the normal path — which is why the handler's
10587 // first instruction can `put_loc` the exception away, and why the depth
10588 // is the same on both paths.
10589 Opcode::Catch => {
10590 if let Some(target) = target {
10591 // The handler is protected by the *enclosing* catch, not by this
10592 // one: an error raised inside it is what the handler's own
10593 // `catch` catches.
10594 worklist.push((target, depth, catch_levels.clone()));
10595 }
10596 catch_levels.push(depth_before);
10597 worklist.push((next, depth, catch_levels));
10598 }
10599 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
10600 // rewind past it too. Its level sits one slot higher than a `catch`'s:
10601 // the iterator and next-method slots occupy the offset's place.
10602 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
10603 if let Some(target) = target {
10604 worklist.push((target, depth, catch_levels.clone()));
10605 }
10606 catch_levels.push(depth_before + 1);
10607 worklist.push((next, depth, catch_levels));
10608 }
10609 // `gosub` calls a subroutine with the return address on top. The opcode
10610 // table records no push for it — `ret` is what pops the slot — so the
10611 // extra one is added here, where the depth of the subroutine's first
10612 // instruction is being computed.
10613 Opcode::Gosub => {
10614 if let Some(target) = target {
10615 worklist.push((target, depth + 1, catch_levels.clone()));
10616 }
10617 worklist.push((next, depth, catch_levels));
10618 }
10619 // `ret` goes back to a `gosub`; nothing here follows it.
10620 Opcode::Ret
10621 | Opcode::Return
10622 | Opcode::ReturnUndef
10623 | Opcode::Throw
10624 | Opcode::ThrowError => {}
10625 _ => worklist.push((next, depth, catch_levels)),
10626 }
10627 }
10628 max_depth
10629}
10630
10631/// Record the stack depth on entry to `pc`, keeping the deeper value if the
10632/// instruction is reachable more than once.
10633fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
10634 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
10635 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
10636 depth_at[pc] = clamped;
10637 }
10638}
10639
10640fn read_u16(code: &[u8], at: usize) -> u16 {
10641 let mut value = 0u16;
10642 for i in 0..2 {
10643 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
10644 }
10645 value
10646}
10647
10648/// The absolute target of a jump instruction, if it has one.
10649fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
10650 let info = op.info();
10651 let position = pc + 1;
10652 match info.format {
10653 crate::opcode::OpFormat::Label8 => {
10654 let offset = *code.get(position)? as i8 as i64;
10655 Some((position as i64 + offset) as usize)
10656 }
10657 crate::opcode::OpFormat::Label16 => {
10658 let offset = read_u16(code, position) as i16 as i64;
10659 Some((position as i64 + offset) as usize)
10660 }
10661 crate::opcode::OpFormat::Label => {
10662 let mut offset = 0i32;
10663 for i in 0..4 {
10664 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
10665 }
10666 Some((position as i64 + offset as i64) as usize)
10667 }
10668 _ => None,
10669 }
10670}
10671
10672fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
10673 use Opcode::*;
10674 match (op, operands.first()) {
10675 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
10676 op.short_form(*value as u32).unwrap_or(op)
10677 }
10678 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
10679 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
10680 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
10681 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
10682 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
10683 // A declared global is reached through its reference cell, so it shares
10684 // the `var_ref` encodings, short forms included.
10685 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
10686 op.short_form(*index).unwrap_or(op)
10687 }
10688 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
10689 op.short_form(*count as u32).unwrap_or(op)
10690 }
10691 _ => op,
10692 }
10693}
10694
10695/// The byte offset each instruction will start at, plus the total code size.
10696fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
10697 let mut offsets = Vec::with_capacity(chosen.len() + 1);
10698 let mut offset = 0usize;
10699 for op in chosen {
10700 offsets.push(offset);
10701 offset += op.size() as usize;
10702 }
10703 offsets.push(offset);
10704 offsets
10705}
10706
10707/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
10708/// the offset actually fits.
10709///
10710/// The choice is circular: an instruction's size decides the offsets of everything after
10711/// it, and the offsets decide whether a jump may be short. So this starts with every jump
10712/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
10713/// Shrinking only ever *shortens* distances, so the loop converges.
10714///
10715/// Doing it in one pass instead — which is what this used to do — silently truncated any
10716/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
10717/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
10718/// with four closures in its body simply stopped, with no error and no output past the
10719/// first iteration.
10720fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
10721 let mut chosen: Vec<Opcode> = kept
10722 .iter()
10723 .map(|(op, operands)| choose_short_form(*op, operands))
10724 .collect();
10725 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
10726 let candidates = |op: Opcode| match op {
10727 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
10728 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
10729 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
10730 _ => None,
10731 };
10732 loop {
10733 let offsets = instruction_offsets(&chosen);
10734 let mut changed = false;
10735 for index in 0..kept.len() {
10736 let (op, operands) = &kept[index];
10737 let Some((short, medium, has_medium)) = candidates(*op) else {
10738 continue;
10739 };
10740 if chosen[index] == short {
10741 continue;
10742 }
10743 let Some(target) = target_kept_index(operands, label_kept) else {
10744 continue;
10745 };
10746 let Some(&target_offset) = offsets.get(target) else {
10747 continue;
10748 };
10749 // A jump is relative to the byte after its opcode, which is the convention
10750 // `jump_target_of` decodes with.
10751 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
10752 if (-128..=127).contains(&relative) {
10753 chosen[index] = short;
10754 changed = true;
10755 } else if has_medium
10756 && chosen[index] == Opcode::Goto
10757 && (-32_768..=32_767).contains(&relative)
10758 {
10759 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
10760 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
10761 // the reference encodes them.
10762 chosen[index] = medium;
10763 changed = true;
10764 }
10765 }
10766 if !changed {
10767 return chosen;
10768 }
10769 }
10770}
10771
10772fn encode_operands(
10773 code: &mut Vec<u8>,
10774 op: Opcode,
10775 operands: &[Op],
10776 position: usize,
10777 offsets: &[usize],
10778) {
10779 use crate::opcode::OpFormat::*;
10780 let info = op.info();
10781 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
10782 let index = match slot {
10783 Slot::Arg(i)
10784 | Slot::Loc(i)
10785 | Slot::VarRef(i)
10786 | Slot::Global(i)
10787 | Slot::GlobalDecl(i) => i,
10788 };
10789 code.extend_from_slice(&(index as u16).to_be_bytes());
10790 };
10791 match info.format {
10792 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
10793 U8 | Const8 => {
10794 if let Some(value) = operands.first().and_then(operand_uint) {
10795 code.push(value as u8);
10796 }
10797 }
10798 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
10799 // like their wide counterparts, only one byte wide.
10800 Loc8 => {
10801 if let Some(Op::Slot(slot)) = operands.first() {
10802 let index = match slot {
10803 Slot::Arg(i)
10804 | Slot::Loc(i)
10805 | Slot::VarRef(i)
10806 | Slot::Global(i)
10807 | Slot::GlobalDecl(i) => *i,
10808 };
10809 code.push(index as u8);
10810 }
10811 }
10812 I8 => {
10813 if let Some(value) = operands.first().and_then(operand_int) {
10814 code.push(value as i8 as u8);
10815 }
10816 }
10817 U16 | Npop => {
10818 if let Some(value) = operands.first().and_then(operand_int) {
10819 code.extend_from_slice(&(value as u16).to_be_bytes());
10820 }
10821 }
10822 I16 => {
10823 if let Some(value) = operands.first().and_then(operand_int) {
10824 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
10825 }
10826 }
10827 I32 => {
10828 if let Some(value) = operands.first().and_then(operand_int) {
10829 code.extend_from_slice(&value.to_be_bytes());
10830 }
10831 }
10832 U32 | Const => {
10833 if let Some(value) = operands.first().and_then(operand_uint) {
10834 code.extend_from_slice(&value.to_be_bytes());
10835 }
10836 }
10837 Loc | Arg | VarRef => {
10838 if let Some(Op::Slot(slot)) = operands.first() {
10839 write_slot(code, *slot);
10840 }
10841 }
10842 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
10843 if let Some(Op::AtomId(index)) = operands.first() {
10844 code.extend_from_slice(&index.to_be_bytes());
10845 }
10846 // The trailing immediate means different things per format, and the
10847 // atom forms that carry a *label* have to resolve it like any other
10848 // jump, so they cannot share the `U8`/`U16` arms above.
10849 match info.format {
10850 AtomU8 | AtomLabelU8 => {
10851 if let Some(value) = operands.get(1).and_then(operand_uint) {
10852 code.push(value as u8);
10853 }
10854 }
10855 AtomU16 | AtomLabelU16 => {
10856 if let Some(value) = operands.get(1).and_then(operand_uint) {
10857 code.extend_from_slice(&(value as u16).to_be_bytes());
10858 }
10859 }
10860 _ => {}
10861 }
10862 }
10863 NpopU16 => {
10864 for operand in operands.iter().take(2) {
10865 if let Some(value) = operand_uint(operand) {
10866 code.extend_from_slice(&(value as u16).to_be_bytes());
10867 }
10868 }
10869 }
10870 Label | Label8 | Label16 | LabelU16 => {
10871 if let Some(Op::Label(label)) = operands.first() {
10872 // Labels were already remapped to kept-instruction indices.
10873 let Some(&target) = offsets.get(label.0 as usize) else {
10874 debug_assert!(false, "label {} is past the end", label.0);
10875 return;
10876 };
10877 let relative = target as i64 - (position as i64 + 1);
10878 match info.format {
10879 Label8 => code.push(relative as i8 as u8),
10880 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
10881 // `label_u16` stores the target followed by an unrelated u16.
10882 LabelU16 => {
10883 code.extend_from_slice(&(relative as i32).to_be_bytes());
10884 if let Some(value) = operands.get(1).and_then(operand_uint) {
10885 code.extend_from_slice(&(value as u16).to_be_bytes());
10886 }
10887 }
10888 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
10889 }
10890 }
10891 }
10892 }
10893}
10894
10895fn operand_int(op: &Op) -> Option<i32> {
10896 match op {
10897 Op::Int(value) => Some(*value),
10898 _ => None,
10899 }
10900}
10901
10902fn operand_uint(op: &Op) -> Option<u32> {
10903 match op {
10904 Op::Const(value) | Op::AtomId(value) => Some(*value),
10905 Op::Int(value) => Some(*value as u32),
10906 _ => None,
10907 }
10908}
10909
10910/// Disassemble a compiled function.
10911pub fn disassemble(function: &CompiledFunction) -> String {
10912 disasm::disassemble_program(function)
10913}
10914
10915/// How many of an object pattern's keys are computed.
10916///
10917/// Only the count matters: a rest element needs a run-time key log exactly when at least one
10918/// key is not a literal, and the log is sized by walking the pattern anyway.
10919fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
10920 properties
10921 .iter()
10922 .flatten()
10923 .filter(|element| {
10924 matches!(
10925 element,
10926 PatternElement::Property {
10927 key: PropName::Computed(_),
10928 ..
10929 }
10930 )
10931 })
10932 .count()
10933}